View.java revision 3f28a1b7ebb3500d13a1672ab76fe68e9c0a75e8
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.Insets;
28import android.graphics.Interpolator;
29import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.Shader;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.text.TextUtils;
51import android.util.AttributeSet;
52import android.util.FloatProperty;
53import android.util.LocaleUtil;
54import android.util.Log;
55import android.util.Pool;
56import android.util.Poolable;
57import android.util.PoolableManager;
58import android.util.Pools;
59import android.util.Property;
60import android.util.SparseArray;
61import android.util.TypedValue;
62import android.view.ContextMenu.ContextMenuInfo;
63import android.view.accessibility.AccessibilityEvent;
64import android.view.accessibility.AccessibilityEventSource;
65import android.view.accessibility.AccessibilityManager;
66import android.view.accessibility.AccessibilityNodeInfo;
67import android.view.accessibility.AccessibilityNodeProvider;
68import android.view.animation.Animation;
69import android.view.animation.AnimationUtils;
70import android.view.animation.Transformation;
71import android.view.inputmethod.EditorInfo;
72import android.view.inputmethod.InputConnection;
73import android.view.inputmethod.InputMethodManager;
74import android.widget.ScrollBarDrawable;
75
76import static android.os.Build.VERSION_CODES.*;
77import static java.lang.Math.max;
78
79import com.android.internal.R;
80import com.android.internal.util.Predicate;
81import com.android.internal.view.menu.MenuBuilder;
82
83import java.lang.ref.WeakReference;
84import java.lang.reflect.InvocationTargetException;
85import java.lang.reflect.Method;
86import java.util.ArrayList;
87import java.util.Arrays;
88import java.util.Locale;
89import java.util.concurrent.CopyOnWriteArrayList;
90
91/**
92 * <p>
93 * This class represents the basic building block for user interface components. A View
94 * occupies a rectangular area on the screen and is responsible for drawing and
95 * event handling. View is the base class for <em>widgets</em>, which are
96 * used to create interactive UI components (buttons, text fields, etc.). The
97 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
98 * are invisible containers that hold other Views (or other ViewGroups) and define
99 * their layout properties.
100 * </p>
101 *
102 * <div class="special reference">
103 * <h3>Developer Guides</h3>
104 * <p>For information about using this class to develop your application's user interface,
105 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
106 * </div>
107 *
108 * <a name="Using"></a>
109 * <h3>Using Views</h3>
110 * <p>
111 * All of the views in a window are arranged in a single tree. You can add views
112 * either from code or by specifying a tree of views in one or more XML layout
113 * files. There are many specialized subclasses of views that act as controls or
114 * are capable of displaying text, images, or other content.
115 * </p>
116 * <p>
117 * Once you have created a tree of views, there are typically a few types of
118 * common operations you may wish to perform:
119 * <ul>
120 * <li><strong>Set properties:</strong> for example setting the text of a
121 * {@link android.widget.TextView}. The available properties and the methods
122 * that set them will vary among the different subclasses of views. Note that
123 * properties that are known at build time can be set in the XML layout
124 * files.</li>
125 * <li><strong>Set focus:</strong> The framework will handled moving focus in
126 * response to user input. To force focus to a specific view, call
127 * {@link #requestFocus}.</li>
128 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
129 * that will be notified when something interesting happens to the view. For
130 * example, all views will let you set a listener to be notified when the view
131 * gains or loses focus. You can register such a listener using
132 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
133 * Other view subclasses offer more specialized listeners. For example, a Button
134 * exposes a listener to notify clients when the button is clicked.</li>
135 * <li><strong>Set visibility:</strong> You can hide or show views using
136 * {@link #setVisibility(int)}.</li>
137 * </ul>
138 * </p>
139 * <p><em>
140 * Note: The Android framework is responsible for measuring, laying out and
141 * drawing views. You should not call methods that perform these actions on
142 * views yourself unless you are actually implementing a
143 * {@link android.view.ViewGroup}.
144 * </em></p>
145 *
146 * <a name="Lifecycle"></a>
147 * <h3>Implementing a Custom View</h3>
148 *
149 * <p>
150 * To implement a custom view, you will usually begin by providing overrides for
151 * some of the standard methods that the framework calls on all views. You do
152 * not need to override all of these methods. In fact, you can start by just
153 * overriding {@link #onDraw(android.graphics.Canvas)}.
154 * <table border="2" width="85%" align="center" cellpadding="5">
155 *     <thead>
156 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
157 *     </thead>
158 *
159 *     <tbody>
160 *     <tr>
161 *         <td rowspan="2">Creation</td>
162 *         <td>Constructors</td>
163 *         <td>There is a form of the constructor that are called when the view
164 *         is created from code and a form that is called when the view is
165 *         inflated from a layout file. The second form should parse and apply
166 *         any attributes defined in the layout file.
167 *         </td>
168 *     </tr>
169 *     <tr>
170 *         <td><code>{@link #onFinishInflate()}</code></td>
171 *         <td>Called after a view and all of its children has been inflated
172 *         from XML.</td>
173 *     </tr>
174 *
175 *     <tr>
176 *         <td rowspan="3">Layout</td>
177 *         <td><code>{@link #onMeasure(int, int)}</code></td>
178 *         <td>Called to determine the size requirements for this view and all
179 *         of its children.
180 *         </td>
181 *     </tr>
182 *     <tr>
183 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
184 *         <td>Called when this view should assign a size and position to all
185 *         of its children.
186 *         </td>
187 *     </tr>
188 *     <tr>
189 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
190 *         <td>Called when the size of this view has changed.
191 *         </td>
192 *     </tr>
193 *
194 *     <tr>
195 *         <td>Drawing</td>
196 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
197 *         <td>Called when the view should render its content.
198 *         </td>
199 *     </tr>
200 *
201 *     <tr>
202 *         <td rowspan="4">Event processing</td>
203 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
204 *         <td>Called when a new key event occurs.
205 *         </td>
206 *     </tr>
207 *     <tr>
208 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
209 *         <td>Called when a key up event occurs.
210 *         </td>
211 *     </tr>
212 *     <tr>
213 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
214 *         <td>Called when a trackball motion event occurs.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
219 *         <td>Called when a touch screen motion event occurs.
220 *         </td>
221 *     </tr>
222 *
223 *     <tr>
224 *         <td rowspan="2">Focus</td>
225 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
226 *         <td>Called when the view gains or loses focus.
227 *         </td>
228 *     </tr>
229 *
230 *     <tr>
231 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
232 *         <td>Called when the window containing the view gains or loses focus.
233 *         </td>
234 *     </tr>
235 *
236 *     <tr>
237 *         <td rowspan="3">Attaching</td>
238 *         <td><code>{@link #onAttachedToWindow()}</code></td>
239 *         <td>Called when the view is attached to a window.
240 *         </td>
241 *     </tr>
242 *
243 *     <tr>
244 *         <td><code>{@link #onDetachedFromWindow}</code></td>
245 *         <td>Called when the view is detached from its window.
246 *         </td>
247 *     </tr>
248 *
249 *     <tr>
250 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
251 *         <td>Called when the visibility of the window containing the view
252 *         has changed.
253 *         </td>
254 *     </tr>
255 *     </tbody>
256 *
257 * </table>
258 * </p>
259 *
260 * <a name="IDs"></a>
261 * <h3>IDs</h3>
262 * Views may have an integer id associated with them. These ids are typically
263 * assigned in the layout XML files, and are used to find specific views within
264 * the view tree. A common pattern is to:
265 * <ul>
266 * <li>Define a Button in the layout file and assign it a unique ID.
267 * <pre>
268 * &lt;Button
269 *     android:id="@+id/my_button"
270 *     android:layout_width="wrap_content"
271 *     android:layout_height="wrap_content"
272 *     android:text="@string/my_button_text"/&gt;
273 * </pre></li>
274 * <li>From the onCreate method of an Activity, find the Button
275 * <pre class="prettyprint">
276 *      Button myButton = (Button) findViewById(R.id.my_button);
277 * </pre></li>
278 * </ul>
279 * <p>
280 * View IDs need not be unique throughout the tree, but it is good practice to
281 * ensure that they are at least unique within the part of the tree you are
282 * searching.
283 * </p>
284 *
285 * <a name="Position"></a>
286 * <h3>Position</h3>
287 * <p>
288 * The geometry of a view is that of a rectangle. A view has a location,
289 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
290 * two dimensions, expressed as a width and a height. The unit for location
291 * and dimensions is the pixel.
292 * </p>
293 *
294 * <p>
295 * It is possible to retrieve the location of a view by invoking the methods
296 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
297 * coordinate of the rectangle representing the view. The latter returns the
298 * top, or Y, coordinate of the rectangle representing the view. These methods
299 * both return the location of the view relative to its parent. For instance,
300 * when getLeft() returns 20, that means the view is located 20 pixels to the
301 * right of the left edge of its direct parent.
302 * </p>
303 *
304 * <p>
305 * In addition, several convenience methods are offered to avoid unnecessary
306 * computations, namely {@link #getRight()} and {@link #getBottom()}.
307 * These methods return the coordinates of the right and bottom edges of the
308 * rectangle representing the view. For instance, calling {@link #getRight()}
309 * is similar to the following computation: <code>getLeft() + getWidth()</code>
310 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
311 * </p>
312 *
313 * <a name="SizePaddingMargins"></a>
314 * <h3>Size, padding and margins</h3>
315 * <p>
316 * The size of a view is expressed with a width and a height. A view actually
317 * possess two pairs of width and height values.
318 * </p>
319 *
320 * <p>
321 * The first pair is known as <em>measured width</em> and
322 * <em>measured height</em>. These dimensions define how big a view wants to be
323 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
324 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
325 * and {@link #getMeasuredHeight()}.
326 * </p>
327 *
328 * <p>
329 * The second pair is simply known as <em>width</em> and <em>height</em>, or
330 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
331 * dimensions define the actual size of the view on screen, at drawing time and
332 * after layout. These values may, but do not have to, be different from the
333 * measured width and height. The width and height can be obtained by calling
334 * {@link #getWidth()} and {@link #getHeight()}.
335 * </p>
336 *
337 * <p>
338 * To measure its dimensions, a view takes into account its padding. The padding
339 * is expressed in pixels for the left, top, right and bottom parts of the view.
340 * Padding can be used to offset the content of the view by a specific amount of
341 * pixels. For instance, a left padding of 2 will push the view's content by
342 * 2 pixels to the right of the left edge. Padding can be set using the
343 * {@link #setPadding(int, int, int, int)} method and queried by calling
344 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, {@link #getPaddingRight()},
345 * {@link #getPaddingBottom()}.
346 * </p>
347 *
348 * <p>
349 * Even though a view can define a padding, it does not provide any support for
350 * margins. However, view groups provide such a support. Refer to
351 * {@link android.view.ViewGroup} and
352 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
353 * </p>
354 *
355 * <a name="Layout"></a>
356 * <h3>Layout</h3>
357 * <p>
358 * Layout is a two pass process: a measure pass and a layout pass. The measuring
359 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
360 * of the view tree. Each view pushes dimension specifications down the tree
361 * during the recursion. At the end of the measure pass, every view has stored
362 * its measurements. The second pass happens in
363 * {@link #layout(int,int,int,int)} and is also top-down. During
364 * this pass each parent is responsible for positioning all of its children
365 * using the sizes computed in the measure pass.
366 * </p>
367 *
368 * <p>
369 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
370 * {@link #getMeasuredHeight()} values must be set, along with those for all of
371 * that view's descendants. A view's measured width and measured height values
372 * must respect the constraints imposed by the view's parents. This guarantees
373 * that at the end of the measure pass, all parents accept all of their
374 * children's measurements. A parent view may call measure() more than once on
375 * its children. For example, the parent may measure each child once with
376 * unspecified dimensions to find out how big they want to be, then call
377 * measure() on them again with actual numbers if the sum of all the children's
378 * unconstrained sizes is too big or too small.
379 * </p>
380 *
381 * <p>
382 * The measure pass uses two classes to communicate dimensions. The
383 * {@link MeasureSpec} class is used by views to tell their parents how they
384 * want to be measured and positioned. The base LayoutParams class just
385 * describes how big the view wants to be for both width and height. For each
386 * dimension, it can specify one of:
387 * <ul>
388 * <li> an exact number
389 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
390 * (minus padding)
391 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
392 * enclose its content (plus padding).
393 * </ul>
394 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
395 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
396 * an X and Y value.
397 * </p>
398 *
399 * <p>
400 * MeasureSpecs are used to push requirements down the tree from parent to
401 * child. A MeasureSpec can be in one of three modes:
402 * <ul>
403 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
404 * of a child view. For example, a LinearLayout may call measure() on its child
405 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
406 * tall the child view wants to be given a width of 240 pixels.
407 * <li>EXACTLY: This is used by the parent to impose an exact size on the
408 * child. The child must use this size, and guarantee that all of its
409 * descendants will fit within this size.
410 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
411 * child. The child must gurantee that it and all of its descendants will fit
412 * within this size.
413 * </ul>
414 * </p>
415 *
416 * <p>
417 * To intiate a layout, call {@link #requestLayout}. This method is typically
418 * called by a view on itself when it believes that is can no longer fit within
419 * its current bounds.
420 * </p>
421 *
422 * <a name="Drawing"></a>
423 * <h3>Drawing</h3>
424 * <p>
425 * Drawing is handled by walking the tree and rendering each view that
426 * intersects the invalid region. Because the tree is traversed in-order,
427 * this means that parents will draw before (i.e., behind) their children, with
428 * siblings drawn in the order they appear in the tree.
429 * If you set a background drawable for a View, then the View will draw it for you
430 * before calling back to its <code>onDraw()</code> method.
431 * </p>
432 *
433 * <p>
434 * Note that the framework will not draw views that are not in the invalid region.
435 * </p>
436 *
437 * <p>
438 * To force a view to draw, call {@link #invalidate()}.
439 * </p>
440 *
441 * <a name="EventHandlingThreading"></a>
442 * <h3>Event Handling and Threading</h3>
443 * <p>
444 * The basic cycle of a view is as follows:
445 * <ol>
446 * <li>An event comes in and is dispatched to the appropriate view. The view
447 * handles the event and notifies any listeners.</li>
448 * <li>If in the course of processing the event, the view's bounds may need
449 * to be changed, the view will call {@link #requestLayout()}.</li>
450 * <li>Similarly, if in the course of processing the event the view's appearance
451 * may need to be changed, the view will call {@link #invalidate()}.</li>
452 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
453 * the framework will take care of measuring, laying out, and drawing the tree
454 * as appropriate.</li>
455 * </ol>
456 * </p>
457 *
458 * <p><em>Note: The entire view tree is single threaded. You must always be on
459 * the UI thread when calling any method on any view.</em>
460 * If you are doing work on other threads and want to update the state of a view
461 * from that thread, you should use a {@link Handler}.
462 * </p>
463 *
464 * <a name="FocusHandling"></a>
465 * <h3>Focus Handling</h3>
466 * <p>
467 * The framework will handle routine focus movement in response to user input.
468 * This includes changing the focus as views are removed or hidden, or as new
469 * views become available. Views indicate their willingness to take focus
470 * through the {@link #isFocusable} method. To change whether a view can take
471 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
472 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
473 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
474 * </p>
475 * <p>
476 * Focus movement is based on an algorithm which finds the nearest neighbor in a
477 * given direction. In rare cases, the default algorithm may not match the
478 * intended behavior of the developer. In these situations, you can provide
479 * explicit overrides by using these XML attributes in the layout file:
480 * <pre>
481 * nextFocusDown
482 * nextFocusLeft
483 * nextFocusRight
484 * nextFocusUp
485 * </pre>
486 * </p>
487 *
488 *
489 * <p>
490 * To get a particular view to take focus, call {@link #requestFocus()}.
491 * </p>
492 *
493 * <a name="TouchMode"></a>
494 * <h3>Touch Mode</h3>
495 * <p>
496 * When a user is navigating a user interface via directional keys such as a D-pad, it is
497 * necessary to give focus to actionable items such as buttons so the user can see
498 * what will take input.  If the device has touch capabilities, however, and the user
499 * begins interacting with the interface by touching it, it is no longer necessary to
500 * always highlight, or give focus to, a particular view.  This motivates a mode
501 * for interaction named 'touch mode'.
502 * </p>
503 * <p>
504 * For a touch capable device, once the user touches the screen, the device
505 * will enter touch mode.  From this point onward, only views for which
506 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
507 * Other views that are touchable, like buttons, will not take focus when touched; they will
508 * only fire the on click listeners.
509 * </p>
510 * <p>
511 * Any time a user hits a directional key, such as a D-pad direction, the view device will
512 * exit touch mode, and find a view to take focus, so that the user may resume interacting
513 * with the user interface without touching the screen again.
514 * </p>
515 * <p>
516 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
517 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
518 * </p>
519 *
520 * <a name="Scrolling"></a>
521 * <h3>Scrolling</h3>
522 * <p>
523 * The framework provides basic support for views that wish to internally
524 * scroll their content. This includes keeping track of the X and Y scroll
525 * offset as well as mechanisms for drawing scrollbars. See
526 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
527 * {@link #awakenScrollBars()} for more details.
528 * </p>
529 *
530 * <a name="Tags"></a>
531 * <h3>Tags</h3>
532 * <p>
533 * Unlike IDs, tags are not used to identify views. Tags are essentially an
534 * extra piece of information that can be associated with a view. They are most
535 * often used as a convenience to store data related to views in the views
536 * themselves rather than by putting them in a separate structure.
537 * </p>
538 *
539 * <a name="Properties"></a>
540 * <h3>Properties</h3>
541 * <p>
542 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
543 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
544 * available both in the {@link Property} form as well as in similarly-named setter/getter
545 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
546 * be used to set persistent state associated with these rendering-related properties on the view.
547 * The properties and methods can also be used in conjunction with
548 * {@link android.animation.Animator Animator}-based animations, described more in the
549 * <a href="#Animation">Animation</a> section.
550 * </p>
551 *
552 * <a name="Animation"></a>
553 * <h3>Animation</h3>
554 * <p>
555 * Starting with Android 3.0, the preferred way of animating views is to use the
556 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
557 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
558 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
559 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
560 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
561 * makes animating these View properties particularly easy and efficient.
562 * </p>
563 * <p>
564 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
565 * You can attach an {@link Animation} object to a view using
566 * {@link #setAnimation(Animation)} or
567 * {@link #startAnimation(Animation)}. The animation can alter the scale,
568 * rotation, translation and alpha of a view over time. If the animation is
569 * attached to a view that has children, the animation will affect the entire
570 * subtree rooted by that node. When an animation is started, the framework will
571 * take care of redrawing the appropriate views until the animation completes.
572 * </p>
573 *
574 * <a name="Security"></a>
575 * <h3>Security</h3>
576 * <p>
577 * Sometimes it is essential that an application be able to verify that an action
578 * is being performed with the full knowledge and consent of the user, such as
579 * granting a permission request, making a purchase or clicking on an advertisement.
580 * Unfortunately, a malicious application could try to spoof the user into
581 * performing these actions, unaware, by concealing the intended purpose of the view.
582 * As a remedy, the framework offers a touch filtering mechanism that can be used to
583 * improve the security of views that provide access to sensitive functionality.
584 * </p><p>
585 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
586 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
587 * will discard touches that are received whenever the view's window is obscured by
588 * another visible window.  As a result, the view will not receive touches whenever a
589 * toast, dialog or other window appears above the view's window.
590 * </p><p>
591 * For more fine-grained control over security, consider overriding the
592 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
593 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
594 * </p>
595 *
596 * @attr ref android.R.styleable#View_alpha
597 * @attr ref android.R.styleable#View_background
598 * @attr ref android.R.styleable#View_clickable
599 * @attr ref android.R.styleable#View_contentDescription
600 * @attr ref android.R.styleable#View_drawingCacheQuality
601 * @attr ref android.R.styleable#View_duplicateParentState
602 * @attr ref android.R.styleable#View_id
603 * @attr ref android.R.styleable#View_requiresFadingEdge
604 * @attr ref android.R.styleable#View_fadeScrollbars
605 * @attr ref android.R.styleable#View_fadingEdgeLength
606 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
607 * @attr ref android.R.styleable#View_fitsSystemWindows
608 * @attr ref android.R.styleable#View_isScrollContainer
609 * @attr ref android.R.styleable#View_focusable
610 * @attr ref android.R.styleable#View_focusableInTouchMode
611 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
612 * @attr ref android.R.styleable#View_keepScreenOn
613 * @attr ref android.R.styleable#View_layerType
614 * @attr ref android.R.styleable#View_longClickable
615 * @attr ref android.R.styleable#View_minHeight
616 * @attr ref android.R.styleable#View_minWidth
617 * @attr ref android.R.styleable#View_nextFocusDown
618 * @attr ref android.R.styleable#View_nextFocusLeft
619 * @attr ref android.R.styleable#View_nextFocusRight
620 * @attr ref android.R.styleable#View_nextFocusUp
621 * @attr ref android.R.styleable#View_onClick
622 * @attr ref android.R.styleable#View_padding
623 * @attr ref android.R.styleable#View_paddingBottom
624 * @attr ref android.R.styleable#View_paddingLeft
625 * @attr ref android.R.styleable#View_paddingRight
626 * @attr ref android.R.styleable#View_paddingTop
627 * @attr ref android.R.styleable#View_saveEnabled
628 * @attr ref android.R.styleable#View_rotation
629 * @attr ref android.R.styleable#View_rotationX
630 * @attr ref android.R.styleable#View_rotationY
631 * @attr ref android.R.styleable#View_scaleX
632 * @attr ref android.R.styleable#View_scaleY
633 * @attr ref android.R.styleable#View_scrollX
634 * @attr ref android.R.styleable#View_scrollY
635 * @attr ref android.R.styleable#View_scrollbarSize
636 * @attr ref android.R.styleable#View_scrollbarStyle
637 * @attr ref android.R.styleable#View_scrollbars
638 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
639 * @attr ref android.R.styleable#View_scrollbarFadeDuration
640 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
641 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
642 * @attr ref android.R.styleable#View_scrollbarThumbVertical
643 * @attr ref android.R.styleable#View_scrollbarTrackVertical
644 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
645 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
646 * @attr ref android.R.styleable#View_soundEffectsEnabled
647 * @attr ref android.R.styleable#View_tag
648 * @attr ref android.R.styleable#View_transformPivotX
649 * @attr ref android.R.styleable#View_transformPivotY
650 * @attr ref android.R.styleable#View_translationX
651 * @attr ref android.R.styleable#View_translationY
652 * @attr ref android.R.styleable#View_visibility
653 *
654 * @see android.view.ViewGroup
655 */
656public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
657        AccessibilityEventSource {
658    private static final boolean DBG = false;
659
660    /**
661     * The logging tag used by this class with android.util.Log.
662     */
663    protected static final String VIEW_LOG_TAG = "View";
664
665    /**
666     * When set to true, apps will draw debugging information about their layouts.
667     *
668     * @hide
669     */
670    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
671
672    /**
673     * Used to mark a View that has no ID.
674     */
675    public static final int NO_ID = -1;
676
677    /**
678     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
679     * calling setFlags.
680     */
681    private static final int NOT_FOCUSABLE = 0x00000000;
682
683    /**
684     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
685     * setFlags.
686     */
687    private static final int FOCUSABLE = 0x00000001;
688
689    /**
690     * Mask for use with setFlags indicating bits used for focus.
691     */
692    private static final int FOCUSABLE_MASK = 0x00000001;
693
694    /**
695     * This view will adjust its padding to fit sytem windows (e.g. status bar)
696     */
697    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
698
699    /**
700     * This view is visible.
701     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
702     * android:visibility}.
703     */
704    public static final int VISIBLE = 0x00000000;
705
706    /**
707     * This view is invisible, but it still takes up space for layout purposes.
708     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
709     * android:visibility}.
710     */
711    public static final int INVISIBLE = 0x00000004;
712
713    /**
714     * This view is invisible, and it doesn't take any space for layout
715     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
716     * android:visibility}.
717     */
718    public static final int GONE = 0x00000008;
719
720    /**
721     * Mask for use with setFlags indicating bits used for visibility.
722     * {@hide}
723     */
724    static final int VISIBILITY_MASK = 0x0000000C;
725
726    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
727
728    /**
729     * This view is enabled. Interpretation varies by subclass.
730     * Use with ENABLED_MASK when calling setFlags.
731     * {@hide}
732     */
733    static final int ENABLED = 0x00000000;
734
735    /**
736     * This view is disabled. Interpretation varies by subclass.
737     * Use with ENABLED_MASK when calling setFlags.
738     * {@hide}
739     */
740    static final int DISABLED = 0x00000020;
741
742   /**
743    * Mask for use with setFlags indicating bits used for indicating whether
744    * this view is enabled
745    * {@hide}
746    */
747    static final int ENABLED_MASK = 0x00000020;
748
749    /**
750     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
751     * called and further optimizations will be performed. It is okay to have
752     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
753     * {@hide}
754     */
755    static final int WILL_NOT_DRAW = 0x00000080;
756
757    /**
758     * Mask for use with setFlags indicating bits used for indicating whether
759     * this view is will draw
760     * {@hide}
761     */
762    static final int DRAW_MASK = 0x00000080;
763
764    /**
765     * <p>This view doesn't show scrollbars.</p>
766     * {@hide}
767     */
768    static final int SCROLLBARS_NONE = 0x00000000;
769
770    /**
771     * <p>This view shows horizontal scrollbars.</p>
772     * {@hide}
773     */
774    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
775
776    /**
777     * <p>This view shows vertical scrollbars.</p>
778     * {@hide}
779     */
780    static final int SCROLLBARS_VERTICAL = 0x00000200;
781
782    /**
783     * <p>Mask for use with setFlags indicating bits used for indicating which
784     * scrollbars are enabled.</p>
785     * {@hide}
786     */
787    static final int SCROLLBARS_MASK = 0x00000300;
788
789    /**
790     * Indicates that the view should filter touches when its window is obscured.
791     * Refer to the class comments for more information about this security feature.
792     * {@hide}
793     */
794    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
795
796    /**
797     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
798     * that they are optional and should be skipped if the window has
799     * requested system UI flags that ignore those insets for layout.
800     */
801    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
802
803    /**
804     * <p>This view doesn't show fading edges.</p>
805     * {@hide}
806     */
807    static final int FADING_EDGE_NONE = 0x00000000;
808
809    /**
810     * <p>This view shows horizontal fading edges.</p>
811     * {@hide}
812     */
813    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
814
815    /**
816     * <p>This view shows vertical fading edges.</p>
817     * {@hide}
818     */
819    static final int FADING_EDGE_VERTICAL = 0x00002000;
820
821    /**
822     * <p>Mask for use with setFlags indicating bits used for indicating which
823     * fading edges are enabled.</p>
824     * {@hide}
825     */
826    static final int FADING_EDGE_MASK = 0x00003000;
827
828    /**
829     * <p>Indicates this view can be clicked. When clickable, a View reacts
830     * to clicks by notifying the OnClickListener.<p>
831     * {@hide}
832     */
833    static final int CLICKABLE = 0x00004000;
834
835    /**
836     * <p>Indicates this view is caching its drawing into a bitmap.</p>
837     * {@hide}
838     */
839    static final int DRAWING_CACHE_ENABLED = 0x00008000;
840
841    /**
842     * <p>Indicates that no icicle should be saved for this view.<p>
843     * {@hide}
844     */
845    static final int SAVE_DISABLED = 0x000010000;
846
847    /**
848     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
849     * property.</p>
850     * {@hide}
851     */
852    static final int SAVE_DISABLED_MASK = 0x000010000;
853
854    /**
855     * <p>Indicates that no drawing cache should ever be created for this view.<p>
856     * {@hide}
857     */
858    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
859
860    /**
861     * <p>Indicates this view can take / keep focus when int touch mode.</p>
862     * {@hide}
863     */
864    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
865
866    /**
867     * <p>Enables low quality mode for the drawing cache.</p>
868     */
869    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
870
871    /**
872     * <p>Enables high quality mode for the drawing cache.</p>
873     */
874    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
875
876    /**
877     * <p>Enables automatic quality mode for the drawing cache.</p>
878     */
879    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
880
881    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
882            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
883    };
884
885    /**
886     * <p>Mask for use with setFlags indicating bits used for the cache
887     * quality property.</p>
888     * {@hide}
889     */
890    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
891
892    /**
893     * <p>
894     * Indicates this view can be long clicked. When long clickable, a View
895     * reacts to long clicks by notifying the OnLongClickListener or showing a
896     * context menu.
897     * </p>
898     * {@hide}
899     */
900    static final int LONG_CLICKABLE = 0x00200000;
901
902    /**
903     * <p>Indicates that this view gets its drawable states from its direct parent
904     * and ignores its original internal states.</p>
905     *
906     * @hide
907     */
908    static final int DUPLICATE_PARENT_STATE = 0x00400000;
909
910    /**
911     * The scrollbar style to display the scrollbars inside the content area,
912     * without increasing the padding. The scrollbars will be overlaid with
913     * translucency on the view's content.
914     */
915    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
916
917    /**
918     * The scrollbar style to display the scrollbars inside the padded area,
919     * increasing the padding of the view. The scrollbars will not overlap the
920     * content area of the view.
921     */
922    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
923
924    /**
925     * The scrollbar style to display the scrollbars at the edge of the view,
926     * without increasing the padding. The scrollbars will be overlaid with
927     * translucency.
928     */
929    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
930
931    /**
932     * The scrollbar style to display the scrollbars at the edge of the view,
933     * increasing the padding of the view. The scrollbars will only overlap the
934     * background, if any.
935     */
936    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
937
938    /**
939     * Mask to check if the scrollbar style is overlay or inset.
940     * {@hide}
941     */
942    static final int SCROLLBARS_INSET_MASK = 0x01000000;
943
944    /**
945     * Mask to check if the scrollbar style is inside or outside.
946     * {@hide}
947     */
948    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
949
950    /**
951     * Mask for scrollbar style.
952     * {@hide}
953     */
954    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
955
956    /**
957     * View flag indicating that the screen should remain on while the
958     * window containing this view is visible to the user.  This effectively
959     * takes care of automatically setting the WindowManager's
960     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
961     */
962    public static final int KEEP_SCREEN_ON = 0x04000000;
963
964    /**
965     * View flag indicating whether this view should have sound effects enabled
966     * for events such as clicking and touching.
967     */
968    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
969
970    /**
971     * View flag indicating whether this view should have haptic feedback
972     * enabled for events such as long presses.
973     */
974    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
975
976    /**
977     * <p>Indicates that the view hierarchy should stop saving state when
978     * it reaches this view.  If state saving is initiated immediately at
979     * the view, it will be allowed.
980     * {@hide}
981     */
982    static final int PARENT_SAVE_DISABLED = 0x20000000;
983
984    /**
985     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
986     * {@hide}
987     */
988    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
989
990    /**
991     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
992     * should add all focusable Views regardless if they are focusable in touch mode.
993     */
994    public static final int FOCUSABLES_ALL = 0x00000000;
995
996    /**
997     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
998     * should add only Views focusable in touch mode.
999     */
1000    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1001
1002    /**
1003     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1004     * should add only accessibility focusable Views.
1005     *
1006     * @hide
1007     */
1008    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
1009
1010    /**
1011     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1012     * item.
1013     */
1014    public static final int FOCUS_BACKWARD = 0x00000001;
1015
1016    /**
1017     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1018     * item.
1019     */
1020    public static final int FOCUS_FORWARD = 0x00000002;
1021
1022    /**
1023     * Use with {@link #focusSearch(int)}. Move focus to the left.
1024     */
1025    public static final int FOCUS_LEFT = 0x00000011;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus up.
1029     */
1030    public static final int FOCUS_UP = 0x00000021;
1031
1032    /**
1033     * Use with {@link #focusSearch(int)}. Move focus to the right.
1034     */
1035    public static final int FOCUS_RIGHT = 0x00000042;
1036
1037    /**
1038     * Use with {@link #focusSearch(int)}. Move focus down.
1039     */
1040    public static final int FOCUS_DOWN = 0x00000082;
1041
1042    // Accessibility focus directions.
1043
1044    /**
1045     * The accessibility focus which is the current user position when
1046     * interacting with the accessibility framework.
1047     */
1048    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1049
1050    /**
1051     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1052     */
1053    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1054
1055    /**
1056     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1057     */
1058    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1059
1060    /**
1061     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1062     */
1063    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1064
1065    /**
1066     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1067     */
1068    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1069
1070    /**
1071     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1072     */
1073    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1074
1075    /**
1076     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1077     */
1078    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1079
1080    /**
1081     * Bits of {@link #getMeasuredWidthAndState()} and
1082     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1083     */
1084    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1085
1086    /**
1087     * Bits of {@link #getMeasuredWidthAndState()} and
1088     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1089     */
1090    public static final int MEASURED_STATE_MASK = 0xff000000;
1091
1092    /**
1093     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1094     * for functions that combine both width and height into a single int,
1095     * such as {@link #getMeasuredState()} and the childState argument of
1096     * {@link #resolveSizeAndState(int, int, int)}.
1097     */
1098    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1099
1100    /**
1101     * Bit of {@link #getMeasuredWidthAndState()} and
1102     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1103     * is smaller that the space the view would like to have.
1104     */
1105    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1106
1107    /**
1108     * Base View state sets
1109     */
1110    // Singles
1111    /**
1112     * Indicates the view has no states set. 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[] EMPTY_STATE_SET;
1120    /**
1121     * Indicates the view is enabled. 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     */
1128    protected static final int[] ENABLED_STATE_SET;
1129    /**
1130     * Indicates the view is focused. States are used with
1131     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1132     * view depending on its state.
1133     *
1134     * @see android.graphics.drawable.Drawable
1135     * @see #getDrawableState()
1136     */
1137    protected static final int[] FOCUSED_STATE_SET;
1138    /**
1139     * Indicates the view is selected. States are used with
1140     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1141     * view depending on its state.
1142     *
1143     * @see android.graphics.drawable.Drawable
1144     * @see #getDrawableState()
1145     */
1146    protected static final int[] SELECTED_STATE_SET;
1147    /**
1148     * Indicates the view is pressed. States are used with
1149     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1150     * view depending on its state.
1151     *
1152     * @see android.graphics.drawable.Drawable
1153     * @see #getDrawableState()
1154     * @hide
1155     */
1156    protected static final int[] PRESSED_STATE_SET;
1157    /**
1158     * Indicates the view's window has focus. States are used with
1159     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1160     * view depending on its state.
1161     *
1162     * @see android.graphics.drawable.Drawable
1163     * @see #getDrawableState()
1164     */
1165    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1166    // Doubles
1167    /**
1168     * Indicates the view is enabled and has the focus.
1169     *
1170     * @see #ENABLED_STATE_SET
1171     * @see #FOCUSED_STATE_SET
1172     */
1173    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1174    /**
1175     * Indicates the view is enabled and selected.
1176     *
1177     * @see #ENABLED_STATE_SET
1178     * @see #SELECTED_STATE_SET
1179     */
1180    protected static final int[] ENABLED_SELECTED_STATE_SET;
1181    /**
1182     * Indicates the view is enabled and that its window has focus.
1183     *
1184     * @see #ENABLED_STATE_SET
1185     * @see #WINDOW_FOCUSED_STATE_SET
1186     */
1187    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1188    /**
1189     * Indicates the view is focused and selected.
1190     *
1191     * @see #FOCUSED_STATE_SET
1192     * @see #SELECTED_STATE_SET
1193     */
1194    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1195    /**
1196     * Indicates the view has the focus and that its window has the focus.
1197     *
1198     * @see #FOCUSED_STATE_SET
1199     * @see #WINDOW_FOCUSED_STATE_SET
1200     */
1201    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1202    /**
1203     * Indicates the view is selected and that its window has the focus.
1204     *
1205     * @see #SELECTED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1209    // Triples
1210    /**
1211     * Indicates the view is enabled, focused and selected.
1212     *
1213     * @see #ENABLED_STATE_SET
1214     * @see #FOCUSED_STATE_SET
1215     * @see #SELECTED_STATE_SET
1216     */
1217    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1218    /**
1219     * Indicates the view is enabled, focused and its window has the focus.
1220     *
1221     * @see #ENABLED_STATE_SET
1222     * @see #FOCUSED_STATE_SET
1223     * @see #WINDOW_FOCUSED_STATE_SET
1224     */
1225    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1226    /**
1227     * Indicates the view is enabled, selected and its window has the focus.
1228     *
1229     * @see #ENABLED_STATE_SET
1230     * @see #SELECTED_STATE_SET
1231     * @see #WINDOW_FOCUSED_STATE_SET
1232     */
1233    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1234    /**
1235     * Indicates the view is focused, selected and its window has the focus.
1236     *
1237     * @see #FOCUSED_STATE_SET
1238     * @see #SELECTED_STATE_SET
1239     * @see #WINDOW_FOCUSED_STATE_SET
1240     */
1241    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1242    /**
1243     * Indicates the view is enabled, focused, selected and its window
1244     * has the focus.
1245     *
1246     * @see #ENABLED_STATE_SET
1247     * @see #FOCUSED_STATE_SET
1248     * @see #SELECTED_STATE_SET
1249     * @see #WINDOW_FOCUSED_STATE_SET
1250     */
1251    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1252    /**
1253     * Indicates the view is pressed and its window has the focus.
1254     *
1255     * @see #PRESSED_STATE_SET
1256     * @see #WINDOW_FOCUSED_STATE_SET
1257     */
1258    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1259    /**
1260     * Indicates the view is pressed and selected.
1261     *
1262     * @see #PRESSED_STATE_SET
1263     * @see #SELECTED_STATE_SET
1264     */
1265    protected static final int[] PRESSED_SELECTED_STATE_SET;
1266    /**
1267     * Indicates the view is pressed, selected and its window has the focus.
1268     *
1269     * @see #PRESSED_STATE_SET
1270     * @see #SELECTED_STATE_SET
1271     * @see #WINDOW_FOCUSED_STATE_SET
1272     */
1273    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1274    /**
1275     * Indicates the view is pressed and focused.
1276     *
1277     * @see #PRESSED_STATE_SET
1278     * @see #FOCUSED_STATE_SET
1279     */
1280    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1281    /**
1282     * Indicates the view is pressed, focused and its window has the focus.
1283     *
1284     * @see #PRESSED_STATE_SET
1285     * @see #FOCUSED_STATE_SET
1286     * @see #WINDOW_FOCUSED_STATE_SET
1287     */
1288    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1289    /**
1290     * Indicates the view is pressed, focused and selected.
1291     *
1292     * @see #PRESSED_STATE_SET
1293     * @see #SELECTED_STATE_SET
1294     * @see #FOCUSED_STATE_SET
1295     */
1296    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1297    /**
1298     * Indicates the view is pressed, focused, selected and its window has the focus.
1299     *
1300     * @see #PRESSED_STATE_SET
1301     * @see #FOCUSED_STATE_SET
1302     * @see #SELECTED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is pressed and enabled.
1308     *
1309     * @see #PRESSED_STATE_SET
1310     * @see #ENABLED_STATE_SET
1311     */
1312    protected static final int[] PRESSED_ENABLED_STATE_SET;
1313    /**
1314     * Indicates the view is pressed, enabled and its window has the focus.
1315     *
1316     * @see #PRESSED_STATE_SET
1317     * @see #ENABLED_STATE_SET
1318     * @see #WINDOW_FOCUSED_STATE_SET
1319     */
1320    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1321    /**
1322     * Indicates the view is pressed, enabled and selected.
1323     *
1324     * @see #PRESSED_STATE_SET
1325     * @see #ENABLED_STATE_SET
1326     * @see #SELECTED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, enabled, selected and its window has the
1331     * focus.
1332     *
1333     * @see #PRESSED_STATE_SET
1334     * @see #ENABLED_STATE_SET
1335     * @see #SELECTED_STATE_SET
1336     * @see #WINDOW_FOCUSED_STATE_SET
1337     */
1338    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1339    /**
1340     * Indicates the view is pressed, enabled and focused.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #ENABLED_STATE_SET
1344     * @see #FOCUSED_STATE_SET
1345     */
1346    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1347    /**
1348     * Indicates the view is pressed, enabled, focused and its window has the
1349     * focus.
1350     *
1351     * @see #PRESSED_STATE_SET
1352     * @see #ENABLED_STATE_SET
1353     * @see #FOCUSED_STATE_SET
1354     * @see #WINDOW_FOCUSED_STATE_SET
1355     */
1356    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1357    /**
1358     * Indicates the view is pressed, enabled, focused and selected.
1359     *
1360     * @see #PRESSED_STATE_SET
1361     * @see #ENABLED_STATE_SET
1362     * @see #SELECTED_STATE_SET
1363     * @see #FOCUSED_STATE_SET
1364     */
1365    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1366    /**
1367     * Indicates the view is pressed, enabled, focused, selected and its window
1368     * has the focus.
1369     *
1370     * @see #PRESSED_STATE_SET
1371     * @see #ENABLED_STATE_SET
1372     * @see #SELECTED_STATE_SET
1373     * @see #FOCUSED_STATE_SET
1374     * @see #WINDOW_FOCUSED_STATE_SET
1375     */
1376    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1377
1378    /**
1379     * The order here is very important to {@link #getDrawableState()}
1380     */
1381    private static final int[][] VIEW_STATE_SETS;
1382
1383    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1384    static final int VIEW_STATE_SELECTED = 1 << 1;
1385    static final int VIEW_STATE_FOCUSED = 1 << 2;
1386    static final int VIEW_STATE_ENABLED = 1 << 3;
1387    static final int VIEW_STATE_PRESSED = 1 << 4;
1388    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1389    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1390    static final int VIEW_STATE_HOVERED = 1 << 7;
1391    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1392    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1393
1394    static final int[] VIEW_STATE_IDS = new int[] {
1395        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1396        R.attr.state_selected,          VIEW_STATE_SELECTED,
1397        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1398        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1399        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1400        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1401        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1402        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1403        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1404        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1405    };
1406
1407    static {
1408        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1409            throw new IllegalStateException(
1410                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1411        }
1412        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1413        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1414            int viewState = R.styleable.ViewDrawableStates[i];
1415            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1416                if (VIEW_STATE_IDS[j] == viewState) {
1417                    orderedIds[i * 2] = viewState;
1418                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1419                }
1420            }
1421        }
1422        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1423        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1424        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1425            int numBits = Integer.bitCount(i);
1426            int[] set = new int[numBits];
1427            int pos = 0;
1428            for (int j = 0; j < orderedIds.length; j += 2) {
1429                if ((i & orderedIds[j+1]) != 0) {
1430                    set[pos++] = orderedIds[j];
1431                }
1432            }
1433            VIEW_STATE_SETS[i] = set;
1434        }
1435
1436        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1437        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1438        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1439        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1441        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1442        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1444        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1446        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1448                | VIEW_STATE_FOCUSED];
1449        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1450        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1452        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1454        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1456                | VIEW_STATE_ENABLED];
1457        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1459        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1461                | VIEW_STATE_ENABLED];
1462        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1464                | VIEW_STATE_ENABLED];
1465        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1467                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1468
1469        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1470        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1472        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1474        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1476                | VIEW_STATE_PRESSED];
1477        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1479        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1481                | VIEW_STATE_PRESSED];
1482        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1483                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1484                | VIEW_STATE_PRESSED];
1485        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1486                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1487                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1488        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1489                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1490        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1491                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1492                | VIEW_STATE_PRESSED];
1493        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1495                | VIEW_STATE_PRESSED];
1496        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1497                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1498                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1499        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1500                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1501                | VIEW_STATE_PRESSED];
1502        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1504                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1505        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1507                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1508        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1510                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1511                | VIEW_STATE_PRESSED];
1512    }
1513
1514    /**
1515     * Accessibility event types that are dispatched for text population.
1516     */
1517    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1518            AccessibilityEvent.TYPE_VIEW_CLICKED
1519            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1520            | AccessibilityEvent.TYPE_VIEW_SELECTED
1521            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1522            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1523            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1524            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1525            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1526            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1527            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED;
1528
1529    /**
1530     * Temporary Rect currently for use in setBackground().  This will probably
1531     * be extended in the future to hold our own class with more than just
1532     * a Rect. :)
1533     */
1534    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1535
1536    /**
1537     * Map used to store views' tags.
1538     */
1539    private SparseArray<Object> mKeyedTags;
1540
1541    /**
1542     * The next available accessiiblity id.
1543     */
1544    private static int sNextAccessibilityViewId;
1545
1546    /**
1547     * The animation currently associated with this view.
1548     * @hide
1549     */
1550    protected Animation mCurrentAnimation = null;
1551
1552    /**
1553     * Width as measured during measure pass.
1554     * {@hide}
1555     */
1556    @ViewDebug.ExportedProperty(category = "measurement")
1557    int mMeasuredWidth;
1558
1559    /**
1560     * Height as measured during measure pass.
1561     * {@hide}
1562     */
1563    @ViewDebug.ExportedProperty(category = "measurement")
1564    int mMeasuredHeight;
1565
1566    /**
1567     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1568     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1569     * its display list. This flag, used only when hw accelerated, allows us to clear the
1570     * flag while retaining this information until it's needed (at getDisplayList() time and
1571     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1572     *
1573     * {@hide}
1574     */
1575    boolean mRecreateDisplayList = false;
1576
1577    /**
1578     * The view's identifier.
1579     * {@hide}
1580     *
1581     * @see #setId(int)
1582     * @see #getId()
1583     */
1584    @ViewDebug.ExportedProperty(resolveId = true)
1585    int mID = NO_ID;
1586
1587    /**
1588     * The stable ID of this view for accessibility purposes.
1589     */
1590    int mAccessibilityViewId = NO_ID;
1591
1592    /**
1593     * The view's tag.
1594     * {@hide}
1595     *
1596     * @see #setTag(Object)
1597     * @see #getTag()
1598     */
1599    protected Object mTag;
1600
1601    // for mPrivateFlags:
1602    /** {@hide} */
1603    static final int WANTS_FOCUS                    = 0x00000001;
1604    /** {@hide} */
1605    static final int FOCUSED                        = 0x00000002;
1606    /** {@hide} */
1607    static final int SELECTED                       = 0x00000004;
1608    /** {@hide} */
1609    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1610    /** {@hide} */
1611    static final int HAS_BOUNDS                     = 0x00000010;
1612    /** {@hide} */
1613    static final int DRAWN                          = 0x00000020;
1614    /**
1615     * When this flag is set, this view is running an animation on behalf of its
1616     * children and should therefore not cancel invalidate requests, even if they
1617     * lie outside of this view's bounds.
1618     *
1619     * {@hide}
1620     */
1621    static final int DRAW_ANIMATION                 = 0x00000040;
1622    /** {@hide} */
1623    static final int SKIP_DRAW                      = 0x00000080;
1624    /** {@hide} */
1625    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1626    /** {@hide} */
1627    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1628    /** {@hide} */
1629    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1630    /** {@hide} */
1631    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1632    /** {@hide} */
1633    static final int FORCE_LAYOUT                   = 0x00001000;
1634    /** {@hide} */
1635    static final int LAYOUT_REQUIRED                = 0x00002000;
1636
1637    private static final int PRESSED                = 0x00004000;
1638
1639    /** {@hide} */
1640    static final int DRAWING_CACHE_VALID            = 0x00008000;
1641    /**
1642     * Flag used to indicate that this view should be drawn once more (and only once
1643     * more) after its animation has completed.
1644     * {@hide}
1645     */
1646    static final int ANIMATION_STARTED              = 0x00010000;
1647
1648    private static final int SAVE_STATE_CALLED      = 0x00020000;
1649
1650    /**
1651     * Indicates that the View returned true when onSetAlpha() was called and that
1652     * the alpha must be restored.
1653     * {@hide}
1654     */
1655    static final int ALPHA_SET                      = 0x00040000;
1656
1657    /**
1658     * Set by {@link #setScrollContainer(boolean)}.
1659     */
1660    static final int SCROLL_CONTAINER               = 0x00080000;
1661
1662    /**
1663     * Set by {@link #setScrollContainer(boolean)}.
1664     */
1665    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1666
1667    /**
1668     * View flag indicating whether this view was invalidated (fully or partially.)
1669     *
1670     * @hide
1671     */
1672    static final int DIRTY                          = 0x00200000;
1673
1674    /**
1675     * View flag indicating whether this view was invalidated by an opaque
1676     * invalidate request.
1677     *
1678     * @hide
1679     */
1680    static final int DIRTY_OPAQUE                   = 0x00400000;
1681
1682    /**
1683     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1684     *
1685     * @hide
1686     */
1687    static final int DIRTY_MASK                     = 0x00600000;
1688
1689    /**
1690     * Indicates whether the background is opaque.
1691     *
1692     * @hide
1693     */
1694    static final int OPAQUE_BACKGROUND              = 0x00800000;
1695
1696    /**
1697     * Indicates whether the scrollbars are opaque.
1698     *
1699     * @hide
1700     */
1701    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1702
1703    /**
1704     * Indicates whether the view is opaque.
1705     *
1706     * @hide
1707     */
1708    static final int OPAQUE_MASK                    = 0x01800000;
1709
1710    /**
1711     * Indicates a prepressed state;
1712     * the short time between ACTION_DOWN and recognizing
1713     * a 'real' press. Prepressed is used to recognize quick taps
1714     * even when they are shorter than ViewConfiguration.getTapTimeout().
1715     *
1716     * @hide
1717     */
1718    private static final int PREPRESSED             = 0x02000000;
1719
1720    /**
1721     * Indicates whether the view is temporarily detached.
1722     *
1723     * @hide
1724     */
1725    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1726
1727    /**
1728     * Indicates that we should awaken scroll bars once attached
1729     *
1730     * @hide
1731     */
1732    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1733
1734    /**
1735     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1736     * @hide
1737     */
1738    private static final int HOVERED              = 0x10000000;
1739
1740    /**
1741     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1742     * for transform operations
1743     *
1744     * @hide
1745     */
1746    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1747
1748    /** {@hide} */
1749    static final int ACTIVATED                    = 0x40000000;
1750
1751    /**
1752     * Indicates that this view was specifically invalidated, not just dirtied because some
1753     * child view was invalidated. The flag is used to determine when we need to recreate
1754     * a view's display list (as opposed to just returning a reference to its existing
1755     * display list).
1756     *
1757     * @hide
1758     */
1759    static final int INVALIDATED                  = 0x80000000;
1760
1761    /* Masks for mPrivateFlags2 */
1762
1763    /**
1764     * Indicates that this view has reported that it can accept the current drag's content.
1765     * Cleared when the drag operation concludes.
1766     * @hide
1767     */
1768    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1769
1770    /**
1771     * Indicates that this view is currently directly under the drag location in a
1772     * drag-and-drop operation involving content that it can accept.  Cleared when
1773     * the drag exits the view, or when the drag operation concludes.
1774     * @hide
1775     */
1776    static final int DRAG_HOVERED                 = 0x00000002;
1777
1778    /**
1779     * Horizontal layout direction of this view is from Left to Right.
1780     * Use with {@link #setLayoutDirection}.
1781     * @hide
1782     */
1783    public static final int LAYOUT_DIRECTION_LTR = 0;
1784
1785    /**
1786     * Horizontal layout direction of this view is from Right to Left.
1787     * Use with {@link #setLayoutDirection}.
1788     * @hide
1789     */
1790    public static final int LAYOUT_DIRECTION_RTL = 1;
1791
1792    /**
1793     * Horizontal layout direction of this view is inherited from its parent.
1794     * Use with {@link #setLayoutDirection}.
1795     * @hide
1796     */
1797    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1798
1799    /**
1800     * Horizontal layout direction of this view is from deduced from the default language
1801     * script for the locale. Use with {@link #setLayoutDirection}.
1802     * @hide
1803     */
1804    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1805
1806    /**
1807     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1808     * @hide
1809     */
1810    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1811
1812    /**
1813     * Mask for use with private flags indicating bits used for horizontal layout direction.
1814     * @hide
1815     */
1816    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1817
1818    /**
1819     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1820     * right-to-left direction.
1821     * @hide
1822     */
1823    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1824
1825    /**
1826     * Indicates whether the view horizontal layout direction has been resolved.
1827     * @hide
1828     */
1829    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1830
1831    /**
1832     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1833     * @hide
1834     */
1835    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1836
1837    /*
1838     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1839     * flag value.
1840     * @hide
1841     */
1842    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1843            LAYOUT_DIRECTION_LTR,
1844            LAYOUT_DIRECTION_RTL,
1845            LAYOUT_DIRECTION_INHERIT,
1846            LAYOUT_DIRECTION_LOCALE
1847    };
1848
1849    /**
1850     * Default horizontal layout direction.
1851     * @hide
1852     */
1853    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1854
1855    /**
1856     * Indicates that the view is tracking some sort of transient state
1857     * that the app should not need to be aware of, but that the framework
1858     * should take special care to preserve.
1859     *
1860     * @hide
1861     */
1862    static final int HAS_TRANSIENT_STATE = 0x00000100;
1863
1864
1865    /**
1866     * Text direction is inherited thru {@link ViewGroup}
1867     * @hide
1868     */
1869    public static final int TEXT_DIRECTION_INHERIT = 0;
1870
1871    /**
1872     * Text direction is using "first strong algorithm". The first strong directional character
1873     * determines the paragraph direction. If there is no strong directional character, the
1874     * paragraph direction is the view's resolved layout direction.
1875     * @hide
1876     */
1877    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1878
1879    /**
1880     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1881     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1882     * If there are neither, the paragraph direction is the view's resolved layout direction.
1883     * @hide
1884     */
1885    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1886
1887    /**
1888     * Text direction is forced to LTR.
1889     * @hide
1890     */
1891    public static final int TEXT_DIRECTION_LTR = 3;
1892
1893    /**
1894     * Text direction is forced to RTL.
1895     * @hide
1896     */
1897    public static final int TEXT_DIRECTION_RTL = 4;
1898
1899    /**
1900     * Text direction is coming from the system Locale.
1901     * @hide
1902     */
1903    public static final int TEXT_DIRECTION_LOCALE = 5;
1904
1905    /**
1906     * Default text direction is inherited
1907     * @hide
1908     */
1909    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1910
1911    /**
1912     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1913     * @hide
1914     */
1915    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1916
1917    /**
1918     * Mask for use with private flags indicating bits used for text direction.
1919     * @hide
1920     */
1921    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1922
1923    /**
1924     * Array of text direction flags for mapping attribute "textDirection" to correct
1925     * flag value.
1926     * @hide
1927     */
1928    private static final int[] TEXT_DIRECTION_FLAGS = {
1929            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1930            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1931            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1932            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1933            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1934            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1935    };
1936
1937    /**
1938     * Indicates whether the view text direction has been resolved.
1939     * @hide
1940     */
1941    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1942
1943    /**
1944     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1945     * @hide
1946     */
1947    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1948
1949    /**
1950     * Mask for use with private flags indicating bits used for resolved text direction.
1951     * @hide
1952     */
1953    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1954
1955    /**
1956     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1957     * @hide
1958     */
1959    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1960            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1961
1962    /*
1963     * Default text alignment. The text alignment of this View is inherited from its parent.
1964     * Use with {@link #setTextAlignment(int)}
1965     * @hide
1966     */
1967    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1968
1969    /**
1970     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1971     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1972     *
1973     * Use with {@link #setTextAlignment(int)}
1974     * @hide
1975     */
1976    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1977
1978    /**
1979     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1980     *
1981     * Use with {@link #setTextAlignment(int)}
1982     * @hide
1983     */
1984    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1985
1986    /**
1987     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1988     *
1989     * Use with {@link #setTextAlignment(int)}
1990     * @hide
1991     */
1992    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1993
1994    /**
1995     * Center the paragraph, e.g. ALIGN_CENTER.
1996     *
1997     * Use with {@link #setTextAlignment(int)}
1998     * @hide
1999     */
2000    public static final int TEXT_ALIGNMENT_CENTER = 4;
2001
2002    /**
2003     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2004     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2005     *
2006     * Use with {@link #setTextAlignment(int)}
2007     * @hide
2008     */
2009    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2010
2011    /**
2012     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2013     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2014     *
2015     * Use with {@link #setTextAlignment(int)}
2016     * @hide
2017     */
2018    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2019
2020    /**
2021     * Default text alignment is inherited
2022     * @hide
2023     */
2024    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2025
2026    /**
2027      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2028      * @hide
2029      */
2030    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2031
2032    /**
2033      * Mask for use with private flags indicating bits used for text alignment.
2034      * @hide
2035      */
2036    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2037
2038    /**
2039     * Array of text direction flags for mapping attribute "textAlignment" to correct
2040     * flag value.
2041     * @hide
2042     */
2043    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2044            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2045            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2046            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2047            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2048            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2049            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2050            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2051    };
2052
2053    /**
2054     * Indicates whether the view text alignment has been resolved.
2055     * @hide
2056     */
2057    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2058
2059    /**
2060     * Bit shift to get the resolved text alignment.
2061     * @hide
2062     */
2063    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2064
2065    /**
2066     * Mask for use with private flags indicating bits used for text alignment.
2067     * @hide
2068     */
2069    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2070
2071    /**
2072     * Indicates whether if the view text alignment has been resolved to gravity
2073     */
2074    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2075            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2076
2077    // Accessiblity constants for mPrivateFlags2
2078
2079    /**
2080     * Shift for accessibility related bits in {@link #mPrivateFlags2}.
2081     */
2082    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2083
2084    /**
2085     * Automatically determine whether a view is important for accessibility.
2086     */
2087    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2088
2089    /**
2090     * The view is important for accessibility.
2091     */
2092    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2093
2094    /**
2095     * The view is not important for accessibility.
2096     */
2097    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2098
2099    /**
2100     * The default whether the view is important for accessiblity.
2101     */
2102    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2103
2104    /**
2105     * Mask for obtainig the bits which specify how to determine
2106     * whether a view is important for accessibility.
2107     */
2108    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2109        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2110        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2111
2112    /**
2113     * Flag indicating whether a view has accessibility focus.
2114     */
2115    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2116
2117    /**
2118     * Flag indicating whether a view state for accessibility has changed.
2119     */
2120    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2121
2122    /* End of masks for mPrivateFlags2 */
2123
2124    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2125
2126    /**
2127     * Always allow a user to over-scroll this view, provided it is a
2128     * view that can scroll.
2129     *
2130     * @see #getOverScrollMode()
2131     * @see #setOverScrollMode(int)
2132     */
2133    public static final int OVER_SCROLL_ALWAYS = 0;
2134
2135    /**
2136     * Allow a user to over-scroll this view only if the content is large
2137     * enough to meaningfully scroll, provided it is a view that can scroll.
2138     *
2139     * @see #getOverScrollMode()
2140     * @see #setOverScrollMode(int)
2141     */
2142    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2143
2144    /**
2145     * Never allow a user to over-scroll this view.
2146     *
2147     * @see #getOverScrollMode()
2148     * @see #setOverScrollMode(int)
2149     */
2150    public static final int OVER_SCROLL_NEVER = 2;
2151
2152    /**
2153     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2154     * requested the system UI (status bar) to be visible (the default).
2155     *
2156     * @see #setSystemUiVisibility(int)
2157     */
2158    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2159
2160    /**
2161     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2162     * system UI to enter an unobtrusive "low profile" mode.
2163     *
2164     * <p>This is for use in games, book readers, video players, or any other
2165     * "immersive" application where the usual system chrome is deemed too distracting.
2166     *
2167     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2168     *
2169     * @see #setSystemUiVisibility(int)
2170     */
2171    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2172
2173    /**
2174     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2175     * system navigation be temporarily hidden.
2176     *
2177     * <p>This is an even less obtrusive state than that called for by
2178     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2179     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2180     * those to disappear. This is useful (in conjunction with the
2181     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2182     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2183     * window flags) for displaying content using every last pixel on the display.
2184     *
2185     * <p>There is a limitation: because navigation controls are so important, the least user
2186     * interaction will cause them to reappear immediately.  When this happens, both
2187     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2188     * so that both elements reappear at the same time.
2189     *
2190     * @see #setSystemUiVisibility(int)
2191     */
2192    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2193
2194    /**
2195     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2196     * into the normal fullscreen mode so that its content can take over the screen
2197     * while still allowing the user to interact with the application.
2198     *
2199     * <p>This has the same visual effect as
2200     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2201     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2202     * meaning that non-critical screen decorations (such as the status bar) will be
2203     * hidden while the user is in the View's window, focusing the experience on
2204     * that content.  Unlike the window flag, if you are using ActionBar in
2205     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2206     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2207     * hide the action bar.
2208     *
2209     * <p>This approach to going fullscreen is best used over the window flag when
2210     * it is a transient state -- that is, the application does this at certain
2211     * points in its user interaction where it wants to allow the user to focus
2212     * on content, but not as a continuous state.  For situations where the application
2213     * would like to simply stay full screen the entire time (such as a game that
2214     * wants to take over the screen), the
2215     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2216     * is usually a better approach.  The state set here will be removed by the system
2217     * in various situations (such as the user moving to another application) like
2218     * the other system UI states.
2219     *
2220     * <p>When using this flag, the application should provide some easy facility
2221     * for the user to go out of it.  A common example would be in an e-book
2222     * reader, where tapping on the screen brings back whatever screen and UI
2223     * decorations that had been hidden while the user was immersed in reading
2224     * the book.
2225     *
2226     * @see #setSystemUiVisibility(int)
2227     */
2228    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2229
2230    /**
2231     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2232     * flags, we would like a stable view of the content insets given to
2233     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2234     * will always represent the worst case that the application can expect
2235     * as a continue state.  In practice this means with any of system bar,
2236     * nav bar, and status bar shown, but not the space that would be needed
2237     * for an input method.
2238     *
2239     * <p>If you are using ActionBar in
2240     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2241     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2242     * insets it adds to those given to the application.
2243     */
2244    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2245
2246    /**
2247     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2248     * to be layed out as if it has requested
2249     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2250     * allows it to avoid artifacts when switching in and out of that mode, at
2251     * the expense that some of its user interface may be covered by screen
2252     * decorations when they are shown.  You can perform layout of your inner
2253     * UI elements to account for the navagation system UI through the
2254     * {@link #fitSystemWindows(Rect)} method.
2255     */
2256    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2257
2258    /**
2259     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2260     * to be layed out as if it has requested
2261     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2262     * allows it to avoid artifacts when switching in and out of that mode, at
2263     * the expense that some of its user interface may be covered by screen
2264     * decorations when they are shown.  You can perform layout of your inner
2265     * UI elements to account for non-fullscreen system UI through the
2266     * {@link #fitSystemWindows(Rect)} method.
2267     */
2268    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2269
2270    /**
2271     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2272     */
2273    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2274
2275    /**
2276     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2277     */
2278    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2279
2280    /**
2281     * @hide
2282     *
2283     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2284     * out of the public fields to keep the undefined bits out of the developer's way.
2285     *
2286     * Flag to make the status bar not expandable.  Unless you also
2287     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2288     */
2289    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2290
2291    /**
2292     * @hide
2293     *
2294     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2295     * out of the public fields to keep the undefined bits out of the developer's way.
2296     *
2297     * Flag to hide notification icons and scrolling ticker text.
2298     */
2299    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2300
2301    /**
2302     * @hide
2303     *
2304     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2305     * out of the public fields to keep the undefined bits out of the developer's way.
2306     *
2307     * Flag to disable incoming notification alerts.  This will not block
2308     * icons, but it will block sound, vibrating and other visual or aural notifications.
2309     */
2310    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2311
2312    /**
2313     * @hide
2314     *
2315     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2316     * out of the public fields to keep the undefined bits out of the developer's way.
2317     *
2318     * Flag to hide only the scrolling ticker.  Note that
2319     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2320     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2321     */
2322    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2323
2324    /**
2325     * @hide
2326     *
2327     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2328     * out of the public fields to keep the undefined bits out of the developer's way.
2329     *
2330     * Flag to hide the center system info area.
2331     */
2332    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2333
2334    /**
2335     * @hide
2336     *
2337     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2338     * out of the public fields to keep the undefined bits out of the developer's way.
2339     *
2340     * Flag to hide only the home button.  Don't use this
2341     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2342     */
2343    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2344
2345    /**
2346     * @hide
2347     *
2348     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2349     * out of the public fields to keep the undefined bits out of the developer's way.
2350     *
2351     * Flag to hide only the back button. Don't use this
2352     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2353     */
2354    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2355
2356    /**
2357     * @hide
2358     *
2359     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2360     * out of the public fields to keep the undefined bits out of the developer's way.
2361     *
2362     * Flag to hide only the clock.  You might use this if your activity has
2363     * its own clock making the status bar's clock redundant.
2364     */
2365    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2366
2367    /**
2368     * @hide
2369     *
2370     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2371     * out of the public fields to keep the undefined bits out of the developer's way.
2372     *
2373     * Flag to hide only the recent apps button. Don't use this
2374     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2375     */
2376    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2377
2378    /**
2379     * @hide
2380     */
2381    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2382
2383    /**
2384     * These are the system UI flags that can be cleared by events outside
2385     * of an application.  Currently this is just the ability to tap on the
2386     * screen while hiding the navigation bar to have it return.
2387     * @hide
2388     */
2389    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2390            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2391            | SYSTEM_UI_FLAG_FULLSCREEN;
2392
2393    /**
2394     * Flags that can impact the layout in relation to system UI.
2395     */
2396    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2397            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2398            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2399
2400    /**
2401     * Find views that render the specified text.
2402     *
2403     * @see #findViewsWithText(ArrayList, CharSequence, int)
2404     */
2405    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2406
2407    /**
2408     * Find find views that contain the specified content description.
2409     *
2410     * @see #findViewsWithText(ArrayList, CharSequence, int)
2411     */
2412    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2413
2414    /**
2415     * Find views that contain {@link AccessibilityNodeProvider}. Such
2416     * a View is a root of virtual view hierarchy and may contain the searched
2417     * text. If this flag is set Views with providers are automatically
2418     * added and it is a responsibility of the client to call the APIs of
2419     * the provider to determine whether the virtual tree rooted at this View
2420     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2421     * represeting the virtual views with this text.
2422     *
2423     * @see #findViewsWithText(ArrayList, CharSequence, int)
2424     *
2425     * @hide
2426     */
2427    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2428
2429    /**
2430     * Indicates that the screen has changed state and is now off.
2431     *
2432     * @see #onScreenStateChanged(int)
2433     */
2434    public static final int SCREEN_STATE_OFF = 0x0;
2435
2436    /**
2437     * Indicates that the screen has changed state and is now on.
2438     *
2439     * @see #onScreenStateChanged(int)
2440     */
2441    public static final int SCREEN_STATE_ON = 0x1;
2442
2443    /**
2444     * Controls the over-scroll mode for this view.
2445     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2446     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2447     * and {@link #OVER_SCROLL_NEVER}.
2448     */
2449    private int mOverScrollMode;
2450
2451    /**
2452     * The parent this view is attached to.
2453     * {@hide}
2454     *
2455     * @see #getParent()
2456     */
2457    protected ViewParent mParent;
2458
2459    /**
2460     * {@hide}
2461     */
2462    AttachInfo mAttachInfo;
2463
2464    /**
2465     * {@hide}
2466     */
2467    @ViewDebug.ExportedProperty(flagMapping = {
2468        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2469                name = "FORCE_LAYOUT"),
2470        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2471                name = "LAYOUT_REQUIRED"),
2472        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2473            name = "DRAWING_CACHE_INVALID", outputIf = false),
2474        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2475        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2476        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2477        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2478    })
2479    int mPrivateFlags;
2480    int mPrivateFlags2;
2481
2482    /**
2483     * This view's request for the visibility of the status bar.
2484     * @hide
2485     */
2486    @ViewDebug.ExportedProperty(flagMapping = {
2487        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2488                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2489                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2490        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2491                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2492                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2493        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2494                                equals = SYSTEM_UI_FLAG_VISIBLE,
2495                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2496    })
2497    int mSystemUiVisibility;
2498
2499    /**
2500     * Reference count for transient state.
2501     * @see #setHasTransientState(boolean)
2502     */
2503    int mTransientStateCount = 0;
2504
2505    /**
2506     * Count of how many windows this view has been attached to.
2507     */
2508    int mWindowAttachCount;
2509
2510    /**
2511     * The layout parameters associated with this view and used by the parent
2512     * {@link android.view.ViewGroup} to determine how this view should be
2513     * laid out.
2514     * {@hide}
2515     */
2516    protected ViewGroup.LayoutParams mLayoutParams;
2517
2518    /**
2519     * The view flags hold various views states.
2520     * {@hide}
2521     */
2522    @ViewDebug.ExportedProperty
2523    int mViewFlags;
2524
2525    static class TransformationInfo {
2526        /**
2527         * The transform matrix for the View. This transform is calculated internally
2528         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2529         * is used by default. Do *not* use this variable directly; instead call
2530         * getMatrix(), which will automatically recalculate the matrix if necessary
2531         * to get the correct matrix based on the latest rotation and scale properties.
2532         */
2533        private final Matrix mMatrix = new Matrix();
2534
2535        /**
2536         * The transform matrix for the View. This transform is calculated internally
2537         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2538         * is used by default. Do *not* use this variable directly; instead call
2539         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2540         * to get the correct matrix based on the latest rotation and scale properties.
2541         */
2542        private Matrix mInverseMatrix;
2543
2544        /**
2545         * An internal variable that tracks whether we need to recalculate the
2546         * transform matrix, based on whether the rotation or scaleX/Y properties
2547         * have changed since the matrix was last calculated.
2548         */
2549        boolean mMatrixDirty = false;
2550
2551        /**
2552         * An internal variable that tracks whether we need to recalculate the
2553         * transform matrix, based on whether the rotation or scaleX/Y properties
2554         * have changed since the matrix was last calculated.
2555         */
2556        private boolean mInverseMatrixDirty = true;
2557
2558        /**
2559         * A variable that tracks whether we need to recalculate the
2560         * transform matrix, based on whether the rotation or scaleX/Y properties
2561         * have changed since the matrix was last calculated. This variable
2562         * is only valid after a call to updateMatrix() or to a function that
2563         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2564         */
2565        private boolean mMatrixIsIdentity = true;
2566
2567        /**
2568         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2569         */
2570        private Camera mCamera = null;
2571
2572        /**
2573         * This matrix is used when computing the matrix for 3D rotations.
2574         */
2575        private Matrix matrix3D = null;
2576
2577        /**
2578         * These prev values are used to recalculate a centered pivot point when necessary. The
2579         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2580         * set), so thes values are only used then as well.
2581         */
2582        private int mPrevWidth = -1;
2583        private int mPrevHeight = -1;
2584
2585        /**
2586         * The degrees rotation around the vertical axis through the pivot point.
2587         */
2588        @ViewDebug.ExportedProperty
2589        float mRotationY = 0f;
2590
2591        /**
2592         * The degrees rotation around the horizontal axis through the pivot point.
2593         */
2594        @ViewDebug.ExportedProperty
2595        float mRotationX = 0f;
2596
2597        /**
2598         * The degrees rotation around the pivot point.
2599         */
2600        @ViewDebug.ExportedProperty
2601        float mRotation = 0f;
2602
2603        /**
2604         * The amount of translation of the object away from its left property (post-layout).
2605         */
2606        @ViewDebug.ExportedProperty
2607        float mTranslationX = 0f;
2608
2609        /**
2610         * The amount of translation of the object away from its top property (post-layout).
2611         */
2612        @ViewDebug.ExportedProperty
2613        float mTranslationY = 0f;
2614
2615        /**
2616         * The amount of scale in the x direction around the pivot point. A
2617         * value of 1 means no scaling is applied.
2618         */
2619        @ViewDebug.ExportedProperty
2620        float mScaleX = 1f;
2621
2622        /**
2623         * The amount of scale in the y direction around the pivot point. A
2624         * value of 1 means no scaling is applied.
2625         */
2626        @ViewDebug.ExportedProperty
2627        float mScaleY = 1f;
2628
2629        /**
2630         * The x location of the point around which the view is rotated and scaled.
2631         */
2632        @ViewDebug.ExportedProperty
2633        float mPivotX = 0f;
2634
2635        /**
2636         * The y location of the point around which the view is rotated and scaled.
2637         */
2638        @ViewDebug.ExportedProperty
2639        float mPivotY = 0f;
2640
2641        /**
2642         * The opacity of the View. This is a value from 0 to 1, where 0 means
2643         * completely transparent and 1 means completely opaque.
2644         */
2645        @ViewDebug.ExportedProperty
2646        float mAlpha = 1f;
2647    }
2648
2649    TransformationInfo mTransformationInfo;
2650
2651    private boolean mLastIsOpaque;
2652
2653    /**
2654     * Convenience value to check for float values that are close enough to zero to be considered
2655     * zero.
2656     */
2657    private static final float NONZERO_EPSILON = .001f;
2658
2659    /**
2660     * The distance in pixels from the left edge of this view's parent
2661     * to the left edge of this view.
2662     * {@hide}
2663     */
2664    @ViewDebug.ExportedProperty(category = "layout")
2665    protected int mLeft;
2666    /**
2667     * The distance in pixels from the left edge of this view's parent
2668     * to the right edge of this view.
2669     * {@hide}
2670     */
2671    @ViewDebug.ExportedProperty(category = "layout")
2672    protected int mRight;
2673    /**
2674     * The distance in pixels from the top edge of this view's parent
2675     * to the top edge of this view.
2676     * {@hide}
2677     */
2678    @ViewDebug.ExportedProperty(category = "layout")
2679    protected int mTop;
2680    /**
2681     * The distance in pixels from the top edge of this view's parent
2682     * to the bottom edge of this view.
2683     * {@hide}
2684     */
2685    @ViewDebug.ExportedProperty(category = "layout")
2686    protected int mBottom;
2687
2688    /**
2689     * The offset, in pixels, by which the content of this view is scrolled
2690     * horizontally.
2691     * {@hide}
2692     */
2693    @ViewDebug.ExportedProperty(category = "scrolling")
2694    protected int mScrollX;
2695    /**
2696     * The offset, in pixels, by which the content of this view is scrolled
2697     * vertically.
2698     * {@hide}
2699     */
2700    @ViewDebug.ExportedProperty(category = "scrolling")
2701    protected int mScrollY;
2702
2703    /**
2704     * The left padding in pixels, that is the distance in pixels between the
2705     * left edge of this view and the left edge of its content.
2706     * {@hide}
2707     */
2708    @ViewDebug.ExportedProperty(category = "padding")
2709    protected int mPaddingLeft;
2710    /**
2711     * The right padding in pixels, that is the distance in pixels between the
2712     * right edge of this view and the right edge of its content.
2713     * {@hide}
2714     */
2715    @ViewDebug.ExportedProperty(category = "padding")
2716    protected int mPaddingRight;
2717    /**
2718     * The top padding in pixels, that is the distance in pixels between the
2719     * top edge of this view and the top edge of its content.
2720     * {@hide}
2721     */
2722    @ViewDebug.ExportedProperty(category = "padding")
2723    protected int mPaddingTop;
2724    /**
2725     * The bottom padding in pixels, that is the distance in pixels between the
2726     * bottom edge of this view and the bottom edge of its content.
2727     * {@hide}
2728     */
2729    @ViewDebug.ExportedProperty(category = "padding")
2730    protected int mPaddingBottom;
2731
2732    /**
2733     * The layout insets in pixels, that is the distance in pixels between the
2734     * visible edges of this view its bounds.
2735     */
2736    private Insets mLayoutInsets;
2737
2738    /**
2739     * Briefly describes the view and is primarily used for accessibility support.
2740     */
2741    private CharSequence mContentDescription;
2742
2743    /**
2744     * Cache the paddingRight set by the user to append to the scrollbar's size.
2745     *
2746     * @hide
2747     */
2748    @ViewDebug.ExportedProperty(category = "padding")
2749    protected int mUserPaddingRight;
2750
2751    /**
2752     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2753     *
2754     * @hide
2755     */
2756    @ViewDebug.ExportedProperty(category = "padding")
2757    protected int mUserPaddingBottom;
2758
2759    /**
2760     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2761     *
2762     * @hide
2763     */
2764    @ViewDebug.ExportedProperty(category = "padding")
2765    protected int mUserPaddingLeft;
2766
2767    /**
2768     * Cache if the user padding is relative.
2769     *
2770     */
2771    @ViewDebug.ExportedProperty(category = "padding")
2772    boolean mUserPaddingRelative;
2773
2774    /**
2775     * Cache the paddingStart set by the user to append to the scrollbar's size.
2776     *
2777     */
2778    @ViewDebug.ExportedProperty(category = "padding")
2779    int mUserPaddingStart;
2780
2781    /**
2782     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2783     *
2784     */
2785    @ViewDebug.ExportedProperty(category = "padding")
2786    int mUserPaddingEnd;
2787
2788    /**
2789     * @hide
2790     */
2791    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2792    /**
2793     * @hide
2794     */
2795    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2796
2797    private Drawable mBackground;
2798
2799    private int mBackgroundResource;
2800    private boolean mBackgroundSizeChanged;
2801
2802    static class ListenerInfo {
2803        /**
2804         * Listener used to dispatch focus change events.
2805         * This field should be made private, so it is hidden from the SDK.
2806         * {@hide}
2807         */
2808        protected OnFocusChangeListener mOnFocusChangeListener;
2809
2810        /**
2811         * Listeners for layout change events.
2812         */
2813        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2814
2815        /**
2816         * Listeners for attach events.
2817         */
2818        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2819
2820        /**
2821         * Listener used to dispatch click events.
2822         * This field should be made private, so it is hidden from the SDK.
2823         * {@hide}
2824         */
2825        public OnClickListener mOnClickListener;
2826
2827        /**
2828         * Listener used to dispatch long click events.
2829         * This field should be made private, so it is hidden from the SDK.
2830         * {@hide}
2831         */
2832        protected OnLongClickListener mOnLongClickListener;
2833
2834        /**
2835         * Listener used to build the context menu.
2836         * This field should be made private, so it is hidden from the SDK.
2837         * {@hide}
2838         */
2839        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2840
2841        private OnKeyListener mOnKeyListener;
2842
2843        private OnTouchListener mOnTouchListener;
2844
2845        private OnHoverListener mOnHoverListener;
2846
2847        private OnGenericMotionListener mOnGenericMotionListener;
2848
2849        private OnDragListener mOnDragListener;
2850
2851        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2852    }
2853
2854    ListenerInfo mListenerInfo;
2855
2856    /**
2857     * The application environment this view lives in.
2858     * This field should be made private, so it is hidden from the SDK.
2859     * {@hide}
2860     */
2861    protected Context mContext;
2862
2863    private final Resources mResources;
2864
2865    private ScrollabilityCache mScrollCache;
2866
2867    private int[] mDrawableState = null;
2868
2869    /**
2870     * Set to true when drawing cache is enabled and cannot be created.
2871     *
2872     * @hide
2873     */
2874    public boolean mCachingFailed;
2875
2876    private Bitmap mDrawingCache;
2877    private Bitmap mUnscaledDrawingCache;
2878    private HardwareLayer mHardwareLayer;
2879    DisplayList mDisplayList;
2880
2881    /**
2882     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2883     * the user may specify which view to go to next.
2884     */
2885    private int mNextFocusLeftId = View.NO_ID;
2886
2887    /**
2888     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2889     * the user may specify which view to go to next.
2890     */
2891    private int mNextFocusRightId = View.NO_ID;
2892
2893    /**
2894     * When this view has focus and the next focus is {@link #FOCUS_UP},
2895     * the user may specify which view to go to next.
2896     */
2897    private int mNextFocusUpId = View.NO_ID;
2898
2899    /**
2900     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2901     * the user may specify which view to go to next.
2902     */
2903    private int mNextFocusDownId = View.NO_ID;
2904
2905    /**
2906     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2907     * the user may specify which view to go to next.
2908     */
2909    int mNextFocusForwardId = View.NO_ID;
2910
2911    private CheckForLongPress mPendingCheckForLongPress;
2912    private CheckForTap mPendingCheckForTap = null;
2913    private PerformClick mPerformClick;
2914    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2915
2916    private UnsetPressedState mUnsetPressedState;
2917
2918    /**
2919     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2920     * up event while a long press is invoked as soon as the long press duration is reached, so
2921     * a long press could be performed before the tap is checked, in which case the tap's action
2922     * should not be invoked.
2923     */
2924    private boolean mHasPerformedLongPress;
2925
2926    /**
2927     * The minimum height of the view. We'll try our best to have the height
2928     * of this view to at least this amount.
2929     */
2930    @ViewDebug.ExportedProperty(category = "measurement")
2931    private int mMinHeight;
2932
2933    /**
2934     * The minimum width of the view. We'll try our best to have the width
2935     * of this view to at least this amount.
2936     */
2937    @ViewDebug.ExportedProperty(category = "measurement")
2938    private int mMinWidth;
2939
2940    /**
2941     * The delegate to handle touch events that are physically in this view
2942     * but should be handled by another view.
2943     */
2944    private TouchDelegate mTouchDelegate = null;
2945
2946    /**
2947     * Solid color to use as a background when creating the drawing cache. Enables
2948     * the cache to use 16 bit bitmaps instead of 32 bit.
2949     */
2950    private int mDrawingCacheBackgroundColor = 0;
2951
2952    /**
2953     * Special tree observer used when mAttachInfo is null.
2954     */
2955    private ViewTreeObserver mFloatingTreeObserver;
2956
2957    /**
2958     * Cache the touch slop from the context that created the view.
2959     */
2960    private int mTouchSlop;
2961
2962    /**
2963     * Object that handles automatic animation of view properties.
2964     */
2965    private ViewPropertyAnimator mAnimator = null;
2966
2967    /**
2968     * Flag indicating that a drag can cross window boundaries.  When
2969     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2970     * with this flag set, all visible applications will be able to participate
2971     * in the drag operation and receive the dragged content.
2972     *
2973     * @hide
2974     */
2975    public static final int DRAG_FLAG_GLOBAL = 1;
2976
2977    /**
2978     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2979     */
2980    private float mVerticalScrollFactor;
2981
2982    /**
2983     * Position of the vertical scroll bar.
2984     */
2985    private int mVerticalScrollbarPosition;
2986
2987    /**
2988     * Position the scroll bar at the default position as determined by the system.
2989     */
2990    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2991
2992    /**
2993     * Position the scroll bar along the left edge.
2994     */
2995    public static final int SCROLLBAR_POSITION_LEFT = 1;
2996
2997    /**
2998     * Position the scroll bar along the right edge.
2999     */
3000    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3001
3002    /**
3003     * Indicates that the view does not have a layer.
3004     *
3005     * @see #getLayerType()
3006     * @see #setLayerType(int, android.graphics.Paint)
3007     * @see #LAYER_TYPE_SOFTWARE
3008     * @see #LAYER_TYPE_HARDWARE
3009     */
3010    public static final int LAYER_TYPE_NONE = 0;
3011
3012    /**
3013     * <p>Indicates that the view has a software layer. A software layer is backed
3014     * by a bitmap and causes the view to be rendered using Android's software
3015     * rendering pipeline, even if hardware acceleration is enabled.</p>
3016     *
3017     * <p>Software layers have various usages:</p>
3018     * <p>When the application is not using hardware acceleration, a software layer
3019     * is useful to apply a specific color filter and/or blending mode and/or
3020     * translucency to a view and all its children.</p>
3021     * <p>When the application is using hardware acceleration, a software layer
3022     * is useful to render drawing primitives not supported by the hardware
3023     * accelerated pipeline. It can also be used to cache a complex view tree
3024     * into a texture and reduce the complexity of drawing operations. For instance,
3025     * when animating a complex view tree with a translation, a software layer can
3026     * be used to render the view tree only once.</p>
3027     * <p>Software layers should be avoided when the affected view tree updates
3028     * often. Every update will require to re-render the software layer, which can
3029     * potentially be slow (particularly when hardware acceleration is turned on
3030     * since the layer will have to be uploaded into a hardware texture after every
3031     * update.)</p>
3032     *
3033     * @see #getLayerType()
3034     * @see #setLayerType(int, android.graphics.Paint)
3035     * @see #LAYER_TYPE_NONE
3036     * @see #LAYER_TYPE_HARDWARE
3037     */
3038    public static final int LAYER_TYPE_SOFTWARE = 1;
3039
3040    /**
3041     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3042     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3043     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3044     * rendering pipeline, but only if hardware acceleration is turned on for the
3045     * view hierarchy. When hardware acceleration is turned off, hardware layers
3046     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3047     *
3048     * <p>A hardware layer is useful to apply a specific color filter and/or
3049     * blending mode and/or translucency to a view and all its children.</p>
3050     * <p>A hardware layer can be used to cache a complex view tree into a
3051     * texture and reduce the complexity of drawing operations. For instance,
3052     * when animating a complex view tree with a translation, a hardware layer can
3053     * be used to render the view tree only once.</p>
3054     * <p>A hardware layer can also be used to increase the rendering quality when
3055     * rotation transformations are applied on a view. It can also be used to
3056     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3057     *
3058     * @see #getLayerType()
3059     * @see #setLayerType(int, android.graphics.Paint)
3060     * @see #LAYER_TYPE_NONE
3061     * @see #LAYER_TYPE_SOFTWARE
3062     */
3063    public static final int LAYER_TYPE_HARDWARE = 2;
3064
3065    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3066            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3067            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3068            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3069    })
3070    int mLayerType = LAYER_TYPE_NONE;
3071    Paint mLayerPaint;
3072    Rect mLocalDirtyRect;
3073
3074    /**
3075     * Set to true when the view is sending hover accessibility events because it
3076     * is the innermost hovered view.
3077     */
3078    private boolean mSendingHoverAccessibilityEvents;
3079
3080    /**
3081     * Simple constructor to use when creating a view from code.
3082     *
3083     * @param context The Context the view is running in, through which it can
3084     *        access the current theme, resources, etc.
3085     */
3086    public View(Context context) {
3087        mContext = context;
3088        mResources = context != null ? context.getResources() : null;
3089        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3090        // Set layout and text direction defaults
3091        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3092                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3093                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3094                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3095        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3096        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3097        mUserPaddingStart = -1;
3098        mUserPaddingEnd = -1;
3099        mUserPaddingRelative = false;
3100    }
3101
3102    /**
3103     * Delegate for injecting accessiblity functionality.
3104     */
3105    AccessibilityDelegate mAccessibilityDelegate;
3106
3107    /**
3108     * Consistency verifier for debugging purposes.
3109     * @hide
3110     */
3111    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3112            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3113                    new InputEventConsistencyVerifier(this, 0) : null;
3114
3115    /**
3116     * Constructor that is called when inflating a view from XML. This is called
3117     * when a view is being constructed from an XML file, supplying attributes
3118     * that were specified in the XML file. This version uses a default style of
3119     * 0, so the only attribute values applied are those in the Context's Theme
3120     * and the given AttributeSet.
3121     *
3122     * <p>
3123     * The method onFinishInflate() will be called after all children have been
3124     * added.
3125     *
3126     * @param context The Context the view is running in, through which it can
3127     *        access the current theme, resources, etc.
3128     * @param attrs The attributes of the XML tag that is inflating the view.
3129     * @see #View(Context, AttributeSet, int)
3130     */
3131    public View(Context context, AttributeSet attrs) {
3132        this(context, attrs, 0);
3133    }
3134
3135    /**
3136     * Perform inflation from XML and apply a class-specific base style. This
3137     * constructor of View allows subclasses to use their own base style when
3138     * they are inflating. For example, a Button class's constructor would call
3139     * this version of the super class constructor and supply
3140     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3141     * the theme's button style to modify all of the base view attributes (in
3142     * particular its background) as well as the Button class's attributes.
3143     *
3144     * @param context The Context the view is running in, through which it can
3145     *        access the current theme, resources, etc.
3146     * @param attrs The attributes of the XML tag that is inflating the view.
3147     * @param defStyle The default style to apply to this view. If 0, no style
3148     *        will be applied (beyond what is included in the theme). This may
3149     *        either be an attribute resource, whose value will be retrieved
3150     *        from the current theme, or an explicit style resource.
3151     * @see #View(Context, AttributeSet)
3152     */
3153    public View(Context context, AttributeSet attrs, int defStyle) {
3154        this(context);
3155
3156        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3157                defStyle, 0);
3158
3159        Drawable background = null;
3160
3161        int leftPadding = -1;
3162        int topPadding = -1;
3163        int rightPadding = -1;
3164        int bottomPadding = -1;
3165        int startPadding = -1;
3166        int endPadding = -1;
3167
3168        int padding = -1;
3169
3170        int viewFlagValues = 0;
3171        int viewFlagMasks = 0;
3172
3173        boolean setScrollContainer = false;
3174
3175        int x = 0;
3176        int y = 0;
3177
3178        float tx = 0;
3179        float ty = 0;
3180        float rotation = 0;
3181        float rotationX = 0;
3182        float rotationY = 0;
3183        float sx = 1f;
3184        float sy = 1f;
3185        boolean transformSet = false;
3186
3187        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3188
3189        int overScrollMode = mOverScrollMode;
3190        final int N = a.getIndexCount();
3191        for (int i = 0; i < N; i++) {
3192            int attr = a.getIndex(i);
3193            switch (attr) {
3194                case com.android.internal.R.styleable.View_background:
3195                    background = a.getDrawable(attr);
3196                    break;
3197                case com.android.internal.R.styleable.View_padding:
3198                    padding = a.getDimensionPixelSize(attr, -1);
3199                    break;
3200                 case com.android.internal.R.styleable.View_paddingLeft:
3201                    leftPadding = a.getDimensionPixelSize(attr, -1);
3202                    break;
3203                case com.android.internal.R.styleable.View_paddingTop:
3204                    topPadding = a.getDimensionPixelSize(attr, -1);
3205                    break;
3206                case com.android.internal.R.styleable.View_paddingRight:
3207                    rightPadding = a.getDimensionPixelSize(attr, -1);
3208                    break;
3209                case com.android.internal.R.styleable.View_paddingBottom:
3210                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3211                    break;
3212                case com.android.internal.R.styleable.View_paddingStart:
3213                    startPadding = a.getDimensionPixelSize(attr, -1);
3214                    break;
3215                case com.android.internal.R.styleable.View_paddingEnd:
3216                    endPadding = a.getDimensionPixelSize(attr, -1);
3217                    break;
3218                case com.android.internal.R.styleable.View_scrollX:
3219                    x = a.getDimensionPixelOffset(attr, 0);
3220                    break;
3221                case com.android.internal.R.styleable.View_scrollY:
3222                    y = a.getDimensionPixelOffset(attr, 0);
3223                    break;
3224                case com.android.internal.R.styleable.View_alpha:
3225                    setAlpha(a.getFloat(attr, 1f));
3226                    break;
3227                case com.android.internal.R.styleable.View_transformPivotX:
3228                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3229                    break;
3230                case com.android.internal.R.styleable.View_transformPivotY:
3231                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3232                    break;
3233                case com.android.internal.R.styleable.View_translationX:
3234                    tx = a.getDimensionPixelOffset(attr, 0);
3235                    transformSet = true;
3236                    break;
3237                case com.android.internal.R.styleable.View_translationY:
3238                    ty = a.getDimensionPixelOffset(attr, 0);
3239                    transformSet = true;
3240                    break;
3241                case com.android.internal.R.styleable.View_rotation:
3242                    rotation = a.getFloat(attr, 0);
3243                    transformSet = true;
3244                    break;
3245                case com.android.internal.R.styleable.View_rotationX:
3246                    rotationX = a.getFloat(attr, 0);
3247                    transformSet = true;
3248                    break;
3249                case com.android.internal.R.styleable.View_rotationY:
3250                    rotationY = a.getFloat(attr, 0);
3251                    transformSet = true;
3252                    break;
3253                case com.android.internal.R.styleable.View_scaleX:
3254                    sx = a.getFloat(attr, 1f);
3255                    transformSet = true;
3256                    break;
3257                case com.android.internal.R.styleable.View_scaleY:
3258                    sy = a.getFloat(attr, 1f);
3259                    transformSet = true;
3260                    break;
3261                case com.android.internal.R.styleable.View_id:
3262                    mID = a.getResourceId(attr, NO_ID);
3263                    break;
3264                case com.android.internal.R.styleable.View_tag:
3265                    mTag = a.getText(attr);
3266                    break;
3267                case com.android.internal.R.styleable.View_fitsSystemWindows:
3268                    if (a.getBoolean(attr, false)) {
3269                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3270                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3271                    }
3272                    break;
3273                case com.android.internal.R.styleable.View_focusable:
3274                    if (a.getBoolean(attr, false)) {
3275                        viewFlagValues |= FOCUSABLE;
3276                        viewFlagMasks |= FOCUSABLE_MASK;
3277                    }
3278                    break;
3279                case com.android.internal.R.styleable.View_focusableInTouchMode:
3280                    if (a.getBoolean(attr, false)) {
3281                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3282                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3283                    }
3284                    break;
3285                case com.android.internal.R.styleable.View_clickable:
3286                    if (a.getBoolean(attr, false)) {
3287                        viewFlagValues |= CLICKABLE;
3288                        viewFlagMasks |= CLICKABLE;
3289                    }
3290                    break;
3291                case com.android.internal.R.styleable.View_longClickable:
3292                    if (a.getBoolean(attr, false)) {
3293                        viewFlagValues |= LONG_CLICKABLE;
3294                        viewFlagMasks |= LONG_CLICKABLE;
3295                    }
3296                    break;
3297                case com.android.internal.R.styleable.View_saveEnabled:
3298                    if (!a.getBoolean(attr, true)) {
3299                        viewFlagValues |= SAVE_DISABLED;
3300                        viewFlagMasks |= SAVE_DISABLED_MASK;
3301                    }
3302                    break;
3303                case com.android.internal.R.styleable.View_duplicateParentState:
3304                    if (a.getBoolean(attr, false)) {
3305                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3306                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3307                    }
3308                    break;
3309                case com.android.internal.R.styleable.View_visibility:
3310                    final int visibility = a.getInt(attr, 0);
3311                    if (visibility != 0) {
3312                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3313                        viewFlagMasks |= VISIBILITY_MASK;
3314                    }
3315                    break;
3316                case com.android.internal.R.styleable.View_layoutDirection:
3317                    // Clear any layout direction flags (included resolved bits) already set
3318                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3319                    // Set the layout direction flags depending on the value of the attribute
3320                    final int layoutDirection = a.getInt(attr, -1);
3321                    final int value = (layoutDirection != -1) ?
3322                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3323                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3324                    break;
3325                case com.android.internal.R.styleable.View_drawingCacheQuality:
3326                    final int cacheQuality = a.getInt(attr, 0);
3327                    if (cacheQuality != 0) {
3328                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3329                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3330                    }
3331                    break;
3332                case com.android.internal.R.styleable.View_contentDescription:
3333                    mContentDescription = a.getString(attr);
3334                    break;
3335                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3336                    if (!a.getBoolean(attr, true)) {
3337                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3338                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3339                    }
3340                    break;
3341                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3342                    if (!a.getBoolean(attr, true)) {
3343                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3344                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3345                    }
3346                    break;
3347                case R.styleable.View_scrollbars:
3348                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3349                    if (scrollbars != SCROLLBARS_NONE) {
3350                        viewFlagValues |= scrollbars;
3351                        viewFlagMasks |= SCROLLBARS_MASK;
3352                        initializeScrollbars(a);
3353                    }
3354                    break;
3355                //noinspection deprecation
3356                case R.styleable.View_fadingEdge:
3357                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3358                        // Ignore the attribute starting with ICS
3359                        break;
3360                    }
3361                    // With builds < ICS, fall through and apply fading edges
3362                case R.styleable.View_requiresFadingEdge:
3363                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3364                    if (fadingEdge != FADING_EDGE_NONE) {
3365                        viewFlagValues |= fadingEdge;
3366                        viewFlagMasks |= FADING_EDGE_MASK;
3367                        initializeFadingEdge(a);
3368                    }
3369                    break;
3370                case R.styleable.View_scrollbarStyle:
3371                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3372                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3373                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3374                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3375                    }
3376                    break;
3377                case R.styleable.View_isScrollContainer:
3378                    setScrollContainer = true;
3379                    if (a.getBoolean(attr, false)) {
3380                        setScrollContainer(true);
3381                    }
3382                    break;
3383                case com.android.internal.R.styleable.View_keepScreenOn:
3384                    if (a.getBoolean(attr, false)) {
3385                        viewFlagValues |= KEEP_SCREEN_ON;
3386                        viewFlagMasks |= KEEP_SCREEN_ON;
3387                    }
3388                    break;
3389                case R.styleable.View_filterTouchesWhenObscured:
3390                    if (a.getBoolean(attr, false)) {
3391                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3392                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3393                    }
3394                    break;
3395                case R.styleable.View_nextFocusLeft:
3396                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3397                    break;
3398                case R.styleable.View_nextFocusRight:
3399                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3400                    break;
3401                case R.styleable.View_nextFocusUp:
3402                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3403                    break;
3404                case R.styleable.View_nextFocusDown:
3405                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3406                    break;
3407                case R.styleable.View_nextFocusForward:
3408                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3409                    break;
3410                case R.styleable.View_minWidth:
3411                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3412                    break;
3413                case R.styleable.View_minHeight:
3414                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3415                    break;
3416                case R.styleable.View_onClick:
3417                    if (context.isRestricted()) {
3418                        throw new IllegalStateException("The android:onClick attribute cannot "
3419                                + "be used within a restricted context");
3420                    }
3421
3422                    final String handlerName = a.getString(attr);
3423                    if (handlerName != null) {
3424                        setOnClickListener(new OnClickListener() {
3425                            private Method mHandler;
3426
3427                            public void onClick(View v) {
3428                                if (mHandler == null) {
3429                                    try {
3430                                        mHandler = getContext().getClass().getMethod(handlerName,
3431                                                View.class);
3432                                    } catch (NoSuchMethodException e) {
3433                                        int id = getId();
3434                                        String idText = id == NO_ID ? "" : " with id '"
3435                                                + getContext().getResources().getResourceEntryName(
3436                                                    id) + "'";
3437                                        throw new IllegalStateException("Could not find a method " +
3438                                                handlerName + "(View) in the activity "
3439                                                + getContext().getClass() + " for onClick handler"
3440                                                + " on view " + View.this.getClass() + idText, e);
3441                                    }
3442                                }
3443
3444                                try {
3445                                    mHandler.invoke(getContext(), View.this);
3446                                } catch (IllegalAccessException e) {
3447                                    throw new IllegalStateException("Could not execute non "
3448                                            + "public method of the activity", e);
3449                                } catch (InvocationTargetException e) {
3450                                    throw new IllegalStateException("Could not execute "
3451                                            + "method of the activity", e);
3452                                }
3453                            }
3454                        });
3455                    }
3456                    break;
3457                case R.styleable.View_overScrollMode:
3458                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3459                    break;
3460                case R.styleable.View_verticalScrollbarPosition:
3461                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3462                    break;
3463                case R.styleable.View_layerType:
3464                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3465                    break;
3466                case R.styleable.View_textDirection:
3467                    // Clear any text direction flag already set
3468                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3469                    // Set the text direction flags depending on the value of the attribute
3470                    final int textDirection = a.getInt(attr, -1);
3471                    if (textDirection != -1) {
3472                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3473                    }
3474                    break;
3475                case R.styleable.View_textAlignment:
3476                    // Clear any text alignment flag already set
3477                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3478                    // Set the text alignment flag depending on the value of the attribute
3479                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3480                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3481                    break;
3482                case R.styleable.View_importantForAccessibility:
3483                    setImportantForAccessibility(a.getInt(attr,
3484                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3485            }
3486        }
3487
3488        a.recycle();
3489
3490        setOverScrollMode(overScrollMode);
3491
3492        if (background != null) {
3493            setBackground(background);
3494        }
3495
3496        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3497        // layout direction). Those cached values will be used later during padding resolution.
3498        mUserPaddingStart = startPadding;
3499        mUserPaddingEnd = endPadding;
3500
3501        updateUserPaddingRelative();
3502
3503        if (padding >= 0) {
3504            leftPadding = padding;
3505            topPadding = padding;
3506            rightPadding = padding;
3507            bottomPadding = padding;
3508        }
3509
3510        // If the user specified the padding (either with android:padding or
3511        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3512        // use the default padding or the padding from the background drawable
3513        // (stored at this point in mPadding*)
3514        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3515                topPadding >= 0 ? topPadding : mPaddingTop,
3516                rightPadding >= 0 ? rightPadding : mPaddingRight,
3517                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3518
3519        if (viewFlagMasks != 0) {
3520            setFlags(viewFlagValues, viewFlagMasks);
3521        }
3522
3523        // Needs to be called after mViewFlags is set
3524        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3525            recomputePadding();
3526        }
3527
3528        if (x != 0 || y != 0) {
3529            scrollTo(x, y);
3530        }
3531
3532        if (transformSet) {
3533            setTranslationX(tx);
3534            setTranslationY(ty);
3535            setRotation(rotation);
3536            setRotationX(rotationX);
3537            setRotationY(rotationY);
3538            setScaleX(sx);
3539            setScaleY(sy);
3540        }
3541
3542        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3543            setScrollContainer(true);
3544        }
3545
3546        computeOpaqueFlags();
3547    }
3548
3549    private void updateUserPaddingRelative() {
3550        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3551    }
3552
3553    /**
3554     * Non-public constructor for use in testing
3555     */
3556    View() {
3557        mResources = null;
3558    }
3559
3560    /**
3561     * <p>
3562     * Initializes the fading edges from a given set of styled attributes. This
3563     * method should be called by subclasses that need fading edges and when an
3564     * instance of these subclasses is created programmatically rather than
3565     * being inflated from XML. This method is automatically called when the XML
3566     * is inflated.
3567     * </p>
3568     *
3569     * @param a the styled attributes set to initialize the fading edges from
3570     */
3571    protected void initializeFadingEdge(TypedArray a) {
3572        initScrollCache();
3573
3574        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3575                R.styleable.View_fadingEdgeLength,
3576                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3577    }
3578
3579    /**
3580     * Returns the size of the vertical faded edges used to indicate that more
3581     * content in this view is visible.
3582     *
3583     * @return The size in pixels of the vertical faded edge or 0 if vertical
3584     *         faded edges are not enabled for this view.
3585     * @attr ref android.R.styleable#View_fadingEdgeLength
3586     */
3587    public int getVerticalFadingEdgeLength() {
3588        if (isVerticalFadingEdgeEnabled()) {
3589            ScrollabilityCache cache = mScrollCache;
3590            if (cache != null) {
3591                return cache.fadingEdgeLength;
3592            }
3593        }
3594        return 0;
3595    }
3596
3597    /**
3598     * Set the size of the faded edge used to indicate that more content in this
3599     * view is available.  Will not change whether the fading edge is enabled; use
3600     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3601     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3602     * for the vertical or horizontal fading edges.
3603     *
3604     * @param length The size in pixels of the faded edge used to indicate that more
3605     *        content in this view is visible.
3606     */
3607    public void setFadingEdgeLength(int length) {
3608        initScrollCache();
3609        mScrollCache.fadingEdgeLength = length;
3610    }
3611
3612    /**
3613     * Returns the size of the horizontal faded edges used to indicate that more
3614     * content in this view is visible.
3615     *
3616     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3617     *         faded edges are not enabled for this view.
3618     * @attr ref android.R.styleable#View_fadingEdgeLength
3619     */
3620    public int getHorizontalFadingEdgeLength() {
3621        if (isHorizontalFadingEdgeEnabled()) {
3622            ScrollabilityCache cache = mScrollCache;
3623            if (cache != null) {
3624                return cache.fadingEdgeLength;
3625            }
3626        }
3627        return 0;
3628    }
3629
3630    /**
3631     * Returns the width of the vertical scrollbar.
3632     *
3633     * @return The width in pixels of the vertical scrollbar or 0 if there
3634     *         is no vertical scrollbar.
3635     */
3636    public int getVerticalScrollbarWidth() {
3637        ScrollabilityCache cache = mScrollCache;
3638        if (cache != null) {
3639            ScrollBarDrawable scrollBar = cache.scrollBar;
3640            if (scrollBar != null) {
3641                int size = scrollBar.getSize(true);
3642                if (size <= 0) {
3643                    size = cache.scrollBarSize;
3644                }
3645                return size;
3646            }
3647            return 0;
3648        }
3649        return 0;
3650    }
3651
3652    /**
3653     * Returns the height of the horizontal scrollbar.
3654     *
3655     * @return The height in pixels of the horizontal scrollbar or 0 if
3656     *         there is no horizontal scrollbar.
3657     */
3658    protected int getHorizontalScrollbarHeight() {
3659        ScrollabilityCache cache = mScrollCache;
3660        if (cache != null) {
3661            ScrollBarDrawable scrollBar = cache.scrollBar;
3662            if (scrollBar != null) {
3663                int size = scrollBar.getSize(false);
3664                if (size <= 0) {
3665                    size = cache.scrollBarSize;
3666                }
3667                return size;
3668            }
3669            return 0;
3670        }
3671        return 0;
3672    }
3673
3674    /**
3675     * <p>
3676     * Initializes the scrollbars from a given set of styled attributes. This
3677     * method should be called by subclasses that need scrollbars and when an
3678     * instance of these subclasses is created programmatically rather than
3679     * being inflated from XML. This method is automatically called when the XML
3680     * is inflated.
3681     * </p>
3682     *
3683     * @param a the styled attributes set to initialize the scrollbars from
3684     */
3685    protected void initializeScrollbars(TypedArray a) {
3686        initScrollCache();
3687
3688        final ScrollabilityCache scrollabilityCache = mScrollCache;
3689
3690        if (scrollabilityCache.scrollBar == null) {
3691            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3692        }
3693
3694        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3695
3696        if (!fadeScrollbars) {
3697            scrollabilityCache.state = ScrollabilityCache.ON;
3698        }
3699        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3700
3701
3702        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3703                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3704                        .getScrollBarFadeDuration());
3705        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3706                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3707                ViewConfiguration.getScrollDefaultDelay());
3708
3709
3710        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3711                com.android.internal.R.styleable.View_scrollbarSize,
3712                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3713
3714        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3715        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3716
3717        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3718        if (thumb != null) {
3719            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3720        }
3721
3722        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3723                false);
3724        if (alwaysDraw) {
3725            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3726        }
3727
3728        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3729        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3730
3731        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3732        if (thumb != null) {
3733            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3734        }
3735
3736        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3737                false);
3738        if (alwaysDraw) {
3739            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3740        }
3741
3742        // Re-apply user/background padding so that scrollbar(s) get added
3743        resolvePadding();
3744    }
3745
3746    /**
3747     * <p>
3748     * Initalizes the scrollability cache if necessary.
3749     * </p>
3750     */
3751    private void initScrollCache() {
3752        if (mScrollCache == null) {
3753            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3754        }
3755    }
3756
3757    private ScrollabilityCache getScrollCache() {
3758        initScrollCache();
3759        return mScrollCache;
3760    }
3761
3762    /**
3763     * Set the position of the vertical scroll bar. Should be one of
3764     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3765     * {@link #SCROLLBAR_POSITION_RIGHT}.
3766     *
3767     * @param position Where the vertical scroll bar should be positioned.
3768     */
3769    public void setVerticalScrollbarPosition(int position) {
3770        if (mVerticalScrollbarPosition != position) {
3771            mVerticalScrollbarPosition = position;
3772            computeOpaqueFlags();
3773            resolvePadding();
3774        }
3775    }
3776
3777    /**
3778     * @return The position where the vertical scroll bar will show, if applicable.
3779     * @see #setVerticalScrollbarPosition(int)
3780     */
3781    public int getVerticalScrollbarPosition() {
3782        return mVerticalScrollbarPosition;
3783    }
3784
3785    ListenerInfo getListenerInfo() {
3786        if (mListenerInfo != null) {
3787            return mListenerInfo;
3788        }
3789        mListenerInfo = new ListenerInfo();
3790        return mListenerInfo;
3791    }
3792
3793    /**
3794     * Register a callback to be invoked when focus of this view changed.
3795     *
3796     * @param l The callback that will run.
3797     */
3798    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3799        getListenerInfo().mOnFocusChangeListener = l;
3800    }
3801
3802    /**
3803     * Add a listener that will be called when the bounds of the view change due to
3804     * layout processing.
3805     *
3806     * @param listener The listener that will be called when layout bounds change.
3807     */
3808    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3809        ListenerInfo li = getListenerInfo();
3810        if (li.mOnLayoutChangeListeners == null) {
3811            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3812        }
3813        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3814            li.mOnLayoutChangeListeners.add(listener);
3815        }
3816    }
3817
3818    /**
3819     * Remove a listener for layout changes.
3820     *
3821     * @param listener The listener for layout bounds change.
3822     */
3823    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3824        ListenerInfo li = mListenerInfo;
3825        if (li == null || li.mOnLayoutChangeListeners == null) {
3826            return;
3827        }
3828        li.mOnLayoutChangeListeners.remove(listener);
3829    }
3830
3831    /**
3832     * Add a listener for attach state changes.
3833     *
3834     * This listener will be called whenever this view is attached or detached
3835     * from a window. Remove the listener using
3836     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3837     *
3838     * @param listener Listener to attach
3839     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3840     */
3841    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3842        ListenerInfo li = getListenerInfo();
3843        if (li.mOnAttachStateChangeListeners == null) {
3844            li.mOnAttachStateChangeListeners
3845                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3846        }
3847        li.mOnAttachStateChangeListeners.add(listener);
3848    }
3849
3850    /**
3851     * Remove a listener for attach state changes. The listener will receive no further
3852     * notification of window attach/detach events.
3853     *
3854     * @param listener Listener to remove
3855     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3856     */
3857    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3858        ListenerInfo li = mListenerInfo;
3859        if (li == null || li.mOnAttachStateChangeListeners == null) {
3860            return;
3861        }
3862        li.mOnAttachStateChangeListeners.remove(listener);
3863    }
3864
3865    /**
3866     * Returns the focus-change callback registered for this view.
3867     *
3868     * @return The callback, or null if one is not registered.
3869     */
3870    public OnFocusChangeListener getOnFocusChangeListener() {
3871        ListenerInfo li = mListenerInfo;
3872        return li != null ? li.mOnFocusChangeListener : null;
3873    }
3874
3875    /**
3876     * Register a callback to be invoked when this view is clicked. If this view is not
3877     * clickable, it becomes clickable.
3878     *
3879     * @param l The callback that will run
3880     *
3881     * @see #setClickable(boolean)
3882     */
3883    public void setOnClickListener(OnClickListener l) {
3884        if (!isClickable()) {
3885            setClickable(true);
3886        }
3887        getListenerInfo().mOnClickListener = l;
3888    }
3889
3890    /**
3891     * Return whether this view has an attached OnClickListener.  Returns
3892     * true if there is a listener, false if there is none.
3893     */
3894    public boolean hasOnClickListeners() {
3895        ListenerInfo li = mListenerInfo;
3896        return (li != null && li.mOnClickListener != null);
3897    }
3898
3899    /**
3900     * Register a callback to be invoked when this view is clicked and held. If this view is not
3901     * long clickable, it becomes long clickable.
3902     *
3903     * @param l The callback that will run
3904     *
3905     * @see #setLongClickable(boolean)
3906     */
3907    public void setOnLongClickListener(OnLongClickListener l) {
3908        if (!isLongClickable()) {
3909            setLongClickable(true);
3910        }
3911        getListenerInfo().mOnLongClickListener = l;
3912    }
3913
3914    /**
3915     * Register a callback to be invoked when the context menu for this view is
3916     * being built. If this view is not long clickable, it becomes long clickable.
3917     *
3918     * @param l The callback that will run
3919     *
3920     */
3921    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3922        if (!isLongClickable()) {
3923            setLongClickable(true);
3924        }
3925        getListenerInfo().mOnCreateContextMenuListener = l;
3926    }
3927
3928    /**
3929     * Call this view's OnClickListener, if it is defined.  Performs all normal
3930     * actions associated with clicking: reporting accessibility event, playing
3931     * a sound, etc.
3932     *
3933     * @return True there was an assigned OnClickListener that was called, false
3934     *         otherwise is returned.
3935     */
3936    public boolean performClick() {
3937        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3938
3939        ListenerInfo li = mListenerInfo;
3940        if (li != null && li.mOnClickListener != null) {
3941            playSoundEffect(SoundEffectConstants.CLICK);
3942            li.mOnClickListener.onClick(this);
3943            return true;
3944        }
3945
3946        return false;
3947    }
3948
3949    /**
3950     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3951     * this only calls the listener, and does not do any associated clicking
3952     * actions like reporting an accessibility event.
3953     *
3954     * @return True there was an assigned OnClickListener that was called, false
3955     *         otherwise is returned.
3956     */
3957    public boolean callOnClick() {
3958        ListenerInfo li = mListenerInfo;
3959        if (li != null && li.mOnClickListener != null) {
3960            li.mOnClickListener.onClick(this);
3961            return true;
3962        }
3963        return false;
3964    }
3965
3966    /**
3967     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3968     * OnLongClickListener did not consume the event.
3969     *
3970     * @return True if one of the above receivers consumed the event, false otherwise.
3971     */
3972    public boolean performLongClick() {
3973        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3974
3975        boolean handled = false;
3976        ListenerInfo li = mListenerInfo;
3977        if (li != null && li.mOnLongClickListener != null) {
3978            handled = li.mOnLongClickListener.onLongClick(View.this);
3979        }
3980        if (!handled) {
3981            handled = showContextMenu();
3982        }
3983        if (handled) {
3984            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3985        }
3986        return handled;
3987    }
3988
3989    /**
3990     * Performs button-related actions during a touch down event.
3991     *
3992     * @param event The event.
3993     * @return True if the down was consumed.
3994     *
3995     * @hide
3996     */
3997    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3998        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3999            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4000                return true;
4001            }
4002        }
4003        return false;
4004    }
4005
4006    /**
4007     * Bring up the context menu for this view.
4008     *
4009     * @return Whether a context menu was displayed.
4010     */
4011    public boolean showContextMenu() {
4012        return getParent().showContextMenuForChild(this);
4013    }
4014
4015    /**
4016     * Bring up the context menu for this view, referring to the item under the specified point.
4017     *
4018     * @param x The referenced x coordinate.
4019     * @param y The referenced y coordinate.
4020     * @param metaState The keyboard modifiers that were pressed.
4021     * @return Whether a context menu was displayed.
4022     *
4023     * @hide
4024     */
4025    public boolean showContextMenu(float x, float y, int metaState) {
4026        return showContextMenu();
4027    }
4028
4029    /**
4030     * Start an action mode.
4031     *
4032     * @param callback Callback that will control the lifecycle of the action mode
4033     * @return The new action mode if it is started, null otherwise
4034     *
4035     * @see ActionMode
4036     */
4037    public ActionMode startActionMode(ActionMode.Callback callback) {
4038        ViewParent parent = getParent();
4039        if (parent == null) return null;
4040        return parent.startActionModeForChild(this, callback);
4041    }
4042
4043    /**
4044     * Register a callback to be invoked when a key is pressed in this view.
4045     * @param l the key listener to attach to this view
4046     */
4047    public void setOnKeyListener(OnKeyListener l) {
4048        getListenerInfo().mOnKeyListener = l;
4049    }
4050
4051    /**
4052     * Register a callback to be invoked when a touch event is sent to this view.
4053     * @param l the touch listener to attach to this view
4054     */
4055    public void setOnTouchListener(OnTouchListener l) {
4056        getListenerInfo().mOnTouchListener = l;
4057    }
4058
4059    /**
4060     * Register a callback to be invoked when a generic motion event is sent to this view.
4061     * @param l the generic motion listener to attach to this view
4062     */
4063    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4064        getListenerInfo().mOnGenericMotionListener = l;
4065    }
4066
4067    /**
4068     * Register a callback to be invoked when a hover event is sent to this view.
4069     * @param l the hover listener to attach to this view
4070     */
4071    public void setOnHoverListener(OnHoverListener l) {
4072        getListenerInfo().mOnHoverListener = l;
4073    }
4074
4075    /**
4076     * Register a drag event listener callback object for this View. The parameter is
4077     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4078     * View, the system calls the
4079     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4080     * @param l An implementation of {@link android.view.View.OnDragListener}.
4081     */
4082    public void setOnDragListener(OnDragListener l) {
4083        getListenerInfo().mOnDragListener = l;
4084    }
4085
4086    /**
4087     * Give this view focus. This will cause
4088     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4089     *
4090     * Note: this does not check whether this {@link View} should get focus, it just
4091     * gives it focus no matter what.  It should only be called internally by framework
4092     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4093     *
4094     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4095     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4096     *        focus moved when requestFocus() is called. It may not always
4097     *        apply, in which case use the default View.FOCUS_DOWN.
4098     * @param previouslyFocusedRect The rectangle of the view that had focus
4099     *        prior in this View's coordinate system.
4100     */
4101    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4102        if (DBG) {
4103            System.out.println(this + " requestFocus()");
4104        }
4105
4106        if ((mPrivateFlags & FOCUSED) == 0) {
4107            mPrivateFlags |= FOCUSED;
4108
4109            if (mParent != null) {
4110                mParent.requestChildFocus(this, this);
4111            }
4112
4113            onFocusChanged(true, direction, previouslyFocusedRect);
4114            refreshDrawableState();
4115
4116            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4117                notifyAccessibilityStateChanged();
4118            }
4119        }
4120    }
4121
4122    /**
4123     * Request that a rectangle of this view be visible on the screen,
4124     * scrolling if necessary just enough.
4125     *
4126     * <p>A View should call this if it maintains some notion of which part
4127     * of its content is interesting.  For example, a text editing view
4128     * should call this when its cursor moves.
4129     *
4130     * @param rectangle The rectangle.
4131     * @return Whether any parent scrolled.
4132     */
4133    public boolean requestRectangleOnScreen(Rect rectangle) {
4134        return requestRectangleOnScreen(rectangle, false);
4135    }
4136
4137    /**
4138     * Request that a rectangle of this view be visible on the screen,
4139     * scrolling if necessary just enough.
4140     *
4141     * <p>A View should call this if it maintains some notion of which part
4142     * of its content is interesting.  For example, a text editing view
4143     * should call this when its cursor moves.
4144     *
4145     * <p>When <code>immediate</code> is set to true, scrolling will not be
4146     * animated.
4147     *
4148     * @param rectangle The rectangle.
4149     * @param immediate True to forbid animated scrolling, false otherwise
4150     * @return Whether any parent scrolled.
4151     */
4152    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4153        View child = this;
4154        ViewParent parent = mParent;
4155        boolean scrolled = false;
4156        while (parent != null) {
4157            scrolled |= parent.requestChildRectangleOnScreen(child,
4158                    rectangle, immediate);
4159
4160            // offset rect so next call has the rectangle in the
4161            // coordinate system of its direct child.
4162            rectangle.offset(child.getLeft(), child.getTop());
4163            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4164
4165            if (!(parent instanceof View)) {
4166                break;
4167            }
4168
4169            child = (View) parent;
4170            parent = child.getParent();
4171        }
4172        return scrolled;
4173    }
4174
4175    /**
4176     * Called when this view wants to give up focus. If focus is cleared
4177     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4178     * <p>
4179     * <strong>Note:</strong> When a View clears focus the framework is trying
4180     * to give focus to the first focusable View from the top. Hence, if this
4181     * View is the first from the top that can take focus, then all callbacks
4182     * related to clearing focus will be invoked after wich the framework will
4183     * give focus to this view.
4184     * </p>
4185     */
4186    public void clearFocus() {
4187        if (DBG) {
4188            System.out.println(this + " clearFocus()");
4189        }
4190
4191        if ((mPrivateFlags & FOCUSED) != 0) {
4192            mPrivateFlags &= ~FOCUSED;
4193
4194            if (mParent != null) {
4195                mParent.clearChildFocus(this);
4196            }
4197
4198            onFocusChanged(false, 0, null);
4199
4200            refreshDrawableState();
4201
4202            ensureInputFocusOnFirstFocusable();
4203
4204            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4205                notifyAccessibilityStateChanged();
4206            }
4207        }
4208    }
4209
4210    void ensureInputFocusOnFirstFocusable() {
4211        View root = getRootView();
4212        if (root != null) {
4213            root.requestFocus();
4214        }
4215    }
4216
4217    /**
4218     * Called internally by the view system when a new view is getting focus.
4219     * This is what clears the old focus.
4220     */
4221    void unFocus() {
4222        if (DBG) {
4223            System.out.println(this + " unFocus()");
4224        }
4225
4226        if ((mPrivateFlags & FOCUSED) != 0) {
4227            mPrivateFlags &= ~FOCUSED;
4228
4229            onFocusChanged(false, 0, null);
4230            refreshDrawableState();
4231
4232            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4233                notifyAccessibilityStateChanged();
4234            }
4235        }
4236    }
4237
4238    /**
4239     * Returns true if this view has focus iteself, or is the ancestor of the
4240     * view that has focus.
4241     *
4242     * @return True if this view has or contains focus, false otherwise.
4243     */
4244    @ViewDebug.ExportedProperty(category = "focus")
4245    public boolean hasFocus() {
4246        return (mPrivateFlags & FOCUSED) != 0;
4247    }
4248
4249    /**
4250     * Returns true if this view is focusable or if it contains a reachable View
4251     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4252     * is a View whose parents do not block descendants focus.
4253     *
4254     * Only {@link #VISIBLE} views are considered focusable.
4255     *
4256     * @return True if the view is focusable or if the view contains a focusable
4257     *         View, false otherwise.
4258     *
4259     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4260     */
4261    public boolean hasFocusable() {
4262        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4263    }
4264
4265    /**
4266     * Called by the view system when the focus state of this view changes.
4267     * When the focus change event is caused by directional navigation, direction
4268     * and previouslyFocusedRect provide insight into where the focus is coming from.
4269     * When overriding, be sure to call up through to the super class so that
4270     * the standard focus handling will occur.
4271     *
4272     * @param gainFocus True if the View has focus; false otherwise.
4273     * @param direction The direction focus has moved when requestFocus()
4274     *                  is called to give this view focus. Values are
4275     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4276     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4277     *                  It may not always apply, in which case use the default.
4278     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4279     *        system, of the previously focused view.  If applicable, this will be
4280     *        passed in as finer grained information about where the focus is coming
4281     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4282     */
4283    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4284        if (gainFocus) {
4285            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4286                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4287                requestAccessibilityFocus();
4288            }
4289        }
4290
4291        InputMethodManager imm = InputMethodManager.peekInstance();
4292        if (!gainFocus) {
4293            if (isPressed()) {
4294                setPressed(false);
4295            }
4296            if (imm != null && mAttachInfo != null
4297                    && mAttachInfo.mHasWindowFocus) {
4298                imm.focusOut(this);
4299            }
4300            onFocusLost();
4301        } else if (imm != null && mAttachInfo != null
4302                && mAttachInfo.mHasWindowFocus) {
4303            imm.focusIn(this);
4304        }
4305
4306        invalidate(true);
4307        ListenerInfo li = mListenerInfo;
4308        if (li != null && li.mOnFocusChangeListener != null) {
4309            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4310        }
4311
4312        if (mAttachInfo != null) {
4313            mAttachInfo.mKeyDispatchState.reset(this);
4314        }
4315    }
4316
4317    /**
4318     * Sends an accessibility event of the given type. If accessiiblity is
4319     * not enabled this method has no effect. The default implementation calls
4320     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4321     * to populate information about the event source (this View), then calls
4322     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4323     * populate the text content of the event source including its descendants,
4324     * and last calls
4325     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4326     * on its parent to resuest sending of the event to interested parties.
4327     * <p>
4328     * If an {@link AccessibilityDelegate} has been specified via calling
4329     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4330     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4331     * responsible for handling this call.
4332     * </p>
4333     *
4334     * @param eventType The type of the event to send, as defined by several types from
4335     * {@link android.view.accessibility.AccessibilityEvent}, such as
4336     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4337     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4338     *
4339     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4340     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4341     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4342     * @see AccessibilityDelegate
4343     */
4344    public void sendAccessibilityEvent(int eventType) {
4345        if (mAccessibilityDelegate != null) {
4346            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4347        } else {
4348            sendAccessibilityEventInternal(eventType);
4349        }
4350    }
4351
4352    /**
4353     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4354     * {@link AccessibilityEvent} to make an announcement which is related to some
4355     * sort of a context change for which none of the events representing UI transitions
4356     * is a good fit. For example, announcing a new page in a book. If accessibility
4357     * is not enabled this method does nothing.
4358     *
4359     * @param text The announcement text.
4360     */
4361    public void announceForAccessibility(CharSequence text) {
4362        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4363            AccessibilityEvent event = AccessibilityEvent.obtain(
4364                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4365            event.getText().add(text);
4366            sendAccessibilityEventUnchecked(event);
4367        }
4368    }
4369
4370    /**
4371     * @see #sendAccessibilityEvent(int)
4372     *
4373     * Note: Called from the default {@link AccessibilityDelegate}.
4374     */
4375    void sendAccessibilityEventInternal(int eventType) {
4376        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4377            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4378        }
4379    }
4380
4381    /**
4382     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4383     * takes as an argument an empty {@link AccessibilityEvent} and does not
4384     * perform a check whether accessibility is enabled.
4385     * <p>
4386     * If an {@link AccessibilityDelegate} has been specified via calling
4387     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4388     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4389     * is responsible for handling this call.
4390     * </p>
4391     *
4392     * @param event The event to send.
4393     *
4394     * @see #sendAccessibilityEvent(int)
4395     */
4396    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4397        if (mAccessibilityDelegate != null) {
4398            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4399        } else {
4400            sendAccessibilityEventUncheckedInternal(event);
4401        }
4402    }
4403
4404    /**
4405     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4406     *
4407     * Note: Called from the default {@link AccessibilityDelegate}.
4408     */
4409    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4410        if (!isShown()) {
4411            return;
4412        }
4413        onInitializeAccessibilityEvent(event);
4414        // Only a subset of accessibility events populates text content.
4415        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4416            dispatchPopulateAccessibilityEvent(event);
4417        }
4418        // Intercept accessibility focus events fired by virtual nodes to keep
4419        // track of accessibility focus position in such nodes.
4420        final int eventType = event.getEventType();
4421        switch (eventType) {
4422            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4423                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4424                        event.getSourceNodeId());
4425                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4426                    ViewRootImpl viewRootImpl = getViewRootImpl();
4427                    if (viewRootImpl != null) {
4428                        viewRootImpl.setAccessibilityFocusedHost(this);
4429                    }
4430                }
4431            } break;
4432            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4433                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4434                        event.getSourceNodeId());
4435                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4436                    ViewRootImpl viewRootImpl = getViewRootImpl();
4437                    if (viewRootImpl != null) {
4438                        viewRootImpl.setAccessibilityFocusedHost(null);
4439                    }
4440                }
4441            } break;
4442        }
4443        // In the beginning we called #isShown(), so we know that getParent() is not null.
4444        getParent().requestSendAccessibilityEvent(this, event);
4445    }
4446
4447    /**
4448     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4449     * to its children for adding their text content to the event. Note that the
4450     * event text is populated in a separate dispatch path since we add to the
4451     * event not only the text of the source but also the text of all its descendants.
4452     * A typical implementation will call
4453     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4454     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4455     * on each child. Override this method if custom population of the event text
4456     * content is required.
4457     * <p>
4458     * If an {@link AccessibilityDelegate} has been specified via calling
4459     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4460     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4461     * is responsible for handling this call.
4462     * </p>
4463     * <p>
4464     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4465     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4466     * </p>
4467     *
4468     * @param event The event.
4469     *
4470     * @return True if the event population was completed.
4471     */
4472    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4473        if (mAccessibilityDelegate != null) {
4474            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4475        } else {
4476            return dispatchPopulateAccessibilityEventInternal(event);
4477        }
4478    }
4479
4480    /**
4481     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4482     *
4483     * Note: Called from the default {@link AccessibilityDelegate}.
4484     */
4485    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4486        onPopulateAccessibilityEvent(event);
4487        return false;
4488    }
4489
4490    /**
4491     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4492     * giving a chance to this View to populate the accessibility event with its
4493     * text content. While this method is free to modify event
4494     * attributes other than text content, doing so should normally be performed in
4495     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4496     * <p>
4497     * Example: Adding formatted date string to an accessibility event in addition
4498     *          to the text added by the super implementation:
4499     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4500     *     super.onPopulateAccessibilityEvent(event);
4501     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4502     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4503     *         mCurrentDate.getTimeInMillis(), flags);
4504     *     event.getText().add(selectedDateUtterance);
4505     * }</pre>
4506     * <p>
4507     * If an {@link AccessibilityDelegate} has been specified via calling
4508     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4509     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4510     * is responsible for handling this call.
4511     * </p>
4512     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4513     * information to the event, in case the default implementation has basic information to add.
4514     * </p>
4515     *
4516     * @param event The accessibility event which to populate.
4517     *
4518     * @see #sendAccessibilityEvent(int)
4519     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4520     */
4521    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4522        if (mAccessibilityDelegate != null) {
4523            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4524        } else {
4525            onPopulateAccessibilityEventInternal(event);
4526        }
4527    }
4528
4529    /**
4530     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4531     *
4532     * Note: Called from the default {@link AccessibilityDelegate}.
4533     */
4534    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4535
4536    }
4537
4538    /**
4539     * Initializes an {@link AccessibilityEvent} with information about
4540     * this View which is the event source. In other words, the source of
4541     * an accessibility event is the view whose state change triggered firing
4542     * the event.
4543     * <p>
4544     * Example: Setting the password property of an event in addition
4545     *          to properties set by the super implementation:
4546     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4547     *     super.onInitializeAccessibilityEvent(event);
4548     *     event.setPassword(true);
4549     * }</pre>
4550     * <p>
4551     * If an {@link AccessibilityDelegate} has been specified via calling
4552     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4553     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4554     * is responsible for handling this call.
4555     * </p>
4556     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4557     * information to the event, in case the default implementation has basic information to add.
4558     * </p>
4559     * @param event The event to initialize.
4560     *
4561     * @see #sendAccessibilityEvent(int)
4562     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4563     */
4564    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4565        if (mAccessibilityDelegate != null) {
4566            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4567        } else {
4568            onInitializeAccessibilityEventInternal(event);
4569        }
4570    }
4571
4572    /**
4573     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4574     *
4575     * Note: Called from the default {@link AccessibilityDelegate}.
4576     */
4577    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4578        event.setSource(this);
4579        event.setClassName(View.class.getName());
4580        event.setPackageName(getContext().getPackageName());
4581        event.setEnabled(isEnabled());
4582        event.setContentDescription(mContentDescription);
4583
4584        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4585            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4586            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4587                    FOCUSABLES_ALL);
4588            event.setItemCount(focusablesTempList.size());
4589            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4590            focusablesTempList.clear();
4591        }
4592    }
4593
4594    /**
4595     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4596     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4597     * This method is responsible for obtaining an accessibility node info from a
4598     * pool of reusable instances and calling
4599     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4600     * initialize the former.
4601     * <p>
4602     * Note: The client is responsible for recycling the obtained instance by calling
4603     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4604     * </p>
4605     *
4606     * @return A populated {@link AccessibilityNodeInfo}.
4607     *
4608     * @see AccessibilityNodeInfo
4609     */
4610    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4611        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4612        if (provider != null) {
4613            return provider.createAccessibilityNodeInfo(View.NO_ID);
4614        } else {
4615            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4616            onInitializeAccessibilityNodeInfo(info);
4617            return info;
4618        }
4619    }
4620
4621    /**
4622     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4623     * The base implementation sets:
4624     * <ul>
4625     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4626     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4627     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4628     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4629     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4630     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4631     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4632     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4633     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4634     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4635     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4636     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4637     * </ul>
4638     * <p>
4639     * Subclasses should override this method, call the super implementation,
4640     * and set additional attributes.
4641     * </p>
4642     * <p>
4643     * If an {@link AccessibilityDelegate} has been specified via calling
4644     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4645     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4646     * is responsible for handling this call.
4647     * </p>
4648     *
4649     * @param info The instance to initialize.
4650     */
4651    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4652        if (mAccessibilityDelegate != null) {
4653            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4654        } else {
4655            onInitializeAccessibilityNodeInfoInternal(info);
4656        }
4657    }
4658
4659    /**
4660     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4661     *
4662     * Note: Called from the default {@link AccessibilityDelegate}.
4663     */
4664    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4665        Rect bounds = mAttachInfo.mTmpInvalRect;
4666        getDrawingRect(bounds);
4667        info.setBoundsInParent(bounds);
4668
4669        getGlobalVisibleRect(bounds);
4670        bounds.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4671        info.setBoundsInScreen(bounds);
4672
4673        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4674            ViewParent parent = getParentForAccessibility();
4675            if (parent instanceof View) {
4676                info.setParent((View) parent);
4677            }
4678        }
4679
4680        info.setPackageName(mContext.getPackageName());
4681        info.setClassName(View.class.getName());
4682        info.setContentDescription(getContentDescription());
4683
4684        info.setEnabled(isEnabled());
4685        info.setClickable(isClickable());
4686        info.setFocusable(isFocusable());
4687        info.setFocused(isFocused());
4688        info.setAccessibilityFocused(isAccessibilityFocused());
4689        info.setSelected(isSelected());
4690        info.setLongClickable(isLongClickable());
4691
4692        // TODO: These make sense only if we are in an AdapterView but all
4693        // views can be selected. Maybe from accessiiblity perspective
4694        // we should report as selectable view in an AdapterView.
4695        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4696        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4697
4698        if (isFocusable()) {
4699            if (isFocused()) {
4700                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4701            } else {
4702                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4703            }
4704        }
4705
4706        info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4707        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4708
4709        if (isClickable()) {
4710            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4711        }
4712
4713        if (isLongClickable()) {
4714            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4715        }
4716
4717        if (getContentDescription() != null) {
4718            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_GRANULARITY);
4719            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_GRANULARITY);
4720            info.setGranularities(AccessibilityNodeInfo.GRANULARITY_CHARACTER
4721                    | AccessibilityNodeInfo.GRANULARITY_WORD);
4722        }
4723    }
4724
4725    /**
4726     * Computes whether this view is visible on the screen.
4727     *
4728     * @return Whether the view is visible on the screen.
4729     */
4730    boolean isDisplayedOnScreen() {
4731        // The first two checks are made also made by isShown() which
4732        // however traverses the tree up to the parent to catch that.
4733        // Therefore, we do some fail fast check to minimize the up
4734        // tree traversal.
4735        return (mAttachInfo != null
4736                && mAttachInfo.mWindowVisibility == View.VISIBLE
4737                && getAlpha() > 0
4738                && isShown()
4739                && getGlobalVisibleRect(mAttachInfo.mTmpInvalRect));
4740    }
4741
4742    /**
4743     * Sets a delegate for implementing accessibility support via compositon as
4744     * opposed to inheritance. The delegate's primary use is for implementing
4745     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4746     *
4747     * @param delegate The delegate instance.
4748     *
4749     * @see AccessibilityDelegate
4750     */
4751    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4752        mAccessibilityDelegate = delegate;
4753    }
4754
4755    /**
4756     * Gets the provider for managing a virtual view hierarchy rooted at this View
4757     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4758     * that explore the window content.
4759     * <p>
4760     * If this method returns an instance, this instance is responsible for managing
4761     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4762     * View including the one representing the View itself. Similarly the returned
4763     * instance is responsible for performing accessibility actions on any virtual
4764     * view or the root view itself.
4765     * </p>
4766     * <p>
4767     * If an {@link AccessibilityDelegate} has been specified via calling
4768     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4769     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4770     * is responsible for handling this call.
4771     * </p>
4772     *
4773     * @return The provider.
4774     *
4775     * @see AccessibilityNodeProvider
4776     */
4777    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4778        if (mAccessibilityDelegate != null) {
4779            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4780        } else {
4781            return null;
4782        }
4783    }
4784
4785    /**
4786     * Gets the unique identifier of this view on the screen for accessibility purposes.
4787     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4788     *
4789     * @return The view accessibility id.
4790     *
4791     * @hide
4792     */
4793    public int getAccessibilityViewId() {
4794        if (mAccessibilityViewId == NO_ID) {
4795            mAccessibilityViewId = sNextAccessibilityViewId++;
4796        }
4797        return mAccessibilityViewId;
4798    }
4799
4800    /**
4801     * Gets the unique identifier of the window in which this View reseides.
4802     *
4803     * @return The window accessibility id.
4804     *
4805     * @hide
4806     */
4807    public int getAccessibilityWindowId() {
4808        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4809    }
4810
4811    /**
4812     * Gets the {@link View} description. It briefly describes the view and is
4813     * primarily used for accessibility support. Set this property to enable
4814     * better accessibility support for your application. This is especially
4815     * true for views that do not have textual representation (For example,
4816     * ImageButton).
4817     *
4818     * @return The content description.
4819     *
4820     * @attr ref android.R.styleable#View_contentDescription
4821     */
4822    @ViewDebug.ExportedProperty(category = "accessibility")
4823    public CharSequence getContentDescription() {
4824        return mContentDescription;
4825    }
4826
4827    /**
4828     * Sets the {@link View} description. It briefly describes the view and is
4829     * primarily used for accessibility support. Set this property to enable
4830     * better accessibility support for your application. This is especially
4831     * true for views that do not have textual representation (For example,
4832     * ImageButton).
4833     *
4834     * @param contentDescription The content description.
4835     *
4836     * @attr ref android.R.styleable#View_contentDescription
4837     */
4838    @RemotableViewMethod
4839    public void setContentDescription(CharSequence contentDescription) {
4840        mContentDescription = contentDescription;
4841    }
4842
4843    /**
4844     * Invoked whenever this view loses focus, either by losing window focus or by losing
4845     * focus within its window. This method can be used to clear any state tied to the
4846     * focus. For instance, if a button is held pressed with the trackball and the window
4847     * loses focus, this method can be used to cancel the press.
4848     *
4849     * Subclasses of View overriding this method should always call super.onFocusLost().
4850     *
4851     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4852     * @see #onWindowFocusChanged(boolean)
4853     *
4854     * @hide pending API council approval
4855     */
4856    protected void onFocusLost() {
4857        resetPressedState();
4858    }
4859
4860    private void resetPressedState() {
4861        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4862            return;
4863        }
4864
4865        if (isPressed()) {
4866            setPressed(false);
4867
4868            if (!mHasPerformedLongPress) {
4869                removeLongPressCallback();
4870            }
4871        }
4872    }
4873
4874    /**
4875     * Returns true if this view has focus
4876     *
4877     * @return True if this view has focus, false otherwise.
4878     */
4879    @ViewDebug.ExportedProperty(category = "focus")
4880    public boolean isFocused() {
4881        return (mPrivateFlags & FOCUSED) != 0;
4882    }
4883
4884    /**
4885     * Find the view in the hierarchy rooted at this view that currently has
4886     * focus.
4887     *
4888     * @return The view that currently has focus, or null if no focused view can
4889     *         be found.
4890     */
4891    public View findFocus() {
4892        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4893    }
4894
4895    /**
4896     * Indicates whether this view is one of the set of scrollable containers in
4897     * its window.
4898     *
4899     * @return whether this view is one of the set of scrollable containers in
4900     * its window
4901     *
4902     * @attr ref android.R.styleable#View_isScrollContainer
4903     */
4904    public boolean isScrollContainer() {
4905        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4906    }
4907
4908    /**
4909     * Change whether this view is one of the set of scrollable containers in
4910     * its window.  This will be used to determine whether the window can
4911     * resize or must pan when a soft input area is open -- scrollable
4912     * containers allow the window to use resize mode since the container
4913     * will appropriately shrink.
4914     *
4915     * @attr ref android.R.styleable#View_isScrollContainer
4916     */
4917    public void setScrollContainer(boolean isScrollContainer) {
4918        if (isScrollContainer) {
4919            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4920                mAttachInfo.mScrollContainers.add(this);
4921                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4922            }
4923            mPrivateFlags |= SCROLL_CONTAINER;
4924        } else {
4925            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4926                mAttachInfo.mScrollContainers.remove(this);
4927            }
4928            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4929        }
4930    }
4931
4932    /**
4933     * Returns the quality of the drawing cache.
4934     *
4935     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4936     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4937     *
4938     * @see #setDrawingCacheQuality(int)
4939     * @see #setDrawingCacheEnabled(boolean)
4940     * @see #isDrawingCacheEnabled()
4941     *
4942     * @attr ref android.R.styleable#View_drawingCacheQuality
4943     */
4944    public int getDrawingCacheQuality() {
4945        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4946    }
4947
4948    /**
4949     * Set the drawing cache quality of this view. This value is used only when the
4950     * drawing cache is enabled
4951     *
4952     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4953     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4954     *
4955     * @see #getDrawingCacheQuality()
4956     * @see #setDrawingCacheEnabled(boolean)
4957     * @see #isDrawingCacheEnabled()
4958     *
4959     * @attr ref android.R.styleable#View_drawingCacheQuality
4960     */
4961    public void setDrawingCacheQuality(int quality) {
4962        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4963    }
4964
4965    /**
4966     * Returns whether the screen should remain on, corresponding to the current
4967     * value of {@link #KEEP_SCREEN_ON}.
4968     *
4969     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4970     *
4971     * @see #setKeepScreenOn(boolean)
4972     *
4973     * @attr ref android.R.styleable#View_keepScreenOn
4974     */
4975    public boolean getKeepScreenOn() {
4976        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4977    }
4978
4979    /**
4980     * Controls whether the screen should remain on, modifying the
4981     * value of {@link #KEEP_SCREEN_ON}.
4982     *
4983     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4984     *
4985     * @see #getKeepScreenOn()
4986     *
4987     * @attr ref android.R.styleable#View_keepScreenOn
4988     */
4989    public void setKeepScreenOn(boolean keepScreenOn) {
4990        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4991    }
4992
4993    /**
4994     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4995     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4996     *
4997     * @attr ref android.R.styleable#View_nextFocusLeft
4998     */
4999    public int getNextFocusLeftId() {
5000        return mNextFocusLeftId;
5001    }
5002
5003    /**
5004     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5005     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5006     * decide automatically.
5007     *
5008     * @attr ref android.R.styleable#View_nextFocusLeft
5009     */
5010    public void setNextFocusLeftId(int nextFocusLeftId) {
5011        mNextFocusLeftId = nextFocusLeftId;
5012    }
5013
5014    /**
5015     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5016     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5017     *
5018     * @attr ref android.R.styleable#View_nextFocusRight
5019     */
5020    public int getNextFocusRightId() {
5021        return mNextFocusRightId;
5022    }
5023
5024    /**
5025     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5026     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5027     * decide automatically.
5028     *
5029     * @attr ref android.R.styleable#View_nextFocusRight
5030     */
5031    public void setNextFocusRightId(int nextFocusRightId) {
5032        mNextFocusRightId = nextFocusRightId;
5033    }
5034
5035    /**
5036     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5037     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5038     *
5039     * @attr ref android.R.styleable#View_nextFocusUp
5040     */
5041    public int getNextFocusUpId() {
5042        return mNextFocusUpId;
5043    }
5044
5045    /**
5046     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5047     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5048     * decide automatically.
5049     *
5050     * @attr ref android.R.styleable#View_nextFocusUp
5051     */
5052    public void setNextFocusUpId(int nextFocusUpId) {
5053        mNextFocusUpId = nextFocusUpId;
5054    }
5055
5056    /**
5057     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5058     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5059     *
5060     * @attr ref android.R.styleable#View_nextFocusDown
5061     */
5062    public int getNextFocusDownId() {
5063        return mNextFocusDownId;
5064    }
5065
5066    /**
5067     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5068     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5069     * decide automatically.
5070     *
5071     * @attr ref android.R.styleable#View_nextFocusDown
5072     */
5073    public void setNextFocusDownId(int nextFocusDownId) {
5074        mNextFocusDownId = nextFocusDownId;
5075    }
5076
5077    /**
5078     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5079     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5080     *
5081     * @attr ref android.R.styleable#View_nextFocusForward
5082     */
5083    public int getNextFocusForwardId() {
5084        return mNextFocusForwardId;
5085    }
5086
5087    /**
5088     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5089     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5090     * decide automatically.
5091     *
5092     * @attr ref android.R.styleable#View_nextFocusForward
5093     */
5094    public void setNextFocusForwardId(int nextFocusForwardId) {
5095        mNextFocusForwardId = nextFocusForwardId;
5096    }
5097
5098    /**
5099     * Returns the visibility of this view and all of its ancestors
5100     *
5101     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5102     */
5103    public boolean isShown() {
5104        View current = this;
5105        //noinspection ConstantConditions
5106        do {
5107            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5108                return false;
5109            }
5110            ViewParent parent = current.mParent;
5111            if (parent == null) {
5112                return false; // We are not attached to the view root
5113            }
5114            if (!(parent instanceof View)) {
5115                return true;
5116            }
5117            current = (View) parent;
5118        } while (current != null);
5119
5120        return false;
5121    }
5122
5123    /**
5124     * Called by the view hierarchy when the content insets for a window have
5125     * changed, to allow it to adjust its content to fit within those windows.
5126     * The content insets tell you the space that the status bar, input method,
5127     * and other system windows infringe on the application's window.
5128     *
5129     * <p>You do not normally need to deal with this function, since the default
5130     * window decoration given to applications takes care of applying it to the
5131     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5132     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5133     * and your content can be placed under those system elements.  You can then
5134     * use this method within your view hierarchy if you have parts of your UI
5135     * which you would like to ensure are not being covered.
5136     *
5137     * <p>The default implementation of this method simply applies the content
5138     * inset's to the view's padding.  This can be enabled through
5139     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5140     * the method and handle the insets however you would like.  Note that the
5141     * insets provided by the framework are always relative to the far edges
5142     * of the window, not accounting for the location of the called view within
5143     * that window.  (In fact when this method is called you do not yet know
5144     * where the layout will place the view, as it is done before layout happens.)
5145     *
5146     * <p>Note: unlike many View methods, there is no dispatch phase to this
5147     * call.  If you are overriding it in a ViewGroup and want to allow the
5148     * call to continue to your children, you must be sure to call the super
5149     * implementation.
5150     *
5151     * @param insets Current content insets of the window.  Prior to
5152     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5153     * the insets or else you and Android will be unhappy.
5154     *
5155     * @return Return true if this view applied the insets and it should not
5156     * continue propagating further down the hierarchy, false otherwise.
5157     */
5158    protected boolean fitSystemWindows(Rect insets) {
5159        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5160            mUserPaddingStart = -1;
5161            mUserPaddingEnd = -1;
5162            mUserPaddingRelative = false;
5163            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5164                    || mAttachInfo == null
5165                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5166                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5167                return true;
5168            } else {
5169                internalSetPadding(0, 0, 0, 0);
5170                return false;
5171            }
5172        }
5173        return false;
5174    }
5175
5176    /**
5177     * Set whether or not this view should account for system screen decorations
5178     * such as the status bar and inset its content. This allows this view to be
5179     * positioned in absolute screen coordinates and remain visible to the user.
5180     *
5181     * <p>This should only be used by top-level window decor views.
5182     *
5183     * @param fitSystemWindows true to inset content for system screen decorations, false for
5184     *                         default behavior.
5185     *
5186     * @attr ref android.R.styleable#View_fitsSystemWindows
5187     */
5188    public void setFitsSystemWindows(boolean fitSystemWindows) {
5189        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5190    }
5191
5192    /**
5193     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
5194     * will account for system screen decorations such as the status bar and inset its
5195     * content. This allows the view to be positioned in absolute screen coordinates
5196     * and remain visible to the user.
5197     *
5198     * @return true if this view will adjust its content bounds for system screen decorations.
5199     *
5200     * @attr ref android.R.styleable#View_fitsSystemWindows
5201     */
5202    public boolean fitsSystemWindows() {
5203        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5204    }
5205
5206    /**
5207     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5208     */
5209    public void requestFitSystemWindows() {
5210        if (mParent != null) {
5211            mParent.requestFitSystemWindows();
5212        }
5213    }
5214
5215    /**
5216     * For use by PhoneWindow to make its own system window fitting optional.
5217     * @hide
5218     */
5219    public void makeOptionalFitsSystemWindows() {
5220        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5221    }
5222
5223    /**
5224     * Returns the visibility status for this view.
5225     *
5226     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5227     * @attr ref android.R.styleable#View_visibility
5228     */
5229    @ViewDebug.ExportedProperty(mapping = {
5230        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5231        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5232        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5233    })
5234    public int getVisibility() {
5235        return mViewFlags & VISIBILITY_MASK;
5236    }
5237
5238    /**
5239     * Set the enabled state of this view.
5240     *
5241     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5242     * @attr ref android.R.styleable#View_visibility
5243     */
5244    @RemotableViewMethod
5245    public void setVisibility(int visibility) {
5246        setFlags(visibility, VISIBILITY_MASK);
5247        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5248    }
5249
5250    /**
5251     * Returns the enabled status for this view. The interpretation of the
5252     * enabled state varies by subclass.
5253     *
5254     * @return True if this view is enabled, false otherwise.
5255     */
5256    @ViewDebug.ExportedProperty
5257    public boolean isEnabled() {
5258        return (mViewFlags & ENABLED_MASK) == ENABLED;
5259    }
5260
5261    /**
5262     * Set the enabled state of this view. The interpretation of the enabled
5263     * state varies by subclass.
5264     *
5265     * @param enabled True if this view is enabled, false otherwise.
5266     */
5267    @RemotableViewMethod
5268    public void setEnabled(boolean enabled) {
5269        if (enabled == isEnabled()) return;
5270
5271        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5272
5273        /*
5274         * The View most likely has to change its appearance, so refresh
5275         * the drawable state.
5276         */
5277        refreshDrawableState();
5278
5279        // Invalidate too, since the default behavior for views is to be
5280        // be drawn at 50% alpha rather than to change the drawable.
5281        invalidate(true);
5282    }
5283
5284    /**
5285     * Set whether this view can receive the focus.
5286     *
5287     * Setting this to false will also ensure that this view is not focusable
5288     * in touch mode.
5289     *
5290     * @param focusable If true, this view can receive the focus.
5291     *
5292     * @see #setFocusableInTouchMode(boolean)
5293     * @attr ref android.R.styleable#View_focusable
5294     */
5295    public void setFocusable(boolean focusable) {
5296        if (!focusable) {
5297            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5298        }
5299        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5300    }
5301
5302    /**
5303     * Set whether this view can receive focus while in touch mode.
5304     *
5305     * Setting this to true will also ensure that this view is focusable.
5306     *
5307     * @param focusableInTouchMode If true, this view can receive the focus while
5308     *   in touch mode.
5309     *
5310     * @see #setFocusable(boolean)
5311     * @attr ref android.R.styleable#View_focusableInTouchMode
5312     */
5313    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5314        // Focusable in touch mode should always be set before the focusable flag
5315        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5316        // which, in touch mode, will not successfully request focus on this view
5317        // because the focusable in touch mode flag is not set
5318        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5319        if (focusableInTouchMode) {
5320            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5321        }
5322    }
5323
5324    /**
5325     * Set whether this view should have sound effects enabled for events such as
5326     * clicking and touching.
5327     *
5328     * <p>You may wish to disable sound effects for a view if you already play sounds,
5329     * for instance, a dial key that plays dtmf tones.
5330     *
5331     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5332     * @see #isSoundEffectsEnabled()
5333     * @see #playSoundEffect(int)
5334     * @attr ref android.R.styleable#View_soundEffectsEnabled
5335     */
5336    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5337        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5338    }
5339
5340    /**
5341     * @return whether this view should have sound effects enabled for events such as
5342     *     clicking and touching.
5343     *
5344     * @see #setSoundEffectsEnabled(boolean)
5345     * @see #playSoundEffect(int)
5346     * @attr ref android.R.styleable#View_soundEffectsEnabled
5347     */
5348    @ViewDebug.ExportedProperty
5349    public boolean isSoundEffectsEnabled() {
5350        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5351    }
5352
5353    /**
5354     * Set whether this view should have haptic feedback for events such as
5355     * long presses.
5356     *
5357     * <p>You may wish to disable haptic feedback if your view already controls
5358     * its own haptic feedback.
5359     *
5360     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5361     * @see #isHapticFeedbackEnabled()
5362     * @see #performHapticFeedback(int)
5363     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5364     */
5365    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5366        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5367    }
5368
5369    /**
5370     * @return whether this view should have haptic feedback enabled for events
5371     * long presses.
5372     *
5373     * @see #setHapticFeedbackEnabled(boolean)
5374     * @see #performHapticFeedback(int)
5375     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5376     */
5377    @ViewDebug.ExportedProperty
5378    public boolean isHapticFeedbackEnabled() {
5379        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5380    }
5381
5382    /**
5383     * Returns the layout direction for this view.
5384     *
5385     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5386     *   {@link #LAYOUT_DIRECTION_RTL},
5387     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5388     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5389     *
5390     * @attr ref android.R.styleable#View_layoutDirection
5391     * @hide
5392     */
5393    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5394        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5395        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5396        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5397        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5398    })
5399    public int getLayoutDirection() {
5400        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5401    }
5402
5403    /**
5404     * Set the layout direction for this view. This will propagate a reset of layout direction
5405     * resolution to the view's children and resolve layout direction for this view.
5406     *
5407     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5408     *   {@link #LAYOUT_DIRECTION_RTL},
5409     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5410     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5411     *
5412     * @attr ref android.R.styleable#View_layoutDirection
5413     * @hide
5414     */
5415    @RemotableViewMethod
5416    public void setLayoutDirection(int layoutDirection) {
5417        if (getLayoutDirection() != layoutDirection) {
5418            // Reset the current layout direction and the resolved one
5419            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5420            resetResolvedLayoutDirection();
5421            // Set the new layout direction (filtered) and ask for a layout pass
5422            mPrivateFlags2 |=
5423                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5424            requestLayout();
5425        }
5426    }
5427
5428    /**
5429     * Returns the resolved layout direction for this view.
5430     *
5431     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5432     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5433     * @hide
5434     */
5435    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5436        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5437        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5438    })
5439    public int getResolvedLayoutDirection() {
5440        // The layout diretion will be resolved only if needed
5441        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5442            resolveLayoutDirection();
5443        }
5444        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5445                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5446    }
5447
5448    /**
5449     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5450     * layout attribute and/or the inherited value from the parent
5451     *
5452     * @return true if the layout is right-to-left.
5453     * @hide
5454     */
5455    @ViewDebug.ExportedProperty(category = "layout")
5456    public boolean isLayoutRtl() {
5457        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5458    }
5459
5460    /**
5461     * Indicates whether the view is currently tracking transient state that the
5462     * app should not need to concern itself with saving and restoring, but that
5463     * the framework should take special note to preserve when possible.
5464     *
5465     * <p>A view with transient state cannot be trivially rebound from an external
5466     * data source, such as an adapter binding item views in a list. This may be
5467     * because the view is performing an animation, tracking user selection
5468     * of content, or similar.</p>
5469     *
5470     * @return true if the view has transient state
5471     */
5472    @ViewDebug.ExportedProperty(category = "layout")
5473    public boolean hasTransientState() {
5474        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5475    }
5476
5477    /**
5478     * Set whether this view is currently tracking transient state that the
5479     * framework should attempt to preserve when possible. This flag is reference counted,
5480     * so every call to setHasTransientState(true) should be paired with a later call
5481     * to setHasTransientState(false).
5482     *
5483     * <p>A view with transient state cannot be trivially rebound from an external
5484     * data source, such as an adapter binding item views in a list. This may be
5485     * because the view is performing an animation, tracking user selection
5486     * of content, or similar.</p>
5487     *
5488     * @param hasTransientState true if this view has transient state
5489     */
5490    public void setHasTransientState(boolean hasTransientState) {
5491        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5492                mTransientStateCount - 1;
5493        if (mTransientStateCount < 0) {
5494            mTransientStateCount = 0;
5495            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5496                    "unmatched pair of setHasTransientState calls");
5497        }
5498        if ((hasTransientState && mTransientStateCount == 1) ||
5499                (hasTransientState && mTransientStateCount == 0)) {
5500            // update flag if we've just incremented up from 0 or decremented down to 0
5501            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5502                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5503            if (mParent != null) {
5504                try {
5505                    mParent.childHasTransientStateChanged(this, hasTransientState);
5506                } catch (AbstractMethodError e) {
5507                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5508                            " does not fully implement ViewParent", e);
5509                }
5510            }
5511        }
5512    }
5513
5514    /**
5515     * If this view doesn't do any drawing on its own, set this flag to
5516     * allow further optimizations. By default, this flag is not set on
5517     * View, but could be set on some View subclasses such as ViewGroup.
5518     *
5519     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5520     * you should clear this flag.
5521     *
5522     * @param willNotDraw whether or not this View draw on its own
5523     */
5524    public void setWillNotDraw(boolean willNotDraw) {
5525        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5526    }
5527
5528    /**
5529     * Returns whether or not this View draws on its own.
5530     *
5531     * @return true if this view has nothing to draw, false otherwise
5532     */
5533    @ViewDebug.ExportedProperty(category = "drawing")
5534    public boolean willNotDraw() {
5535        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5536    }
5537
5538    /**
5539     * When a View's drawing cache is enabled, drawing is redirected to an
5540     * offscreen bitmap. Some views, like an ImageView, must be able to
5541     * bypass this mechanism if they already draw a single bitmap, to avoid
5542     * unnecessary usage of the memory.
5543     *
5544     * @param willNotCacheDrawing true if this view does not cache its
5545     *        drawing, false otherwise
5546     */
5547    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5548        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5549    }
5550
5551    /**
5552     * Returns whether or not this View can cache its drawing or not.
5553     *
5554     * @return true if this view does not cache its drawing, false otherwise
5555     */
5556    @ViewDebug.ExportedProperty(category = "drawing")
5557    public boolean willNotCacheDrawing() {
5558        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5559    }
5560
5561    /**
5562     * Indicates whether this view reacts to click events or not.
5563     *
5564     * @return true if the view is clickable, false otherwise
5565     *
5566     * @see #setClickable(boolean)
5567     * @attr ref android.R.styleable#View_clickable
5568     */
5569    @ViewDebug.ExportedProperty
5570    public boolean isClickable() {
5571        return (mViewFlags & CLICKABLE) == CLICKABLE;
5572    }
5573
5574    /**
5575     * Enables or disables click events for this view. When a view
5576     * is clickable it will change its state to "pressed" on every click.
5577     * Subclasses should set the view clickable to visually react to
5578     * user's clicks.
5579     *
5580     * @param clickable true to make the view clickable, false otherwise
5581     *
5582     * @see #isClickable()
5583     * @attr ref android.R.styleable#View_clickable
5584     */
5585    public void setClickable(boolean clickable) {
5586        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5587    }
5588
5589    /**
5590     * Indicates whether this view reacts to long click events or not.
5591     *
5592     * @return true if the view is long clickable, false otherwise
5593     *
5594     * @see #setLongClickable(boolean)
5595     * @attr ref android.R.styleable#View_longClickable
5596     */
5597    public boolean isLongClickable() {
5598        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5599    }
5600
5601    /**
5602     * Enables or disables long click events for this view. When a view is long
5603     * clickable it reacts to the user holding down the button for a longer
5604     * duration than a tap. This event can either launch the listener or a
5605     * context menu.
5606     *
5607     * @param longClickable true to make the view long clickable, false otherwise
5608     * @see #isLongClickable()
5609     * @attr ref android.R.styleable#View_longClickable
5610     */
5611    public void setLongClickable(boolean longClickable) {
5612        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5613    }
5614
5615    /**
5616     * Sets the pressed state for this view.
5617     *
5618     * @see #isClickable()
5619     * @see #setClickable(boolean)
5620     *
5621     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5622     *        the View's internal state from a previously set "pressed" state.
5623     */
5624    public void setPressed(boolean pressed) {
5625        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5626
5627        if (pressed) {
5628            mPrivateFlags |= PRESSED;
5629        } else {
5630            mPrivateFlags &= ~PRESSED;
5631        }
5632
5633        if (needsRefresh) {
5634            refreshDrawableState();
5635        }
5636        dispatchSetPressed(pressed);
5637    }
5638
5639    /**
5640     * Dispatch setPressed to all of this View's children.
5641     *
5642     * @see #setPressed(boolean)
5643     *
5644     * @param pressed The new pressed state
5645     */
5646    protected void dispatchSetPressed(boolean pressed) {
5647    }
5648
5649    /**
5650     * Indicates whether the view is currently in pressed state. Unless
5651     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5652     * the pressed state.
5653     *
5654     * @see #setPressed(boolean)
5655     * @see #isClickable()
5656     * @see #setClickable(boolean)
5657     *
5658     * @return true if the view is currently pressed, false otherwise
5659     */
5660    public boolean isPressed() {
5661        return (mPrivateFlags & PRESSED) == PRESSED;
5662    }
5663
5664    /**
5665     * Indicates whether this view will save its state (that is,
5666     * whether its {@link #onSaveInstanceState} method will be called).
5667     *
5668     * @return Returns true if the view state saving is enabled, else false.
5669     *
5670     * @see #setSaveEnabled(boolean)
5671     * @attr ref android.R.styleable#View_saveEnabled
5672     */
5673    public boolean isSaveEnabled() {
5674        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5675    }
5676
5677    /**
5678     * Controls whether the saving of this view's state is
5679     * enabled (that is, whether its {@link #onSaveInstanceState} method
5680     * will be called).  Note that even if freezing is enabled, the
5681     * view still must have an id assigned to it (via {@link #setId(int)})
5682     * for its state to be saved.  This flag can only disable the
5683     * saving of this view; any child views may still have their state saved.
5684     *
5685     * @param enabled Set to false to <em>disable</em> state saving, or true
5686     * (the default) to allow it.
5687     *
5688     * @see #isSaveEnabled()
5689     * @see #setId(int)
5690     * @see #onSaveInstanceState()
5691     * @attr ref android.R.styleable#View_saveEnabled
5692     */
5693    public void setSaveEnabled(boolean enabled) {
5694        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5695    }
5696
5697    /**
5698     * Gets whether the framework should discard touches when the view's
5699     * window is obscured by another visible window.
5700     * Refer to the {@link View} security documentation for more details.
5701     *
5702     * @return True if touch filtering is enabled.
5703     *
5704     * @see #setFilterTouchesWhenObscured(boolean)
5705     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5706     */
5707    @ViewDebug.ExportedProperty
5708    public boolean getFilterTouchesWhenObscured() {
5709        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5710    }
5711
5712    /**
5713     * Sets whether the framework should discard touches when the view's
5714     * window is obscured by another visible window.
5715     * Refer to the {@link View} security documentation for more details.
5716     *
5717     * @param enabled True if touch filtering should be enabled.
5718     *
5719     * @see #getFilterTouchesWhenObscured
5720     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5721     */
5722    public void setFilterTouchesWhenObscured(boolean enabled) {
5723        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5724                FILTER_TOUCHES_WHEN_OBSCURED);
5725    }
5726
5727    /**
5728     * Indicates whether the entire hierarchy under this view will save its
5729     * state when a state saving traversal occurs from its parent.  The default
5730     * is true; if false, these views will not be saved unless
5731     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5732     *
5733     * @return Returns true if the view state saving from parent is enabled, else false.
5734     *
5735     * @see #setSaveFromParentEnabled(boolean)
5736     */
5737    public boolean isSaveFromParentEnabled() {
5738        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5739    }
5740
5741    /**
5742     * Controls whether the entire hierarchy under this view will save its
5743     * state when a state saving traversal occurs from its parent.  The default
5744     * is true; if false, these views will not be saved unless
5745     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5746     *
5747     * @param enabled Set to false to <em>disable</em> state saving, or true
5748     * (the default) to allow it.
5749     *
5750     * @see #isSaveFromParentEnabled()
5751     * @see #setId(int)
5752     * @see #onSaveInstanceState()
5753     */
5754    public void setSaveFromParentEnabled(boolean enabled) {
5755        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5756    }
5757
5758
5759    /**
5760     * Returns whether this View is able to take focus.
5761     *
5762     * @return True if this view can take focus, or false otherwise.
5763     * @attr ref android.R.styleable#View_focusable
5764     */
5765    @ViewDebug.ExportedProperty(category = "focus")
5766    public final boolean isFocusable() {
5767        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5768    }
5769
5770    /**
5771     * When a view is focusable, it may not want to take focus when in touch mode.
5772     * For example, a button would like focus when the user is navigating via a D-pad
5773     * so that the user can click on it, but once the user starts touching the screen,
5774     * the button shouldn't take focus
5775     * @return Whether the view is focusable in touch mode.
5776     * @attr ref android.R.styleable#View_focusableInTouchMode
5777     */
5778    @ViewDebug.ExportedProperty
5779    public final boolean isFocusableInTouchMode() {
5780        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5781    }
5782
5783    /**
5784     * Find the nearest view in the specified direction that can take focus.
5785     * This does not actually give focus to that view.
5786     *
5787     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5788     *
5789     * @return The nearest focusable in the specified direction, or null if none
5790     *         can be found.
5791     */
5792    public View focusSearch(int direction) {
5793        if (mParent != null) {
5794            return mParent.focusSearch(this, direction);
5795        } else {
5796            return null;
5797        }
5798    }
5799
5800    /**
5801     * This method is the last chance for the focused view and its ancestors to
5802     * respond to an arrow key. This is called when the focused view did not
5803     * consume the key internally, nor could the view system find a new view in
5804     * the requested direction to give focus to.
5805     *
5806     * @param focused The currently focused view.
5807     * @param direction The direction focus wants to move. One of FOCUS_UP,
5808     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5809     * @return True if the this view consumed this unhandled move.
5810     */
5811    public boolean dispatchUnhandledMove(View focused, int direction) {
5812        return false;
5813    }
5814
5815    /**
5816     * If a user manually specified the next view id for a particular direction,
5817     * use the root to look up the view.
5818     * @param root The root view of the hierarchy containing this view.
5819     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5820     * or FOCUS_BACKWARD.
5821     * @return The user specified next view, or null if there is none.
5822     */
5823    View findUserSetNextFocus(View root, int direction) {
5824        switch (direction) {
5825            case FOCUS_LEFT:
5826                if (mNextFocusLeftId == View.NO_ID) return null;
5827                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5828            case FOCUS_RIGHT:
5829                if (mNextFocusRightId == View.NO_ID) return null;
5830                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5831            case FOCUS_UP:
5832                if (mNextFocusUpId == View.NO_ID) return null;
5833                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5834            case FOCUS_DOWN:
5835                if (mNextFocusDownId == View.NO_ID) return null;
5836                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5837            case FOCUS_FORWARD:
5838                if (mNextFocusForwardId == View.NO_ID) return null;
5839                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5840            case FOCUS_BACKWARD: {
5841                if (mID == View.NO_ID) return null;
5842                final int id = mID;
5843                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5844                    @Override
5845                    public boolean apply(View t) {
5846                        return t.mNextFocusForwardId == id;
5847                    }
5848                });
5849            }
5850        }
5851        return null;
5852    }
5853
5854    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5855        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5856            @Override
5857            public boolean apply(View t) {
5858                return t.mID == childViewId;
5859            }
5860        });
5861
5862        if (result == null) {
5863            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5864                    + "by user for id " + childViewId);
5865        }
5866        return result;
5867    }
5868
5869    /**
5870     * Find and return all focusable views that are descendants of this view,
5871     * possibly including this view if it is focusable itself.
5872     *
5873     * @param direction The direction of the focus
5874     * @return A list of focusable views
5875     */
5876    public ArrayList<View> getFocusables(int direction) {
5877        ArrayList<View> result = new ArrayList<View>(24);
5878        addFocusables(result, direction);
5879        return result;
5880    }
5881
5882    /**
5883     * Add any focusable views that are descendants of this view (possibly
5884     * including this view if it is focusable itself) to views.  If we are in touch mode,
5885     * only add views that are also focusable in touch mode.
5886     *
5887     * @param views Focusable views found so far
5888     * @param direction The direction of the focus
5889     */
5890    public void addFocusables(ArrayList<View> views, int direction) {
5891        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5892    }
5893
5894    /**
5895     * Adds any focusable views that are descendants of this view (possibly
5896     * including this view if it is focusable itself) to views. This method
5897     * adds all focusable views regardless if we are in touch mode or
5898     * only views focusable in touch mode if we are in touch mode or
5899     * only views that can take accessibility focus if accessibility is enabeld
5900     * depending on the focusable mode paramater.
5901     *
5902     * @param views Focusable views found so far or null if all we are interested is
5903     *        the number of focusables.
5904     * @param direction The direction of the focus.
5905     * @param focusableMode The type of focusables to be added.
5906     *
5907     * @see #FOCUSABLES_ALL
5908     * @see #FOCUSABLES_TOUCH_MODE
5909     */
5910    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5911        if (views == null) {
5912            return;
5913        }
5914        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
5915            if (AccessibilityManager.getInstance(mContext).isEnabled()
5916                    && includeForAccessibility()) {
5917                views.add(this);
5918                return;
5919            }
5920        }
5921        if (!isFocusable()) {
5922            return;
5923        }
5924        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
5925                && isInTouchMode() && !isFocusableInTouchMode()) {
5926            return;
5927        }
5928        views.add(this);
5929    }
5930
5931    /**
5932     * Finds the Views that contain given text. The containment is case insensitive.
5933     * The search is performed by either the text that the View renders or the content
5934     * description that describes the view for accessibility purposes and the view does
5935     * not render or both. Clients can specify how the search is to be performed via
5936     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5937     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5938     *
5939     * @param outViews The output list of matching Views.
5940     * @param searched The text to match against.
5941     *
5942     * @see #FIND_VIEWS_WITH_TEXT
5943     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5944     * @see #setContentDescription(CharSequence)
5945     */
5946    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5947        if (getAccessibilityNodeProvider() != null) {
5948            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5949                outViews.add(this);
5950            }
5951        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5952                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5953            String searchedLowerCase = searched.toString().toLowerCase();
5954            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5955            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5956                outViews.add(this);
5957            }
5958        }
5959    }
5960
5961    /**
5962     * Find and return all touchable views that are descendants of this view,
5963     * possibly including this view if it is touchable itself.
5964     *
5965     * @return A list of touchable views
5966     */
5967    public ArrayList<View> getTouchables() {
5968        ArrayList<View> result = new ArrayList<View>();
5969        addTouchables(result);
5970        return result;
5971    }
5972
5973    /**
5974     * Add any touchable views that are descendants of this view (possibly
5975     * including this view if it is touchable itself) to views.
5976     *
5977     * @param views Touchable views found so far
5978     */
5979    public void addTouchables(ArrayList<View> views) {
5980        final int viewFlags = mViewFlags;
5981
5982        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5983                && (viewFlags & ENABLED_MASK) == ENABLED) {
5984            views.add(this);
5985        }
5986    }
5987
5988    /**
5989     * Returns whether this View is accessibility focused.
5990     *
5991     * @return True if this View is accessibility focused.
5992     */
5993    boolean isAccessibilityFocused() {
5994        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
5995    }
5996
5997    /**
5998     * Call this to try to give accessibility focus to this view.
5999     *
6000     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6001     * returns false or the view is no visible or the view already has accessibility
6002     * focus.
6003     *
6004     * See also {@link #focusSearch(int)}, which is what you call to say that you
6005     * have focus, and you want your parent to look for the next one.
6006     *
6007     * @return Whether this view actually took accessibility focus.
6008     *
6009     * @hide
6010     */
6011    public boolean requestAccessibilityFocus() {
6012        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6013        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6014            return false;
6015        }
6016        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6017            return false;
6018        }
6019        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6020            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6021            ViewRootImpl viewRootImpl = getViewRootImpl();
6022            if (viewRootImpl != null) {
6023                viewRootImpl.setAccessibilityFocusedHost(this);
6024            }
6025            invalidate();
6026            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6027            notifyAccessibilityStateChanged();
6028            // Try to give input focus to this view - not a descendant.
6029            requestFocusNoSearch(View.FOCUS_DOWN, null);
6030            return true;
6031        }
6032        return false;
6033    }
6034
6035    /**
6036     * Call this to try to clear accessibility focus of this view.
6037     *
6038     * See also {@link #focusSearch(int)}, which is what you call to say that you
6039     * have focus, and you want your parent to look for the next one.
6040     *
6041     * @hide
6042     */
6043    public void clearAccessibilityFocus() {
6044        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6045            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6046            ViewRootImpl viewRootImpl = getViewRootImpl();
6047            if (viewRootImpl != null) {
6048                viewRootImpl.setAccessibilityFocusedHost(null);
6049            }
6050            invalidate();
6051            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6052            notifyAccessibilityStateChanged();
6053            // Try to move accessibility focus to the input focus.
6054            View rootView = getRootView();
6055            if (rootView != null) {
6056                View inputFocus = rootView.findFocus();
6057                if (inputFocus != null) {
6058                    inputFocus.requestAccessibilityFocus();
6059                }
6060            }
6061        }
6062    }
6063
6064    /**
6065     * Find the best view to take accessibility focus from a hover.
6066     * This function finds the deepest actionable view and if that
6067     * fails ask the parent to take accessibility focus from hover.
6068     *
6069     * @param x The X hovered location in this view coorditantes.
6070     * @param y The Y hovered location in this view coorditantes.
6071     * @return Whether the request was handled.
6072     *
6073     * @hide
6074     */
6075    public boolean requestAccessibilityFocusFromHover(float x, float y) {
6076        if (onRequestAccessibilityFocusFromHover(x, y)) {
6077            return true;
6078        }
6079        ViewParent parent = mParent;
6080        if (parent instanceof View) {
6081            View parentView = (View) parent;
6082
6083            float[] position = mAttachInfo.mTmpTransformLocation;
6084            position[0] = x;
6085            position[1] = y;
6086
6087            // Compensate for the transformation of the current matrix.
6088            if (!hasIdentityMatrix()) {
6089                getMatrix().mapPoints(position);
6090            }
6091
6092            // Compensate for the parent scroll and the offset
6093            // of this view stop from the parent top.
6094            position[0] += mLeft - parentView.mScrollX;
6095            position[1] += mTop - parentView.mScrollY;
6096
6097            return parentView.requestAccessibilityFocusFromHover(position[0], position[1]);
6098        }
6099        return false;
6100    }
6101
6102    /**
6103     * Requests to give this View focus from hover.
6104     *
6105     * @param x The X hovered location in this view coorditantes.
6106     * @param y The Y hovered location in this view coorditantes.
6107     * @return Whether the request was handled.
6108     *
6109     * @hide
6110     */
6111    public boolean onRequestAccessibilityFocusFromHover(float x, float y) {
6112        if (includeForAccessibility()
6113                && (isActionableForAccessibility() || hasListenersForAccessibility())) {
6114            return requestAccessibilityFocus();
6115        }
6116        return false;
6117    }
6118
6119    /**
6120     * Clears accessibility focus without calling any callback methods
6121     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6122     * is used for clearing accessibility focus when giving this focus to
6123     * another view.
6124     */
6125    void clearAccessibilityFocusNoCallbacks() {
6126        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6127            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6128            invalidate();
6129        }
6130    }
6131
6132    /**
6133     * Call this to try to give focus to a specific view or to one of its
6134     * descendants.
6135     *
6136     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6137     * false), or if it is focusable and it is not focusable in touch mode
6138     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6139     *
6140     * See also {@link #focusSearch(int)}, which is what you call to say that you
6141     * have focus, and you want your parent to look for the next one.
6142     *
6143     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6144     * {@link #FOCUS_DOWN} and <code>null</code>.
6145     *
6146     * @return Whether this view or one of its descendants actually took focus.
6147     */
6148    public final boolean requestFocus() {
6149        return requestFocus(View.FOCUS_DOWN);
6150    }
6151
6152    /**
6153     * Call this to try to give focus to a specific view or to one of its
6154     * descendants and give it a hint about what direction focus is heading.
6155     *
6156     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6157     * false), or if it is focusable and it is not focusable in touch mode
6158     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6159     *
6160     * See also {@link #focusSearch(int)}, which is what you call to say that you
6161     * have focus, and you want your parent to look for the next one.
6162     *
6163     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6164     * <code>null</code> set for the previously focused rectangle.
6165     *
6166     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6167     * @return Whether this view or one of its descendants actually took focus.
6168     */
6169    public final boolean requestFocus(int direction) {
6170        return requestFocus(direction, null);
6171    }
6172
6173    /**
6174     * Call this to try to give focus to a specific view or to one of its descendants
6175     * and give it hints about the direction and a specific rectangle that the focus
6176     * is coming from.  The rectangle can help give larger views a finer grained hint
6177     * about where focus is coming from, and therefore, where to show selection, or
6178     * forward focus change internally.
6179     *
6180     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6181     * false), or if it is focusable and it is not focusable in touch mode
6182     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6183     *
6184     * A View will not take focus if it is not visible.
6185     *
6186     * A View will not take focus if one of its parents has
6187     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6188     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6189     *
6190     * See also {@link #focusSearch(int)}, which is what you call to say that you
6191     * have focus, and you want your parent to look for the next one.
6192     *
6193     * You may wish to override this method if your custom {@link View} has an internal
6194     * {@link View} that it wishes to forward the request to.
6195     *
6196     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6197     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6198     *        to give a finer grained hint about where focus is coming from.  May be null
6199     *        if there is no hint.
6200     * @return Whether this view or one of its descendants actually took focus.
6201     */
6202    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6203        return requestFocusNoSearch(direction, previouslyFocusedRect);
6204    }
6205
6206    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6207        // need to be focusable
6208        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6209                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6210            return false;
6211        }
6212
6213        // need to be focusable in touch mode if in touch mode
6214        if (isInTouchMode() &&
6215            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6216               return false;
6217        }
6218
6219        // need to not have any parents blocking us
6220        if (hasAncestorThatBlocksDescendantFocus()) {
6221            return false;
6222        }
6223
6224        handleFocusGainInternal(direction, previouslyFocusedRect);
6225        return true;
6226    }
6227
6228    /**
6229     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6230     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6231     * touch mode to request focus when they are touched.
6232     *
6233     * @return Whether this view or one of its descendants actually took focus.
6234     *
6235     * @see #isInTouchMode()
6236     *
6237     */
6238    public final boolean requestFocusFromTouch() {
6239        // Leave touch mode if we need to
6240        if (isInTouchMode()) {
6241            ViewRootImpl viewRoot = getViewRootImpl();
6242            if (viewRoot != null) {
6243                viewRoot.ensureTouchMode(false);
6244            }
6245        }
6246        return requestFocus(View.FOCUS_DOWN);
6247    }
6248
6249    /**
6250     * @return Whether any ancestor of this view blocks descendant focus.
6251     */
6252    private boolean hasAncestorThatBlocksDescendantFocus() {
6253        ViewParent ancestor = mParent;
6254        while (ancestor instanceof ViewGroup) {
6255            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6256            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6257                return true;
6258            } else {
6259                ancestor = vgAncestor.getParent();
6260            }
6261        }
6262        return false;
6263    }
6264
6265    /**
6266     * Gets the mode for determining whether this View is important for accessibility
6267     * which is if it fires accessibility events and if it is reported to
6268     * accessibility services that query the screen.
6269     *
6270     * @return The mode for determining whether a View is important for accessibility.
6271     *
6272     * @attr ref android.R.styleable#View_importantForAccessibility
6273     *
6274     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6275     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6276     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6277     */
6278    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6279            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6280                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6281            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6282                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6283            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6284                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6285        })
6286    public int getImportantForAccessibility() {
6287        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6288                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6289    }
6290
6291    /**
6292     * Sets how to determine whether this view is important for accessibility
6293     * which is if it fires accessibility events and if it is reported to
6294     * accessibility services that query the screen.
6295     *
6296     * @param mode How to determine whether this view is important for accessibility.
6297     *
6298     * @attr ref android.R.styleable#View_importantForAccessibility
6299     *
6300     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6301     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6302     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6303     */
6304    public void setImportantForAccessibility(int mode) {
6305        if (mode != getImportantForAccessibility()) {
6306            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6307            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6308                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6309            notifyAccessibilityStateChanged();
6310        }
6311    }
6312
6313    /**
6314     * Gets whether this view should be exposed for accessibility.
6315     *
6316     * @return Whether the view is exposed for accessibility.
6317     *
6318     * @hide
6319     */
6320    public boolean isImportantForAccessibility() {
6321        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6322                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6323        switch (mode) {
6324            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6325                return true;
6326            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6327                return false;
6328            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6329                return isActionableForAccessibility() || hasListenersForAccessibility();
6330            default:
6331                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6332                        + mode);
6333        }
6334    }
6335
6336    /**
6337     * Gets the parent for accessibility purposes. Note that the parent for
6338     * accessibility is not necessary the immediate parent. It is the first
6339     * predecessor that is important for accessibility.
6340     *
6341     * @return The parent for accessibility purposes.
6342     */
6343    public ViewParent getParentForAccessibility() {
6344        if (mParent instanceof View) {
6345            View parentView = (View) mParent;
6346            if (parentView.includeForAccessibility()) {
6347                return mParent;
6348            } else {
6349                return mParent.getParentForAccessibility();
6350            }
6351        }
6352        return null;
6353    }
6354
6355    /**
6356     * Adds the children of a given View for accessibility. Since some Views are
6357     * not important for accessibility the children for accessibility are not
6358     * necessarily direct children of the riew, rather they are the first level of
6359     * descendants important for accessibility.
6360     *
6361     * @param children The list of children for accessibility.
6362     */
6363    public void addChildrenForAccessibility(ArrayList<View> children) {
6364        if (includeForAccessibility()) {
6365            children.add(this);
6366        }
6367    }
6368
6369    /**
6370     * Whether to regard this view for accessibility. A view is regarded for
6371     * accessibility if it is important for accessibility or the querying
6372     * accessibility service has explicitly requested that view not
6373     * important for accessibility are regarded.
6374     *
6375     * @return Whether to regard the view for accessibility.
6376     */
6377    boolean includeForAccessibility() {
6378        if (mAttachInfo != null) {
6379            if (!mAttachInfo.mIncludeNotImportantViews) {
6380                return isImportantForAccessibility() && isDisplayedOnScreen();
6381            } else {
6382                return isDisplayedOnScreen();
6383            }
6384        }
6385        return false;
6386    }
6387
6388    /**
6389     * Returns whether the View is considered actionable from
6390     * accessibility perspective. Such view are important for
6391     * accessiiblity.
6392     *
6393     * @return True if the view is actionable for accessibility.
6394     */
6395    private boolean isActionableForAccessibility() {
6396        return (isClickable() || isLongClickable() || isFocusable());
6397    }
6398
6399    /**
6400     * Returns whether the View has registered callbacks wich makes it
6401     * important for accessiiblity.
6402     *
6403     * @return True if the view is actionable for accessibility.
6404     */
6405    private boolean hasListenersForAccessibility() {
6406        ListenerInfo info = getListenerInfo();
6407        return mTouchDelegate != null || info.mOnKeyListener != null
6408                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6409                || info.mOnHoverListener != null || info.mOnDragListener != null;
6410    }
6411
6412    /**
6413     * Notifies accessibility services that some view's important for
6414     * accessibility state has changed. Note that such notifications
6415     * are made at most once every
6416     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6417     * to avoid unnecessary load to the system. Also once a view has
6418     * made a notifucation this method is a NOP until the notification has
6419     * been sent to clients.
6420     *
6421     * @hide
6422     *
6423     * TODO: Makse sure this method is called for any view state change
6424     *       that is interesting for accessilility purposes.
6425     */
6426    public void notifyAccessibilityStateChanged() {
6427        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6428            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6429            if (mParent != null) {
6430                mParent.childAccessibilityStateChanged(this);
6431            }
6432        }
6433    }
6434
6435    /**
6436     * Reset the state indicating the this view has requested clients
6437     * interested in its accessiblity state to be notified.
6438     *
6439     * @hide
6440     */
6441    public void resetAccessibilityStateChanged() {
6442        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6443    }
6444
6445    /**
6446     * Performs the specified accessibility action on the view. For
6447     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6448     *
6449     * @param action The action to perform.
6450     * @return Whether the action was performed.
6451     */
6452    public boolean performAccessibilityAction(int action, Bundle args) {
6453        switch (action) {
6454            case AccessibilityNodeInfo.ACTION_CLICK: {
6455                if (isClickable()) {
6456                    return performClick();
6457                }
6458            } break;
6459            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6460                if (isLongClickable()) {
6461                    return performLongClick();
6462                }
6463            } break;
6464            case AccessibilityNodeInfo.ACTION_FOCUS: {
6465                if (!hasFocus()) {
6466                    // Get out of touch mode since accessibility
6467                    // wants to move focus around.
6468                    getViewRootImpl().ensureTouchMode(false);
6469                    return requestFocus();
6470                }
6471            } break;
6472            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6473                if (hasFocus()) {
6474                    clearFocus();
6475                    return !isFocused();
6476                }
6477            } break;
6478            case AccessibilityNodeInfo.ACTION_SELECT: {
6479                if (!isSelected()) {
6480                    setSelected(true);
6481                    return isSelected();
6482                }
6483            } break;
6484            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6485                if (isSelected()) {
6486                    setSelected(false);
6487                    return !isSelected();
6488                }
6489            } break;
6490            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6491                if (!isAccessibilityFocused()) {
6492                    return requestAccessibilityFocus();
6493                }
6494            } break;
6495            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6496                if (isAccessibilityFocused()) {
6497                    clearAccessibilityFocus();
6498                    return true;
6499                }
6500            } break;
6501        }
6502        return false;
6503    }
6504
6505    /**
6506     * @hide
6507     */
6508    public void dispatchStartTemporaryDetach() {
6509        onStartTemporaryDetach();
6510    }
6511
6512    /**
6513     * This is called when a container is going to temporarily detach a child, with
6514     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6515     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6516     * {@link #onDetachedFromWindow()} when the container is done.
6517     */
6518    public void onStartTemporaryDetach() {
6519        removeUnsetPressCallback();
6520        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6521    }
6522
6523    /**
6524     * @hide
6525     */
6526    public void dispatchFinishTemporaryDetach() {
6527        onFinishTemporaryDetach();
6528    }
6529
6530    /**
6531     * Called after {@link #onStartTemporaryDetach} when the container is done
6532     * changing the view.
6533     */
6534    public void onFinishTemporaryDetach() {
6535    }
6536
6537    /**
6538     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6539     * for this view's window.  Returns null if the view is not currently attached
6540     * to the window.  Normally you will not need to use this directly, but
6541     * just use the standard high-level event callbacks like
6542     * {@link #onKeyDown(int, KeyEvent)}.
6543     */
6544    public KeyEvent.DispatcherState getKeyDispatcherState() {
6545        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6546    }
6547
6548    /**
6549     * Dispatch a key event before it is processed by any input method
6550     * associated with the view hierarchy.  This can be used to intercept
6551     * key events in special situations before the IME consumes them; a
6552     * typical example would be handling the BACK key to update the application's
6553     * UI instead of allowing the IME to see it and close itself.
6554     *
6555     * @param event The key event to be dispatched.
6556     * @return True if the event was handled, false otherwise.
6557     */
6558    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6559        return onKeyPreIme(event.getKeyCode(), event);
6560    }
6561
6562    /**
6563     * Dispatch a key event to the next view on the focus path. This path runs
6564     * from the top of the view tree down to the currently focused view. If this
6565     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6566     * the next node down the focus path. This method also fires any key
6567     * listeners.
6568     *
6569     * @param event The key event to be dispatched.
6570     * @return True if the event was handled, false otherwise.
6571     */
6572    public boolean dispatchKeyEvent(KeyEvent event) {
6573        if (mInputEventConsistencyVerifier != null) {
6574            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6575        }
6576
6577        // Give any attached key listener a first crack at the event.
6578        //noinspection SimplifiableIfStatement
6579        ListenerInfo li = mListenerInfo;
6580        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6581                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6582            return true;
6583        }
6584
6585        if (event.dispatch(this, mAttachInfo != null
6586                ? mAttachInfo.mKeyDispatchState : null, this)) {
6587            return true;
6588        }
6589
6590        if (mInputEventConsistencyVerifier != null) {
6591            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6592        }
6593        return false;
6594    }
6595
6596    /**
6597     * Dispatches a key shortcut event.
6598     *
6599     * @param event The key event to be dispatched.
6600     * @return True if the event was handled by the view, false otherwise.
6601     */
6602    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6603        return onKeyShortcut(event.getKeyCode(), event);
6604    }
6605
6606    /**
6607     * Pass the touch screen motion event down to the target view, or this
6608     * view if it is the target.
6609     *
6610     * @param event The motion event to be dispatched.
6611     * @return True if the event was handled by the view, false otherwise.
6612     */
6613    public boolean dispatchTouchEvent(MotionEvent event) {
6614        if (mInputEventConsistencyVerifier != null) {
6615            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6616        }
6617
6618        if (onFilterTouchEventForSecurity(event)) {
6619            //noinspection SimplifiableIfStatement
6620            ListenerInfo li = mListenerInfo;
6621            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6622                    && li.mOnTouchListener.onTouch(this, event)) {
6623                return true;
6624            }
6625
6626            if (onTouchEvent(event)) {
6627                return true;
6628            }
6629        }
6630
6631        if (mInputEventConsistencyVerifier != null) {
6632            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6633        }
6634        return false;
6635    }
6636
6637    /**
6638     * Filter the touch event to apply security policies.
6639     *
6640     * @param event The motion event to be filtered.
6641     * @return True if the event should be dispatched, false if the event should be dropped.
6642     *
6643     * @see #getFilterTouchesWhenObscured
6644     */
6645    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6646        //noinspection RedundantIfStatement
6647        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6648                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6649            // Window is obscured, drop this touch.
6650            return false;
6651        }
6652        return true;
6653    }
6654
6655    /**
6656     * Pass a trackball motion event down to the focused view.
6657     *
6658     * @param event The motion event to be dispatched.
6659     * @return True if the event was handled by the view, false otherwise.
6660     */
6661    public boolean dispatchTrackballEvent(MotionEvent event) {
6662        if (mInputEventConsistencyVerifier != null) {
6663            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6664        }
6665
6666        return onTrackballEvent(event);
6667    }
6668
6669    /**
6670     * Dispatch a generic motion event.
6671     * <p>
6672     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6673     * are delivered to the view under the pointer.  All other generic motion events are
6674     * delivered to the focused view.  Hover events are handled specially and are delivered
6675     * to {@link #onHoverEvent(MotionEvent)}.
6676     * </p>
6677     *
6678     * @param event The motion event to be dispatched.
6679     * @return True if the event was handled by the view, false otherwise.
6680     */
6681    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6682        if (mInputEventConsistencyVerifier != null) {
6683            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6684        }
6685
6686        final int source = event.getSource();
6687        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6688            final int action = event.getAction();
6689            if (action == MotionEvent.ACTION_HOVER_ENTER
6690                    || action == MotionEvent.ACTION_HOVER_MOVE
6691                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6692                if (dispatchHoverEvent(event)) {
6693                    return true;
6694                }
6695            } else if (dispatchGenericPointerEvent(event)) {
6696                return true;
6697            }
6698        } else if (dispatchGenericFocusedEvent(event)) {
6699            return true;
6700        }
6701
6702        if (dispatchGenericMotionEventInternal(event)) {
6703            return true;
6704        }
6705
6706        if (mInputEventConsistencyVerifier != null) {
6707            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6708        }
6709        return false;
6710    }
6711
6712    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6713        //noinspection SimplifiableIfStatement
6714        ListenerInfo li = mListenerInfo;
6715        if (li != null && li.mOnGenericMotionListener != null
6716                && (mViewFlags & ENABLED_MASK) == ENABLED
6717                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6718            return true;
6719        }
6720
6721        if (onGenericMotionEvent(event)) {
6722            return true;
6723        }
6724
6725        if (mInputEventConsistencyVerifier != null) {
6726            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6727        }
6728        return false;
6729    }
6730
6731    /**
6732     * Dispatch a hover event.
6733     * <p>
6734     * Do not call this method directly.
6735     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6736     * </p>
6737     *
6738     * @param event The motion event to be dispatched.
6739     * @return True if the event was handled by the view, false otherwise.
6740     */
6741    protected boolean dispatchHoverEvent(MotionEvent event) {
6742        //noinspection SimplifiableIfStatement
6743        ListenerInfo li = mListenerInfo;
6744        if (li != null && li.mOnHoverListener != null
6745                && (mViewFlags & ENABLED_MASK) == ENABLED
6746                && li.mOnHoverListener.onHover(this, event)) {
6747            return true;
6748        }
6749
6750        return onHoverEvent(event);
6751    }
6752
6753    /**
6754     * Returns true if the view has a child to which it has recently sent
6755     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
6756     * it does not have a hovered child, then it must be the innermost hovered view.
6757     * @hide
6758     */
6759    protected boolean hasHoveredChild() {
6760        return false;
6761    }
6762
6763    /**
6764     * Dispatch a generic motion event to the view under the first pointer.
6765     * <p>
6766     * Do not call this method directly.
6767     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6768     * </p>
6769     *
6770     * @param event The motion event to be dispatched.
6771     * @return True if the event was handled by the view, false otherwise.
6772     */
6773    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
6774        return false;
6775    }
6776
6777    /**
6778     * Dispatch a generic motion event to the currently focused view.
6779     * <p>
6780     * Do not call this method directly.
6781     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6782     * </p>
6783     *
6784     * @param event The motion event to be dispatched.
6785     * @return True if the event was handled by the view, false otherwise.
6786     */
6787    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
6788        return false;
6789    }
6790
6791    /**
6792     * Dispatch a pointer event.
6793     * <p>
6794     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
6795     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
6796     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
6797     * and should not be expected to handle other pointing device features.
6798     * </p>
6799     *
6800     * @param event The motion event to be dispatched.
6801     * @return True if the event was handled by the view, false otherwise.
6802     * @hide
6803     */
6804    public final boolean dispatchPointerEvent(MotionEvent event) {
6805        if (event.isTouchEvent()) {
6806            return dispatchTouchEvent(event);
6807        } else {
6808            return dispatchGenericMotionEvent(event);
6809        }
6810    }
6811
6812    /**
6813     * Called when the window containing this view gains or loses window focus.
6814     * ViewGroups should override to route to their children.
6815     *
6816     * @param hasFocus True if the window containing this view now has focus,
6817     *        false otherwise.
6818     */
6819    public void dispatchWindowFocusChanged(boolean hasFocus) {
6820        onWindowFocusChanged(hasFocus);
6821    }
6822
6823    /**
6824     * Called when the window containing this view gains or loses focus.  Note
6825     * that this is separate from view focus: to receive key events, both
6826     * your view and its window must have focus.  If a window is displayed
6827     * on top of yours that takes input focus, then your own window will lose
6828     * focus but the view focus will remain unchanged.
6829     *
6830     * @param hasWindowFocus True if the window containing this view now has
6831     *        focus, false otherwise.
6832     */
6833    public void onWindowFocusChanged(boolean hasWindowFocus) {
6834        InputMethodManager imm = InputMethodManager.peekInstance();
6835        if (!hasWindowFocus) {
6836            if (isPressed()) {
6837                setPressed(false);
6838            }
6839            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6840                imm.focusOut(this);
6841            }
6842            removeLongPressCallback();
6843            removeTapCallback();
6844            onFocusLost();
6845        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6846            imm.focusIn(this);
6847        }
6848        refreshDrawableState();
6849    }
6850
6851    /**
6852     * Returns true if this view is in a window that currently has window focus.
6853     * Note that this is not the same as the view itself having focus.
6854     *
6855     * @return True if this view is in a window that currently has window focus.
6856     */
6857    public boolean hasWindowFocus() {
6858        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
6859    }
6860
6861    /**
6862     * Dispatch a view visibility change down the view hierarchy.
6863     * ViewGroups should override to route to their children.
6864     * @param changedView The view whose visibility changed. Could be 'this' or
6865     * an ancestor view.
6866     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6867     * {@link #INVISIBLE} or {@link #GONE}.
6868     */
6869    protected void dispatchVisibilityChanged(View changedView, int visibility) {
6870        onVisibilityChanged(changedView, visibility);
6871    }
6872
6873    /**
6874     * Called when the visibility of the view or an ancestor of the view is changed.
6875     * @param changedView The view whose visibility changed. Could be 'this' or
6876     * an ancestor view.
6877     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6878     * {@link #INVISIBLE} or {@link #GONE}.
6879     */
6880    protected void onVisibilityChanged(View changedView, int visibility) {
6881        if (visibility == VISIBLE) {
6882            if (mAttachInfo != null) {
6883                initialAwakenScrollBars();
6884            } else {
6885                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
6886            }
6887        }
6888    }
6889
6890    /**
6891     * Dispatch a hint about whether this view is displayed. For instance, when
6892     * a View moves out of the screen, it might receives a display hint indicating
6893     * the view is not displayed. Applications should not <em>rely</em> on this hint
6894     * as there is no guarantee that they will receive one.
6895     *
6896     * @param hint A hint about whether or not this view is displayed:
6897     * {@link #VISIBLE} or {@link #INVISIBLE}.
6898     */
6899    public void dispatchDisplayHint(int hint) {
6900        onDisplayHint(hint);
6901    }
6902
6903    /**
6904     * Gives this view a hint about whether is displayed or not. For instance, when
6905     * a View moves out of the screen, it might receives a display hint indicating
6906     * the view is not displayed. Applications should not <em>rely</em> on this hint
6907     * as there is no guarantee that they will receive one.
6908     *
6909     * @param hint A hint about whether or not this view is displayed:
6910     * {@link #VISIBLE} or {@link #INVISIBLE}.
6911     */
6912    protected void onDisplayHint(int hint) {
6913    }
6914
6915    /**
6916     * Dispatch a window visibility change down the view hierarchy.
6917     * ViewGroups should override to route to their children.
6918     *
6919     * @param visibility The new visibility of the window.
6920     *
6921     * @see #onWindowVisibilityChanged(int)
6922     */
6923    public void dispatchWindowVisibilityChanged(int visibility) {
6924        onWindowVisibilityChanged(visibility);
6925    }
6926
6927    /**
6928     * Called when the window containing has change its visibility
6929     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
6930     * that this tells you whether or not your window is being made visible
6931     * to the window manager; this does <em>not</em> tell you whether or not
6932     * your window is obscured by other windows on the screen, even if it
6933     * is itself visible.
6934     *
6935     * @param visibility The new visibility of the window.
6936     */
6937    protected void onWindowVisibilityChanged(int visibility) {
6938        if (visibility == VISIBLE) {
6939            initialAwakenScrollBars();
6940        }
6941    }
6942
6943    /**
6944     * Returns the current visibility of the window this view is attached to
6945     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6946     *
6947     * @return Returns the current visibility of the view's window.
6948     */
6949    public int getWindowVisibility() {
6950        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6951    }
6952
6953    /**
6954     * Retrieve the overall visible display size in which the window this view is
6955     * attached to has been positioned in.  This takes into account screen
6956     * decorations above the window, for both cases where the window itself
6957     * is being position inside of them or the window is being placed under
6958     * then and covered insets are used for the window to position its content
6959     * inside.  In effect, this tells you the available area where content can
6960     * be placed and remain visible to users.
6961     *
6962     * <p>This function requires an IPC back to the window manager to retrieve
6963     * the requested information, so should not be used in performance critical
6964     * code like drawing.
6965     *
6966     * @param outRect Filled in with the visible display frame.  If the view
6967     * is not attached to a window, this is simply the raw display size.
6968     */
6969    public void getWindowVisibleDisplayFrame(Rect outRect) {
6970        if (mAttachInfo != null) {
6971            try {
6972                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6973            } catch (RemoteException e) {
6974                return;
6975            }
6976            // XXX This is really broken, and probably all needs to be done
6977            // in the window manager, and we need to know more about whether
6978            // we want the area behind or in front of the IME.
6979            final Rect insets = mAttachInfo.mVisibleInsets;
6980            outRect.left += insets.left;
6981            outRect.top += insets.top;
6982            outRect.right -= insets.right;
6983            outRect.bottom -= insets.bottom;
6984            return;
6985        }
6986        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6987        d.getRectSize(outRect);
6988    }
6989
6990    /**
6991     * Dispatch a notification about a resource configuration change down
6992     * the view hierarchy.
6993     * ViewGroups should override to route to their children.
6994     *
6995     * @param newConfig The new resource configuration.
6996     *
6997     * @see #onConfigurationChanged(android.content.res.Configuration)
6998     */
6999    public void dispatchConfigurationChanged(Configuration newConfig) {
7000        onConfigurationChanged(newConfig);
7001    }
7002
7003    /**
7004     * Called when the current configuration of the resources being used
7005     * by the application have changed.  You can use this to decide when
7006     * to reload resources that can changed based on orientation and other
7007     * configuration characterstics.  You only need to use this if you are
7008     * not relying on the normal {@link android.app.Activity} mechanism of
7009     * recreating the activity instance upon a configuration change.
7010     *
7011     * @param newConfig The new resource configuration.
7012     */
7013    protected void onConfigurationChanged(Configuration newConfig) {
7014    }
7015
7016    /**
7017     * Private function to aggregate all per-view attributes in to the view
7018     * root.
7019     */
7020    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7021        performCollectViewAttributes(attachInfo, visibility);
7022    }
7023
7024    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7025        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7026            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7027                attachInfo.mKeepScreenOn = true;
7028            }
7029            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7030            ListenerInfo li = mListenerInfo;
7031            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7032                attachInfo.mHasSystemUiListeners = true;
7033            }
7034        }
7035    }
7036
7037    void needGlobalAttributesUpdate(boolean force) {
7038        final AttachInfo ai = mAttachInfo;
7039        if (ai != null) {
7040            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7041                    || ai.mHasSystemUiListeners) {
7042                ai.mRecomputeGlobalAttributes = true;
7043            }
7044        }
7045    }
7046
7047    /**
7048     * Returns whether the device is currently in touch mode.  Touch mode is entered
7049     * once the user begins interacting with the device by touch, and affects various
7050     * things like whether focus is always visible to the user.
7051     *
7052     * @return Whether the device is in touch mode.
7053     */
7054    @ViewDebug.ExportedProperty
7055    public boolean isInTouchMode() {
7056        if (mAttachInfo != null) {
7057            return mAttachInfo.mInTouchMode;
7058        } else {
7059            return ViewRootImpl.isInTouchMode();
7060        }
7061    }
7062
7063    /**
7064     * Returns the context the view is running in, through which it can
7065     * access the current theme, resources, etc.
7066     *
7067     * @return The view's Context.
7068     */
7069    @ViewDebug.CapturedViewProperty
7070    public final Context getContext() {
7071        return mContext;
7072    }
7073
7074    /**
7075     * Handle a key event before it is processed by any input method
7076     * associated with the view hierarchy.  This can be used to intercept
7077     * key events in special situations before the IME consumes them; a
7078     * typical example would be handling the BACK key to update the application's
7079     * UI instead of allowing the IME to see it and close itself.
7080     *
7081     * @param keyCode The value in event.getKeyCode().
7082     * @param event Description of the key event.
7083     * @return If you handled the event, return true. If you want to allow the
7084     *         event to be handled by the next receiver, return false.
7085     */
7086    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7087        return false;
7088    }
7089
7090    /**
7091     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7092     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7093     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7094     * is released, if the view is enabled and clickable.
7095     *
7096     * @param keyCode A key code that represents the button pressed, from
7097     *                {@link android.view.KeyEvent}.
7098     * @param event   The KeyEvent object that defines the button action.
7099     */
7100    public boolean onKeyDown(int keyCode, KeyEvent event) {
7101        boolean result = false;
7102
7103        switch (keyCode) {
7104            case KeyEvent.KEYCODE_DPAD_CENTER:
7105            case KeyEvent.KEYCODE_ENTER: {
7106                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7107                    return true;
7108                }
7109                // Long clickable items don't necessarily have to be clickable
7110                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7111                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7112                        (event.getRepeatCount() == 0)) {
7113                    setPressed(true);
7114                    checkForLongClick(0);
7115                    return true;
7116                }
7117                break;
7118            }
7119        }
7120        return result;
7121    }
7122
7123    /**
7124     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7125     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7126     * the event).
7127     */
7128    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7129        return false;
7130    }
7131
7132    /**
7133     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7134     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7135     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7136     * {@link KeyEvent#KEYCODE_ENTER} is released.
7137     *
7138     * @param keyCode A key code that represents the button pressed, from
7139     *                {@link android.view.KeyEvent}.
7140     * @param event   The KeyEvent object that defines the button action.
7141     */
7142    public boolean onKeyUp(int keyCode, KeyEvent event) {
7143        boolean result = false;
7144
7145        switch (keyCode) {
7146            case KeyEvent.KEYCODE_DPAD_CENTER:
7147            case KeyEvent.KEYCODE_ENTER: {
7148                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7149                    return true;
7150                }
7151                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7152                    setPressed(false);
7153
7154                    if (!mHasPerformedLongPress) {
7155                        // This is a tap, so remove the longpress check
7156                        removeLongPressCallback();
7157
7158                        result = performClick();
7159                    }
7160                }
7161                break;
7162            }
7163        }
7164        return result;
7165    }
7166
7167    /**
7168     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7169     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7170     * the event).
7171     *
7172     * @param keyCode     A key code that represents the button pressed, from
7173     *                    {@link android.view.KeyEvent}.
7174     * @param repeatCount The number of times the action was made.
7175     * @param event       The KeyEvent object that defines the button action.
7176     */
7177    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7178        return false;
7179    }
7180
7181    /**
7182     * Called on the focused view when a key shortcut event is not handled.
7183     * Override this method to implement local key shortcuts for the View.
7184     * Key shortcuts can also be implemented by setting the
7185     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7186     *
7187     * @param keyCode The value in event.getKeyCode().
7188     * @param event Description of the key event.
7189     * @return If you handled the event, return true. If you want to allow the
7190     *         event to be handled by the next receiver, return false.
7191     */
7192    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7193        return false;
7194    }
7195
7196    /**
7197     * Check whether the called view is a text editor, in which case it
7198     * would make sense to automatically display a soft input window for
7199     * it.  Subclasses should override this if they implement
7200     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7201     * a call on that method would return a non-null InputConnection, and
7202     * they are really a first-class editor that the user would normally
7203     * start typing on when the go into a window containing your view.
7204     *
7205     * <p>The default implementation always returns false.  This does
7206     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7207     * will not be called or the user can not otherwise perform edits on your
7208     * view; it is just a hint to the system that this is not the primary
7209     * purpose of this view.
7210     *
7211     * @return Returns true if this view is a text editor, else false.
7212     */
7213    public boolean onCheckIsTextEditor() {
7214        return false;
7215    }
7216
7217    /**
7218     * Create a new InputConnection for an InputMethod to interact
7219     * with the view.  The default implementation returns null, since it doesn't
7220     * support input methods.  You can override this to implement such support.
7221     * This is only needed for views that take focus and text input.
7222     *
7223     * <p>When implementing this, you probably also want to implement
7224     * {@link #onCheckIsTextEditor()} to indicate you will return a
7225     * non-null InputConnection.
7226     *
7227     * @param outAttrs Fill in with attribute information about the connection.
7228     */
7229    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7230        return null;
7231    }
7232
7233    /**
7234     * Called by the {@link android.view.inputmethod.InputMethodManager}
7235     * when a view who is not the current
7236     * input connection target is trying to make a call on the manager.  The
7237     * default implementation returns false; you can override this to return
7238     * true for certain views if you are performing InputConnection proxying
7239     * to them.
7240     * @param view The View that is making the InputMethodManager call.
7241     * @return Return true to allow the call, false to reject.
7242     */
7243    public boolean checkInputConnectionProxy(View view) {
7244        return false;
7245    }
7246
7247    /**
7248     * Show the context menu for this view. It is not safe to hold on to the
7249     * menu after returning from this method.
7250     *
7251     * You should normally not overload this method. Overload
7252     * {@link #onCreateContextMenu(ContextMenu)} or define an
7253     * {@link OnCreateContextMenuListener} to add items to the context menu.
7254     *
7255     * @param menu The context menu to populate
7256     */
7257    public void createContextMenu(ContextMenu menu) {
7258        ContextMenuInfo menuInfo = getContextMenuInfo();
7259
7260        // Sets the current menu info so all items added to menu will have
7261        // my extra info set.
7262        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7263
7264        onCreateContextMenu(menu);
7265        ListenerInfo li = mListenerInfo;
7266        if (li != null && li.mOnCreateContextMenuListener != null) {
7267            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7268        }
7269
7270        // Clear the extra information so subsequent items that aren't mine don't
7271        // have my extra info.
7272        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7273
7274        if (mParent != null) {
7275            mParent.createContextMenu(menu);
7276        }
7277    }
7278
7279    /**
7280     * Views should implement this if they have extra information to associate
7281     * with the context menu. The return result is supplied as a parameter to
7282     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7283     * callback.
7284     *
7285     * @return Extra information about the item for which the context menu
7286     *         should be shown. This information will vary across different
7287     *         subclasses of View.
7288     */
7289    protected ContextMenuInfo getContextMenuInfo() {
7290        return null;
7291    }
7292
7293    /**
7294     * Views should implement this if the view itself is going to add items to
7295     * the context menu.
7296     *
7297     * @param menu the context menu to populate
7298     */
7299    protected void onCreateContextMenu(ContextMenu menu) {
7300    }
7301
7302    /**
7303     * Implement this method to handle trackball motion events.  The
7304     * <em>relative</em> movement of the trackball since the last event
7305     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7306     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7307     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7308     * they will often be fractional values, representing the more fine-grained
7309     * movement information available from a trackball).
7310     *
7311     * @param event The motion event.
7312     * @return True if the event was handled, false otherwise.
7313     */
7314    public boolean onTrackballEvent(MotionEvent event) {
7315        return false;
7316    }
7317
7318    /**
7319     * Implement this method to handle generic motion events.
7320     * <p>
7321     * Generic motion events describe joystick movements, mouse hovers, track pad
7322     * touches, scroll wheel movements and other input events.  The
7323     * {@link MotionEvent#getSource() source} of the motion event specifies
7324     * the class of input that was received.  Implementations of this method
7325     * must examine the bits in the source before processing the event.
7326     * The following code example shows how this is done.
7327     * </p><p>
7328     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7329     * are delivered to the view under the pointer.  All other generic motion events are
7330     * delivered to the focused view.
7331     * </p>
7332     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7333     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7334     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7335     *             // process the joystick movement...
7336     *             return true;
7337     *         }
7338     *     }
7339     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7340     *         switch (event.getAction()) {
7341     *             case MotionEvent.ACTION_HOVER_MOVE:
7342     *                 // process the mouse hover movement...
7343     *                 return true;
7344     *             case MotionEvent.ACTION_SCROLL:
7345     *                 // process the scroll wheel movement...
7346     *                 return true;
7347     *         }
7348     *     }
7349     *     return super.onGenericMotionEvent(event);
7350     * }</pre>
7351     *
7352     * @param event The generic motion event being processed.
7353     * @return True if the event was handled, false otherwise.
7354     */
7355    public boolean onGenericMotionEvent(MotionEvent event) {
7356        return false;
7357    }
7358
7359    /**
7360     * Implement this method to handle hover events.
7361     * <p>
7362     * This method is called whenever a pointer is hovering into, over, or out of the
7363     * bounds of a view and the view is not currently being touched.
7364     * Hover events are represented as pointer events with action
7365     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7366     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7367     * </p>
7368     * <ul>
7369     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7370     * when the pointer enters the bounds of the view.</li>
7371     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7372     * when the pointer has already entered the bounds of the view and has moved.</li>
7373     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7374     * when the pointer has exited the bounds of the view or when the pointer is
7375     * about to go down due to a button click, tap, or similar user action that
7376     * causes the view to be touched.</li>
7377     * </ul>
7378     * <p>
7379     * The view should implement this method to return true to indicate that it is
7380     * handling the hover event, such as by changing its drawable state.
7381     * </p><p>
7382     * The default implementation calls {@link #setHovered} to update the hovered state
7383     * of the view when a hover enter or hover exit event is received, if the view
7384     * is enabled and is clickable.  The default implementation also sends hover
7385     * accessibility events.
7386     * </p>
7387     *
7388     * @param event The motion event that describes the hover.
7389     * @return True if the view handled the hover event.
7390     *
7391     * @see #isHovered
7392     * @see #setHovered
7393     * @see #onHoverChanged
7394     */
7395    public boolean onHoverEvent(MotionEvent event) {
7396        // The root view may receive hover (or touch) events that are outside the bounds of
7397        // the window.  This code ensures that we only send accessibility events for
7398        // hovers that are actually within the bounds of the root view.
7399        final int action = event.getActionMasked();
7400        if (!mSendingHoverAccessibilityEvents) {
7401            if ((action == MotionEvent.ACTION_HOVER_ENTER
7402                    || action == MotionEvent.ACTION_HOVER_MOVE)
7403                    && !hasHoveredChild()
7404                    && pointInView(event.getX(), event.getY())) {
7405                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7406                mSendingHoverAccessibilityEvents = true;
7407                requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY());
7408            }
7409        } else {
7410            if (action == MotionEvent.ACTION_HOVER_EXIT
7411                    || (action == MotionEvent.ACTION_MOVE
7412                            && !pointInView(event.getX(), event.getY()))) {
7413                mSendingHoverAccessibilityEvents = false;
7414                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7415                // If the window does not have input focus we take away accessibility
7416                // focus as soon as the user stop hovering over the view.
7417                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7418                    getViewRootImpl().setAccessibilityFocusedHost(null);
7419                }
7420            }
7421        }
7422
7423        if (isHoverable()) {
7424            switch (action) {
7425                case MotionEvent.ACTION_HOVER_ENTER:
7426                    setHovered(true);
7427                    break;
7428                case MotionEvent.ACTION_HOVER_EXIT:
7429                    setHovered(false);
7430                    break;
7431            }
7432
7433            // Dispatch the event to onGenericMotionEvent before returning true.
7434            // This is to provide compatibility with existing applications that
7435            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7436            // break because of the new default handling for hoverable views
7437            // in onHoverEvent.
7438            // Note that onGenericMotionEvent will be called by default when
7439            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7440            dispatchGenericMotionEventInternal(event);
7441            return true;
7442        }
7443
7444        return false;
7445    }
7446
7447    /**
7448     * Returns true if the view should handle {@link #onHoverEvent}
7449     * by calling {@link #setHovered} to change its hovered state.
7450     *
7451     * @return True if the view is hoverable.
7452     */
7453    private boolean isHoverable() {
7454        final int viewFlags = mViewFlags;
7455        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7456            return false;
7457        }
7458
7459        return (viewFlags & CLICKABLE) == CLICKABLE
7460                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7461    }
7462
7463    /**
7464     * Returns true if the view is currently hovered.
7465     *
7466     * @return True if the view is currently hovered.
7467     *
7468     * @see #setHovered
7469     * @see #onHoverChanged
7470     */
7471    @ViewDebug.ExportedProperty
7472    public boolean isHovered() {
7473        return (mPrivateFlags & HOVERED) != 0;
7474    }
7475
7476    /**
7477     * Sets whether the view is currently hovered.
7478     * <p>
7479     * Calling this method also changes the drawable state of the view.  This
7480     * enables the view to react to hover by using different drawable resources
7481     * to change its appearance.
7482     * </p><p>
7483     * The {@link #onHoverChanged} method is called when the hovered state changes.
7484     * </p>
7485     *
7486     * @param hovered True if the view is hovered.
7487     *
7488     * @see #isHovered
7489     * @see #onHoverChanged
7490     */
7491    public void setHovered(boolean hovered) {
7492        if (hovered) {
7493            if ((mPrivateFlags & HOVERED) == 0) {
7494                mPrivateFlags |= HOVERED;
7495                refreshDrawableState();
7496                onHoverChanged(true);
7497            }
7498        } else {
7499            if ((mPrivateFlags & HOVERED) != 0) {
7500                mPrivateFlags &= ~HOVERED;
7501                refreshDrawableState();
7502                onHoverChanged(false);
7503            }
7504        }
7505    }
7506
7507    /**
7508     * Implement this method to handle hover state changes.
7509     * <p>
7510     * This method is called whenever the hover state changes as a result of a
7511     * call to {@link #setHovered}.
7512     * </p>
7513     *
7514     * @param hovered The current hover state, as returned by {@link #isHovered}.
7515     *
7516     * @see #isHovered
7517     * @see #setHovered
7518     */
7519    public void onHoverChanged(boolean hovered) {
7520    }
7521
7522    /**
7523     * Implement this method to handle touch screen motion events.
7524     *
7525     * @param event The motion event.
7526     * @return True if the event was handled, false otherwise.
7527     */
7528    public boolean onTouchEvent(MotionEvent event) {
7529        final int viewFlags = mViewFlags;
7530
7531        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7532            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7533                setPressed(false);
7534            }
7535            // A disabled view that is clickable still consumes the touch
7536            // events, it just doesn't respond to them.
7537            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7538                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7539        }
7540
7541        if (mTouchDelegate != null) {
7542            if (mTouchDelegate.onTouchEvent(event)) {
7543                return true;
7544            }
7545        }
7546
7547        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7548                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7549            switch (event.getAction()) {
7550                case MotionEvent.ACTION_UP:
7551                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7552                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7553                        // take focus if we don't have it already and we should in
7554                        // touch mode.
7555                        boolean focusTaken = false;
7556                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7557                            focusTaken = requestFocus();
7558                        }
7559
7560                        if (prepressed) {
7561                            // The button is being released before we actually
7562                            // showed it as pressed.  Make it show the pressed
7563                            // state now (before scheduling the click) to ensure
7564                            // the user sees it.
7565                            setPressed(true);
7566                       }
7567
7568                        if (!mHasPerformedLongPress) {
7569                            // This is a tap, so remove the longpress check
7570                            removeLongPressCallback();
7571
7572                            // Only perform take click actions if we were in the pressed state
7573                            if (!focusTaken) {
7574                                // Use a Runnable and post this rather than calling
7575                                // performClick directly. This lets other visual state
7576                                // of the view update before click actions start.
7577                                if (mPerformClick == null) {
7578                                    mPerformClick = new PerformClick();
7579                                }
7580                                if (!post(mPerformClick)) {
7581                                    performClick();
7582                                }
7583                            }
7584                        }
7585
7586                        if (mUnsetPressedState == null) {
7587                            mUnsetPressedState = new UnsetPressedState();
7588                        }
7589
7590                        if (prepressed) {
7591                            postDelayed(mUnsetPressedState,
7592                                    ViewConfiguration.getPressedStateDuration());
7593                        } else if (!post(mUnsetPressedState)) {
7594                            // If the post failed, unpress right now
7595                            mUnsetPressedState.run();
7596                        }
7597                        removeTapCallback();
7598                    }
7599                    break;
7600
7601                case MotionEvent.ACTION_DOWN:
7602                    mHasPerformedLongPress = false;
7603
7604                    if (performButtonActionOnTouchDown(event)) {
7605                        break;
7606                    }
7607
7608                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7609                    boolean isInScrollingContainer = isInScrollingContainer();
7610
7611                    // For views inside a scrolling container, delay the pressed feedback for
7612                    // a short period in case this is a scroll.
7613                    if (isInScrollingContainer) {
7614                        mPrivateFlags |= PREPRESSED;
7615                        if (mPendingCheckForTap == null) {
7616                            mPendingCheckForTap = new CheckForTap();
7617                        }
7618                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7619                    } else {
7620                        // Not inside a scrolling container, so show the feedback right away
7621                        setPressed(true);
7622                        checkForLongClick(0);
7623                    }
7624                    break;
7625
7626                case MotionEvent.ACTION_CANCEL:
7627                    setPressed(false);
7628                    removeTapCallback();
7629                    break;
7630
7631                case MotionEvent.ACTION_MOVE:
7632                    final int x = (int) event.getX();
7633                    final int y = (int) event.getY();
7634
7635                    // Be lenient about moving outside of buttons
7636                    if (!pointInView(x, y, mTouchSlop)) {
7637                        // Outside button
7638                        removeTapCallback();
7639                        if ((mPrivateFlags & PRESSED) != 0) {
7640                            // Remove any future long press/tap checks
7641                            removeLongPressCallback();
7642
7643                            setPressed(false);
7644                        }
7645                    }
7646                    break;
7647            }
7648            return true;
7649        }
7650
7651        return false;
7652    }
7653
7654    /**
7655     * @hide
7656     */
7657    public boolean isInScrollingContainer() {
7658        ViewParent p = getParent();
7659        while (p != null && p instanceof ViewGroup) {
7660            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7661                return true;
7662            }
7663            p = p.getParent();
7664        }
7665        return false;
7666    }
7667
7668    /**
7669     * Remove the longpress detection timer.
7670     */
7671    private void removeLongPressCallback() {
7672        if (mPendingCheckForLongPress != null) {
7673          removeCallbacks(mPendingCheckForLongPress);
7674        }
7675    }
7676
7677    /**
7678     * Remove the pending click action
7679     */
7680    private void removePerformClickCallback() {
7681        if (mPerformClick != null) {
7682            removeCallbacks(mPerformClick);
7683        }
7684    }
7685
7686    /**
7687     * Remove the prepress detection timer.
7688     */
7689    private void removeUnsetPressCallback() {
7690        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7691            setPressed(false);
7692            removeCallbacks(mUnsetPressedState);
7693        }
7694    }
7695
7696    /**
7697     * Remove the tap detection timer.
7698     */
7699    private void removeTapCallback() {
7700        if (mPendingCheckForTap != null) {
7701            mPrivateFlags &= ~PREPRESSED;
7702            removeCallbacks(mPendingCheckForTap);
7703        }
7704    }
7705
7706    /**
7707     * Cancels a pending long press.  Your subclass can use this if you
7708     * want the context menu to come up if the user presses and holds
7709     * at the same place, but you don't want it to come up if they press
7710     * and then move around enough to cause scrolling.
7711     */
7712    public void cancelLongPress() {
7713        removeLongPressCallback();
7714
7715        /*
7716         * The prepressed state handled by the tap callback is a display
7717         * construct, but the tap callback will post a long press callback
7718         * less its own timeout. Remove it here.
7719         */
7720        removeTapCallback();
7721    }
7722
7723    /**
7724     * Remove the pending callback for sending a
7725     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7726     */
7727    private void removeSendViewScrolledAccessibilityEventCallback() {
7728        if (mSendViewScrolledAccessibilityEvent != null) {
7729            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7730        }
7731    }
7732
7733    /**
7734     * Sets the TouchDelegate for this View.
7735     */
7736    public void setTouchDelegate(TouchDelegate delegate) {
7737        mTouchDelegate = delegate;
7738    }
7739
7740    /**
7741     * Gets the TouchDelegate for this View.
7742     */
7743    public TouchDelegate getTouchDelegate() {
7744        return mTouchDelegate;
7745    }
7746
7747    /**
7748     * Set flags controlling behavior of this view.
7749     *
7750     * @param flags Constant indicating the value which should be set
7751     * @param mask Constant indicating the bit range that should be changed
7752     */
7753    void setFlags(int flags, int mask) {
7754        int old = mViewFlags;
7755        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
7756
7757        int changed = mViewFlags ^ old;
7758        if (changed == 0) {
7759            return;
7760        }
7761        int privateFlags = mPrivateFlags;
7762
7763        /* Check if the FOCUSABLE bit has changed */
7764        if (((changed & FOCUSABLE_MASK) != 0) &&
7765                ((privateFlags & HAS_BOUNDS) !=0)) {
7766            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
7767                    && ((privateFlags & FOCUSED) != 0)) {
7768                /* Give up focus if we are no longer focusable */
7769                clearFocus();
7770            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
7771                    && ((privateFlags & FOCUSED) == 0)) {
7772                /*
7773                 * Tell the view system that we are now available to take focus
7774                 * if no one else already has it.
7775                 */
7776                if (mParent != null) mParent.focusableViewAvailable(this);
7777            }
7778            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7779                notifyAccessibilityStateChanged();
7780            }
7781        }
7782
7783        if ((flags & VISIBILITY_MASK) == VISIBLE) {
7784            if ((changed & VISIBILITY_MASK) != 0) {
7785                /*
7786                 * If this view is becoming visible, invalidate it in case it changed while
7787                 * it was not visible. Marking it drawn ensures that the invalidation will
7788                 * go through.
7789                 */
7790                mPrivateFlags |= DRAWN;
7791                invalidate(true);
7792
7793                needGlobalAttributesUpdate(true);
7794
7795                // a view becoming visible is worth notifying the parent
7796                // about in case nothing has focus.  even if this specific view
7797                // isn't focusable, it may contain something that is, so let
7798                // the root view try to give this focus if nothing else does.
7799                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
7800                    mParent.focusableViewAvailable(this);
7801                }
7802            }
7803        }
7804
7805        /* Check if the GONE bit has changed */
7806        if ((changed & GONE) != 0) {
7807            needGlobalAttributesUpdate(false);
7808            requestLayout();
7809
7810            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
7811                if (hasFocus()) clearFocus();
7812                clearAccessibilityFocus();
7813                destroyDrawingCache();
7814                if (mParent instanceof View) {
7815                    // GONE views noop invalidation, so invalidate the parent
7816                    ((View) mParent).invalidate(true);
7817                }
7818                // Mark the view drawn to ensure that it gets invalidated properly the next
7819                // time it is visible and gets invalidated
7820                mPrivateFlags |= DRAWN;
7821            }
7822            if (mAttachInfo != null) {
7823                mAttachInfo.mViewVisibilityChanged = true;
7824            }
7825        }
7826
7827        /* Check if the VISIBLE bit has changed */
7828        if ((changed & INVISIBLE) != 0) {
7829            needGlobalAttributesUpdate(false);
7830            /*
7831             * If this view is becoming invisible, set the DRAWN flag so that
7832             * the next invalidate() will not be skipped.
7833             */
7834            mPrivateFlags |= DRAWN;
7835
7836            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
7837                // root view becoming invisible shouldn't clear focus and accessibility focus
7838                if (getRootView() != this) {
7839                    clearFocus();
7840                    clearAccessibilityFocus();
7841                }
7842            }
7843            if (mAttachInfo != null) {
7844                mAttachInfo.mViewVisibilityChanged = true;
7845            }
7846        }
7847
7848        if ((changed & VISIBILITY_MASK) != 0) {
7849            if (mParent instanceof ViewGroup) {
7850                ((ViewGroup) mParent).onChildVisibilityChanged(this,
7851                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
7852                ((View) mParent).invalidate(true);
7853            } else if (mParent != null) {
7854                mParent.invalidateChild(this, null);
7855            }
7856            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
7857        }
7858
7859        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
7860            destroyDrawingCache();
7861        }
7862
7863        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
7864            destroyDrawingCache();
7865            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7866            invalidateParentCaches();
7867        }
7868
7869        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
7870            destroyDrawingCache();
7871            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7872        }
7873
7874        if ((changed & DRAW_MASK) != 0) {
7875            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
7876                if (mBackground != null) {
7877                    mPrivateFlags &= ~SKIP_DRAW;
7878                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7879                } else {
7880                    mPrivateFlags |= SKIP_DRAW;
7881                }
7882            } else {
7883                mPrivateFlags &= ~SKIP_DRAW;
7884            }
7885            requestLayout();
7886            invalidate(true);
7887        }
7888
7889        if ((changed & KEEP_SCREEN_ON) != 0) {
7890            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
7891                mParent.recomputeViewAttributes(this);
7892            }
7893        }
7894
7895        if (AccessibilityManager.getInstance(mContext).isEnabled()
7896                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
7897                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
7898            notifyAccessibilityStateChanged();
7899        }
7900    }
7901
7902    /**
7903     * Change the view's z order in the tree, so it's on top of other sibling
7904     * views
7905     */
7906    public void bringToFront() {
7907        if (mParent != null) {
7908            mParent.bringChildToFront(this);
7909        }
7910    }
7911
7912    /**
7913     * This is called in response to an internal scroll in this view (i.e., the
7914     * view scrolled its own contents). This is typically as a result of
7915     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
7916     * called.
7917     *
7918     * @param l Current horizontal scroll origin.
7919     * @param t Current vertical scroll origin.
7920     * @param oldl Previous horizontal scroll origin.
7921     * @param oldt Previous vertical scroll origin.
7922     */
7923    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
7924        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7925            postSendViewScrolledAccessibilityEventCallback();
7926        }
7927
7928        mBackgroundSizeChanged = true;
7929
7930        final AttachInfo ai = mAttachInfo;
7931        if (ai != null) {
7932            ai.mViewScrollChanged = true;
7933        }
7934    }
7935
7936    /**
7937     * Interface definition for a callback to be invoked when the layout bounds of a view
7938     * changes due to layout processing.
7939     */
7940    public interface OnLayoutChangeListener {
7941        /**
7942         * Called when the focus state of a view has changed.
7943         *
7944         * @param v The view whose state has changed.
7945         * @param left The new value of the view's left property.
7946         * @param top The new value of the view's top property.
7947         * @param right The new value of the view's right property.
7948         * @param bottom The new value of the view's bottom property.
7949         * @param oldLeft The previous value of the view's left property.
7950         * @param oldTop The previous value of the view's top property.
7951         * @param oldRight The previous value of the view's right property.
7952         * @param oldBottom The previous value of the view's bottom property.
7953         */
7954        void onLayoutChange(View v, int left, int top, int right, int bottom,
7955            int oldLeft, int oldTop, int oldRight, int oldBottom);
7956    }
7957
7958    /**
7959     * This is called during layout when the size of this view has changed. If
7960     * you were just added to the view hierarchy, you're called with the old
7961     * values of 0.
7962     *
7963     * @param w Current width of this view.
7964     * @param h Current height of this view.
7965     * @param oldw Old width of this view.
7966     * @param oldh Old height of this view.
7967     */
7968    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7969    }
7970
7971    /**
7972     * Called by draw to draw the child views. This may be overridden
7973     * by derived classes to gain control just before its children are drawn
7974     * (but after its own view has been drawn).
7975     * @param canvas the canvas on which to draw the view
7976     */
7977    protected void dispatchDraw(Canvas canvas) {
7978
7979    }
7980
7981    /**
7982     * Gets the parent of this view. Note that the parent is a
7983     * ViewParent and not necessarily a View.
7984     *
7985     * @return Parent of this view.
7986     */
7987    public final ViewParent getParent() {
7988        return mParent;
7989    }
7990
7991    /**
7992     * Set the horizontal scrolled position of your view. This will cause a call to
7993     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7994     * invalidated.
7995     * @param value the x position to scroll to
7996     */
7997    public void setScrollX(int value) {
7998        scrollTo(value, mScrollY);
7999    }
8000
8001    /**
8002     * Set the vertical scrolled position of your view. This will cause a call to
8003     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8004     * invalidated.
8005     * @param value the y position to scroll to
8006     */
8007    public void setScrollY(int value) {
8008        scrollTo(mScrollX, value);
8009    }
8010
8011    /**
8012     * Return the scrolled left position of this view. This is the left edge of
8013     * the displayed part of your view. You do not need to draw any pixels
8014     * farther left, since those are outside of the frame of your view on
8015     * screen.
8016     *
8017     * @return The left edge of the displayed part of your view, in pixels.
8018     */
8019    public final int getScrollX() {
8020        return mScrollX;
8021    }
8022
8023    /**
8024     * Return the scrolled top position of this view. This is the top edge of
8025     * the displayed part of your view. You do not need to draw any pixels above
8026     * it, since those are outside of the frame of your view on screen.
8027     *
8028     * @return The top edge of the displayed part of your view, in pixels.
8029     */
8030    public final int getScrollY() {
8031        return mScrollY;
8032    }
8033
8034    /**
8035     * Return the width of the your view.
8036     *
8037     * @return The width of your view, in pixels.
8038     */
8039    @ViewDebug.ExportedProperty(category = "layout")
8040    public final int getWidth() {
8041        return mRight - mLeft;
8042    }
8043
8044    /**
8045     * Return the height of your view.
8046     *
8047     * @return The height of your view, in pixels.
8048     */
8049    @ViewDebug.ExportedProperty(category = "layout")
8050    public final int getHeight() {
8051        return mBottom - mTop;
8052    }
8053
8054    /**
8055     * Return the visible drawing bounds of your view. Fills in the output
8056     * rectangle with the values from getScrollX(), getScrollY(),
8057     * getWidth(), and getHeight().
8058     *
8059     * @param outRect The (scrolled) drawing bounds of the view.
8060     */
8061    public void getDrawingRect(Rect outRect) {
8062        outRect.left = mScrollX;
8063        outRect.top = mScrollY;
8064        outRect.right = mScrollX + (mRight - mLeft);
8065        outRect.bottom = mScrollY + (mBottom - mTop);
8066    }
8067
8068    /**
8069     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8070     * raw width component (that is the result is masked by
8071     * {@link #MEASURED_SIZE_MASK}).
8072     *
8073     * @return The raw measured width of this view.
8074     */
8075    public final int getMeasuredWidth() {
8076        return mMeasuredWidth & MEASURED_SIZE_MASK;
8077    }
8078
8079    /**
8080     * Return the full width measurement information for this view as computed
8081     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8082     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8083     * This should be used during measurement and layout calculations only. Use
8084     * {@link #getWidth()} to see how wide a view is after layout.
8085     *
8086     * @return The measured width of this view as a bit mask.
8087     */
8088    public final int getMeasuredWidthAndState() {
8089        return mMeasuredWidth;
8090    }
8091
8092    /**
8093     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8094     * raw width component (that is the result is masked by
8095     * {@link #MEASURED_SIZE_MASK}).
8096     *
8097     * @return The raw measured height of this view.
8098     */
8099    public final int getMeasuredHeight() {
8100        return mMeasuredHeight & MEASURED_SIZE_MASK;
8101    }
8102
8103    /**
8104     * Return the full height measurement information for this view as computed
8105     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8106     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8107     * This should be used during measurement and layout calculations only. Use
8108     * {@link #getHeight()} to see how wide a view is after layout.
8109     *
8110     * @return The measured width of this view as a bit mask.
8111     */
8112    public final int getMeasuredHeightAndState() {
8113        return mMeasuredHeight;
8114    }
8115
8116    /**
8117     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8118     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8119     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8120     * and the height component is at the shifted bits
8121     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8122     */
8123    public final int getMeasuredState() {
8124        return (mMeasuredWidth&MEASURED_STATE_MASK)
8125                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8126                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8127    }
8128
8129    /**
8130     * The transform matrix of this view, which is calculated based on the current
8131     * roation, scale, and pivot properties.
8132     *
8133     * @see #getRotation()
8134     * @see #getScaleX()
8135     * @see #getScaleY()
8136     * @see #getPivotX()
8137     * @see #getPivotY()
8138     * @return The current transform matrix for the view
8139     */
8140    public Matrix getMatrix() {
8141        if (mTransformationInfo != null) {
8142            updateMatrix();
8143            return mTransformationInfo.mMatrix;
8144        }
8145        return Matrix.IDENTITY_MATRIX;
8146    }
8147
8148    /**
8149     * Utility function to determine if the value is far enough away from zero to be
8150     * considered non-zero.
8151     * @param value A floating point value to check for zero-ness
8152     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8153     */
8154    private static boolean nonzero(float value) {
8155        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8156    }
8157
8158    /**
8159     * Returns true if the transform matrix is the identity matrix.
8160     * Recomputes the matrix if necessary.
8161     *
8162     * @return True if the transform matrix is the identity matrix, false otherwise.
8163     */
8164    final boolean hasIdentityMatrix() {
8165        if (mTransformationInfo != null) {
8166            updateMatrix();
8167            return mTransformationInfo.mMatrixIsIdentity;
8168        }
8169        return true;
8170    }
8171
8172    void ensureTransformationInfo() {
8173        if (mTransformationInfo == null) {
8174            mTransformationInfo = new TransformationInfo();
8175        }
8176    }
8177
8178    /**
8179     * Recomputes the transform matrix if necessary.
8180     */
8181    private void updateMatrix() {
8182        final TransformationInfo info = mTransformationInfo;
8183        if (info == null) {
8184            return;
8185        }
8186        if (info.mMatrixDirty) {
8187            // transform-related properties have changed since the last time someone
8188            // asked for the matrix; recalculate it with the current values
8189
8190            // Figure out if we need to update the pivot point
8191            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8192                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8193                    info.mPrevWidth = mRight - mLeft;
8194                    info.mPrevHeight = mBottom - mTop;
8195                    info.mPivotX = info.mPrevWidth / 2f;
8196                    info.mPivotY = info.mPrevHeight / 2f;
8197                }
8198            }
8199            info.mMatrix.reset();
8200            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8201                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8202                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8203                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8204            } else {
8205                if (info.mCamera == null) {
8206                    info.mCamera = new Camera();
8207                    info.matrix3D = new Matrix();
8208                }
8209                info.mCamera.save();
8210                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8211                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8212                info.mCamera.getMatrix(info.matrix3D);
8213                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8214                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8215                        info.mPivotY + info.mTranslationY);
8216                info.mMatrix.postConcat(info.matrix3D);
8217                info.mCamera.restore();
8218            }
8219            info.mMatrixDirty = false;
8220            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8221            info.mInverseMatrixDirty = true;
8222        }
8223    }
8224
8225    /**
8226     * Utility method to retrieve the inverse of the current mMatrix property.
8227     * We cache the matrix to avoid recalculating it when transform properties
8228     * have not changed.
8229     *
8230     * @return The inverse of the current matrix of this view.
8231     */
8232    final Matrix getInverseMatrix() {
8233        final TransformationInfo info = mTransformationInfo;
8234        if (info != null) {
8235            updateMatrix();
8236            if (info.mInverseMatrixDirty) {
8237                if (info.mInverseMatrix == null) {
8238                    info.mInverseMatrix = new Matrix();
8239                }
8240                info.mMatrix.invert(info.mInverseMatrix);
8241                info.mInverseMatrixDirty = false;
8242            }
8243            return info.mInverseMatrix;
8244        }
8245        return Matrix.IDENTITY_MATRIX;
8246    }
8247
8248    /**
8249     * Gets the distance along the Z axis from the camera to this view.
8250     *
8251     * @see #setCameraDistance(float)
8252     *
8253     * @return The distance along the Z axis.
8254     */
8255    public float getCameraDistance() {
8256        ensureTransformationInfo();
8257        final float dpi = mResources.getDisplayMetrics().densityDpi;
8258        final TransformationInfo info = mTransformationInfo;
8259        if (info.mCamera == null) {
8260            info.mCamera = new Camera();
8261            info.matrix3D = new Matrix();
8262        }
8263        return -(info.mCamera.getLocationZ() * dpi);
8264    }
8265
8266    /**
8267     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8268     * views are drawn) from the camera to this view. The camera's distance
8269     * affects 3D transformations, for instance rotations around the X and Y
8270     * axis. If the rotationX or rotationY properties are changed and this view is
8271     * large (more than half the size of the screen), it is recommended to always
8272     * use a camera distance that's greater than the height (X axis rotation) or
8273     * the width (Y axis rotation) of this view.</p>
8274     *
8275     * <p>The distance of the camera from the view plane can have an affect on the
8276     * perspective distortion of the view when it is rotated around the x or y axis.
8277     * For example, a large distance will result in a large viewing angle, and there
8278     * will not be much perspective distortion of the view as it rotates. A short
8279     * distance may cause much more perspective distortion upon rotation, and can
8280     * also result in some drawing artifacts if the rotated view ends up partially
8281     * behind the camera (which is why the recommendation is to use a distance at
8282     * least as far as the size of the view, if the view is to be rotated.)</p>
8283     *
8284     * <p>The distance is expressed in "depth pixels." The default distance depends
8285     * on the screen density. For instance, on a medium density display, the
8286     * default distance is 1280. On a high density display, the default distance
8287     * is 1920.</p>
8288     *
8289     * <p>If you want to specify a distance that leads to visually consistent
8290     * results across various densities, use the following formula:</p>
8291     * <pre>
8292     * float scale = context.getResources().getDisplayMetrics().density;
8293     * view.setCameraDistance(distance * scale);
8294     * </pre>
8295     *
8296     * <p>The density scale factor of a high density display is 1.5,
8297     * and 1920 = 1280 * 1.5.</p>
8298     *
8299     * @param distance The distance in "depth pixels", if negative the opposite
8300     *        value is used
8301     *
8302     * @see #setRotationX(float)
8303     * @see #setRotationY(float)
8304     */
8305    public void setCameraDistance(float distance) {
8306        invalidateViewProperty(true, false);
8307
8308        ensureTransformationInfo();
8309        final float dpi = mResources.getDisplayMetrics().densityDpi;
8310        final TransformationInfo info = mTransformationInfo;
8311        if (info.mCamera == null) {
8312            info.mCamera = new Camera();
8313            info.matrix3D = new Matrix();
8314        }
8315
8316        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8317        info.mMatrixDirty = true;
8318
8319        invalidateViewProperty(false, false);
8320        if (mDisplayList != null) {
8321            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8322        }
8323    }
8324
8325    /**
8326     * The degrees that the view is rotated around the pivot point.
8327     *
8328     * @see #setRotation(float)
8329     * @see #getPivotX()
8330     * @see #getPivotY()
8331     *
8332     * @return The degrees of rotation.
8333     */
8334    @ViewDebug.ExportedProperty(category = "drawing")
8335    public float getRotation() {
8336        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8337    }
8338
8339    /**
8340     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8341     * result in clockwise rotation.
8342     *
8343     * @param rotation The degrees of rotation.
8344     *
8345     * @see #getRotation()
8346     * @see #getPivotX()
8347     * @see #getPivotY()
8348     * @see #setRotationX(float)
8349     * @see #setRotationY(float)
8350     *
8351     * @attr ref android.R.styleable#View_rotation
8352     */
8353    public void setRotation(float rotation) {
8354        ensureTransformationInfo();
8355        final TransformationInfo info = mTransformationInfo;
8356        if (info.mRotation != rotation) {
8357            // Double-invalidation is necessary to capture view's old and new areas
8358            invalidateViewProperty(true, false);
8359            info.mRotation = rotation;
8360            info.mMatrixDirty = true;
8361            invalidateViewProperty(false, true);
8362            if (mDisplayList != null) {
8363                mDisplayList.setRotation(rotation);
8364            }
8365        }
8366    }
8367
8368    /**
8369     * The degrees that the view is rotated around the vertical axis through the pivot point.
8370     *
8371     * @see #getPivotX()
8372     * @see #getPivotY()
8373     * @see #setRotationY(float)
8374     *
8375     * @return The degrees of Y rotation.
8376     */
8377    @ViewDebug.ExportedProperty(category = "drawing")
8378    public float getRotationY() {
8379        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8380    }
8381
8382    /**
8383     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8384     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8385     * down the y axis.
8386     *
8387     * When rotating large views, it is recommended to adjust the camera distance
8388     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8389     *
8390     * @param rotationY The degrees of Y rotation.
8391     *
8392     * @see #getRotationY()
8393     * @see #getPivotX()
8394     * @see #getPivotY()
8395     * @see #setRotation(float)
8396     * @see #setRotationX(float)
8397     * @see #setCameraDistance(float)
8398     *
8399     * @attr ref android.R.styleable#View_rotationY
8400     */
8401    public void setRotationY(float rotationY) {
8402        ensureTransformationInfo();
8403        final TransformationInfo info = mTransformationInfo;
8404        if (info.mRotationY != rotationY) {
8405            invalidateViewProperty(true, false);
8406            info.mRotationY = rotationY;
8407            info.mMatrixDirty = true;
8408            invalidateViewProperty(false, true);
8409            if (mDisplayList != null) {
8410                mDisplayList.setRotationY(rotationY);
8411            }
8412        }
8413    }
8414
8415    /**
8416     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8417     *
8418     * @see #getPivotX()
8419     * @see #getPivotY()
8420     * @see #setRotationX(float)
8421     *
8422     * @return The degrees of X rotation.
8423     */
8424    @ViewDebug.ExportedProperty(category = "drawing")
8425    public float getRotationX() {
8426        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8427    }
8428
8429    /**
8430     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8431     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8432     * x axis.
8433     *
8434     * When rotating large views, it is recommended to adjust the camera distance
8435     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8436     *
8437     * @param rotationX The degrees of X rotation.
8438     *
8439     * @see #getRotationX()
8440     * @see #getPivotX()
8441     * @see #getPivotY()
8442     * @see #setRotation(float)
8443     * @see #setRotationY(float)
8444     * @see #setCameraDistance(float)
8445     *
8446     * @attr ref android.R.styleable#View_rotationX
8447     */
8448    public void setRotationX(float rotationX) {
8449        ensureTransformationInfo();
8450        final TransformationInfo info = mTransformationInfo;
8451        if (info.mRotationX != rotationX) {
8452            invalidateViewProperty(true, false);
8453            info.mRotationX = rotationX;
8454            info.mMatrixDirty = true;
8455            invalidateViewProperty(false, true);
8456            if (mDisplayList != null) {
8457                mDisplayList.setRotationX(rotationX);
8458            }
8459        }
8460    }
8461
8462    /**
8463     * The amount that the view is scaled in x around the pivot point, as a proportion of
8464     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8465     *
8466     * <p>By default, this is 1.0f.
8467     *
8468     * @see #getPivotX()
8469     * @see #getPivotY()
8470     * @return The scaling factor.
8471     */
8472    @ViewDebug.ExportedProperty(category = "drawing")
8473    public float getScaleX() {
8474        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8475    }
8476
8477    /**
8478     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8479     * the view's unscaled width. A value of 1 means that no scaling is applied.
8480     *
8481     * @param scaleX The scaling factor.
8482     * @see #getPivotX()
8483     * @see #getPivotY()
8484     *
8485     * @attr ref android.R.styleable#View_scaleX
8486     */
8487    public void setScaleX(float scaleX) {
8488        ensureTransformationInfo();
8489        final TransformationInfo info = mTransformationInfo;
8490        if (info.mScaleX != scaleX) {
8491            invalidateViewProperty(true, false);
8492            info.mScaleX = scaleX;
8493            info.mMatrixDirty = true;
8494            invalidateViewProperty(false, true);
8495            if (mDisplayList != null) {
8496                mDisplayList.setScaleX(scaleX);
8497            }
8498        }
8499    }
8500
8501    /**
8502     * The amount that the view is scaled in y around the pivot point, as a proportion of
8503     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8504     *
8505     * <p>By default, this is 1.0f.
8506     *
8507     * @see #getPivotX()
8508     * @see #getPivotY()
8509     * @return The scaling factor.
8510     */
8511    @ViewDebug.ExportedProperty(category = "drawing")
8512    public float getScaleY() {
8513        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8514    }
8515
8516    /**
8517     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8518     * the view's unscaled width. A value of 1 means that no scaling is applied.
8519     *
8520     * @param scaleY The scaling factor.
8521     * @see #getPivotX()
8522     * @see #getPivotY()
8523     *
8524     * @attr ref android.R.styleable#View_scaleY
8525     */
8526    public void setScaleY(float scaleY) {
8527        ensureTransformationInfo();
8528        final TransformationInfo info = mTransformationInfo;
8529        if (info.mScaleY != scaleY) {
8530            invalidateViewProperty(true, false);
8531            info.mScaleY = scaleY;
8532            info.mMatrixDirty = true;
8533            invalidateViewProperty(false, true);
8534            if (mDisplayList != null) {
8535                mDisplayList.setScaleY(scaleY);
8536            }
8537        }
8538    }
8539
8540    /**
8541     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8542     * and {@link #setScaleX(float) scaled}.
8543     *
8544     * @see #getRotation()
8545     * @see #getScaleX()
8546     * @see #getScaleY()
8547     * @see #getPivotY()
8548     * @return The x location of the pivot point.
8549     *
8550     * @attr ref android.R.styleable#View_transformPivotX
8551     */
8552    @ViewDebug.ExportedProperty(category = "drawing")
8553    public float getPivotX() {
8554        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8555    }
8556
8557    /**
8558     * Sets the x location of the point around which the view is
8559     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8560     * By default, the pivot point is centered on the object.
8561     * Setting this property disables this behavior and causes the view to use only the
8562     * explicitly set pivotX and pivotY values.
8563     *
8564     * @param pivotX The x location of the pivot point.
8565     * @see #getRotation()
8566     * @see #getScaleX()
8567     * @see #getScaleY()
8568     * @see #getPivotY()
8569     *
8570     * @attr ref android.R.styleable#View_transformPivotX
8571     */
8572    public void setPivotX(float pivotX) {
8573        ensureTransformationInfo();
8574        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8575        final TransformationInfo info = mTransformationInfo;
8576        if (info.mPivotX != pivotX) {
8577            invalidateViewProperty(true, false);
8578            info.mPivotX = pivotX;
8579            info.mMatrixDirty = true;
8580            invalidateViewProperty(false, true);
8581            if (mDisplayList != null) {
8582                mDisplayList.setPivotX(pivotX);
8583            }
8584        }
8585    }
8586
8587    /**
8588     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8589     * and {@link #setScaleY(float) scaled}.
8590     *
8591     * @see #getRotation()
8592     * @see #getScaleX()
8593     * @see #getScaleY()
8594     * @see #getPivotY()
8595     * @return The y location of the pivot point.
8596     *
8597     * @attr ref android.R.styleable#View_transformPivotY
8598     */
8599    @ViewDebug.ExportedProperty(category = "drawing")
8600    public float getPivotY() {
8601        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8602    }
8603
8604    /**
8605     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8606     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8607     * Setting this property disables this behavior and causes the view to use only the
8608     * explicitly set pivotX and pivotY values.
8609     *
8610     * @param pivotY The y location of the pivot point.
8611     * @see #getRotation()
8612     * @see #getScaleX()
8613     * @see #getScaleY()
8614     * @see #getPivotY()
8615     *
8616     * @attr ref android.R.styleable#View_transformPivotY
8617     */
8618    public void setPivotY(float pivotY) {
8619        ensureTransformationInfo();
8620        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8621        final TransformationInfo info = mTransformationInfo;
8622        if (info.mPivotY != pivotY) {
8623            invalidateViewProperty(true, false);
8624            info.mPivotY = pivotY;
8625            info.mMatrixDirty = true;
8626            invalidateViewProperty(false, true);
8627            if (mDisplayList != null) {
8628                mDisplayList.setPivotY(pivotY);
8629            }
8630        }
8631    }
8632
8633    /**
8634     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8635     * completely transparent and 1 means the view is completely opaque.
8636     *
8637     * <p>By default this is 1.0f.
8638     * @return The opacity of the view.
8639     */
8640    @ViewDebug.ExportedProperty(category = "drawing")
8641    public float getAlpha() {
8642        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8643    }
8644
8645    /**
8646     * Returns whether this View has content which overlaps. This function, intended to be
8647     * overridden by specific View types, is an optimization when alpha is set on a view. If
8648     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8649     * and then composited it into place, which can be expensive. If the view has no overlapping
8650     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8651     * An example of overlapping rendering is a TextView with a background image, such as a
8652     * Button. An example of non-overlapping rendering is a TextView with no background, or
8653     * an ImageView with only the foreground image. The default implementation returns true;
8654     * subclasses should override if they have cases which can be optimized.
8655     *
8656     * @return true if the content in this view might overlap, false otherwise.
8657     */
8658    public boolean hasOverlappingRendering() {
8659        return true;
8660    }
8661
8662    /**
8663     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8664     * completely transparent and 1 means the view is completely opaque.</p>
8665     *
8666     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8667     * responsible for applying the opacity itself. Otherwise, calling this method is
8668     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8669     * setting a hardware layer.</p>
8670     *
8671     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8672     * performance implications. It is generally best to use the alpha property sparingly and
8673     * transiently, as in the case of fading animations.</p>
8674     *
8675     * @param alpha The opacity of the view.
8676     *
8677     * @see #setLayerType(int, android.graphics.Paint)
8678     *
8679     * @attr ref android.R.styleable#View_alpha
8680     */
8681    public void setAlpha(float alpha) {
8682        ensureTransformationInfo();
8683        if (mTransformationInfo.mAlpha != alpha) {
8684            mTransformationInfo.mAlpha = alpha;
8685            if (onSetAlpha((int) (alpha * 255))) {
8686                mPrivateFlags |= ALPHA_SET;
8687                // subclass is handling alpha - don't optimize rendering cache invalidation
8688                invalidateParentCaches();
8689                invalidate(true);
8690            } else {
8691                mPrivateFlags &= ~ALPHA_SET;
8692                invalidateViewProperty(true, false);
8693                if (mDisplayList != null) {
8694                    mDisplayList.setAlpha(alpha);
8695                }
8696            }
8697        }
8698    }
8699
8700    /**
8701     * Faster version of setAlpha() which performs the same steps except there are
8702     * no calls to invalidate(). The caller of this function should perform proper invalidation
8703     * on the parent and this object. The return value indicates whether the subclass handles
8704     * alpha (the return value for onSetAlpha()).
8705     *
8706     * @param alpha The new value for the alpha property
8707     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
8708     *         the new value for the alpha property is different from the old value
8709     */
8710    boolean setAlphaNoInvalidation(float alpha) {
8711        ensureTransformationInfo();
8712        if (mTransformationInfo.mAlpha != alpha) {
8713            mTransformationInfo.mAlpha = alpha;
8714            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
8715            if (subclassHandlesAlpha) {
8716                mPrivateFlags |= ALPHA_SET;
8717                return true;
8718            } else {
8719                mPrivateFlags &= ~ALPHA_SET;
8720                if (mDisplayList != null) {
8721                    mDisplayList.setAlpha(alpha);
8722                }
8723            }
8724        }
8725        return false;
8726    }
8727
8728    /**
8729     * Top position of this view relative to its parent.
8730     *
8731     * @return The top of this view, in pixels.
8732     */
8733    @ViewDebug.CapturedViewProperty
8734    public final int getTop() {
8735        return mTop;
8736    }
8737
8738    /**
8739     * Sets the top position of this view relative to its parent. This method is meant to be called
8740     * by the layout system and should not generally be called otherwise, because the property
8741     * may be changed at any time by the layout.
8742     *
8743     * @param top The top of this view, in pixels.
8744     */
8745    public final void setTop(int top) {
8746        if (top != mTop) {
8747            updateMatrix();
8748            final boolean matrixIsIdentity = mTransformationInfo == null
8749                    || mTransformationInfo.mMatrixIsIdentity;
8750            if (matrixIsIdentity) {
8751                if (mAttachInfo != null) {
8752                    int minTop;
8753                    int yLoc;
8754                    if (top < mTop) {
8755                        minTop = top;
8756                        yLoc = top - mTop;
8757                    } else {
8758                        minTop = mTop;
8759                        yLoc = 0;
8760                    }
8761                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
8762                }
8763            } else {
8764                // Double-invalidation is necessary to capture view's old and new areas
8765                invalidate(true);
8766            }
8767
8768            int width = mRight - mLeft;
8769            int oldHeight = mBottom - mTop;
8770
8771            mTop = top;
8772            if (mDisplayList != null) {
8773                mDisplayList.setTop(mTop);
8774            }
8775
8776            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8777
8778            if (!matrixIsIdentity) {
8779                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8780                    // A change in dimension means an auto-centered pivot point changes, too
8781                    mTransformationInfo.mMatrixDirty = true;
8782                }
8783                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8784                invalidate(true);
8785            }
8786            mBackgroundSizeChanged = true;
8787            invalidateParentIfNeeded();
8788        }
8789    }
8790
8791    /**
8792     * Bottom position of this view relative to its parent.
8793     *
8794     * @return The bottom of this view, in pixels.
8795     */
8796    @ViewDebug.CapturedViewProperty
8797    public final int getBottom() {
8798        return mBottom;
8799    }
8800
8801    /**
8802     * True if this view has changed since the last time being drawn.
8803     *
8804     * @return The dirty state of this view.
8805     */
8806    public boolean isDirty() {
8807        return (mPrivateFlags & DIRTY_MASK) != 0;
8808    }
8809
8810    /**
8811     * Sets the bottom position of this view relative to its parent. This method is meant to be
8812     * called by the layout system and should not generally be called otherwise, because the
8813     * property may be changed at any time by the layout.
8814     *
8815     * @param bottom The bottom of this view, in pixels.
8816     */
8817    public final void setBottom(int bottom) {
8818        if (bottom != mBottom) {
8819            updateMatrix();
8820            final boolean matrixIsIdentity = mTransformationInfo == null
8821                    || mTransformationInfo.mMatrixIsIdentity;
8822            if (matrixIsIdentity) {
8823                if (mAttachInfo != null) {
8824                    int maxBottom;
8825                    if (bottom < mBottom) {
8826                        maxBottom = mBottom;
8827                    } else {
8828                        maxBottom = bottom;
8829                    }
8830                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
8831                }
8832            } else {
8833                // Double-invalidation is necessary to capture view's old and new areas
8834                invalidate(true);
8835            }
8836
8837            int width = mRight - mLeft;
8838            int oldHeight = mBottom - mTop;
8839
8840            mBottom = bottom;
8841            if (mDisplayList != null) {
8842                mDisplayList.setBottom(mBottom);
8843            }
8844
8845            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8846
8847            if (!matrixIsIdentity) {
8848                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8849                    // A change in dimension means an auto-centered pivot point changes, too
8850                    mTransformationInfo.mMatrixDirty = true;
8851                }
8852                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8853                invalidate(true);
8854            }
8855            mBackgroundSizeChanged = true;
8856            invalidateParentIfNeeded();
8857        }
8858    }
8859
8860    /**
8861     * Left position of this view relative to its parent.
8862     *
8863     * @return The left edge of this view, in pixels.
8864     */
8865    @ViewDebug.CapturedViewProperty
8866    public final int getLeft() {
8867        return mLeft;
8868    }
8869
8870    /**
8871     * Sets the left position of this view relative to its parent. This method is meant to be called
8872     * by the layout system and should not generally be called otherwise, because the property
8873     * may be changed at any time by the layout.
8874     *
8875     * @param left The bottom of this view, in pixels.
8876     */
8877    public final void setLeft(int left) {
8878        if (left != mLeft) {
8879            updateMatrix();
8880            final boolean matrixIsIdentity = mTransformationInfo == null
8881                    || mTransformationInfo.mMatrixIsIdentity;
8882            if (matrixIsIdentity) {
8883                if (mAttachInfo != null) {
8884                    int minLeft;
8885                    int xLoc;
8886                    if (left < mLeft) {
8887                        minLeft = left;
8888                        xLoc = left - mLeft;
8889                    } else {
8890                        minLeft = mLeft;
8891                        xLoc = 0;
8892                    }
8893                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
8894                }
8895            } else {
8896                // Double-invalidation is necessary to capture view's old and new areas
8897                invalidate(true);
8898            }
8899
8900            int oldWidth = mRight - mLeft;
8901            int height = mBottom - mTop;
8902
8903            mLeft = left;
8904            if (mDisplayList != null) {
8905                mDisplayList.setLeft(left);
8906            }
8907
8908            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8909
8910            if (!matrixIsIdentity) {
8911                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8912                    // A change in dimension means an auto-centered pivot point changes, too
8913                    mTransformationInfo.mMatrixDirty = true;
8914                }
8915                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8916                invalidate(true);
8917            }
8918            mBackgroundSizeChanged = true;
8919            invalidateParentIfNeeded();
8920        }
8921    }
8922
8923    /**
8924     * Right position of this view relative to its parent.
8925     *
8926     * @return The right edge of this view, in pixels.
8927     */
8928    @ViewDebug.CapturedViewProperty
8929    public final int getRight() {
8930        return mRight;
8931    }
8932
8933    /**
8934     * Sets the right position of this view relative to its parent. This method is meant to be called
8935     * by the layout system and should not generally be called otherwise, because the property
8936     * may be changed at any time by the layout.
8937     *
8938     * @param right The bottom of this view, in pixels.
8939     */
8940    public final void setRight(int right) {
8941        if (right != mRight) {
8942            updateMatrix();
8943            final boolean matrixIsIdentity = mTransformationInfo == null
8944                    || mTransformationInfo.mMatrixIsIdentity;
8945            if (matrixIsIdentity) {
8946                if (mAttachInfo != null) {
8947                    int maxRight;
8948                    if (right < mRight) {
8949                        maxRight = mRight;
8950                    } else {
8951                        maxRight = right;
8952                    }
8953                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
8954                }
8955            } else {
8956                // Double-invalidation is necessary to capture view's old and new areas
8957                invalidate(true);
8958            }
8959
8960            int oldWidth = mRight - mLeft;
8961            int height = mBottom - mTop;
8962
8963            mRight = right;
8964            if (mDisplayList != null) {
8965                mDisplayList.setRight(mRight);
8966            }
8967
8968            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8969
8970            if (!matrixIsIdentity) {
8971                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8972                    // A change in dimension means an auto-centered pivot point changes, too
8973                    mTransformationInfo.mMatrixDirty = true;
8974                }
8975                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8976                invalidate(true);
8977            }
8978            mBackgroundSizeChanged = true;
8979            invalidateParentIfNeeded();
8980        }
8981    }
8982
8983    /**
8984     * The visual x position of this view, in pixels. This is equivalent to the
8985     * {@link #setTranslationX(float) translationX} property plus the current
8986     * {@link #getLeft() left} property.
8987     *
8988     * @return The visual x position of this view, in pixels.
8989     */
8990    @ViewDebug.ExportedProperty(category = "drawing")
8991    public float getX() {
8992        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8993    }
8994
8995    /**
8996     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8997     * {@link #setTranslationX(float) translationX} property to be the difference between
8998     * the x value passed in and the current {@link #getLeft() left} property.
8999     *
9000     * @param x The visual x position of this view, in pixels.
9001     */
9002    public void setX(float x) {
9003        setTranslationX(x - mLeft);
9004    }
9005
9006    /**
9007     * The visual y position of this view, in pixels. This is equivalent to the
9008     * {@link #setTranslationY(float) translationY} property plus the current
9009     * {@link #getTop() top} property.
9010     *
9011     * @return The visual y position of this view, in pixels.
9012     */
9013    @ViewDebug.ExportedProperty(category = "drawing")
9014    public float getY() {
9015        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9016    }
9017
9018    /**
9019     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9020     * {@link #setTranslationY(float) translationY} property to be the difference between
9021     * the y value passed in and the current {@link #getTop() top} property.
9022     *
9023     * @param y The visual y position of this view, in pixels.
9024     */
9025    public void setY(float y) {
9026        setTranslationY(y - mTop);
9027    }
9028
9029
9030    /**
9031     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9032     * This position is post-layout, in addition to wherever the object's
9033     * layout placed it.
9034     *
9035     * @return The horizontal position of this view relative to its left position, in pixels.
9036     */
9037    @ViewDebug.ExportedProperty(category = "drawing")
9038    public float getTranslationX() {
9039        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9040    }
9041
9042    /**
9043     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9044     * This effectively positions the object post-layout, in addition to wherever the object's
9045     * layout placed it.
9046     *
9047     * @param translationX The horizontal position of this view relative to its left position,
9048     * in pixels.
9049     *
9050     * @attr ref android.R.styleable#View_translationX
9051     */
9052    public void setTranslationX(float translationX) {
9053        ensureTransformationInfo();
9054        final TransformationInfo info = mTransformationInfo;
9055        if (info.mTranslationX != translationX) {
9056            // Double-invalidation is necessary to capture view's old and new areas
9057            invalidateViewProperty(true, false);
9058            info.mTranslationX = translationX;
9059            info.mMatrixDirty = true;
9060            invalidateViewProperty(false, true);
9061            if (mDisplayList != null) {
9062                mDisplayList.setTranslationX(translationX);
9063            }
9064        }
9065    }
9066
9067    /**
9068     * The horizontal location of this view relative to its {@link #getTop() top} position.
9069     * This position is post-layout, in addition to wherever the object's
9070     * layout placed it.
9071     *
9072     * @return The vertical position of this view relative to its top position,
9073     * in pixels.
9074     */
9075    @ViewDebug.ExportedProperty(category = "drawing")
9076    public float getTranslationY() {
9077        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9078    }
9079
9080    /**
9081     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9082     * This effectively positions the object post-layout, in addition to wherever the object's
9083     * layout placed it.
9084     *
9085     * @param translationY The vertical position of this view relative to its top position,
9086     * in pixels.
9087     *
9088     * @attr ref android.R.styleable#View_translationY
9089     */
9090    public void setTranslationY(float translationY) {
9091        ensureTransformationInfo();
9092        final TransformationInfo info = mTransformationInfo;
9093        if (info.mTranslationY != translationY) {
9094            invalidateViewProperty(true, false);
9095            info.mTranslationY = translationY;
9096            info.mMatrixDirty = true;
9097            invalidateViewProperty(false, true);
9098            if (mDisplayList != null) {
9099                mDisplayList.setTranslationY(translationY);
9100            }
9101        }
9102    }
9103
9104    /**
9105     * Hit rectangle in parent's coordinates
9106     *
9107     * @param outRect The hit rectangle of the view.
9108     */
9109    public void getHitRect(Rect outRect) {
9110        updateMatrix();
9111        final TransformationInfo info = mTransformationInfo;
9112        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9113            outRect.set(mLeft, mTop, mRight, mBottom);
9114        } else {
9115            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9116            tmpRect.set(-info.mPivotX, -info.mPivotY,
9117                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9118            info.mMatrix.mapRect(tmpRect);
9119            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9120                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9121        }
9122    }
9123
9124    /**
9125     * Determines whether the given point, in local coordinates is inside the view.
9126     */
9127    /*package*/ final boolean pointInView(float localX, float localY) {
9128        return localX >= 0 && localX < (mRight - mLeft)
9129                && localY >= 0 && localY < (mBottom - mTop);
9130    }
9131
9132    /**
9133     * Utility method to determine whether the given point, in local coordinates,
9134     * is inside the view, where the area of the view is expanded by the slop factor.
9135     * This method is called while processing touch-move events to determine if the event
9136     * is still within the view.
9137     */
9138    private boolean pointInView(float localX, float localY, float slop) {
9139        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9140                localY < ((mBottom - mTop) + slop);
9141    }
9142
9143    /**
9144     * When a view has focus and the user navigates away from it, the next view is searched for
9145     * starting from the rectangle filled in by this method.
9146     *
9147     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9148     * of the view.  However, if your view maintains some idea of internal selection,
9149     * such as a cursor, or a selected row or column, you should override this method and
9150     * fill in a more specific rectangle.
9151     *
9152     * @param r The rectangle to fill in, in this view's coordinates.
9153     */
9154    public void getFocusedRect(Rect r) {
9155        getDrawingRect(r);
9156    }
9157
9158    /**
9159     * If some part of this view is not clipped by any of its parents, then
9160     * return that area in r in global (root) coordinates. To convert r to local
9161     * coordinates (without taking possible View rotations into account), offset
9162     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9163     * If the view is completely clipped or translated out, return false.
9164     *
9165     * @param r If true is returned, r holds the global coordinates of the
9166     *        visible portion of this view.
9167     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9168     *        between this view and its root. globalOffet may be null.
9169     * @return true if r is non-empty (i.e. part of the view is visible at the
9170     *         root level.
9171     */
9172    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9173        int width = mRight - mLeft;
9174        int height = mBottom - mTop;
9175        if (width > 0 && height > 0) {
9176            r.set(0, 0, width, height);
9177            if (globalOffset != null) {
9178                globalOffset.set(-mScrollX, -mScrollY);
9179            }
9180            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9181        }
9182        return false;
9183    }
9184
9185    public final boolean getGlobalVisibleRect(Rect r) {
9186        return getGlobalVisibleRect(r, null);
9187    }
9188
9189    public final boolean getLocalVisibleRect(Rect r) {
9190        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9191        if (getGlobalVisibleRect(r, offset)) {
9192            r.offset(-offset.x, -offset.y); // make r local
9193            return true;
9194        }
9195        return false;
9196    }
9197
9198    /**
9199     * Offset this view's vertical location by the specified number of pixels.
9200     *
9201     * @param offset the number of pixels to offset the view by
9202     */
9203    public void offsetTopAndBottom(int offset) {
9204        if (offset != 0) {
9205            updateMatrix();
9206            final boolean matrixIsIdentity = mTransformationInfo == null
9207                    || mTransformationInfo.mMatrixIsIdentity;
9208            if (matrixIsIdentity) {
9209                if (mDisplayList != null) {
9210                    invalidateViewProperty(false, false);
9211                } else {
9212                    final ViewParent p = mParent;
9213                    if (p != null && mAttachInfo != null) {
9214                        final Rect r = mAttachInfo.mTmpInvalRect;
9215                        int minTop;
9216                        int maxBottom;
9217                        int yLoc;
9218                        if (offset < 0) {
9219                            minTop = mTop + offset;
9220                            maxBottom = mBottom;
9221                            yLoc = offset;
9222                        } else {
9223                            minTop = mTop;
9224                            maxBottom = mBottom + offset;
9225                            yLoc = 0;
9226                        }
9227                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9228                        p.invalidateChild(this, r);
9229                    }
9230                }
9231            } else {
9232                invalidateViewProperty(false, false);
9233            }
9234
9235            mTop += offset;
9236            mBottom += offset;
9237            if (mDisplayList != null) {
9238                mDisplayList.offsetTopBottom(offset);
9239                invalidateViewProperty(false, false);
9240            } else {
9241                if (!matrixIsIdentity) {
9242                    invalidateViewProperty(false, true);
9243                }
9244                invalidateParentIfNeeded();
9245            }
9246        }
9247    }
9248
9249    /**
9250     * Offset this view's horizontal location by the specified amount of pixels.
9251     *
9252     * @param offset the numer of pixels to offset the view by
9253     */
9254    public void offsetLeftAndRight(int offset) {
9255        if (offset != 0) {
9256            updateMatrix();
9257            final boolean matrixIsIdentity = mTransformationInfo == null
9258                    || mTransformationInfo.mMatrixIsIdentity;
9259            if (matrixIsIdentity) {
9260                if (mDisplayList != null) {
9261                    invalidateViewProperty(false, false);
9262                } else {
9263                    final ViewParent p = mParent;
9264                    if (p != null && mAttachInfo != null) {
9265                        final Rect r = mAttachInfo.mTmpInvalRect;
9266                        int minLeft;
9267                        int maxRight;
9268                        if (offset < 0) {
9269                            minLeft = mLeft + offset;
9270                            maxRight = mRight;
9271                        } else {
9272                            minLeft = mLeft;
9273                            maxRight = mRight + offset;
9274                        }
9275                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9276                        p.invalidateChild(this, r);
9277                    }
9278                }
9279            } else {
9280                invalidateViewProperty(false, false);
9281            }
9282
9283            mLeft += offset;
9284            mRight += offset;
9285            if (mDisplayList != null) {
9286                mDisplayList.offsetLeftRight(offset);
9287                invalidateViewProperty(false, false);
9288            } else {
9289                if (!matrixIsIdentity) {
9290                    invalidateViewProperty(false, true);
9291                }
9292                invalidateParentIfNeeded();
9293            }
9294        }
9295    }
9296
9297    /**
9298     * Get the LayoutParams associated with this view. All views should have
9299     * layout parameters. These supply parameters to the <i>parent</i> of this
9300     * view specifying how it should be arranged. There are many subclasses of
9301     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9302     * of ViewGroup that are responsible for arranging their children.
9303     *
9304     * This method may return null if this View is not attached to a parent
9305     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9306     * was not invoked successfully. When a View is attached to a parent
9307     * ViewGroup, this method must not return null.
9308     *
9309     * @return The LayoutParams associated with this view, or null if no
9310     *         parameters have been set yet
9311     */
9312    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9313    public ViewGroup.LayoutParams getLayoutParams() {
9314        return mLayoutParams;
9315    }
9316
9317    /**
9318     * Set the layout parameters associated with this view. These supply
9319     * parameters to the <i>parent</i> of this view specifying how it should be
9320     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9321     * correspond to the different subclasses of ViewGroup that are responsible
9322     * for arranging their children.
9323     *
9324     * @param params The layout parameters for this view, cannot be null
9325     */
9326    public void setLayoutParams(ViewGroup.LayoutParams params) {
9327        if (params == null) {
9328            throw new NullPointerException("Layout parameters cannot be null");
9329        }
9330        mLayoutParams = params;
9331        if (mParent instanceof ViewGroup) {
9332            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9333        }
9334        requestLayout();
9335    }
9336
9337    /**
9338     * Set the scrolled position of your view. This will cause a call to
9339     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9340     * invalidated.
9341     * @param x the x position to scroll to
9342     * @param y the y position to scroll to
9343     */
9344    public void scrollTo(int x, int y) {
9345        if (mScrollX != x || mScrollY != y) {
9346            int oldX = mScrollX;
9347            int oldY = mScrollY;
9348            mScrollX = x;
9349            mScrollY = y;
9350            invalidateParentCaches();
9351            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9352            if (!awakenScrollBars()) {
9353                postInvalidateOnAnimation();
9354            }
9355        }
9356    }
9357
9358    /**
9359     * Move the scrolled position of your view. This will cause a call to
9360     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9361     * invalidated.
9362     * @param x the amount of pixels to scroll by horizontally
9363     * @param y the amount of pixels to scroll by vertically
9364     */
9365    public void scrollBy(int x, int y) {
9366        scrollTo(mScrollX + x, mScrollY + y);
9367    }
9368
9369    /**
9370     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9371     * animation to fade the scrollbars out after a default delay. If a subclass
9372     * provides animated scrolling, the start delay should equal the duration
9373     * of the scrolling animation.</p>
9374     *
9375     * <p>The animation starts only if at least one of the scrollbars is
9376     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9377     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9378     * this method returns true, and false otherwise. If the animation is
9379     * started, this method calls {@link #invalidate()}; in that case the
9380     * caller should not call {@link #invalidate()}.</p>
9381     *
9382     * <p>This method should be invoked every time a subclass directly updates
9383     * the scroll parameters.</p>
9384     *
9385     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9386     * and {@link #scrollTo(int, int)}.</p>
9387     *
9388     * @return true if the animation is played, false otherwise
9389     *
9390     * @see #awakenScrollBars(int)
9391     * @see #scrollBy(int, int)
9392     * @see #scrollTo(int, int)
9393     * @see #isHorizontalScrollBarEnabled()
9394     * @see #isVerticalScrollBarEnabled()
9395     * @see #setHorizontalScrollBarEnabled(boolean)
9396     * @see #setVerticalScrollBarEnabled(boolean)
9397     */
9398    protected boolean awakenScrollBars() {
9399        return mScrollCache != null &&
9400                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9401    }
9402
9403    /**
9404     * Trigger the scrollbars to draw.
9405     * This method differs from awakenScrollBars() only in its default duration.
9406     * initialAwakenScrollBars() will show the scroll bars for longer than
9407     * usual to give the user more of a chance to notice them.
9408     *
9409     * @return true if the animation is played, false otherwise.
9410     */
9411    private boolean initialAwakenScrollBars() {
9412        return mScrollCache != null &&
9413                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9414    }
9415
9416    /**
9417     * <p>
9418     * Trigger the scrollbars to draw. When invoked this method starts an
9419     * animation to fade the scrollbars out after a fixed delay. If a subclass
9420     * provides animated scrolling, the start delay should equal the duration of
9421     * the scrolling animation.
9422     * </p>
9423     *
9424     * <p>
9425     * The animation starts only if at least one of the scrollbars is enabled,
9426     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9427     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9428     * this method returns true, and false otherwise. If the animation is
9429     * started, this method calls {@link #invalidate()}; in that case the caller
9430     * should not call {@link #invalidate()}.
9431     * </p>
9432     *
9433     * <p>
9434     * This method should be invoked everytime a subclass directly updates the
9435     * scroll parameters.
9436     * </p>
9437     *
9438     * @param startDelay the delay, in milliseconds, after which the animation
9439     *        should start; when the delay is 0, the animation starts
9440     *        immediately
9441     * @return true if the animation is played, false otherwise
9442     *
9443     * @see #scrollBy(int, int)
9444     * @see #scrollTo(int, int)
9445     * @see #isHorizontalScrollBarEnabled()
9446     * @see #isVerticalScrollBarEnabled()
9447     * @see #setHorizontalScrollBarEnabled(boolean)
9448     * @see #setVerticalScrollBarEnabled(boolean)
9449     */
9450    protected boolean awakenScrollBars(int startDelay) {
9451        return awakenScrollBars(startDelay, true);
9452    }
9453
9454    /**
9455     * <p>
9456     * Trigger the scrollbars to draw. When invoked this method starts an
9457     * animation to fade the scrollbars out after a fixed delay. If a subclass
9458     * provides animated scrolling, the start delay should equal the duration of
9459     * the scrolling animation.
9460     * </p>
9461     *
9462     * <p>
9463     * The animation starts only if at least one of the scrollbars is enabled,
9464     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9465     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9466     * this method returns true, and false otherwise. If the animation is
9467     * started, this method calls {@link #invalidate()} if the invalidate parameter
9468     * is set to true; in that case the caller
9469     * should not call {@link #invalidate()}.
9470     * </p>
9471     *
9472     * <p>
9473     * This method should be invoked everytime a subclass directly updates the
9474     * scroll parameters.
9475     * </p>
9476     *
9477     * @param startDelay the delay, in milliseconds, after which the animation
9478     *        should start; when the delay is 0, the animation starts
9479     *        immediately
9480     *
9481     * @param invalidate Wheter this method should call invalidate
9482     *
9483     * @return true if the animation is played, false otherwise
9484     *
9485     * @see #scrollBy(int, int)
9486     * @see #scrollTo(int, int)
9487     * @see #isHorizontalScrollBarEnabled()
9488     * @see #isVerticalScrollBarEnabled()
9489     * @see #setHorizontalScrollBarEnabled(boolean)
9490     * @see #setVerticalScrollBarEnabled(boolean)
9491     */
9492    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9493        final ScrollabilityCache scrollCache = mScrollCache;
9494
9495        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9496            return false;
9497        }
9498
9499        if (scrollCache.scrollBar == null) {
9500            scrollCache.scrollBar = new ScrollBarDrawable();
9501        }
9502
9503        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9504
9505            if (invalidate) {
9506                // Invalidate to show the scrollbars
9507                postInvalidateOnAnimation();
9508            }
9509
9510            if (scrollCache.state == ScrollabilityCache.OFF) {
9511                // FIXME: this is copied from WindowManagerService.
9512                // We should get this value from the system when it
9513                // is possible to do so.
9514                final int KEY_REPEAT_FIRST_DELAY = 750;
9515                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9516            }
9517
9518            // Tell mScrollCache when we should start fading. This may
9519            // extend the fade start time if one was already scheduled
9520            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9521            scrollCache.fadeStartTime = fadeStartTime;
9522            scrollCache.state = ScrollabilityCache.ON;
9523
9524            // Schedule our fader to run, unscheduling any old ones first
9525            if (mAttachInfo != null) {
9526                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9527                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9528            }
9529
9530            return true;
9531        }
9532
9533        return false;
9534    }
9535
9536    /**
9537     * Do not invalidate views which are not visible and which are not running an animation. They
9538     * will not get drawn and they should not set dirty flags as if they will be drawn
9539     */
9540    private boolean skipInvalidate() {
9541        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9542                (!(mParent instanceof ViewGroup) ||
9543                        !((ViewGroup) mParent).isViewTransitioning(this));
9544    }
9545    /**
9546     * Mark the area defined by dirty as needing to be drawn. If the view is
9547     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9548     * in the future. This must be called from a UI thread. To call from a non-UI
9549     * thread, call {@link #postInvalidate()}.
9550     *
9551     * WARNING: This method is destructive to dirty.
9552     * @param dirty the rectangle representing the bounds of the dirty region
9553     */
9554    public void invalidate(Rect dirty) {
9555        if (ViewDebug.TRACE_HIERARCHY) {
9556            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9557        }
9558
9559        if (skipInvalidate()) {
9560            return;
9561        }
9562        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9563                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9564                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9565            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9566            mPrivateFlags |= INVALIDATED;
9567            mPrivateFlags |= DIRTY;
9568            final ViewParent p = mParent;
9569            final AttachInfo ai = mAttachInfo;
9570            //noinspection PointlessBooleanExpression,ConstantConditions
9571            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9572                if (p != null && ai != null && ai.mHardwareAccelerated) {
9573                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9574                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9575                    p.invalidateChild(this, null);
9576                    return;
9577                }
9578            }
9579            if (p != null && ai != null) {
9580                final int scrollX = mScrollX;
9581                final int scrollY = mScrollY;
9582                final Rect r = ai.mTmpInvalRect;
9583                r.set(dirty.left - scrollX, dirty.top - scrollY,
9584                        dirty.right - scrollX, dirty.bottom - scrollY);
9585                mParent.invalidateChild(this, r);
9586            }
9587        }
9588    }
9589
9590    /**
9591     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9592     * The coordinates of the dirty rect are relative to the view.
9593     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9594     * will be called at some point in the future. This must be called from
9595     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9596     * @param l the left position of the dirty region
9597     * @param t the top position of the dirty region
9598     * @param r the right position of the dirty region
9599     * @param b the bottom position of the dirty region
9600     */
9601    public void invalidate(int l, int t, int r, int b) {
9602        if (ViewDebug.TRACE_HIERARCHY) {
9603            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9604        }
9605
9606        if (skipInvalidate()) {
9607            return;
9608        }
9609        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9610                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9611                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9612            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9613            mPrivateFlags |= INVALIDATED;
9614            mPrivateFlags |= DIRTY;
9615            final ViewParent p = mParent;
9616            final AttachInfo ai = mAttachInfo;
9617            //noinspection PointlessBooleanExpression,ConstantConditions
9618            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9619                if (p != null && ai != null && ai.mHardwareAccelerated) {
9620                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9621                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9622                    p.invalidateChild(this, null);
9623                    return;
9624                }
9625            }
9626            if (p != null && ai != null && l < r && t < b) {
9627                final int scrollX = mScrollX;
9628                final int scrollY = mScrollY;
9629                final Rect tmpr = ai.mTmpInvalRect;
9630                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9631                p.invalidateChild(this, tmpr);
9632            }
9633        }
9634    }
9635
9636    /**
9637     * Invalidate the whole view. If the view is visible,
9638     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9639     * the future. This must be called from a UI thread. To call from a non-UI thread,
9640     * call {@link #postInvalidate()}.
9641     */
9642    public void invalidate() {
9643        invalidate(true);
9644    }
9645
9646    /**
9647     * This is where the invalidate() work actually happens. A full invalidate()
9648     * causes the drawing cache to be invalidated, but this function can be called with
9649     * invalidateCache set to false to skip that invalidation step for cases that do not
9650     * need it (for example, a component that remains at the same dimensions with the same
9651     * content).
9652     *
9653     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9654     * well. This is usually true for a full invalidate, but may be set to false if the
9655     * View's contents or dimensions have not changed.
9656     */
9657    void invalidate(boolean invalidateCache) {
9658        if (ViewDebug.TRACE_HIERARCHY) {
9659            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9660        }
9661
9662        if (skipInvalidate()) {
9663            return;
9664        }
9665        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9666                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9667                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9668            mLastIsOpaque = isOpaque();
9669            mPrivateFlags &= ~DRAWN;
9670            mPrivateFlags |= DIRTY;
9671            if (invalidateCache) {
9672                mPrivateFlags |= INVALIDATED;
9673                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9674            }
9675            final AttachInfo ai = mAttachInfo;
9676            final ViewParent p = mParent;
9677            //noinspection PointlessBooleanExpression,ConstantConditions
9678            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9679                if (p != null && ai != null && ai.mHardwareAccelerated) {
9680                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9681                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9682                    p.invalidateChild(this, null);
9683                    return;
9684                }
9685            }
9686
9687            if (p != null && ai != null) {
9688                final Rect r = ai.mTmpInvalRect;
9689                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9690                // Don't call invalidate -- we don't want to internally scroll
9691                // our own bounds
9692                p.invalidateChild(this, r);
9693            }
9694        }
9695    }
9696
9697    /**
9698     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
9699     * set any flags or handle all of the cases handled by the default invalidation methods.
9700     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
9701     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
9702     * walk up the hierarchy, transforming the dirty rect as necessary.
9703     *
9704     * The method also handles normal invalidation logic if display list properties are not
9705     * being used in this view. The invalidateParent and forceRedraw flags are used by that
9706     * backup approach, to handle these cases used in the various property-setting methods.
9707     *
9708     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
9709     * are not being used in this view
9710     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
9711     * list properties are not being used in this view
9712     */
9713    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
9714        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
9715            if (invalidateParent) {
9716                invalidateParentCaches();
9717            }
9718            if (forceRedraw) {
9719                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9720            }
9721            invalidate(false);
9722        } else {
9723            final AttachInfo ai = mAttachInfo;
9724            final ViewParent p = mParent;
9725            if (p != null && ai != null) {
9726                final Rect r = ai.mTmpInvalRect;
9727                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9728                if (mParent instanceof ViewGroup) {
9729                    ((ViewGroup) mParent).invalidateChildFast(this, r);
9730                } else {
9731                    mParent.invalidateChild(this, r);
9732                }
9733            }
9734        }
9735    }
9736
9737    /**
9738     * Utility method to transform a given Rect by the current matrix of this view.
9739     */
9740    void transformRect(final Rect rect) {
9741        if (!getMatrix().isIdentity()) {
9742            RectF boundingRect = mAttachInfo.mTmpTransformRect;
9743            boundingRect.set(rect);
9744            getMatrix().mapRect(boundingRect);
9745            rect.set((int) (boundingRect.left - 0.5f),
9746                    (int) (boundingRect.top - 0.5f),
9747                    (int) (boundingRect.right + 0.5f),
9748                    (int) (boundingRect.bottom + 0.5f));
9749        }
9750    }
9751
9752    /**
9753     * Used to indicate that the parent of this view should clear its caches. This functionality
9754     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9755     * which is necessary when various parent-managed properties of the view change, such as
9756     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
9757     * clears the parent caches and does not causes an invalidate event.
9758     *
9759     * @hide
9760     */
9761    protected void invalidateParentCaches() {
9762        if (mParent instanceof View) {
9763            ((View) mParent).mPrivateFlags |= INVALIDATED;
9764        }
9765    }
9766
9767    /**
9768     * Used to indicate that the parent of this view should be invalidated. This functionality
9769     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9770     * which is necessary when various parent-managed properties of the view change, such as
9771     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
9772     * an invalidation event to the parent.
9773     *
9774     * @hide
9775     */
9776    protected void invalidateParentIfNeeded() {
9777        if (isHardwareAccelerated() && mParent instanceof View) {
9778            ((View) mParent).invalidate(true);
9779        }
9780    }
9781
9782    /**
9783     * Indicates whether this View is opaque. An opaque View guarantees that it will
9784     * draw all the pixels overlapping its bounds using a fully opaque color.
9785     *
9786     * Subclasses of View should override this method whenever possible to indicate
9787     * whether an instance is opaque. Opaque Views are treated in a special way by
9788     * the View hierarchy, possibly allowing it to perform optimizations during
9789     * invalidate/draw passes.
9790     *
9791     * @return True if this View is guaranteed to be fully opaque, false otherwise.
9792     */
9793    @ViewDebug.ExportedProperty(category = "drawing")
9794    public boolean isOpaque() {
9795        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
9796                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
9797                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
9798    }
9799
9800    /**
9801     * @hide
9802     */
9803    protected void computeOpaqueFlags() {
9804        // Opaque if:
9805        //   - Has a background
9806        //   - Background is opaque
9807        //   - Doesn't have scrollbars or scrollbars are inside overlay
9808
9809        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
9810            mPrivateFlags |= OPAQUE_BACKGROUND;
9811        } else {
9812            mPrivateFlags &= ~OPAQUE_BACKGROUND;
9813        }
9814
9815        final int flags = mViewFlags;
9816        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
9817                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
9818            mPrivateFlags |= OPAQUE_SCROLLBARS;
9819        } else {
9820            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
9821        }
9822    }
9823
9824    /**
9825     * @hide
9826     */
9827    protected boolean hasOpaqueScrollbars() {
9828        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
9829    }
9830
9831    /**
9832     * @return A handler associated with the thread running the View. This
9833     * handler can be used to pump events in the UI events queue.
9834     */
9835    public Handler getHandler() {
9836        if (mAttachInfo != null) {
9837            return mAttachInfo.mHandler;
9838        }
9839        return null;
9840    }
9841
9842    /**
9843     * Gets the view root associated with the View.
9844     * @return The view root, or null if none.
9845     * @hide
9846     */
9847    public ViewRootImpl getViewRootImpl() {
9848        if (mAttachInfo != null) {
9849            return mAttachInfo.mViewRootImpl;
9850        }
9851        return null;
9852    }
9853
9854    /**
9855     * <p>Causes the Runnable to be added to the message queue.
9856     * The runnable will be run on the user interface thread.</p>
9857     *
9858     * <p>This method can be invoked from outside of the UI thread
9859     * only when this View is attached to a window.</p>
9860     *
9861     * @param action The Runnable that will be executed.
9862     *
9863     * @return Returns true if the Runnable was successfully placed in to the
9864     *         message queue.  Returns false on failure, usually because the
9865     *         looper processing the message queue is exiting.
9866     *
9867     * @see #postDelayed
9868     * @see #removeCallbacks
9869     */
9870    public boolean post(Runnable action) {
9871        final AttachInfo attachInfo = mAttachInfo;
9872        if (attachInfo != null) {
9873            return attachInfo.mHandler.post(action);
9874        }
9875        // Assume that post will succeed later
9876        ViewRootImpl.getRunQueue().post(action);
9877        return true;
9878    }
9879
9880    /**
9881     * <p>Causes the Runnable to be added to the message queue, to be run
9882     * after the specified amount of time elapses.
9883     * The runnable will be run on the user interface thread.</p>
9884     *
9885     * <p>This method can be invoked from outside of the UI thread
9886     * only when this View is attached to a window.</p>
9887     *
9888     * @param action The Runnable that will be executed.
9889     * @param delayMillis The delay (in milliseconds) until the Runnable
9890     *        will be executed.
9891     *
9892     * @return true if the Runnable was successfully placed in to the
9893     *         message queue.  Returns false on failure, usually because the
9894     *         looper processing the message queue is exiting.  Note that a
9895     *         result of true does not mean the Runnable will be processed --
9896     *         if the looper is quit before the delivery time of the message
9897     *         occurs then the message will be dropped.
9898     *
9899     * @see #post
9900     * @see #removeCallbacks
9901     */
9902    public boolean postDelayed(Runnable action, long delayMillis) {
9903        final AttachInfo attachInfo = mAttachInfo;
9904        if (attachInfo != null) {
9905            return attachInfo.mHandler.postDelayed(action, delayMillis);
9906        }
9907        // Assume that post will succeed later
9908        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9909        return true;
9910    }
9911
9912    /**
9913     * <p>Causes the Runnable to execute on the next animation time step.
9914     * The runnable will be run on the user interface thread.</p>
9915     *
9916     * <p>This method can be invoked from outside of the UI thread
9917     * only when this View is attached to a window.</p>
9918     *
9919     * @param action The Runnable that will be executed.
9920     *
9921     * @see #postOnAnimationDelayed
9922     * @see #removeCallbacks
9923     */
9924    public void postOnAnimation(Runnable action) {
9925        final AttachInfo attachInfo = mAttachInfo;
9926        if (attachInfo != null) {
9927            attachInfo.mViewRootImpl.mChoreographer.postCallback(
9928                    Choreographer.CALLBACK_ANIMATION, action, null);
9929        } else {
9930            // Assume that post will succeed later
9931            ViewRootImpl.getRunQueue().post(action);
9932        }
9933    }
9934
9935    /**
9936     * <p>Causes the Runnable to execute on the next animation time step,
9937     * after the specified amount of time elapses.
9938     * The runnable will be run on the user interface thread.</p>
9939     *
9940     * <p>This method can be invoked from outside of the UI thread
9941     * only when this View is attached to a window.</p>
9942     *
9943     * @param action The Runnable that will be executed.
9944     * @param delayMillis The delay (in milliseconds) until the Runnable
9945     *        will be executed.
9946     *
9947     * @see #postOnAnimation
9948     * @see #removeCallbacks
9949     */
9950    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
9951        final AttachInfo attachInfo = mAttachInfo;
9952        if (attachInfo != null) {
9953            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
9954                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
9955        } else {
9956            // Assume that post will succeed later
9957            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9958        }
9959    }
9960
9961    /**
9962     * <p>Removes the specified Runnable from the message queue.</p>
9963     *
9964     * <p>This method can be invoked from outside of the UI thread
9965     * only when this View is attached to a window.</p>
9966     *
9967     * @param action The Runnable to remove from the message handling queue
9968     *
9969     * @return true if this view could ask the Handler to remove the Runnable,
9970     *         false otherwise. When the returned value is true, the Runnable
9971     *         may or may not have been actually removed from the message queue
9972     *         (for instance, if the Runnable was not in the queue already.)
9973     *
9974     * @see #post
9975     * @see #postDelayed
9976     * @see #postOnAnimation
9977     * @see #postOnAnimationDelayed
9978     */
9979    public boolean removeCallbacks(Runnable action) {
9980        if (action != null) {
9981            final AttachInfo attachInfo = mAttachInfo;
9982            if (attachInfo != null) {
9983                attachInfo.mHandler.removeCallbacks(action);
9984                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
9985                        Choreographer.CALLBACK_ANIMATION, action, null);
9986            } else {
9987                // Assume that post will succeed later
9988                ViewRootImpl.getRunQueue().removeCallbacks(action);
9989            }
9990        }
9991        return true;
9992    }
9993
9994    /**
9995     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
9996     * Use this to invalidate the View from a non-UI thread.</p>
9997     *
9998     * <p>This method can be invoked from outside of the UI thread
9999     * only when this View is attached to a window.</p>
10000     *
10001     * @see #invalidate()
10002     * @see #postInvalidateDelayed(long)
10003     */
10004    public void postInvalidate() {
10005        postInvalidateDelayed(0);
10006    }
10007
10008    /**
10009     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10010     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10011     *
10012     * <p>This method can be invoked from outside of the UI thread
10013     * only when this View is attached to a window.</p>
10014     *
10015     * @param left The left coordinate of the rectangle to invalidate.
10016     * @param top The top coordinate of the rectangle to invalidate.
10017     * @param right The right coordinate of the rectangle to invalidate.
10018     * @param bottom The bottom coordinate of the rectangle to invalidate.
10019     *
10020     * @see #invalidate(int, int, int, int)
10021     * @see #invalidate(Rect)
10022     * @see #postInvalidateDelayed(long, int, int, int, int)
10023     */
10024    public void postInvalidate(int left, int top, int right, int bottom) {
10025        postInvalidateDelayed(0, left, top, right, bottom);
10026    }
10027
10028    /**
10029     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10030     * loop. Waits for the specified amount of time.</p>
10031     *
10032     * <p>This method can be invoked from outside of the UI thread
10033     * only when this View is attached to a window.</p>
10034     *
10035     * @param delayMilliseconds the duration in milliseconds to delay the
10036     *         invalidation by
10037     *
10038     * @see #invalidate()
10039     * @see #postInvalidate()
10040     */
10041    public void postInvalidateDelayed(long delayMilliseconds) {
10042        // We try only with the AttachInfo because there's no point in invalidating
10043        // if we are not attached to our window
10044        final AttachInfo attachInfo = mAttachInfo;
10045        if (attachInfo != null) {
10046            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10047        }
10048    }
10049
10050    /**
10051     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10052     * through the event loop. Waits for the specified amount of time.</p>
10053     *
10054     * <p>This method can be invoked from outside of the UI thread
10055     * only when this View is attached to a window.</p>
10056     *
10057     * @param delayMilliseconds the duration in milliseconds to delay the
10058     *         invalidation by
10059     * @param left The left coordinate of the rectangle to invalidate.
10060     * @param top The top coordinate of the rectangle to invalidate.
10061     * @param right The right coordinate of the rectangle to invalidate.
10062     * @param bottom The bottom coordinate of the rectangle to invalidate.
10063     *
10064     * @see #invalidate(int, int, int, int)
10065     * @see #invalidate(Rect)
10066     * @see #postInvalidate(int, int, int, int)
10067     */
10068    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10069            int right, int bottom) {
10070
10071        // We try only with the AttachInfo because there's no point in invalidating
10072        // if we are not attached to our window
10073        final AttachInfo attachInfo = mAttachInfo;
10074        if (attachInfo != null) {
10075            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10076            info.target = this;
10077            info.left = left;
10078            info.top = top;
10079            info.right = right;
10080            info.bottom = bottom;
10081
10082            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10083        }
10084    }
10085
10086    /**
10087     * <p>Cause an invalidate to happen on the next animation time step, typically the
10088     * next display frame.</p>
10089     *
10090     * <p>This method can be invoked from outside of the UI thread
10091     * only when this View is attached to a window.</p>
10092     *
10093     * @see #invalidate()
10094     */
10095    public void postInvalidateOnAnimation() {
10096        // We try only with the AttachInfo because there's no point in invalidating
10097        // if we are not attached to our window
10098        final AttachInfo attachInfo = mAttachInfo;
10099        if (attachInfo != null) {
10100            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10101        }
10102    }
10103
10104    /**
10105     * <p>Cause an invalidate of the specified area to happen on the next animation
10106     * time step, typically the next display frame.</p>
10107     *
10108     * <p>This method can be invoked from outside of the UI thread
10109     * only when this View is attached to a window.</p>
10110     *
10111     * @param left The left coordinate of the rectangle to invalidate.
10112     * @param top The top coordinate of the rectangle to invalidate.
10113     * @param right The right coordinate of the rectangle to invalidate.
10114     * @param bottom The bottom coordinate of the rectangle to invalidate.
10115     *
10116     * @see #invalidate(int, int, int, int)
10117     * @see #invalidate(Rect)
10118     */
10119    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10120        // We try only with the AttachInfo because there's no point in invalidating
10121        // if we are not attached to our window
10122        final AttachInfo attachInfo = mAttachInfo;
10123        if (attachInfo != null) {
10124            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10125            info.target = this;
10126            info.left = left;
10127            info.top = top;
10128            info.right = right;
10129            info.bottom = bottom;
10130
10131            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10132        }
10133    }
10134
10135    /**
10136     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10137     * This event is sent at most once every
10138     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10139     */
10140    private void postSendViewScrolledAccessibilityEventCallback() {
10141        if (mSendViewScrolledAccessibilityEvent == null) {
10142            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10143        }
10144        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10145            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10146            postDelayed(mSendViewScrolledAccessibilityEvent,
10147                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10148        }
10149    }
10150
10151    /**
10152     * Called by a parent to request that a child update its values for mScrollX
10153     * and mScrollY if necessary. This will typically be done if the child is
10154     * animating a scroll using a {@link android.widget.Scroller Scroller}
10155     * object.
10156     */
10157    public void computeScroll() {
10158    }
10159
10160    /**
10161     * <p>Indicate whether the horizontal edges are faded when the view is
10162     * scrolled horizontally.</p>
10163     *
10164     * @return true if the horizontal edges should are faded on scroll, false
10165     *         otherwise
10166     *
10167     * @see #setHorizontalFadingEdgeEnabled(boolean)
10168     *
10169     * @attr ref android.R.styleable#View_requiresFadingEdge
10170     */
10171    public boolean isHorizontalFadingEdgeEnabled() {
10172        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10173    }
10174
10175    /**
10176     * <p>Define whether the horizontal edges should be faded when this view
10177     * is scrolled horizontally.</p>
10178     *
10179     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10180     *                                    be faded when the view is scrolled
10181     *                                    horizontally
10182     *
10183     * @see #isHorizontalFadingEdgeEnabled()
10184     *
10185     * @attr ref android.R.styleable#View_requiresFadingEdge
10186     */
10187    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10188        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10189            if (horizontalFadingEdgeEnabled) {
10190                initScrollCache();
10191            }
10192
10193            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10194        }
10195    }
10196
10197    /**
10198     * <p>Indicate whether the vertical edges are faded when the view is
10199     * scrolled horizontally.</p>
10200     *
10201     * @return true if the vertical edges should are faded on scroll, false
10202     *         otherwise
10203     *
10204     * @see #setVerticalFadingEdgeEnabled(boolean)
10205     *
10206     * @attr ref android.R.styleable#View_requiresFadingEdge
10207     */
10208    public boolean isVerticalFadingEdgeEnabled() {
10209        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10210    }
10211
10212    /**
10213     * <p>Define whether the vertical edges should be faded when this view
10214     * is scrolled vertically.</p>
10215     *
10216     * @param verticalFadingEdgeEnabled true if the vertical edges should
10217     *                                  be faded when the view is scrolled
10218     *                                  vertically
10219     *
10220     * @see #isVerticalFadingEdgeEnabled()
10221     *
10222     * @attr ref android.R.styleable#View_requiresFadingEdge
10223     */
10224    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10225        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10226            if (verticalFadingEdgeEnabled) {
10227                initScrollCache();
10228            }
10229
10230            mViewFlags ^= FADING_EDGE_VERTICAL;
10231        }
10232    }
10233
10234    /**
10235     * Returns the strength, or intensity, of the top faded edge. The strength is
10236     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10237     * returns 0.0 or 1.0 but no value in between.
10238     *
10239     * Subclasses should override this method to provide a smoother fade transition
10240     * when scrolling occurs.
10241     *
10242     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10243     */
10244    protected float getTopFadingEdgeStrength() {
10245        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10246    }
10247
10248    /**
10249     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10250     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10251     * returns 0.0 or 1.0 but no value in between.
10252     *
10253     * Subclasses should override this method to provide a smoother fade transition
10254     * when scrolling occurs.
10255     *
10256     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10257     */
10258    protected float getBottomFadingEdgeStrength() {
10259        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10260                computeVerticalScrollRange() ? 1.0f : 0.0f;
10261    }
10262
10263    /**
10264     * Returns the strength, or intensity, of the left faded edge. The strength is
10265     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10266     * returns 0.0 or 1.0 but no value in between.
10267     *
10268     * Subclasses should override this method to provide a smoother fade transition
10269     * when scrolling occurs.
10270     *
10271     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10272     */
10273    protected float getLeftFadingEdgeStrength() {
10274        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10275    }
10276
10277    /**
10278     * Returns the strength, or intensity, of the right faded edge. The strength is
10279     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10280     * returns 0.0 or 1.0 but no value in between.
10281     *
10282     * Subclasses should override this method to provide a smoother fade transition
10283     * when scrolling occurs.
10284     *
10285     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10286     */
10287    protected float getRightFadingEdgeStrength() {
10288        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10289                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10290    }
10291
10292    /**
10293     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10294     * scrollbar is not drawn by default.</p>
10295     *
10296     * @return true if the horizontal scrollbar should be painted, false
10297     *         otherwise
10298     *
10299     * @see #setHorizontalScrollBarEnabled(boolean)
10300     */
10301    public boolean isHorizontalScrollBarEnabled() {
10302        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10303    }
10304
10305    /**
10306     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10307     * scrollbar is not drawn by default.</p>
10308     *
10309     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10310     *                                   be painted
10311     *
10312     * @see #isHorizontalScrollBarEnabled()
10313     */
10314    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10315        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10316            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10317            computeOpaqueFlags();
10318            resolvePadding();
10319        }
10320    }
10321
10322    /**
10323     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10324     * scrollbar is not drawn by default.</p>
10325     *
10326     * @return true if the vertical scrollbar should be painted, false
10327     *         otherwise
10328     *
10329     * @see #setVerticalScrollBarEnabled(boolean)
10330     */
10331    public boolean isVerticalScrollBarEnabled() {
10332        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10333    }
10334
10335    /**
10336     * <p>Define whether the vertical scrollbar should be drawn or not. The
10337     * scrollbar is not drawn by default.</p>
10338     *
10339     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10340     *                                 be painted
10341     *
10342     * @see #isVerticalScrollBarEnabled()
10343     */
10344    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10345        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10346            mViewFlags ^= SCROLLBARS_VERTICAL;
10347            computeOpaqueFlags();
10348            resolvePadding();
10349        }
10350    }
10351
10352    /**
10353     * @hide
10354     */
10355    protected void recomputePadding() {
10356        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10357    }
10358
10359    /**
10360     * Define whether scrollbars will fade when the view is not scrolling.
10361     *
10362     * @param fadeScrollbars wheter to enable fading
10363     *
10364     * @attr ref android.R.styleable#View_fadeScrollbars
10365     */
10366    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10367        initScrollCache();
10368        final ScrollabilityCache scrollabilityCache = mScrollCache;
10369        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10370        if (fadeScrollbars) {
10371            scrollabilityCache.state = ScrollabilityCache.OFF;
10372        } else {
10373            scrollabilityCache.state = ScrollabilityCache.ON;
10374        }
10375    }
10376
10377    /**
10378     *
10379     * Returns true if scrollbars will fade when this view is not scrolling
10380     *
10381     * @return true if scrollbar fading is enabled
10382     *
10383     * @attr ref android.R.styleable#View_fadeScrollbars
10384     */
10385    public boolean isScrollbarFadingEnabled() {
10386        return mScrollCache != null && mScrollCache.fadeScrollBars;
10387    }
10388
10389    /**
10390     *
10391     * Returns the delay before scrollbars fade.
10392     *
10393     * @return the delay before scrollbars fade
10394     *
10395     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10396     */
10397    public int getScrollBarDefaultDelayBeforeFade() {
10398        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10399                mScrollCache.scrollBarDefaultDelayBeforeFade;
10400    }
10401
10402    /**
10403     * Define the delay before scrollbars fade.
10404     *
10405     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10406     *
10407     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10408     */
10409    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10410        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10411    }
10412
10413    /**
10414     *
10415     * Returns the scrollbar fade duration.
10416     *
10417     * @return the scrollbar fade duration
10418     *
10419     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10420     */
10421    public int getScrollBarFadeDuration() {
10422        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10423                mScrollCache.scrollBarFadeDuration;
10424    }
10425
10426    /**
10427     * Define the scrollbar fade duration.
10428     *
10429     * @param scrollBarFadeDuration - the scrollbar fade duration
10430     *
10431     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10432     */
10433    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10434        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10435    }
10436
10437    /**
10438     *
10439     * Returns the scrollbar size.
10440     *
10441     * @return the scrollbar size
10442     *
10443     * @attr ref android.R.styleable#View_scrollbarSize
10444     */
10445    public int getScrollBarSize() {
10446        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10447                mScrollCache.scrollBarSize;
10448    }
10449
10450    /**
10451     * Define the scrollbar size.
10452     *
10453     * @param scrollBarSize - the scrollbar size
10454     *
10455     * @attr ref android.R.styleable#View_scrollbarSize
10456     */
10457    public void setScrollBarSize(int scrollBarSize) {
10458        getScrollCache().scrollBarSize = scrollBarSize;
10459    }
10460
10461    /**
10462     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10463     * inset. When inset, they add to the padding of the view. And the scrollbars
10464     * can be drawn inside the padding area or on the edge of the view. For example,
10465     * if a view has a background drawable and you want to draw the scrollbars
10466     * inside the padding specified by the drawable, you can use
10467     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10468     * appear at the edge of the view, ignoring the padding, then you can use
10469     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10470     * @param style the style of the scrollbars. Should be one of
10471     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10472     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10473     * @see #SCROLLBARS_INSIDE_OVERLAY
10474     * @see #SCROLLBARS_INSIDE_INSET
10475     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10476     * @see #SCROLLBARS_OUTSIDE_INSET
10477     *
10478     * @attr ref android.R.styleable#View_scrollbarStyle
10479     */
10480    public void setScrollBarStyle(int style) {
10481        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10482            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10483            computeOpaqueFlags();
10484            resolvePadding();
10485        }
10486    }
10487
10488    /**
10489     * <p>Returns the current scrollbar style.</p>
10490     * @return the current scrollbar style
10491     * @see #SCROLLBARS_INSIDE_OVERLAY
10492     * @see #SCROLLBARS_INSIDE_INSET
10493     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10494     * @see #SCROLLBARS_OUTSIDE_INSET
10495     *
10496     * @attr ref android.R.styleable#View_scrollbarStyle
10497     */
10498    @ViewDebug.ExportedProperty(mapping = {
10499            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10500            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10501            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10502            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10503    })
10504    public int getScrollBarStyle() {
10505        return mViewFlags & SCROLLBARS_STYLE_MASK;
10506    }
10507
10508    /**
10509     * <p>Compute the horizontal range that the horizontal scrollbar
10510     * represents.</p>
10511     *
10512     * <p>The range is expressed in arbitrary units that must be the same as the
10513     * units used by {@link #computeHorizontalScrollExtent()} and
10514     * {@link #computeHorizontalScrollOffset()}.</p>
10515     *
10516     * <p>The default range is the drawing width of this view.</p>
10517     *
10518     * @return the total horizontal range represented by the horizontal
10519     *         scrollbar
10520     *
10521     * @see #computeHorizontalScrollExtent()
10522     * @see #computeHorizontalScrollOffset()
10523     * @see android.widget.ScrollBarDrawable
10524     */
10525    protected int computeHorizontalScrollRange() {
10526        return getWidth();
10527    }
10528
10529    /**
10530     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10531     * within the horizontal range. This value is used to compute the position
10532     * of the thumb within the scrollbar's track.</p>
10533     *
10534     * <p>The range is expressed in arbitrary units that must be the same as the
10535     * units used by {@link #computeHorizontalScrollRange()} and
10536     * {@link #computeHorizontalScrollExtent()}.</p>
10537     *
10538     * <p>The default offset is the scroll offset of this view.</p>
10539     *
10540     * @return the horizontal offset of the scrollbar's thumb
10541     *
10542     * @see #computeHorizontalScrollRange()
10543     * @see #computeHorizontalScrollExtent()
10544     * @see android.widget.ScrollBarDrawable
10545     */
10546    protected int computeHorizontalScrollOffset() {
10547        return mScrollX;
10548    }
10549
10550    /**
10551     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10552     * within the horizontal range. This value is used to compute the length
10553     * of the thumb within the scrollbar's track.</p>
10554     *
10555     * <p>The range is expressed in arbitrary units that must be the same as the
10556     * units used by {@link #computeHorizontalScrollRange()} and
10557     * {@link #computeHorizontalScrollOffset()}.</p>
10558     *
10559     * <p>The default extent is the drawing width of this view.</p>
10560     *
10561     * @return the horizontal extent of the scrollbar's thumb
10562     *
10563     * @see #computeHorizontalScrollRange()
10564     * @see #computeHorizontalScrollOffset()
10565     * @see android.widget.ScrollBarDrawable
10566     */
10567    protected int computeHorizontalScrollExtent() {
10568        return getWidth();
10569    }
10570
10571    /**
10572     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10573     *
10574     * <p>The range is expressed in arbitrary units that must be the same as the
10575     * units used by {@link #computeVerticalScrollExtent()} and
10576     * {@link #computeVerticalScrollOffset()}.</p>
10577     *
10578     * @return the total vertical range represented by the vertical scrollbar
10579     *
10580     * <p>The default range is the drawing height of this view.</p>
10581     *
10582     * @see #computeVerticalScrollExtent()
10583     * @see #computeVerticalScrollOffset()
10584     * @see android.widget.ScrollBarDrawable
10585     */
10586    protected int computeVerticalScrollRange() {
10587        return getHeight();
10588    }
10589
10590    /**
10591     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10592     * within the horizontal range. This value is used to compute the position
10593     * of the thumb within the scrollbar's track.</p>
10594     *
10595     * <p>The range is expressed in arbitrary units that must be the same as the
10596     * units used by {@link #computeVerticalScrollRange()} and
10597     * {@link #computeVerticalScrollExtent()}.</p>
10598     *
10599     * <p>The default offset is the scroll offset of this view.</p>
10600     *
10601     * @return the vertical offset of the scrollbar's thumb
10602     *
10603     * @see #computeVerticalScrollRange()
10604     * @see #computeVerticalScrollExtent()
10605     * @see android.widget.ScrollBarDrawable
10606     */
10607    protected int computeVerticalScrollOffset() {
10608        return mScrollY;
10609    }
10610
10611    /**
10612     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10613     * within the vertical range. This value is used to compute the length
10614     * of the thumb within the scrollbar's track.</p>
10615     *
10616     * <p>The range is expressed in arbitrary units that must be the same as the
10617     * units used by {@link #computeVerticalScrollRange()} and
10618     * {@link #computeVerticalScrollOffset()}.</p>
10619     *
10620     * <p>The default extent is the drawing height of this view.</p>
10621     *
10622     * @return the vertical extent of the scrollbar's thumb
10623     *
10624     * @see #computeVerticalScrollRange()
10625     * @see #computeVerticalScrollOffset()
10626     * @see android.widget.ScrollBarDrawable
10627     */
10628    protected int computeVerticalScrollExtent() {
10629        return getHeight();
10630    }
10631
10632    /**
10633     * Check if this view can be scrolled horizontally in a certain direction.
10634     *
10635     * @param direction Negative to check scrolling left, positive to check scrolling right.
10636     * @return true if this view can be scrolled in the specified direction, false otherwise.
10637     */
10638    public boolean canScrollHorizontally(int direction) {
10639        final int offset = computeHorizontalScrollOffset();
10640        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10641        if (range == 0) return false;
10642        if (direction < 0) {
10643            return offset > 0;
10644        } else {
10645            return offset < range - 1;
10646        }
10647    }
10648
10649    /**
10650     * Check if this view can be scrolled vertically in a certain direction.
10651     *
10652     * @param direction Negative to check scrolling up, positive to check scrolling down.
10653     * @return true if this view can be scrolled in the specified direction, false otherwise.
10654     */
10655    public boolean canScrollVertically(int direction) {
10656        final int offset = computeVerticalScrollOffset();
10657        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10658        if (range == 0) return false;
10659        if (direction < 0) {
10660            return offset > 0;
10661        } else {
10662            return offset < range - 1;
10663        }
10664    }
10665
10666    /**
10667     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10668     * scrollbars are painted only if they have been awakened first.</p>
10669     *
10670     * @param canvas the canvas on which to draw the scrollbars
10671     *
10672     * @see #awakenScrollBars(int)
10673     */
10674    protected final void onDrawScrollBars(Canvas canvas) {
10675        // scrollbars are drawn only when the animation is running
10676        final ScrollabilityCache cache = mScrollCache;
10677        if (cache != null) {
10678
10679            int state = cache.state;
10680
10681            if (state == ScrollabilityCache.OFF) {
10682                return;
10683            }
10684
10685            boolean invalidate = false;
10686
10687            if (state == ScrollabilityCache.FADING) {
10688                // We're fading -- get our fade interpolation
10689                if (cache.interpolatorValues == null) {
10690                    cache.interpolatorValues = new float[1];
10691                }
10692
10693                float[] values = cache.interpolatorValues;
10694
10695                // Stops the animation if we're done
10696                if (cache.scrollBarInterpolator.timeToValues(values) ==
10697                        Interpolator.Result.FREEZE_END) {
10698                    cache.state = ScrollabilityCache.OFF;
10699                } else {
10700                    cache.scrollBar.setAlpha(Math.round(values[0]));
10701                }
10702
10703                // This will make the scroll bars inval themselves after
10704                // drawing. We only want this when we're fading so that
10705                // we prevent excessive redraws
10706                invalidate = true;
10707            } else {
10708                // We're just on -- but we may have been fading before so
10709                // reset alpha
10710                cache.scrollBar.setAlpha(255);
10711            }
10712
10713
10714            final int viewFlags = mViewFlags;
10715
10716            final boolean drawHorizontalScrollBar =
10717                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10718            final boolean drawVerticalScrollBar =
10719                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
10720                && !isVerticalScrollBarHidden();
10721
10722            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
10723                final int width = mRight - mLeft;
10724                final int height = mBottom - mTop;
10725
10726                final ScrollBarDrawable scrollBar = cache.scrollBar;
10727
10728                final int scrollX = mScrollX;
10729                final int scrollY = mScrollY;
10730                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
10731
10732                int left, top, right, bottom;
10733
10734                if (drawHorizontalScrollBar) {
10735                    int size = scrollBar.getSize(false);
10736                    if (size <= 0) {
10737                        size = cache.scrollBarSize;
10738                    }
10739
10740                    scrollBar.setParameters(computeHorizontalScrollRange(),
10741                                            computeHorizontalScrollOffset(),
10742                                            computeHorizontalScrollExtent(), false);
10743                    final int verticalScrollBarGap = drawVerticalScrollBar ?
10744                            getVerticalScrollbarWidth() : 0;
10745                    top = scrollY + height - size - (mUserPaddingBottom & inside);
10746                    left = scrollX + (mPaddingLeft & inside);
10747                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
10748                    bottom = top + size;
10749                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
10750                    if (invalidate) {
10751                        invalidate(left, top, right, bottom);
10752                    }
10753                }
10754
10755                if (drawVerticalScrollBar) {
10756                    int size = scrollBar.getSize(true);
10757                    if (size <= 0) {
10758                        size = cache.scrollBarSize;
10759                    }
10760
10761                    scrollBar.setParameters(computeVerticalScrollRange(),
10762                                            computeVerticalScrollOffset(),
10763                                            computeVerticalScrollExtent(), true);
10764                    switch (mVerticalScrollbarPosition) {
10765                        default:
10766                        case SCROLLBAR_POSITION_DEFAULT:
10767                        case SCROLLBAR_POSITION_RIGHT:
10768                            left = scrollX + width - size - (mUserPaddingRight & inside);
10769                            break;
10770                        case SCROLLBAR_POSITION_LEFT:
10771                            left = scrollX + (mUserPaddingLeft & inside);
10772                            break;
10773                    }
10774                    top = scrollY + (mPaddingTop & inside);
10775                    right = left + size;
10776                    bottom = scrollY + height - (mUserPaddingBottom & inside);
10777                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
10778                    if (invalidate) {
10779                        invalidate(left, top, right, bottom);
10780                    }
10781                }
10782            }
10783        }
10784    }
10785
10786    /**
10787     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
10788     * FastScroller is visible.
10789     * @return whether to temporarily hide the vertical scrollbar
10790     * @hide
10791     */
10792    protected boolean isVerticalScrollBarHidden() {
10793        return false;
10794    }
10795
10796    /**
10797     * <p>Draw the horizontal scrollbar if
10798     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
10799     *
10800     * @param canvas the canvas on which to draw the scrollbar
10801     * @param scrollBar the scrollbar's drawable
10802     *
10803     * @see #isHorizontalScrollBarEnabled()
10804     * @see #computeHorizontalScrollRange()
10805     * @see #computeHorizontalScrollExtent()
10806     * @see #computeHorizontalScrollOffset()
10807     * @see android.widget.ScrollBarDrawable
10808     * @hide
10809     */
10810    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
10811            int l, int t, int r, int b) {
10812        scrollBar.setBounds(l, t, r, b);
10813        scrollBar.draw(canvas);
10814    }
10815
10816    /**
10817     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
10818     * returns true.</p>
10819     *
10820     * @param canvas the canvas on which to draw the scrollbar
10821     * @param scrollBar the scrollbar's drawable
10822     *
10823     * @see #isVerticalScrollBarEnabled()
10824     * @see #computeVerticalScrollRange()
10825     * @see #computeVerticalScrollExtent()
10826     * @see #computeVerticalScrollOffset()
10827     * @see android.widget.ScrollBarDrawable
10828     * @hide
10829     */
10830    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
10831            int l, int t, int r, int b) {
10832        scrollBar.setBounds(l, t, r, b);
10833        scrollBar.draw(canvas);
10834    }
10835
10836    /**
10837     * Implement this to do your drawing.
10838     *
10839     * @param canvas the canvas on which the background will be drawn
10840     */
10841    protected void onDraw(Canvas canvas) {
10842    }
10843
10844    /*
10845     * Caller is responsible for calling requestLayout if necessary.
10846     * (This allows addViewInLayout to not request a new layout.)
10847     */
10848    void assignParent(ViewParent parent) {
10849        if (mParent == null) {
10850            mParent = parent;
10851        } else if (parent == null) {
10852            mParent = null;
10853        } else {
10854            throw new RuntimeException("view " + this + " being added, but"
10855                    + " it already has a parent");
10856        }
10857    }
10858
10859    /**
10860     * This is called when the view is attached to a window.  At this point it
10861     * has a Surface and will start drawing.  Note that this function is
10862     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
10863     * however it may be called any time before the first onDraw -- including
10864     * before or after {@link #onMeasure(int, int)}.
10865     *
10866     * @see #onDetachedFromWindow()
10867     */
10868    protected void onAttachedToWindow() {
10869        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
10870            mParent.requestTransparentRegion(this);
10871        }
10872        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
10873            initialAwakenScrollBars();
10874            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
10875        }
10876        jumpDrawablesToCurrentState();
10877        // Order is important here: LayoutDirection MUST be resolved before Padding
10878        // and TextDirection
10879        resolveLayoutDirection();
10880        resolvePadding();
10881        resolveTextDirection();
10882        resolveTextAlignment();
10883        clearAccessibilityFocus();
10884        if (isFocused()) {
10885            InputMethodManager imm = InputMethodManager.peekInstance();
10886            imm.focusIn(this);
10887        }
10888    }
10889
10890    /**
10891     * @see #onScreenStateChanged(int)
10892     */
10893    void dispatchScreenStateChanged(int screenState) {
10894        onScreenStateChanged(screenState);
10895    }
10896
10897    /**
10898     * This method is called whenever the state of the screen this view is
10899     * attached to changes. A state change will usually occurs when the screen
10900     * turns on or off (whether it happens automatically or the user does it
10901     * manually.)
10902     *
10903     * @param screenState The new state of the screen. Can be either
10904     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
10905     */
10906    public void onScreenStateChanged(int screenState) {
10907    }
10908
10909    /**
10910     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
10911     */
10912    private boolean hasRtlSupport() {
10913        return mContext.getApplicationInfo().hasRtlSupport();
10914    }
10915
10916    /**
10917     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
10918     * that the parent directionality can and will be resolved before its children.
10919     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
10920     * @hide
10921     */
10922    public void resolveLayoutDirection() {
10923        // Clear any previous layout direction resolution
10924        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10925
10926        if (hasRtlSupport()) {
10927            // Set resolved depending on layout direction
10928            switch (getLayoutDirection()) {
10929                case LAYOUT_DIRECTION_INHERIT:
10930                    // If this is root view, no need to look at parent's layout dir.
10931                    if (canResolveLayoutDirection()) {
10932                        ViewGroup viewGroup = ((ViewGroup) mParent);
10933
10934                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
10935                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10936                        }
10937                    } else {
10938                        // Nothing to do, LTR by default
10939                    }
10940                    break;
10941                case LAYOUT_DIRECTION_RTL:
10942                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10943                    break;
10944                case LAYOUT_DIRECTION_LOCALE:
10945                    if(isLayoutDirectionRtl(Locale.getDefault())) {
10946                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10947                    }
10948                    break;
10949                default:
10950                    // Nothing to do, LTR by default
10951            }
10952        }
10953
10954        // Set to resolved
10955        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
10956        onResolvedLayoutDirectionChanged();
10957        // Resolve padding
10958        resolvePadding();
10959    }
10960
10961    /**
10962     * Called when layout direction has been resolved.
10963     *
10964     * The default implementation does nothing.
10965     * @hide
10966     */
10967    public void onResolvedLayoutDirectionChanged() {
10968    }
10969
10970    /**
10971     * Resolve padding depending on layout direction.
10972     * @hide
10973     */
10974    public void resolvePadding() {
10975        // If the user specified the absolute padding (either with android:padding or
10976        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
10977        // use the default padding or the padding from the background drawable
10978        // (stored at this point in mPadding*)
10979        int resolvedLayoutDirection = getResolvedLayoutDirection();
10980        switch (resolvedLayoutDirection) {
10981            case LAYOUT_DIRECTION_RTL:
10982                // Start user padding override Right user padding. Otherwise, if Right user
10983                // padding is not defined, use the default Right padding. If Right user padding
10984                // is defined, just use it.
10985                if (mUserPaddingStart >= 0) {
10986                    mUserPaddingRight = mUserPaddingStart;
10987                } else if (mUserPaddingRight < 0) {
10988                    mUserPaddingRight = mPaddingRight;
10989                }
10990                if (mUserPaddingEnd >= 0) {
10991                    mUserPaddingLeft = mUserPaddingEnd;
10992                } else if (mUserPaddingLeft < 0) {
10993                    mUserPaddingLeft = mPaddingLeft;
10994                }
10995                break;
10996            case LAYOUT_DIRECTION_LTR:
10997            default:
10998                // Start user padding override Left user padding. Otherwise, if Left user
10999                // padding is not defined, use the default left padding. If Left user padding
11000                // is defined, just use it.
11001                if (mUserPaddingStart >= 0) {
11002                    mUserPaddingLeft = mUserPaddingStart;
11003                } else if (mUserPaddingLeft < 0) {
11004                    mUserPaddingLeft = mPaddingLeft;
11005                }
11006                if (mUserPaddingEnd >= 0) {
11007                    mUserPaddingRight = mUserPaddingEnd;
11008                } else if (mUserPaddingRight < 0) {
11009                    mUserPaddingRight = mPaddingRight;
11010                }
11011        }
11012
11013        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11014
11015        if(isPaddingRelative()) {
11016            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11017        } else {
11018            recomputePadding();
11019        }
11020        onPaddingChanged(resolvedLayoutDirection);
11021    }
11022
11023    /**
11024     * Resolve padding depending on the layout direction. Subclasses that care about
11025     * padding resolution should override this method. The default implementation does
11026     * nothing.
11027     *
11028     * @param layoutDirection the direction of the layout
11029     *
11030     * @see {@link #LAYOUT_DIRECTION_LTR}
11031     * @see {@link #LAYOUT_DIRECTION_RTL}
11032     * @hide
11033     */
11034    public void onPaddingChanged(int layoutDirection) {
11035    }
11036
11037    /**
11038     * Check if layout direction resolution can be done.
11039     *
11040     * @return true if layout direction resolution can be done otherwise return false.
11041     * @hide
11042     */
11043    public boolean canResolveLayoutDirection() {
11044        switch (getLayoutDirection()) {
11045            case LAYOUT_DIRECTION_INHERIT:
11046                return (mParent != null) && (mParent instanceof ViewGroup);
11047            default:
11048                return true;
11049        }
11050    }
11051
11052    /**
11053     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11054     * when reset is done.
11055     * @hide
11056     */
11057    public void resetResolvedLayoutDirection() {
11058        // Reset the current resolved bits
11059        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11060        onResolvedLayoutDirectionReset();
11061        // Reset also the text direction
11062        resetResolvedTextDirection();
11063    }
11064
11065    /**
11066     * Called during reset of resolved layout direction.
11067     *
11068     * Subclasses need to override this method to clear cached information that depends on the
11069     * resolved layout direction, or to inform child views that inherit their layout direction.
11070     *
11071     * The default implementation does nothing.
11072     * @hide
11073     */
11074    public void onResolvedLayoutDirectionReset() {
11075    }
11076
11077    /**
11078     * Check if a Locale uses an RTL script.
11079     *
11080     * @param locale Locale to check
11081     * @return true if the Locale uses an RTL script.
11082     * @hide
11083     */
11084    protected static boolean isLayoutDirectionRtl(Locale locale) {
11085        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11086    }
11087
11088    /**
11089     * This is called when the view is detached from a window.  At this point it
11090     * no longer has a surface for drawing.
11091     *
11092     * @see #onAttachedToWindow()
11093     */
11094    protected void onDetachedFromWindow() {
11095        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11096
11097        removeUnsetPressCallback();
11098        removeLongPressCallback();
11099        removePerformClickCallback();
11100        removeSendViewScrolledAccessibilityEventCallback();
11101
11102        destroyDrawingCache();
11103
11104        destroyLayer(false);
11105
11106        if (mAttachInfo != null) {
11107            if (mDisplayList != null) {
11108                mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList);
11109            }
11110            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11111        } else {
11112            if (mDisplayList != null) {
11113                // Should never happen
11114                mDisplayList.invalidate();
11115            }
11116        }
11117
11118        mCurrentAnimation = null;
11119
11120        resetResolvedLayoutDirection();
11121        resetResolvedTextAlignment();
11122        resetAccessibilityStateChanged();
11123        clearAccessibilityFocus();
11124    }
11125
11126    /**
11127     * @return The number of times this view has been attached to a window
11128     */
11129    protected int getWindowAttachCount() {
11130        return mWindowAttachCount;
11131    }
11132
11133    /**
11134     * Retrieve a unique token identifying the window this view is attached to.
11135     * @return Return the window's token for use in
11136     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11137     */
11138    public IBinder getWindowToken() {
11139        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11140    }
11141
11142    /**
11143     * Retrieve a unique token identifying the top-level "real" window of
11144     * the window that this view is attached to.  That is, this is like
11145     * {@link #getWindowToken}, except if the window this view in is a panel
11146     * window (attached to another containing window), then the token of
11147     * the containing window is returned instead.
11148     *
11149     * @return Returns the associated window token, either
11150     * {@link #getWindowToken()} or the containing window's token.
11151     */
11152    public IBinder getApplicationWindowToken() {
11153        AttachInfo ai = mAttachInfo;
11154        if (ai != null) {
11155            IBinder appWindowToken = ai.mPanelParentWindowToken;
11156            if (appWindowToken == null) {
11157                appWindowToken = ai.mWindowToken;
11158            }
11159            return appWindowToken;
11160        }
11161        return null;
11162    }
11163
11164    /**
11165     * Retrieve private session object this view hierarchy is using to
11166     * communicate with the window manager.
11167     * @return the session object to communicate with the window manager
11168     */
11169    /*package*/ IWindowSession getWindowSession() {
11170        return mAttachInfo != null ? mAttachInfo.mSession : null;
11171    }
11172
11173    /**
11174     * @param info the {@link android.view.View.AttachInfo} to associated with
11175     *        this view
11176     */
11177    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11178        //System.out.println("Attached! " + this);
11179        mAttachInfo = info;
11180        mWindowAttachCount++;
11181        // We will need to evaluate the drawable state at least once.
11182        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11183        if (mFloatingTreeObserver != null) {
11184            info.mTreeObserver.merge(mFloatingTreeObserver);
11185            mFloatingTreeObserver = null;
11186        }
11187        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11188            mAttachInfo.mScrollContainers.add(this);
11189            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11190        }
11191        performCollectViewAttributes(mAttachInfo, visibility);
11192        onAttachedToWindow();
11193
11194        ListenerInfo li = mListenerInfo;
11195        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11196                li != null ? li.mOnAttachStateChangeListeners : null;
11197        if (listeners != null && listeners.size() > 0) {
11198            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11199            // perform the dispatching. The iterator is a safe guard against listeners that
11200            // could mutate the list by calling the various add/remove methods. This prevents
11201            // the array from being modified while we iterate it.
11202            for (OnAttachStateChangeListener listener : listeners) {
11203                listener.onViewAttachedToWindow(this);
11204            }
11205        }
11206
11207        int vis = info.mWindowVisibility;
11208        if (vis != GONE) {
11209            onWindowVisibilityChanged(vis);
11210        }
11211        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11212            // If nobody has evaluated the drawable state yet, then do it now.
11213            refreshDrawableState();
11214        }
11215    }
11216
11217    void dispatchDetachedFromWindow() {
11218        AttachInfo info = mAttachInfo;
11219        if (info != null) {
11220            int vis = info.mWindowVisibility;
11221            if (vis != GONE) {
11222                onWindowVisibilityChanged(GONE);
11223            }
11224        }
11225
11226        onDetachedFromWindow();
11227
11228        ListenerInfo li = mListenerInfo;
11229        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11230                li != null ? li.mOnAttachStateChangeListeners : null;
11231        if (listeners != null && listeners.size() > 0) {
11232            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11233            // perform the dispatching. The iterator is a safe guard against listeners that
11234            // could mutate the list by calling the various add/remove methods. This prevents
11235            // the array from being modified while we iterate it.
11236            for (OnAttachStateChangeListener listener : listeners) {
11237                listener.onViewDetachedFromWindow(this);
11238            }
11239        }
11240
11241        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11242            mAttachInfo.mScrollContainers.remove(this);
11243            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11244        }
11245
11246        mAttachInfo = null;
11247    }
11248
11249    /**
11250     * Store this view hierarchy's frozen state into the given container.
11251     *
11252     * @param container The SparseArray in which to save the view's state.
11253     *
11254     * @see #restoreHierarchyState(android.util.SparseArray)
11255     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11256     * @see #onSaveInstanceState()
11257     */
11258    public void saveHierarchyState(SparseArray<Parcelable> container) {
11259        dispatchSaveInstanceState(container);
11260    }
11261
11262    /**
11263     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11264     * this view and its children. May be overridden to modify how freezing happens to a
11265     * view's children; for example, some views may want to not store state for their children.
11266     *
11267     * @param container The SparseArray in which to save the view's state.
11268     *
11269     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11270     * @see #saveHierarchyState(android.util.SparseArray)
11271     * @see #onSaveInstanceState()
11272     */
11273    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11274        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11275            mPrivateFlags &= ~SAVE_STATE_CALLED;
11276            Parcelable state = onSaveInstanceState();
11277            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11278                throw new IllegalStateException(
11279                        "Derived class did not call super.onSaveInstanceState()");
11280            }
11281            if (state != null) {
11282                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11283                // + ": " + state);
11284                container.put(mID, state);
11285            }
11286        }
11287    }
11288
11289    /**
11290     * Hook allowing a view to generate a representation of its internal state
11291     * that can later be used to create a new instance with that same state.
11292     * This state should only contain information that is not persistent or can
11293     * not be reconstructed later. For example, you will never store your
11294     * current position on screen because that will be computed again when a
11295     * new instance of the view is placed in its view hierarchy.
11296     * <p>
11297     * Some examples of things you may store here: the current cursor position
11298     * in a text view (but usually not the text itself since that is stored in a
11299     * content provider or other persistent storage), the currently selected
11300     * item in a list view.
11301     *
11302     * @return Returns a Parcelable object containing the view's current dynamic
11303     *         state, or null if there is nothing interesting to save. The
11304     *         default implementation returns null.
11305     * @see #onRestoreInstanceState(android.os.Parcelable)
11306     * @see #saveHierarchyState(android.util.SparseArray)
11307     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11308     * @see #setSaveEnabled(boolean)
11309     */
11310    protected Parcelable onSaveInstanceState() {
11311        mPrivateFlags |= SAVE_STATE_CALLED;
11312        return BaseSavedState.EMPTY_STATE;
11313    }
11314
11315    /**
11316     * Restore this view hierarchy's frozen state from the given container.
11317     *
11318     * @param container The SparseArray which holds previously frozen states.
11319     *
11320     * @see #saveHierarchyState(android.util.SparseArray)
11321     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11322     * @see #onRestoreInstanceState(android.os.Parcelable)
11323     */
11324    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11325        dispatchRestoreInstanceState(container);
11326    }
11327
11328    /**
11329     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11330     * state for this view and its children. May be overridden to modify how restoring
11331     * happens to a view's children; for example, some views may want to not store state
11332     * for their children.
11333     *
11334     * @param container The SparseArray which holds previously saved state.
11335     *
11336     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11337     * @see #restoreHierarchyState(android.util.SparseArray)
11338     * @see #onRestoreInstanceState(android.os.Parcelable)
11339     */
11340    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11341        if (mID != NO_ID) {
11342            Parcelable state = container.get(mID);
11343            if (state != null) {
11344                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11345                // + ": " + state);
11346                mPrivateFlags &= ~SAVE_STATE_CALLED;
11347                onRestoreInstanceState(state);
11348                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11349                    throw new IllegalStateException(
11350                            "Derived class did not call super.onRestoreInstanceState()");
11351                }
11352            }
11353        }
11354    }
11355
11356    /**
11357     * Hook allowing a view to re-apply a representation of its internal state that had previously
11358     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11359     * null state.
11360     *
11361     * @param state The frozen state that had previously been returned by
11362     *        {@link #onSaveInstanceState}.
11363     *
11364     * @see #onSaveInstanceState()
11365     * @see #restoreHierarchyState(android.util.SparseArray)
11366     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11367     */
11368    protected void onRestoreInstanceState(Parcelable state) {
11369        mPrivateFlags |= SAVE_STATE_CALLED;
11370        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11371            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11372                    + "received " + state.getClass().toString() + " instead. This usually happens "
11373                    + "when two views of different type have the same id in the same hierarchy. "
11374                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11375                    + "other views do not use the same id.");
11376        }
11377    }
11378
11379    /**
11380     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11381     *
11382     * @return the drawing start time in milliseconds
11383     */
11384    public long getDrawingTime() {
11385        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11386    }
11387
11388    /**
11389     * <p>Enables or disables the duplication of the parent's state into this view. When
11390     * duplication is enabled, this view gets its drawable state from its parent rather
11391     * than from its own internal properties.</p>
11392     *
11393     * <p>Note: in the current implementation, setting this property to true after the
11394     * view was added to a ViewGroup might have no effect at all. This property should
11395     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11396     *
11397     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11398     * property is enabled, an exception will be thrown.</p>
11399     *
11400     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11401     * parent, these states should not be affected by this method.</p>
11402     *
11403     * @param enabled True to enable duplication of the parent's drawable state, false
11404     *                to disable it.
11405     *
11406     * @see #getDrawableState()
11407     * @see #isDuplicateParentStateEnabled()
11408     */
11409    public void setDuplicateParentStateEnabled(boolean enabled) {
11410        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11411    }
11412
11413    /**
11414     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11415     *
11416     * @return True if this view's drawable state is duplicated from the parent,
11417     *         false otherwise
11418     *
11419     * @see #getDrawableState()
11420     * @see #setDuplicateParentStateEnabled(boolean)
11421     */
11422    public boolean isDuplicateParentStateEnabled() {
11423        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11424    }
11425
11426    /**
11427     * <p>Specifies the type of layer backing this view. The layer can be
11428     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11429     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11430     *
11431     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11432     * instance that controls how the layer is composed on screen. The following
11433     * properties of the paint are taken into account when composing the layer:</p>
11434     * <ul>
11435     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11436     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11437     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11438     * </ul>
11439     *
11440     * <p>If this view has an alpha value set to < 1.0 by calling
11441     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11442     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11443     * equivalent to setting a hardware layer on this view and providing a paint with
11444     * the desired alpha value.<p>
11445     *
11446     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11447     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11448     * for more information on when and how to use layers.</p>
11449     *
11450     * @param layerType The ype of layer to use with this view, must be one of
11451     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11452     *        {@link #LAYER_TYPE_HARDWARE}
11453     * @param paint The paint used to compose the layer. This argument is optional
11454     *        and can be null. It is ignored when the layer type is
11455     *        {@link #LAYER_TYPE_NONE}
11456     *
11457     * @see #getLayerType()
11458     * @see #LAYER_TYPE_NONE
11459     * @see #LAYER_TYPE_SOFTWARE
11460     * @see #LAYER_TYPE_HARDWARE
11461     * @see #setAlpha(float)
11462     *
11463     * @attr ref android.R.styleable#View_layerType
11464     */
11465    public void setLayerType(int layerType, Paint paint) {
11466        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11467            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11468                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11469        }
11470
11471        if (layerType == mLayerType) {
11472            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11473                mLayerPaint = paint == null ? new Paint() : paint;
11474                invalidateParentCaches();
11475                invalidate(true);
11476            }
11477            return;
11478        }
11479
11480        // Destroy any previous software drawing cache if needed
11481        switch (mLayerType) {
11482            case LAYER_TYPE_HARDWARE:
11483                destroyLayer(false);
11484                // fall through - non-accelerated views may use software layer mechanism instead
11485            case LAYER_TYPE_SOFTWARE:
11486                destroyDrawingCache();
11487                break;
11488            default:
11489                break;
11490        }
11491
11492        mLayerType = layerType;
11493        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11494        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11495        mLocalDirtyRect = layerDisabled ? null : new Rect();
11496
11497        invalidateParentCaches();
11498        invalidate(true);
11499    }
11500
11501    /**
11502     * Indicates whether this view has a static layer. A view with layer type
11503     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11504     * dynamic.
11505     */
11506    boolean hasStaticLayer() {
11507        return true;
11508    }
11509
11510    /**
11511     * Indicates what type of layer is currently associated with this view. By default
11512     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11513     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11514     * for more information on the different types of layers.
11515     *
11516     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11517     *         {@link #LAYER_TYPE_HARDWARE}
11518     *
11519     * @see #setLayerType(int, android.graphics.Paint)
11520     * @see #buildLayer()
11521     * @see #LAYER_TYPE_NONE
11522     * @see #LAYER_TYPE_SOFTWARE
11523     * @see #LAYER_TYPE_HARDWARE
11524     */
11525    public int getLayerType() {
11526        return mLayerType;
11527    }
11528
11529    /**
11530     * Forces this view's layer to be created and this view to be rendered
11531     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11532     * invoking this method will have no effect.
11533     *
11534     * This method can for instance be used to render a view into its layer before
11535     * starting an animation. If this view is complex, rendering into the layer
11536     * before starting the animation will avoid skipping frames.
11537     *
11538     * @throws IllegalStateException If this view is not attached to a window
11539     *
11540     * @see #setLayerType(int, android.graphics.Paint)
11541     */
11542    public void buildLayer() {
11543        if (mLayerType == LAYER_TYPE_NONE) return;
11544
11545        if (mAttachInfo == null) {
11546            throw new IllegalStateException("This view must be attached to a window first");
11547        }
11548
11549        switch (mLayerType) {
11550            case LAYER_TYPE_HARDWARE:
11551                if (mAttachInfo.mHardwareRenderer != null &&
11552                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11553                        mAttachInfo.mHardwareRenderer.validate()) {
11554                    getHardwareLayer();
11555                }
11556                break;
11557            case LAYER_TYPE_SOFTWARE:
11558                buildDrawingCache(true);
11559                break;
11560        }
11561    }
11562
11563    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11564    void flushLayer() {
11565        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11566            mHardwareLayer.flush();
11567        }
11568    }
11569
11570    /**
11571     * <p>Returns a hardware layer that can be used to draw this view again
11572     * without executing its draw method.</p>
11573     *
11574     * @return A HardwareLayer ready to render, or null if an error occurred.
11575     */
11576    HardwareLayer getHardwareLayer() {
11577        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11578                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11579            return null;
11580        }
11581
11582        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11583
11584        final int width = mRight - mLeft;
11585        final int height = mBottom - mTop;
11586
11587        if (width == 0 || height == 0) {
11588            return null;
11589        }
11590
11591        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11592            if (mHardwareLayer == null) {
11593                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11594                        width, height, isOpaque());
11595                mLocalDirtyRect.set(0, 0, width, height);
11596            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11597                mHardwareLayer.resize(width, height);
11598                mLocalDirtyRect.set(0, 0, width, height);
11599            }
11600
11601            // The layer is not valid if the underlying GPU resources cannot be allocated
11602            if (!mHardwareLayer.isValid()) {
11603                return null;
11604            }
11605
11606            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11607            mLocalDirtyRect.setEmpty();
11608        }
11609
11610        return mHardwareLayer;
11611    }
11612
11613    /**
11614     * Destroys this View's hardware layer if possible.
11615     *
11616     * @return True if the layer was destroyed, false otherwise.
11617     *
11618     * @see #setLayerType(int, android.graphics.Paint)
11619     * @see #LAYER_TYPE_HARDWARE
11620     */
11621    boolean destroyLayer(boolean valid) {
11622        if (mHardwareLayer != null) {
11623            AttachInfo info = mAttachInfo;
11624            if (info != null && info.mHardwareRenderer != null &&
11625                    info.mHardwareRenderer.isEnabled() &&
11626                    (valid || info.mHardwareRenderer.validate())) {
11627                mHardwareLayer.destroy();
11628                mHardwareLayer = null;
11629
11630                invalidate(true);
11631                invalidateParentCaches();
11632            }
11633            return true;
11634        }
11635        return false;
11636    }
11637
11638    /**
11639     * Destroys all hardware rendering resources. This method is invoked
11640     * when the system needs to reclaim resources. Upon execution of this
11641     * method, you should free any OpenGL resources created by the view.
11642     *
11643     * Note: you <strong>must</strong> call
11644     * <code>super.destroyHardwareResources()</code> when overriding
11645     * this method.
11646     *
11647     * @hide
11648     */
11649    protected void destroyHardwareResources() {
11650        destroyLayer(true);
11651    }
11652
11653    /**
11654     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11655     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11656     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11657     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11658     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11659     * null.</p>
11660     *
11661     * <p>Enabling the drawing cache is similar to
11662     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11663     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11664     * drawing cache has no effect on rendering because the system uses a different mechanism
11665     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11666     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11667     * for information on how to enable software and hardware layers.</p>
11668     *
11669     * <p>This API can be used to manually generate
11670     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11671     * {@link #getDrawingCache()}.</p>
11672     *
11673     * @param enabled true to enable the drawing cache, false otherwise
11674     *
11675     * @see #isDrawingCacheEnabled()
11676     * @see #getDrawingCache()
11677     * @see #buildDrawingCache()
11678     * @see #setLayerType(int, android.graphics.Paint)
11679     */
11680    public void setDrawingCacheEnabled(boolean enabled) {
11681        mCachingFailed = false;
11682        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
11683    }
11684
11685    /**
11686     * <p>Indicates whether the drawing cache is enabled for this view.</p>
11687     *
11688     * @return true if the drawing cache is enabled
11689     *
11690     * @see #setDrawingCacheEnabled(boolean)
11691     * @see #getDrawingCache()
11692     */
11693    @ViewDebug.ExportedProperty(category = "drawing")
11694    public boolean isDrawingCacheEnabled() {
11695        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
11696    }
11697
11698    /**
11699     * Debugging utility which recursively outputs the dirty state of a view and its
11700     * descendants.
11701     *
11702     * @hide
11703     */
11704    @SuppressWarnings({"UnusedDeclaration"})
11705    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
11706        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
11707                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
11708                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
11709                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
11710        if (clear) {
11711            mPrivateFlags &= clearMask;
11712        }
11713        if (this instanceof ViewGroup) {
11714            ViewGroup parent = (ViewGroup) this;
11715            final int count = parent.getChildCount();
11716            for (int i = 0; i < count; i++) {
11717                final View child = parent.getChildAt(i);
11718                child.outputDirtyFlags(indent + "  ", clear, clearMask);
11719            }
11720        }
11721    }
11722
11723    /**
11724     * This method is used by ViewGroup to cause its children to restore or recreate their
11725     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
11726     * to recreate its own display list, which would happen if it went through the normal
11727     * draw/dispatchDraw mechanisms.
11728     *
11729     * @hide
11730     */
11731    protected void dispatchGetDisplayList() {}
11732
11733    /**
11734     * A view that is not attached or hardware accelerated cannot create a display list.
11735     * This method checks these conditions and returns the appropriate result.
11736     *
11737     * @return true if view has the ability to create a display list, false otherwise.
11738     *
11739     * @hide
11740     */
11741    public boolean canHaveDisplayList() {
11742        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
11743    }
11744
11745    /**
11746     * @return The HardwareRenderer associated with that view or null if hardware rendering
11747     * is not supported or this this has not been attached to a window.
11748     *
11749     * @hide
11750     */
11751    public HardwareRenderer getHardwareRenderer() {
11752        if (mAttachInfo != null) {
11753            return mAttachInfo.mHardwareRenderer;
11754        }
11755        return null;
11756    }
11757
11758    /**
11759     * Returns a DisplayList. If the incoming displayList is null, one will be created.
11760     * Otherwise, the same display list will be returned (after having been rendered into
11761     * along the way, depending on the invalidation state of the view).
11762     *
11763     * @param displayList The previous version of this displayList, could be null.
11764     * @param isLayer Whether the requester of the display list is a layer. If so,
11765     * the view will avoid creating a layer inside the resulting display list.
11766     * @return A new or reused DisplayList object.
11767     */
11768    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
11769        if (!canHaveDisplayList()) {
11770            return null;
11771        }
11772
11773        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
11774                displayList == null || !displayList.isValid() ||
11775                (!isLayer && mRecreateDisplayList))) {
11776            // Don't need to recreate the display list, just need to tell our
11777            // children to restore/recreate theirs
11778            if (displayList != null && displayList.isValid() &&
11779                    !isLayer && !mRecreateDisplayList) {
11780                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11781                mPrivateFlags &= ~DIRTY_MASK;
11782                dispatchGetDisplayList();
11783
11784                return displayList;
11785            }
11786
11787            if (!isLayer) {
11788                // If we got here, we're recreating it. Mark it as such to ensure that
11789                // we copy in child display lists into ours in drawChild()
11790                mRecreateDisplayList = true;
11791            }
11792            if (displayList == null) {
11793                final String name = getClass().getSimpleName();
11794                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
11795                // If we're creating a new display list, make sure our parent gets invalidated
11796                // since they will need to recreate their display list to account for this
11797                // new child display list.
11798                invalidateParentCaches();
11799            }
11800
11801            boolean caching = false;
11802            final HardwareCanvas canvas = displayList.start();
11803            int restoreCount = 0;
11804            int width = mRight - mLeft;
11805            int height = mBottom - mTop;
11806
11807            try {
11808                canvas.setViewport(width, height);
11809                // The dirty rect should always be null for a display list
11810                canvas.onPreDraw(null);
11811                int layerType = (
11812                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
11813                        getLayerType() : LAYER_TYPE_NONE;
11814                if (!isLayer && layerType != LAYER_TYPE_NONE) {
11815                    if (layerType == LAYER_TYPE_HARDWARE) {
11816                        final HardwareLayer layer = getHardwareLayer();
11817                        if (layer != null && layer.isValid()) {
11818                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
11819                        } else {
11820                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
11821                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
11822                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11823                        }
11824                        caching = true;
11825                    } else {
11826                        buildDrawingCache(true);
11827                        Bitmap cache = getDrawingCache(true);
11828                        if (cache != null) {
11829                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
11830                            caching = true;
11831                        }
11832                    }
11833                } else {
11834
11835                    computeScroll();
11836
11837                    canvas.translate(-mScrollX, -mScrollY);
11838                    if (!isLayer) {
11839                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11840                        mPrivateFlags &= ~DIRTY_MASK;
11841                    }
11842
11843                    // Fast path for layouts with no backgrounds
11844                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11845                        dispatchDraw(canvas);
11846                    } else {
11847                        draw(canvas);
11848                    }
11849                }
11850            } finally {
11851                canvas.onPostDraw();
11852
11853                displayList.end();
11854                displayList.setCaching(caching);
11855                if (isLayer) {
11856                    displayList.setLeftTopRightBottom(0, 0, width, height);
11857                } else {
11858                    setDisplayListProperties(displayList);
11859                }
11860            }
11861        } else if (!isLayer) {
11862            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11863            mPrivateFlags &= ~DIRTY_MASK;
11864        }
11865
11866        return displayList;
11867    }
11868
11869    /**
11870     * Get the DisplayList for the HardwareLayer
11871     *
11872     * @param layer The HardwareLayer whose DisplayList we want
11873     * @return A DisplayList fopr the specified HardwareLayer
11874     */
11875    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
11876        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
11877        layer.setDisplayList(displayList);
11878        return displayList;
11879    }
11880
11881
11882    /**
11883     * <p>Returns a display list that can be used to draw this view again
11884     * without executing its draw method.</p>
11885     *
11886     * @return A DisplayList ready to replay, or null if caching is not enabled.
11887     *
11888     * @hide
11889     */
11890    public DisplayList getDisplayList() {
11891        mDisplayList = getDisplayList(mDisplayList, false);
11892        return mDisplayList;
11893    }
11894
11895    /**
11896     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
11897     *
11898     * @return A non-scaled bitmap representing this view or null if cache is disabled.
11899     *
11900     * @see #getDrawingCache(boolean)
11901     */
11902    public Bitmap getDrawingCache() {
11903        return getDrawingCache(false);
11904    }
11905
11906    /**
11907     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
11908     * is null when caching is disabled. If caching is enabled and the cache is not ready,
11909     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
11910     * draw from the cache when the cache is enabled. To benefit from the cache, you must
11911     * request the drawing cache by calling this method and draw it on screen if the
11912     * returned bitmap is not null.</p>
11913     *
11914     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11915     * this method will create a bitmap of the same size as this view. Because this bitmap
11916     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11917     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11918     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11919     * size than the view. This implies that your application must be able to handle this
11920     * size.</p>
11921     *
11922     * @param autoScale Indicates whether the generated bitmap should be scaled based on
11923     *        the current density of the screen when the application is in compatibility
11924     *        mode.
11925     *
11926     * @return A bitmap representing this view or null if cache is disabled.
11927     *
11928     * @see #setDrawingCacheEnabled(boolean)
11929     * @see #isDrawingCacheEnabled()
11930     * @see #buildDrawingCache(boolean)
11931     * @see #destroyDrawingCache()
11932     */
11933    public Bitmap getDrawingCache(boolean autoScale) {
11934        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
11935            return null;
11936        }
11937        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
11938            buildDrawingCache(autoScale);
11939        }
11940        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
11941    }
11942
11943    /**
11944     * <p>Frees the resources used by the drawing cache. If you call
11945     * {@link #buildDrawingCache()} manually without calling
11946     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11947     * should cleanup the cache with this method afterwards.</p>
11948     *
11949     * @see #setDrawingCacheEnabled(boolean)
11950     * @see #buildDrawingCache()
11951     * @see #getDrawingCache()
11952     */
11953    public void destroyDrawingCache() {
11954        if (mDrawingCache != null) {
11955            mDrawingCache.recycle();
11956            mDrawingCache = null;
11957        }
11958        if (mUnscaledDrawingCache != null) {
11959            mUnscaledDrawingCache.recycle();
11960            mUnscaledDrawingCache = null;
11961        }
11962    }
11963
11964    /**
11965     * Setting a solid background color for the drawing cache's bitmaps will improve
11966     * performance and memory usage. Note, though that this should only be used if this
11967     * view will always be drawn on top of a solid color.
11968     *
11969     * @param color The background color to use for the drawing cache's bitmap
11970     *
11971     * @see #setDrawingCacheEnabled(boolean)
11972     * @see #buildDrawingCache()
11973     * @see #getDrawingCache()
11974     */
11975    public void setDrawingCacheBackgroundColor(int color) {
11976        if (color != mDrawingCacheBackgroundColor) {
11977            mDrawingCacheBackgroundColor = color;
11978            mPrivateFlags &= ~DRAWING_CACHE_VALID;
11979        }
11980    }
11981
11982    /**
11983     * @see #setDrawingCacheBackgroundColor(int)
11984     *
11985     * @return The background color to used for the drawing cache's bitmap
11986     */
11987    public int getDrawingCacheBackgroundColor() {
11988        return mDrawingCacheBackgroundColor;
11989    }
11990
11991    /**
11992     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
11993     *
11994     * @see #buildDrawingCache(boolean)
11995     */
11996    public void buildDrawingCache() {
11997        buildDrawingCache(false);
11998    }
11999
12000    /**
12001     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12002     *
12003     * <p>If you call {@link #buildDrawingCache()} manually without calling
12004     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12005     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12006     *
12007     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12008     * this method will create a bitmap of the same size as this view. Because this bitmap
12009     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12010     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12011     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12012     * size than the view. This implies that your application must be able to handle this
12013     * size.</p>
12014     *
12015     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12016     * you do not need the drawing cache bitmap, calling this method will increase memory
12017     * usage and cause the view to be rendered in software once, thus negatively impacting
12018     * performance.</p>
12019     *
12020     * @see #getDrawingCache()
12021     * @see #destroyDrawingCache()
12022     */
12023    public void buildDrawingCache(boolean autoScale) {
12024        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12025                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12026            mCachingFailed = false;
12027
12028            if (ViewDebug.TRACE_HIERARCHY) {
12029                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
12030            }
12031
12032            int width = mRight - mLeft;
12033            int height = mBottom - mTop;
12034
12035            final AttachInfo attachInfo = mAttachInfo;
12036            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12037
12038            if (autoScale && scalingRequired) {
12039                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12040                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12041            }
12042
12043            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12044            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12045            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12046
12047            if (width <= 0 || height <= 0 ||
12048                     // Projected bitmap size in bytes
12049                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12050                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12051                destroyDrawingCache();
12052                mCachingFailed = true;
12053                return;
12054            }
12055
12056            boolean clear = true;
12057            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12058
12059            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12060                Bitmap.Config quality;
12061                if (!opaque) {
12062                    // Never pick ARGB_4444 because it looks awful
12063                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12064                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12065                        case DRAWING_CACHE_QUALITY_AUTO:
12066                            quality = Bitmap.Config.ARGB_8888;
12067                            break;
12068                        case DRAWING_CACHE_QUALITY_LOW:
12069                            quality = Bitmap.Config.ARGB_8888;
12070                            break;
12071                        case DRAWING_CACHE_QUALITY_HIGH:
12072                            quality = Bitmap.Config.ARGB_8888;
12073                            break;
12074                        default:
12075                            quality = Bitmap.Config.ARGB_8888;
12076                            break;
12077                    }
12078                } else {
12079                    // Optimization for translucent windows
12080                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12081                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12082                }
12083
12084                // Try to cleanup memory
12085                if (bitmap != null) bitmap.recycle();
12086
12087                try {
12088                    bitmap = Bitmap.createBitmap(width, height, quality);
12089                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12090                    if (autoScale) {
12091                        mDrawingCache = bitmap;
12092                    } else {
12093                        mUnscaledDrawingCache = bitmap;
12094                    }
12095                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12096                } catch (OutOfMemoryError e) {
12097                    // If there is not enough memory to create the bitmap cache, just
12098                    // ignore the issue as bitmap caches are not required to draw the
12099                    // view hierarchy
12100                    if (autoScale) {
12101                        mDrawingCache = null;
12102                    } else {
12103                        mUnscaledDrawingCache = null;
12104                    }
12105                    mCachingFailed = true;
12106                    return;
12107                }
12108
12109                clear = drawingCacheBackgroundColor != 0;
12110            }
12111
12112            Canvas canvas;
12113            if (attachInfo != null) {
12114                canvas = attachInfo.mCanvas;
12115                if (canvas == null) {
12116                    canvas = new Canvas();
12117                }
12118                canvas.setBitmap(bitmap);
12119                // Temporarily clobber the cached Canvas in case one of our children
12120                // is also using a drawing cache. Without this, the children would
12121                // steal the canvas by attaching their own bitmap to it and bad, bad
12122                // thing would happen (invisible views, corrupted drawings, etc.)
12123                attachInfo.mCanvas = null;
12124            } else {
12125                // This case should hopefully never or seldom happen
12126                canvas = new Canvas(bitmap);
12127            }
12128
12129            if (clear) {
12130                bitmap.eraseColor(drawingCacheBackgroundColor);
12131            }
12132
12133            computeScroll();
12134            final int restoreCount = canvas.save();
12135
12136            if (autoScale && scalingRequired) {
12137                final float scale = attachInfo.mApplicationScale;
12138                canvas.scale(scale, scale);
12139            }
12140
12141            canvas.translate(-mScrollX, -mScrollY);
12142
12143            mPrivateFlags |= DRAWN;
12144            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12145                    mLayerType != LAYER_TYPE_NONE) {
12146                mPrivateFlags |= DRAWING_CACHE_VALID;
12147            }
12148
12149            // Fast path for layouts with no backgrounds
12150            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12151                if (ViewDebug.TRACE_HIERARCHY) {
12152                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12153                }
12154                mPrivateFlags &= ~DIRTY_MASK;
12155                dispatchDraw(canvas);
12156            } else {
12157                draw(canvas);
12158            }
12159
12160            canvas.restoreToCount(restoreCount);
12161            canvas.setBitmap(null);
12162
12163            if (attachInfo != null) {
12164                // Restore the cached Canvas for our siblings
12165                attachInfo.mCanvas = canvas;
12166            }
12167        }
12168    }
12169
12170    /**
12171     * Create a snapshot of the view into a bitmap.  We should probably make
12172     * some form of this public, but should think about the API.
12173     */
12174    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12175        int width = mRight - mLeft;
12176        int height = mBottom - mTop;
12177
12178        final AttachInfo attachInfo = mAttachInfo;
12179        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12180        width = (int) ((width * scale) + 0.5f);
12181        height = (int) ((height * scale) + 0.5f);
12182
12183        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12184        if (bitmap == null) {
12185            throw new OutOfMemoryError();
12186        }
12187
12188        Resources resources = getResources();
12189        if (resources != null) {
12190            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12191        }
12192
12193        Canvas canvas;
12194        if (attachInfo != null) {
12195            canvas = attachInfo.mCanvas;
12196            if (canvas == null) {
12197                canvas = new Canvas();
12198            }
12199            canvas.setBitmap(bitmap);
12200            // Temporarily clobber the cached Canvas in case one of our children
12201            // is also using a drawing cache. Without this, the children would
12202            // steal the canvas by attaching their own bitmap to it and bad, bad
12203            // things would happen (invisible views, corrupted drawings, etc.)
12204            attachInfo.mCanvas = null;
12205        } else {
12206            // This case should hopefully never or seldom happen
12207            canvas = new Canvas(bitmap);
12208        }
12209
12210        if ((backgroundColor & 0xff000000) != 0) {
12211            bitmap.eraseColor(backgroundColor);
12212        }
12213
12214        computeScroll();
12215        final int restoreCount = canvas.save();
12216        canvas.scale(scale, scale);
12217        canvas.translate(-mScrollX, -mScrollY);
12218
12219        // Temporarily remove the dirty mask
12220        int flags = mPrivateFlags;
12221        mPrivateFlags &= ~DIRTY_MASK;
12222
12223        // Fast path for layouts with no backgrounds
12224        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12225            dispatchDraw(canvas);
12226        } else {
12227            draw(canvas);
12228        }
12229
12230        mPrivateFlags = flags;
12231
12232        canvas.restoreToCount(restoreCount);
12233        canvas.setBitmap(null);
12234
12235        if (attachInfo != null) {
12236            // Restore the cached Canvas for our siblings
12237            attachInfo.mCanvas = canvas;
12238        }
12239
12240        return bitmap;
12241    }
12242
12243    /**
12244     * Indicates whether this View is currently in edit mode. A View is usually
12245     * in edit mode when displayed within a developer tool. For instance, if
12246     * this View is being drawn by a visual user interface builder, this method
12247     * should return true.
12248     *
12249     * Subclasses should check the return value of this method to provide
12250     * different behaviors if their normal behavior might interfere with the
12251     * host environment. For instance: the class spawns a thread in its
12252     * constructor, the drawing code relies on device-specific features, etc.
12253     *
12254     * This method is usually checked in the drawing code of custom widgets.
12255     *
12256     * @return True if this View is in edit mode, false otherwise.
12257     */
12258    public boolean isInEditMode() {
12259        return false;
12260    }
12261
12262    /**
12263     * If the View draws content inside its padding and enables fading edges,
12264     * it needs to support padding offsets. Padding offsets are added to the
12265     * fading edges to extend the length of the fade so that it covers pixels
12266     * drawn inside the padding.
12267     *
12268     * Subclasses of this class should override this method if they need
12269     * to draw content inside the padding.
12270     *
12271     * @return True if padding offset must be applied, false otherwise.
12272     *
12273     * @see #getLeftPaddingOffset()
12274     * @see #getRightPaddingOffset()
12275     * @see #getTopPaddingOffset()
12276     * @see #getBottomPaddingOffset()
12277     *
12278     * @since CURRENT
12279     */
12280    protected boolean isPaddingOffsetRequired() {
12281        return false;
12282    }
12283
12284    /**
12285     * Amount by which to extend the left fading region. Called only when
12286     * {@link #isPaddingOffsetRequired()} returns true.
12287     *
12288     * @return The left padding offset in pixels.
12289     *
12290     * @see #isPaddingOffsetRequired()
12291     *
12292     * @since CURRENT
12293     */
12294    protected int getLeftPaddingOffset() {
12295        return 0;
12296    }
12297
12298    /**
12299     * Amount by which to extend the right fading region. Called only when
12300     * {@link #isPaddingOffsetRequired()} returns true.
12301     *
12302     * @return The right padding offset in pixels.
12303     *
12304     * @see #isPaddingOffsetRequired()
12305     *
12306     * @since CURRENT
12307     */
12308    protected int getRightPaddingOffset() {
12309        return 0;
12310    }
12311
12312    /**
12313     * Amount by which to extend the top fading region. Called only when
12314     * {@link #isPaddingOffsetRequired()} returns true.
12315     *
12316     * @return The top padding offset in pixels.
12317     *
12318     * @see #isPaddingOffsetRequired()
12319     *
12320     * @since CURRENT
12321     */
12322    protected int getTopPaddingOffset() {
12323        return 0;
12324    }
12325
12326    /**
12327     * Amount by which to extend the bottom fading region. Called only when
12328     * {@link #isPaddingOffsetRequired()} returns true.
12329     *
12330     * @return The bottom padding offset in pixels.
12331     *
12332     * @see #isPaddingOffsetRequired()
12333     *
12334     * @since CURRENT
12335     */
12336    protected int getBottomPaddingOffset() {
12337        return 0;
12338    }
12339
12340    /**
12341     * @hide
12342     * @param offsetRequired
12343     */
12344    protected int getFadeTop(boolean offsetRequired) {
12345        int top = mPaddingTop;
12346        if (offsetRequired) top += getTopPaddingOffset();
12347        return top;
12348    }
12349
12350    /**
12351     * @hide
12352     * @param offsetRequired
12353     */
12354    protected int getFadeHeight(boolean offsetRequired) {
12355        int padding = mPaddingTop;
12356        if (offsetRequired) padding += getTopPaddingOffset();
12357        return mBottom - mTop - mPaddingBottom - padding;
12358    }
12359
12360    /**
12361     * <p>Indicates whether this view is attached to a hardware accelerated
12362     * window or not.</p>
12363     *
12364     * <p>Even if this method returns true, it does not mean that every call
12365     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12366     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12367     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12368     * window is hardware accelerated,
12369     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12370     * return false, and this method will return true.</p>
12371     *
12372     * @return True if the view is attached to a window and the window is
12373     *         hardware accelerated; false in any other case.
12374     */
12375    public boolean isHardwareAccelerated() {
12376        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12377    }
12378
12379    /**
12380     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12381     * case of an active Animation being run on the view.
12382     */
12383    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12384            Animation a, boolean scalingRequired) {
12385        Transformation invalidationTransform;
12386        final int flags = parent.mGroupFlags;
12387        final boolean initialized = a.isInitialized();
12388        if (!initialized) {
12389            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12390            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12391            onAnimationStart();
12392        }
12393
12394        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12395        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12396            if (parent.mInvalidationTransformation == null) {
12397                parent.mInvalidationTransformation = new Transformation();
12398            }
12399            invalidationTransform = parent.mInvalidationTransformation;
12400            a.getTransformation(drawingTime, invalidationTransform, 1f);
12401        } else {
12402            invalidationTransform = parent.mChildTransformation;
12403        }
12404        if (more) {
12405            if (!a.willChangeBounds()) {
12406                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12407                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12408                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12409                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12410                    // The child need to draw an animation, potentially offscreen, so
12411                    // make sure we do not cancel invalidate requests
12412                    parent.mPrivateFlags |= DRAW_ANIMATION;
12413                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12414                }
12415            } else {
12416                if (parent.mInvalidateRegion == null) {
12417                    parent.mInvalidateRegion = new RectF();
12418                }
12419                final RectF region = parent.mInvalidateRegion;
12420                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12421                        invalidationTransform);
12422
12423                // The child need to draw an animation, potentially offscreen, so
12424                // make sure we do not cancel invalidate requests
12425                parent.mPrivateFlags |= DRAW_ANIMATION;
12426
12427                final int left = mLeft + (int) region.left;
12428                final int top = mTop + (int) region.top;
12429                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12430                        top + (int) (region.height() + .5f));
12431            }
12432        }
12433        return more;
12434    }
12435
12436    void setDisplayListProperties() {
12437        setDisplayListProperties(mDisplayList);
12438    }
12439
12440    /**
12441     * This method is called by getDisplayList() when a display list is created or re-rendered.
12442     * It sets or resets the current value of all properties on that display list (resetting is
12443     * necessary when a display list is being re-created, because we need to make sure that
12444     * previously-set transform values
12445     */
12446    void setDisplayListProperties(DisplayList displayList) {
12447        if (displayList != null) {
12448            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12449            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12450            if (mParent instanceof ViewGroup) {
12451                displayList.setClipChildren(
12452                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12453            }
12454            float alpha = 1;
12455            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12456                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12457                ViewGroup parentVG = (ViewGroup) mParent;
12458                final boolean hasTransform =
12459                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12460                if (hasTransform) {
12461                    Transformation transform = parentVG.mChildTransformation;
12462                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12463                    if (transformType != Transformation.TYPE_IDENTITY) {
12464                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12465                            alpha = transform.getAlpha();
12466                        }
12467                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12468                            displayList.setStaticMatrix(transform.getMatrix());
12469                        }
12470                    }
12471                }
12472            }
12473            if (mTransformationInfo != null) {
12474                alpha *= mTransformationInfo.mAlpha;
12475                if (alpha < 1) {
12476                    final int multipliedAlpha = (int) (255 * alpha);
12477                    if (onSetAlpha(multipliedAlpha)) {
12478                        alpha = 1;
12479                    }
12480                }
12481                displayList.setTransformationInfo(alpha,
12482                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12483                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12484                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12485                        mTransformationInfo.mScaleY);
12486                if (mTransformationInfo.mCamera == null) {
12487                    mTransformationInfo.mCamera = new Camera();
12488                    mTransformationInfo.matrix3D = new Matrix();
12489                }
12490                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12491                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12492                    displayList.setPivotX(getPivotX());
12493                    displayList.setPivotY(getPivotY());
12494                }
12495            } else if (alpha < 1) {
12496                displayList.setAlpha(alpha);
12497            }
12498        }
12499    }
12500
12501    /**
12502     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12503     * This draw() method is an implementation detail and is not intended to be overridden or
12504     * to be called from anywhere else other than ViewGroup.drawChild().
12505     */
12506    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12507        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12508        boolean more = false;
12509        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12510        final int flags = parent.mGroupFlags;
12511
12512        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12513            parent.mChildTransformation.clear();
12514            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12515        }
12516
12517        Transformation transformToApply = null;
12518        boolean concatMatrix = false;
12519
12520        boolean scalingRequired = false;
12521        boolean caching;
12522        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12523
12524        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12525        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12526                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12527            caching = true;
12528            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12529            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12530        } else {
12531            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12532        }
12533
12534        final Animation a = getAnimation();
12535        if (a != null) {
12536            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12537            concatMatrix = a.willChangeTransformationMatrix();
12538            transformToApply = parent.mChildTransformation;
12539        } else if (!useDisplayListProperties &&
12540                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12541            final boolean hasTransform =
12542                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
12543            if (hasTransform) {
12544                final int transformType = parent.mChildTransformation.getTransformationType();
12545                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12546                        parent.mChildTransformation : null;
12547                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12548            }
12549        }
12550
12551        concatMatrix |= !childHasIdentityMatrix;
12552
12553        // Sets the flag as early as possible to allow draw() implementations
12554        // to call invalidate() successfully when doing animations
12555        mPrivateFlags |= DRAWN;
12556
12557        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12558                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12559            return more;
12560        }
12561
12562        if (hardwareAccelerated) {
12563            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12564            // retain the flag's value temporarily in the mRecreateDisplayList flag
12565            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12566            mPrivateFlags &= ~INVALIDATED;
12567        }
12568
12569        computeScroll();
12570
12571        final int sx = mScrollX;
12572        final int sy = mScrollY;
12573
12574        DisplayList displayList = null;
12575        Bitmap cache = null;
12576        boolean hasDisplayList = false;
12577        if (caching) {
12578            if (!hardwareAccelerated) {
12579                if (layerType != LAYER_TYPE_NONE) {
12580                    layerType = LAYER_TYPE_SOFTWARE;
12581                    buildDrawingCache(true);
12582                }
12583                cache = getDrawingCache(true);
12584            } else {
12585                switch (layerType) {
12586                    case LAYER_TYPE_SOFTWARE:
12587                        if (useDisplayListProperties) {
12588                            hasDisplayList = canHaveDisplayList();
12589                        } else {
12590                            buildDrawingCache(true);
12591                            cache = getDrawingCache(true);
12592                        }
12593                        break;
12594                    case LAYER_TYPE_HARDWARE:
12595                        if (useDisplayListProperties) {
12596                            hasDisplayList = canHaveDisplayList();
12597                        }
12598                        break;
12599                    case LAYER_TYPE_NONE:
12600                        // Delay getting the display list until animation-driven alpha values are
12601                        // set up and possibly passed on to the view
12602                        hasDisplayList = canHaveDisplayList();
12603                        break;
12604                }
12605            }
12606        }
12607        useDisplayListProperties &= hasDisplayList;
12608        if (useDisplayListProperties) {
12609            displayList = getDisplayList();
12610            if (!displayList.isValid()) {
12611                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12612                // to getDisplayList(), the display list will be marked invalid and we should not
12613                // try to use it again.
12614                displayList = null;
12615                hasDisplayList = false;
12616                useDisplayListProperties = false;
12617            }
12618        }
12619
12620        final boolean hasNoCache = cache == null || hasDisplayList;
12621        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12622                layerType != LAYER_TYPE_HARDWARE;
12623
12624        int restoreTo = -1;
12625        if (!useDisplayListProperties || transformToApply != null) {
12626            restoreTo = canvas.save();
12627        }
12628        if (offsetForScroll) {
12629            canvas.translate(mLeft - sx, mTop - sy);
12630        } else {
12631            if (!useDisplayListProperties) {
12632                canvas.translate(mLeft, mTop);
12633            }
12634            if (scalingRequired) {
12635                if (useDisplayListProperties) {
12636                    // TODO: Might not need this if we put everything inside the DL
12637                    restoreTo = canvas.save();
12638                }
12639                // mAttachInfo cannot be null, otherwise scalingRequired == false
12640                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12641                canvas.scale(scale, scale);
12642            }
12643        }
12644
12645        float alpha = useDisplayListProperties ? 1 : getAlpha();
12646        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12647            if (transformToApply != null || !childHasIdentityMatrix) {
12648                int transX = 0;
12649                int transY = 0;
12650
12651                if (offsetForScroll) {
12652                    transX = -sx;
12653                    transY = -sy;
12654                }
12655
12656                if (transformToApply != null) {
12657                    if (concatMatrix) {
12658                        if (useDisplayListProperties) {
12659                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12660                        } else {
12661                            // Undo the scroll translation, apply the transformation matrix,
12662                            // then redo the scroll translate to get the correct result.
12663                            canvas.translate(-transX, -transY);
12664                            canvas.concat(transformToApply.getMatrix());
12665                            canvas.translate(transX, transY);
12666                        }
12667                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12668                    }
12669
12670                    float transformAlpha = transformToApply.getAlpha();
12671                    if (transformAlpha < 1) {
12672                        alpha *= transformToApply.getAlpha();
12673                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12674                    }
12675                }
12676
12677                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12678                    canvas.translate(-transX, -transY);
12679                    canvas.concat(getMatrix());
12680                    canvas.translate(transX, transY);
12681                }
12682            }
12683
12684            if (alpha < 1) {
12685                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12686                if (hasNoCache) {
12687                    final int multipliedAlpha = (int) (255 * alpha);
12688                    if (!onSetAlpha(multipliedAlpha)) {
12689                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12690                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
12691                                layerType != LAYER_TYPE_NONE) {
12692                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
12693                        }
12694                        if (useDisplayListProperties) {
12695                            displayList.setAlpha(alpha * getAlpha());
12696                        } else  if (layerType == LAYER_TYPE_NONE) {
12697                            final int scrollX = hasDisplayList ? 0 : sx;
12698                            final int scrollY = hasDisplayList ? 0 : sy;
12699                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
12700                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
12701                        }
12702                    } else {
12703                        // Alpha is handled by the child directly, clobber the layer's alpha
12704                        mPrivateFlags |= ALPHA_SET;
12705                    }
12706                }
12707            }
12708        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12709            onSetAlpha(255);
12710            mPrivateFlags &= ~ALPHA_SET;
12711        }
12712
12713        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
12714                !useDisplayListProperties) {
12715            if (offsetForScroll) {
12716                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
12717            } else {
12718                if (!scalingRequired || cache == null) {
12719                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
12720                } else {
12721                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
12722                }
12723            }
12724        }
12725
12726        if (!useDisplayListProperties && hasDisplayList) {
12727            displayList = getDisplayList();
12728            if (!displayList.isValid()) {
12729                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12730                // to getDisplayList(), the display list will be marked invalid and we should not
12731                // try to use it again.
12732                displayList = null;
12733                hasDisplayList = false;
12734            }
12735        }
12736
12737        if (hasNoCache) {
12738            boolean layerRendered = false;
12739            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
12740                final HardwareLayer layer = getHardwareLayer();
12741                if (layer != null && layer.isValid()) {
12742                    mLayerPaint.setAlpha((int) (alpha * 255));
12743                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
12744                    layerRendered = true;
12745                } else {
12746                    final int scrollX = hasDisplayList ? 0 : sx;
12747                    final int scrollY = hasDisplayList ? 0 : sy;
12748                    canvas.saveLayer(scrollX, scrollY,
12749                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
12750                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12751                }
12752            }
12753
12754            if (!layerRendered) {
12755                if (!hasDisplayList) {
12756                    // Fast path for layouts with no backgrounds
12757                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12758                        if (ViewDebug.TRACE_HIERARCHY) {
12759                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
12760                        }
12761                        mPrivateFlags &= ~DIRTY_MASK;
12762                        dispatchDraw(canvas);
12763                    } else {
12764                        draw(canvas);
12765                    }
12766                } else {
12767                    mPrivateFlags &= ~DIRTY_MASK;
12768                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
12769                }
12770            }
12771        } else if (cache != null) {
12772            mPrivateFlags &= ~DIRTY_MASK;
12773            Paint cachePaint;
12774
12775            if (layerType == LAYER_TYPE_NONE) {
12776                cachePaint = parent.mCachePaint;
12777                if (cachePaint == null) {
12778                    cachePaint = new Paint();
12779                    cachePaint.setDither(false);
12780                    parent.mCachePaint = cachePaint;
12781                }
12782                if (alpha < 1) {
12783                    cachePaint.setAlpha((int) (alpha * 255));
12784                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12785                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
12786                    cachePaint.setAlpha(255);
12787                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12788                }
12789            } else {
12790                cachePaint = mLayerPaint;
12791                cachePaint.setAlpha((int) (alpha * 255));
12792            }
12793            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
12794        }
12795
12796        if (restoreTo >= 0) {
12797            canvas.restoreToCount(restoreTo);
12798        }
12799
12800        if (a != null && !more) {
12801            if (!hardwareAccelerated && !a.getFillAfter()) {
12802                onSetAlpha(255);
12803            }
12804            parent.finishAnimatingView(this, a);
12805        }
12806
12807        if (more && hardwareAccelerated) {
12808            // invalidation is the trigger to recreate display lists, so if we're using
12809            // display lists to render, force an invalidate to allow the animation to
12810            // continue drawing another frame
12811            parent.invalidate(true);
12812            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12813                // alpha animations should cause the child to recreate its display list
12814                invalidate(true);
12815            }
12816        }
12817
12818        mRecreateDisplayList = false;
12819
12820        return more;
12821    }
12822
12823    /**
12824     * Manually render this view (and all of its children) to the given Canvas.
12825     * The view must have already done a full layout before this function is
12826     * called.  When implementing a view, implement
12827     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
12828     * If you do need to override this method, call the superclass version.
12829     *
12830     * @param canvas The Canvas to which the View is rendered.
12831     */
12832    public void draw(Canvas canvas) {
12833        if (ViewDebug.TRACE_HIERARCHY) {
12834            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12835        }
12836
12837        final int privateFlags = mPrivateFlags;
12838        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
12839                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
12840        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
12841
12842        /*
12843         * Draw traversal performs several drawing steps which must be executed
12844         * in the appropriate order:
12845         *
12846         *      1. Draw the background
12847         *      2. If necessary, save the canvas' layers to prepare for fading
12848         *      3. Draw view's content
12849         *      4. Draw children
12850         *      5. If necessary, draw the fading edges and restore layers
12851         *      6. Draw decorations (scrollbars for instance)
12852         */
12853
12854        // Step 1, draw the background, if needed
12855        int saveCount;
12856
12857        if (!dirtyOpaque) {
12858            final Drawable background = mBackground;
12859            if (background != null) {
12860                final int scrollX = mScrollX;
12861                final int scrollY = mScrollY;
12862
12863                if (mBackgroundSizeChanged) {
12864                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
12865                    mBackgroundSizeChanged = false;
12866                }
12867
12868                if ((scrollX | scrollY) == 0) {
12869                    background.draw(canvas);
12870                } else {
12871                    canvas.translate(scrollX, scrollY);
12872                    background.draw(canvas);
12873                    canvas.translate(-scrollX, -scrollY);
12874                }
12875            }
12876        }
12877
12878        // skip step 2 & 5 if possible (common case)
12879        final int viewFlags = mViewFlags;
12880        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
12881        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
12882        if (!verticalEdges && !horizontalEdges) {
12883            // Step 3, draw the content
12884            if (!dirtyOpaque) onDraw(canvas);
12885
12886            // Step 4, draw the children
12887            dispatchDraw(canvas);
12888
12889            // Step 6, draw decorations (scrollbars)
12890            onDrawScrollBars(canvas);
12891
12892            // we're done...
12893            return;
12894        }
12895
12896        /*
12897         * Here we do the full fledged routine...
12898         * (this is an uncommon case where speed matters less,
12899         * this is why we repeat some of the tests that have been
12900         * done above)
12901         */
12902
12903        boolean drawTop = false;
12904        boolean drawBottom = false;
12905        boolean drawLeft = false;
12906        boolean drawRight = false;
12907
12908        float topFadeStrength = 0.0f;
12909        float bottomFadeStrength = 0.0f;
12910        float leftFadeStrength = 0.0f;
12911        float rightFadeStrength = 0.0f;
12912
12913        // Step 2, save the canvas' layers
12914        int paddingLeft = mPaddingLeft;
12915
12916        final boolean offsetRequired = isPaddingOffsetRequired();
12917        if (offsetRequired) {
12918            paddingLeft += getLeftPaddingOffset();
12919        }
12920
12921        int left = mScrollX + paddingLeft;
12922        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
12923        int top = mScrollY + getFadeTop(offsetRequired);
12924        int bottom = top + getFadeHeight(offsetRequired);
12925
12926        if (offsetRequired) {
12927            right += getRightPaddingOffset();
12928            bottom += getBottomPaddingOffset();
12929        }
12930
12931        final ScrollabilityCache scrollabilityCache = mScrollCache;
12932        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
12933        int length = (int) fadeHeight;
12934
12935        // clip the fade length if top and bottom fades overlap
12936        // overlapping fades produce odd-looking artifacts
12937        if (verticalEdges && (top + length > bottom - length)) {
12938            length = (bottom - top) / 2;
12939        }
12940
12941        // also clip horizontal fades if necessary
12942        if (horizontalEdges && (left + length > right - length)) {
12943            length = (right - left) / 2;
12944        }
12945
12946        if (verticalEdges) {
12947            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
12948            drawTop = topFadeStrength * fadeHeight > 1.0f;
12949            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
12950            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
12951        }
12952
12953        if (horizontalEdges) {
12954            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
12955            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
12956            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
12957            drawRight = rightFadeStrength * fadeHeight > 1.0f;
12958        }
12959
12960        saveCount = canvas.getSaveCount();
12961
12962        int solidColor = getSolidColor();
12963        if (solidColor == 0) {
12964            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12965
12966            if (drawTop) {
12967                canvas.saveLayer(left, top, right, top + length, null, flags);
12968            }
12969
12970            if (drawBottom) {
12971                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
12972            }
12973
12974            if (drawLeft) {
12975                canvas.saveLayer(left, top, left + length, bottom, null, flags);
12976            }
12977
12978            if (drawRight) {
12979                canvas.saveLayer(right - length, top, right, bottom, null, flags);
12980            }
12981        } else {
12982            scrollabilityCache.setFadeColor(solidColor);
12983        }
12984
12985        // Step 3, draw the content
12986        if (!dirtyOpaque) onDraw(canvas);
12987
12988        // Step 4, draw the children
12989        dispatchDraw(canvas);
12990
12991        // Step 5, draw the fade effect and restore layers
12992        final Paint p = scrollabilityCache.paint;
12993        final Matrix matrix = scrollabilityCache.matrix;
12994        final Shader fade = scrollabilityCache.shader;
12995
12996        if (drawTop) {
12997            matrix.setScale(1, fadeHeight * topFadeStrength);
12998            matrix.postTranslate(left, top);
12999            fade.setLocalMatrix(matrix);
13000            canvas.drawRect(left, top, right, top + length, p);
13001        }
13002
13003        if (drawBottom) {
13004            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13005            matrix.postRotate(180);
13006            matrix.postTranslate(left, bottom);
13007            fade.setLocalMatrix(matrix);
13008            canvas.drawRect(left, bottom - length, right, bottom, p);
13009        }
13010
13011        if (drawLeft) {
13012            matrix.setScale(1, fadeHeight * leftFadeStrength);
13013            matrix.postRotate(-90);
13014            matrix.postTranslate(left, top);
13015            fade.setLocalMatrix(matrix);
13016            canvas.drawRect(left, top, left + length, bottom, p);
13017        }
13018
13019        if (drawRight) {
13020            matrix.setScale(1, fadeHeight * rightFadeStrength);
13021            matrix.postRotate(90);
13022            matrix.postTranslate(right, top);
13023            fade.setLocalMatrix(matrix);
13024            canvas.drawRect(right - length, top, right, bottom, p);
13025        }
13026
13027        canvas.restoreToCount(saveCount);
13028
13029        // Step 6, draw decorations (scrollbars)
13030        onDrawScrollBars(canvas);
13031    }
13032
13033    /**
13034     * Override this if your view is known to always be drawn on top of a solid color background,
13035     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13036     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13037     * should be set to 0xFF.
13038     *
13039     * @see #setVerticalFadingEdgeEnabled(boolean)
13040     * @see #setHorizontalFadingEdgeEnabled(boolean)
13041     *
13042     * @return The known solid color background for this view, or 0 if the color may vary
13043     */
13044    @ViewDebug.ExportedProperty(category = "drawing")
13045    public int getSolidColor() {
13046        return 0;
13047    }
13048
13049    /**
13050     * Build a human readable string representation of the specified view flags.
13051     *
13052     * @param flags the view flags to convert to a string
13053     * @return a String representing the supplied flags
13054     */
13055    private static String printFlags(int flags) {
13056        String output = "";
13057        int numFlags = 0;
13058        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13059            output += "TAKES_FOCUS";
13060            numFlags++;
13061        }
13062
13063        switch (flags & VISIBILITY_MASK) {
13064        case INVISIBLE:
13065            if (numFlags > 0) {
13066                output += " ";
13067            }
13068            output += "INVISIBLE";
13069            // USELESS HERE numFlags++;
13070            break;
13071        case GONE:
13072            if (numFlags > 0) {
13073                output += " ";
13074            }
13075            output += "GONE";
13076            // USELESS HERE numFlags++;
13077            break;
13078        default:
13079            break;
13080        }
13081        return output;
13082    }
13083
13084    /**
13085     * Build a human readable string representation of the specified private
13086     * view flags.
13087     *
13088     * @param privateFlags the private view flags to convert to a string
13089     * @return a String representing the supplied flags
13090     */
13091    private static String printPrivateFlags(int privateFlags) {
13092        String output = "";
13093        int numFlags = 0;
13094
13095        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13096            output += "WANTS_FOCUS";
13097            numFlags++;
13098        }
13099
13100        if ((privateFlags & FOCUSED) == FOCUSED) {
13101            if (numFlags > 0) {
13102                output += " ";
13103            }
13104            output += "FOCUSED";
13105            numFlags++;
13106        }
13107
13108        if ((privateFlags & SELECTED) == SELECTED) {
13109            if (numFlags > 0) {
13110                output += " ";
13111            }
13112            output += "SELECTED";
13113            numFlags++;
13114        }
13115
13116        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13117            if (numFlags > 0) {
13118                output += " ";
13119            }
13120            output += "IS_ROOT_NAMESPACE";
13121            numFlags++;
13122        }
13123
13124        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13125            if (numFlags > 0) {
13126                output += " ";
13127            }
13128            output += "HAS_BOUNDS";
13129            numFlags++;
13130        }
13131
13132        if ((privateFlags & DRAWN) == DRAWN) {
13133            if (numFlags > 0) {
13134                output += " ";
13135            }
13136            output += "DRAWN";
13137            // USELESS HERE numFlags++;
13138        }
13139        return output;
13140    }
13141
13142    /**
13143     * <p>Indicates whether or not this view's layout will be requested during
13144     * the next hierarchy layout pass.</p>
13145     *
13146     * @return true if the layout will be forced during next layout pass
13147     */
13148    public boolean isLayoutRequested() {
13149        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13150    }
13151
13152    /**
13153     * Assign a size and position to a view and all of its
13154     * descendants
13155     *
13156     * <p>This is the second phase of the layout mechanism.
13157     * (The first is measuring). In this phase, each parent calls
13158     * layout on all of its children to position them.
13159     * This is typically done using the child measurements
13160     * that were stored in the measure pass().</p>
13161     *
13162     * <p>Derived classes should not override this method.
13163     * Derived classes with children should override
13164     * onLayout. In that method, they should
13165     * call layout on each of their children.</p>
13166     *
13167     * @param l Left position, relative to parent
13168     * @param t Top position, relative to parent
13169     * @param r Right position, relative to parent
13170     * @param b Bottom position, relative to parent
13171     */
13172    @SuppressWarnings({"unchecked"})
13173    public void layout(int l, int t, int r, int b) {
13174        int oldL = mLeft;
13175        int oldT = mTop;
13176        int oldB = mBottom;
13177        int oldR = mRight;
13178        boolean changed = setFrame(l, t, r, b);
13179        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13180            if (ViewDebug.TRACE_HIERARCHY) {
13181                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13182            }
13183
13184            onLayout(changed, l, t, r, b);
13185            mPrivateFlags &= ~LAYOUT_REQUIRED;
13186
13187            ListenerInfo li = mListenerInfo;
13188            if (li != null && li.mOnLayoutChangeListeners != null) {
13189                ArrayList<OnLayoutChangeListener> listenersCopy =
13190                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13191                int numListeners = listenersCopy.size();
13192                for (int i = 0; i < numListeners; ++i) {
13193                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13194                }
13195            }
13196        }
13197        mPrivateFlags &= ~FORCE_LAYOUT;
13198    }
13199
13200    /**
13201     * Called from layout when this view should
13202     * assign a size and position to each of its children.
13203     *
13204     * Derived classes with children should override
13205     * this method and call layout on each of
13206     * their children.
13207     * @param changed This is a new size or position for this view
13208     * @param left Left position, relative to parent
13209     * @param top Top position, relative to parent
13210     * @param right Right position, relative to parent
13211     * @param bottom Bottom position, relative to parent
13212     */
13213    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13214    }
13215
13216    /**
13217     * Assign a size and position to this view.
13218     *
13219     * This is called from layout.
13220     *
13221     * @param left Left position, relative to parent
13222     * @param top Top position, relative to parent
13223     * @param right Right position, relative to parent
13224     * @param bottom Bottom position, relative to parent
13225     * @return true if the new size and position are different than the
13226     *         previous ones
13227     * {@hide}
13228     */
13229    protected boolean setFrame(int left, int top, int right, int bottom) {
13230        boolean changed = false;
13231
13232        if (DBG) {
13233            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13234                    + right + "," + bottom + ")");
13235        }
13236
13237        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13238            changed = true;
13239
13240            // Remember our drawn bit
13241            int drawn = mPrivateFlags & DRAWN;
13242
13243            int oldWidth = mRight - mLeft;
13244            int oldHeight = mBottom - mTop;
13245            int newWidth = right - left;
13246            int newHeight = bottom - top;
13247            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13248
13249            // Invalidate our old position
13250            invalidate(sizeChanged);
13251
13252            mLeft = left;
13253            mTop = top;
13254            mRight = right;
13255            mBottom = bottom;
13256            if (mDisplayList != null) {
13257                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13258            }
13259
13260            mPrivateFlags |= HAS_BOUNDS;
13261
13262
13263            if (sizeChanged) {
13264                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13265                    // A change in dimension means an auto-centered pivot point changes, too
13266                    if (mTransformationInfo != null) {
13267                        mTransformationInfo.mMatrixDirty = true;
13268                    }
13269                }
13270                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13271            }
13272
13273            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13274                // If we are visible, force the DRAWN bit to on so that
13275                // this invalidate will go through (at least to our parent).
13276                // This is because someone may have invalidated this view
13277                // before this call to setFrame came in, thereby clearing
13278                // the DRAWN bit.
13279                mPrivateFlags |= DRAWN;
13280                invalidate(sizeChanged);
13281                // parent display list may need to be recreated based on a change in the bounds
13282                // of any child
13283                invalidateParentCaches();
13284            }
13285
13286            // Reset drawn bit to original value (invalidate turns it off)
13287            mPrivateFlags |= drawn;
13288
13289            mBackgroundSizeChanged = true;
13290        }
13291        return changed;
13292    }
13293
13294    /**
13295     * Finalize inflating a view from XML.  This is called as the last phase
13296     * of inflation, after all child views have been added.
13297     *
13298     * <p>Even if the subclass overrides onFinishInflate, they should always be
13299     * sure to call the super method, so that we get called.
13300     */
13301    protected void onFinishInflate() {
13302    }
13303
13304    /**
13305     * Returns the resources associated with this view.
13306     *
13307     * @return Resources object.
13308     */
13309    public Resources getResources() {
13310        return mResources;
13311    }
13312
13313    /**
13314     * Invalidates the specified Drawable.
13315     *
13316     * @param drawable the drawable to invalidate
13317     */
13318    public void invalidateDrawable(Drawable drawable) {
13319        if (verifyDrawable(drawable)) {
13320            final Rect dirty = drawable.getBounds();
13321            final int scrollX = mScrollX;
13322            final int scrollY = mScrollY;
13323
13324            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13325                    dirty.right + scrollX, dirty.bottom + scrollY);
13326        }
13327    }
13328
13329    /**
13330     * Schedules an action on a drawable to occur at a specified time.
13331     *
13332     * @param who the recipient of the action
13333     * @param what the action to run on the drawable
13334     * @param when the time at which the action must occur. Uses the
13335     *        {@link SystemClock#uptimeMillis} timebase.
13336     */
13337    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13338        if (verifyDrawable(who) && what != null) {
13339            final long delay = when - SystemClock.uptimeMillis();
13340            if (mAttachInfo != null) {
13341                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13342                        Choreographer.CALLBACK_ANIMATION, what, who,
13343                        Choreographer.subtractFrameDelay(delay));
13344            } else {
13345                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13346            }
13347        }
13348    }
13349
13350    /**
13351     * Cancels a scheduled action on a drawable.
13352     *
13353     * @param who the recipient of the action
13354     * @param what the action to cancel
13355     */
13356    public void unscheduleDrawable(Drawable who, Runnable what) {
13357        if (verifyDrawable(who) && what != null) {
13358            if (mAttachInfo != null) {
13359                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13360                        Choreographer.CALLBACK_ANIMATION, what, who);
13361            } else {
13362                ViewRootImpl.getRunQueue().removeCallbacks(what);
13363            }
13364        }
13365    }
13366
13367    /**
13368     * Unschedule any events associated with the given Drawable.  This can be
13369     * used when selecting a new Drawable into a view, so that the previous
13370     * one is completely unscheduled.
13371     *
13372     * @param who The Drawable to unschedule.
13373     *
13374     * @see #drawableStateChanged
13375     */
13376    public void unscheduleDrawable(Drawable who) {
13377        if (mAttachInfo != null && who != null) {
13378            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13379                    Choreographer.CALLBACK_ANIMATION, null, who);
13380        }
13381    }
13382
13383    /**
13384    * Return the layout direction of a given Drawable.
13385    *
13386    * @param who the Drawable to query
13387    * @hide
13388    */
13389    public int getResolvedLayoutDirection(Drawable who) {
13390        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13391    }
13392
13393    /**
13394     * If your view subclass is displaying its own Drawable objects, it should
13395     * override this function and return true for any Drawable it is
13396     * displaying.  This allows animations for those drawables to be
13397     * scheduled.
13398     *
13399     * <p>Be sure to call through to the super class when overriding this
13400     * function.
13401     *
13402     * @param who The Drawable to verify.  Return true if it is one you are
13403     *            displaying, else return the result of calling through to the
13404     *            super class.
13405     *
13406     * @return boolean If true than the Drawable is being displayed in the
13407     *         view; else false and it is not allowed to animate.
13408     *
13409     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13410     * @see #drawableStateChanged()
13411     */
13412    protected boolean verifyDrawable(Drawable who) {
13413        return who == mBackground;
13414    }
13415
13416    /**
13417     * This function is called whenever the state of the view changes in such
13418     * a way that it impacts the state of drawables being shown.
13419     *
13420     * <p>Be sure to call through to the superclass when overriding this
13421     * function.
13422     *
13423     * @see Drawable#setState(int[])
13424     */
13425    protected void drawableStateChanged() {
13426        Drawable d = mBackground;
13427        if (d != null && d.isStateful()) {
13428            d.setState(getDrawableState());
13429        }
13430    }
13431
13432    /**
13433     * Call this to force a view to update its drawable state. This will cause
13434     * drawableStateChanged to be called on this view. Views that are interested
13435     * in the new state should call getDrawableState.
13436     *
13437     * @see #drawableStateChanged
13438     * @see #getDrawableState
13439     */
13440    public void refreshDrawableState() {
13441        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13442        drawableStateChanged();
13443
13444        ViewParent parent = mParent;
13445        if (parent != null) {
13446            parent.childDrawableStateChanged(this);
13447        }
13448    }
13449
13450    /**
13451     * Return an array of resource IDs of the drawable states representing the
13452     * current state of the view.
13453     *
13454     * @return The current drawable state
13455     *
13456     * @see Drawable#setState(int[])
13457     * @see #drawableStateChanged()
13458     * @see #onCreateDrawableState(int)
13459     */
13460    public final int[] getDrawableState() {
13461        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13462            return mDrawableState;
13463        } else {
13464            mDrawableState = onCreateDrawableState(0);
13465            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13466            return mDrawableState;
13467        }
13468    }
13469
13470    /**
13471     * Generate the new {@link android.graphics.drawable.Drawable} state for
13472     * this view. This is called by the view
13473     * system when the cached Drawable state is determined to be invalid.  To
13474     * retrieve the current state, you should use {@link #getDrawableState}.
13475     *
13476     * @param extraSpace if non-zero, this is the number of extra entries you
13477     * would like in the returned array in which you can place your own
13478     * states.
13479     *
13480     * @return Returns an array holding the current {@link Drawable} state of
13481     * the view.
13482     *
13483     * @see #mergeDrawableStates(int[], int[])
13484     */
13485    protected int[] onCreateDrawableState(int extraSpace) {
13486        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13487                mParent instanceof View) {
13488            return ((View) mParent).onCreateDrawableState(extraSpace);
13489        }
13490
13491        int[] drawableState;
13492
13493        int privateFlags = mPrivateFlags;
13494
13495        int viewStateIndex = 0;
13496        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13497        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13498        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13499        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13500        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13501        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13502        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13503                HardwareRenderer.isAvailable()) {
13504            // This is set if HW acceleration is requested, even if the current
13505            // process doesn't allow it.  This is just to allow app preview
13506            // windows to better match their app.
13507            viewStateIndex |= VIEW_STATE_ACCELERATED;
13508        }
13509        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13510
13511        final int privateFlags2 = mPrivateFlags2;
13512        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13513        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13514
13515        drawableState = VIEW_STATE_SETS[viewStateIndex];
13516
13517        //noinspection ConstantIfStatement
13518        if (false) {
13519            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13520            Log.i("View", toString()
13521                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13522                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13523                    + " fo=" + hasFocus()
13524                    + " sl=" + ((privateFlags & SELECTED) != 0)
13525                    + " wf=" + hasWindowFocus()
13526                    + ": " + Arrays.toString(drawableState));
13527        }
13528
13529        if (extraSpace == 0) {
13530            return drawableState;
13531        }
13532
13533        final int[] fullState;
13534        if (drawableState != null) {
13535            fullState = new int[drawableState.length + extraSpace];
13536            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13537        } else {
13538            fullState = new int[extraSpace];
13539        }
13540
13541        return fullState;
13542    }
13543
13544    /**
13545     * Merge your own state values in <var>additionalState</var> into the base
13546     * state values <var>baseState</var> that were returned by
13547     * {@link #onCreateDrawableState(int)}.
13548     *
13549     * @param baseState The base state values returned by
13550     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13551     * own additional state values.
13552     *
13553     * @param additionalState The additional state values you would like
13554     * added to <var>baseState</var>; this array is not modified.
13555     *
13556     * @return As a convenience, the <var>baseState</var> array you originally
13557     * passed into the function is returned.
13558     *
13559     * @see #onCreateDrawableState(int)
13560     */
13561    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13562        final int N = baseState.length;
13563        int i = N - 1;
13564        while (i >= 0 && baseState[i] == 0) {
13565            i--;
13566        }
13567        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13568        return baseState;
13569    }
13570
13571    /**
13572     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13573     * on all Drawable objects associated with this view.
13574     */
13575    public void jumpDrawablesToCurrentState() {
13576        if (mBackground != null) {
13577            mBackground.jumpToCurrentState();
13578        }
13579    }
13580
13581    /**
13582     * Sets the background color for this view.
13583     * @param color the color of the background
13584     */
13585    @RemotableViewMethod
13586    public void setBackgroundColor(int color) {
13587        if (mBackground instanceof ColorDrawable) {
13588            ((ColorDrawable) mBackground).setColor(color);
13589        } else {
13590            setBackground(new ColorDrawable(color));
13591        }
13592    }
13593
13594    /**
13595     * Set the background to a given resource. The resource should refer to
13596     * a Drawable object or 0 to remove the background.
13597     * @param resid The identifier of the resource.
13598     *
13599     * @attr ref android.R.styleable#View_background
13600     */
13601    @RemotableViewMethod
13602    public void setBackgroundResource(int resid) {
13603        if (resid != 0 && resid == mBackgroundResource) {
13604            return;
13605        }
13606
13607        Drawable d= null;
13608        if (resid != 0) {
13609            d = mResources.getDrawable(resid);
13610        }
13611        setBackground(d);
13612
13613        mBackgroundResource = resid;
13614    }
13615
13616    /**
13617     * Set the background to a given Drawable, or remove the background. If the
13618     * background has padding, this View's padding is set to the background's
13619     * padding. However, when a background is removed, this View's padding isn't
13620     * touched. If setting the padding is desired, please use
13621     * {@link #setPadding(int, int, int, int)}.
13622     *
13623     * @param background The Drawable to use as the background, or null to remove the
13624     *        background
13625     */
13626    public void setBackground(Drawable background) {
13627        //noinspection deprecation
13628        setBackgroundDrawable(background);
13629    }
13630
13631    /**
13632     * @deprecated use {@link #setBackground(Drawable)} instead
13633     */
13634    @Deprecated
13635    public void setBackgroundDrawable(Drawable background) {
13636        if (background == mBackground) {
13637            return;
13638        }
13639
13640        boolean requestLayout = false;
13641
13642        mBackgroundResource = 0;
13643
13644        /*
13645         * Regardless of whether we're setting a new background or not, we want
13646         * to clear the previous drawable.
13647         */
13648        if (mBackground != null) {
13649            mBackground.setCallback(null);
13650            unscheduleDrawable(mBackground);
13651        }
13652
13653        if (background != null) {
13654            Rect padding = sThreadLocal.get();
13655            if (padding == null) {
13656                padding = new Rect();
13657                sThreadLocal.set(padding);
13658            }
13659            if (background.getPadding(padding)) {
13660                switch (background.getResolvedLayoutDirectionSelf()) {
13661                    case LAYOUT_DIRECTION_RTL:
13662                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13663                        break;
13664                    case LAYOUT_DIRECTION_LTR:
13665                    default:
13666                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13667                }
13668            }
13669
13670            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13671            // if it has a different minimum size, we should layout again
13672            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13673                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13674                requestLayout = true;
13675            }
13676
13677            background.setCallback(this);
13678            if (background.isStateful()) {
13679                background.setState(getDrawableState());
13680            }
13681            background.setVisible(getVisibility() == VISIBLE, false);
13682            mBackground = background;
13683
13684            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13685                mPrivateFlags &= ~SKIP_DRAW;
13686                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13687                requestLayout = true;
13688            }
13689        } else {
13690            /* Remove the background */
13691            mBackground = null;
13692
13693            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
13694                /*
13695                 * This view ONLY drew the background before and we're removing
13696                 * the background, so now it won't draw anything
13697                 * (hence we SKIP_DRAW)
13698                 */
13699                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
13700                mPrivateFlags |= SKIP_DRAW;
13701            }
13702
13703            /*
13704             * When the background is set, we try to apply its padding to this
13705             * View. When the background is removed, we don't touch this View's
13706             * padding. This is noted in the Javadocs. Hence, we don't need to
13707             * requestLayout(), the invalidate() below is sufficient.
13708             */
13709
13710            // The old background's minimum size could have affected this
13711            // View's layout, so let's requestLayout
13712            requestLayout = true;
13713        }
13714
13715        computeOpaqueFlags();
13716
13717        if (requestLayout) {
13718            requestLayout();
13719        }
13720
13721        mBackgroundSizeChanged = true;
13722        invalidate(true);
13723    }
13724
13725    /**
13726     * Gets the background drawable
13727     *
13728     * @return The drawable used as the background for this view, if any.
13729     *
13730     * @see #setBackground(Drawable)
13731     *
13732     * @attr ref android.R.styleable#View_background
13733     */
13734    public Drawable getBackground() {
13735        return mBackground;
13736    }
13737
13738    /**
13739     * Sets the padding. The view may add on the space required to display
13740     * the scrollbars, depending on the style and visibility of the scrollbars.
13741     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
13742     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
13743     * from the values set in this call.
13744     *
13745     * @attr ref android.R.styleable#View_padding
13746     * @attr ref android.R.styleable#View_paddingBottom
13747     * @attr ref android.R.styleable#View_paddingLeft
13748     * @attr ref android.R.styleable#View_paddingRight
13749     * @attr ref android.R.styleable#View_paddingTop
13750     * @param left the left padding in pixels
13751     * @param top the top padding in pixels
13752     * @param right the right padding in pixels
13753     * @param bottom the bottom padding in pixels
13754     */
13755    public void setPadding(int left, int top, int right, int bottom) {
13756        mUserPaddingStart = -1;
13757        mUserPaddingEnd = -1;
13758        mUserPaddingRelative = false;
13759
13760        internalSetPadding(left, top, right, bottom);
13761    }
13762
13763    private void internalSetPadding(int left, int top, int right, int bottom) {
13764        mUserPaddingLeft = left;
13765        mUserPaddingRight = right;
13766        mUserPaddingBottom = bottom;
13767
13768        final int viewFlags = mViewFlags;
13769        boolean changed = false;
13770
13771        // Common case is there are no scroll bars.
13772        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
13773            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
13774                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
13775                        ? 0 : getVerticalScrollbarWidth();
13776                switch (mVerticalScrollbarPosition) {
13777                    case SCROLLBAR_POSITION_DEFAULT:
13778                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13779                            left += offset;
13780                        } else {
13781                            right += offset;
13782                        }
13783                        break;
13784                    case SCROLLBAR_POSITION_RIGHT:
13785                        right += offset;
13786                        break;
13787                    case SCROLLBAR_POSITION_LEFT:
13788                        left += offset;
13789                        break;
13790                }
13791            }
13792            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
13793                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
13794                        ? 0 : getHorizontalScrollbarHeight();
13795            }
13796        }
13797
13798        if (mPaddingLeft != left) {
13799            changed = true;
13800            mPaddingLeft = left;
13801        }
13802        if (mPaddingTop != top) {
13803            changed = true;
13804            mPaddingTop = top;
13805        }
13806        if (mPaddingRight != right) {
13807            changed = true;
13808            mPaddingRight = right;
13809        }
13810        if (mPaddingBottom != bottom) {
13811            changed = true;
13812            mPaddingBottom = bottom;
13813        }
13814
13815        if (changed) {
13816            requestLayout();
13817        }
13818    }
13819
13820    /**
13821     * Sets the relative padding. The view may add on the space required to display
13822     * the scrollbars, depending on the style and visibility of the scrollbars.
13823     * from the values set in this call.
13824     *
13825     * @param start the start padding in pixels
13826     * @param top the top padding in pixels
13827     * @param end the end padding in pixels
13828     * @param bottom the bottom padding in pixels
13829     * @hide
13830     */
13831    public void setPaddingRelative(int start, int top, int end, int bottom) {
13832        mUserPaddingStart = start;
13833        mUserPaddingEnd = end;
13834        mUserPaddingRelative = true;
13835
13836        switch(getResolvedLayoutDirection()) {
13837            case LAYOUT_DIRECTION_RTL:
13838                internalSetPadding(end, top, start, bottom);
13839                break;
13840            case LAYOUT_DIRECTION_LTR:
13841            default:
13842                internalSetPadding(start, top, end, bottom);
13843        }
13844    }
13845
13846    /**
13847     * Returns the top padding of this view.
13848     *
13849     * @return the top padding in pixels
13850     */
13851    public int getPaddingTop() {
13852        return mPaddingTop;
13853    }
13854
13855    /**
13856     * Returns the bottom padding of this view. If there are inset and enabled
13857     * scrollbars, this value may include the space required to display the
13858     * scrollbars as well.
13859     *
13860     * @return the bottom padding in pixels
13861     */
13862    public int getPaddingBottom() {
13863        return mPaddingBottom;
13864    }
13865
13866    /**
13867     * Returns the left padding of this view. If there are inset and enabled
13868     * scrollbars, this value may include the space required to display the
13869     * scrollbars as well.
13870     *
13871     * @return the left padding in pixels
13872     */
13873    public int getPaddingLeft() {
13874        return mPaddingLeft;
13875    }
13876
13877    /**
13878     * Returns the start padding of this view depending on its resolved layout direction.
13879     * If there are inset and enabled scrollbars, this value may include the space
13880     * required to display the scrollbars as well.
13881     *
13882     * @return the start padding in pixels
13883     * @hide
13884     */
13885    public int getPaddingStart() {
13886        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13887                mPaddingRight : mPaddingLeft;
13888    }
13889
13890    /**
13891     * Returns the right padding of this view. If there are inset and enabled
13892     * scrollbars, this value may include the space required to display the
13893     * scrollbars as well.
13894     *
13895     * @return the right padding in pixels
13896     */
13897    public int getPaddingRight() {
13898        return mPaddingRight;
13899    }
13900
13901    /**
13902     * Returns the end padding of this view depending on its resolved layout direction.
13903     * If there are inset and enabled scrollbars, this value may include the space
13904     * required to display the scrollbars as well.
13905     *
13906     * @return the end padding in pixels
13907     * @hide
13908     */
13909    public int getPaddingEnd() {
13910        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13911                mPaddingLeft : mPaddingRight;
13912    }
13913
13914    /**
13915     * Return if the padding as been set thru relative values
13916     * {@link #setPaddingRelative(int, int, int, int)}
13917     *
13918     * @return true if the padding is relative or false if it is not.
13919     * @hide
13920     */
13921    public boolean isPaddingRelative() {
13922        return mUserPaddingRelative;
13923    }
13924
13925    /**
13926     * @hide
13927     */
13928    public Insets getOpticalInsets() {
13929        if (mLayoutInsets == null) {
13930            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
13931        }
13932        return mLayoutInsets;
13933    }
13934
13935    /**
13936     * @hide
13937     */
13938    public void setLayoutInsets(Insets layoutInsets) {
13939        mLayoutInsets = layoutInsets;
13940    }
13941
13942    /**
13943     * Changes the selection state of this view. A view can be selected or not.
13944     * Note that selection is not the same as focus. Views are typically
13945     * selected in the context of an AdapterView like ListView or GridView;
13946     * the selected view is the view that is highlighted.
13947     *
13948     * @param selected true if the view must be selected, false otherwise
13949     */
13950    public void setSelected(boolean selected) {
13951        if (((mPrivateFlags & SELECTED) != 0) != selected) {
13952            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
13953            if (!selected) resetPressedState();
13954            invalidate(true);
13955            refreshDrawableState();
13956            dispatchSetSelected(selected);
13957            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
13958                notifyAccessibilityStateChanged();
13959            }
13960        }
13961    }
13962
13963    /**
13964     * Dispatch setSelected to all of this View's children.
13965     *
13966     * @see #setSelected(boolean)
13967     *
13968     * @param selected The new selected state
13969     */
13970    protected void dispatchSetSelected(boolean selected) {
13971    }
13972
13973    /**
13974     * Indicates the selection state of this view.
13975     *
13976     * @return true if the view is selected, false otherwise
13977     */
13978    @ViewDebug.ExportedProperty
13979    public boolean isSelected() {
13980        return (mPrivateFlags & SELECTED) != 0;
13981    }
13982
13983    /**
13984     * Changes the activated state of this view. A view can be activated or not.
13985     * Note that activation is not the same as selection.  Selection is
13986     * a transient property, representing the view (hierarchy) the user is
13987     * currently interacting with.  Activation is a longer-term state that the
13988     * user can move views in and out of.  For example, in a list view with
13989     * single or multiple selection enabled, the views in the current selection
13990     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
13991     * here.)  The activated state is propagated down to children of the view it
13992     * is set on.
13993     *
13994     * @param activated true if the view must be activated, false otherwise
13995     */
13996    public void setActivated(boolean activated) {
13997        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
13998            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
13999            invalidate(true);
14000            refreshDrawableState();
14001            dispatchSetActivated(activated);
14002        }
14003    }
14004
14005    /**
14006     * Dispatch setActivated to all of this View's children.
14007     *
14008     * @see #setActivated(boolean)
14009     *
14010     * @param activated The new activated state
14011     */
14012    protected void dispatchSetActivated(boolean activated) {
14013    }
14014
14015    /**
14016     * Indicates the activation state of this view.
14017     *
14018     * @return true if the view is activated, false otherwise
14019     */
14020    @ViewDebug.ExportedProperty
14021    public boolean isActivated() {
14022        return (mPrivateFlags & ACTIVATED) != 0;
14023    }
14024
14025    /**
14026     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14027     * observer can be used to get notifications when global events, like
14028     * layout, happen.
14029     *
14030     * The returned ViewTreeObserver observer is not guaranteed to remain
14031     * valid for the lifetime of this View. If the caller of this method keeps
14032     * a long-lived reference to ViewTreeObserver, it should always check for
14033     * the return value of {@link ViewTreeObserver#isAlive()}.
14034     *
14035     * @return The ViewTreeObserver for this view's hierarchy.
14036     */
14037    public ViewTreeObserver getViewTreeObserver() {
14038        if (mAttachInfo != null) {
14039            return mAttachInfo.mTreeObserver;
14040        }
14041        if (mFloatingTreeObserver == null) {
14042            mFloatingTreeObserver = new ViewTreeObserver();
14043        }
14044        return mFloatingTreeObserver;
14045    }
14046
14047    /**
14048     * <p>Finds the topmost view in the current view hierarchy.</p>
14049     *
14050     * @return the topmost view containing this view
14051     */
14052    public View getRootView() {
14053        if (mAttachInfo != null) {
14054            final View v = mAttachInfo.mRootView;
14055            if (v != null) {
14056                return v;
14057            }
14058        }
14059
14060        View parent = this;
14061
14062        while (parent.mParent != null && parent.mParent instanceof View) {
14063            parent = (View) parent.mParent;
14064        }
14065
14066        return parent;
14067    }
14068
14069    /**
14070     * <p>Computes the coordinates of this view on the screen. The argument
14071     * must be an array of two integers. After the method returns, the array
14072     * contains the x and y location in that order.</p>
14073     *
14074     * @param location an array of two integers in which to hold the coordinates
14075     */
14076    public void getLocationOnScreen(int[] location) {
14077        getLocationInWindow(location);
14078
14079        final AttachInfo info = mAttachInfo;
14080        if (info != null) {
14081            location[0] += info.mWindowLeft;
14082            location[1] += info.mWindowTop;
14083        }
14084    }
14085
14086    /**
14087     * <p>Computes the coordinates of this view in its window. The argument
14088     * must be an array of two integers. After the method returns, the array
14089     * contains the x and y location in that order.</p>
14090     *
14091     * @param location an array of two integers in which to hold the coordinates
14092     */
14093    public void getLocationInWindow(int[] location) {
14094        if (location == null || location.length < 2) {
14095            throw new IllegalArgumentException("location must be an array of two integers");
14096        }
14097
14098        if (mAttachInfo == null) {
14099            // When the view is not attached to a window, this method does not make sense
14100            location[0] = location[1] = 0;
14101            return;
14102        }
14103
14104        float[] position = mAttachInfo.mTmpTransformLocation;
14105        position[0] = position[1] = 0.0f;
14106
14107        if (!hasIdentityMatrix()) {
14108            getMatrix().mapPoints(position);
14109        }
14110
14111        position[0] += mLeft;
14112        position[1] += mTop;
14113
14114        ViewParent viewParent = mParent;
14115        while (viewParent instanceof View) {
14116            final View view = (View) viewParent;
14117
14118            position[0] -= view.mScrollX;
14119            position[1] -= view.mScrollY;
14120
14121            if (!view.hasIdentityMatrix()) {
14122                view.getMatrix().mapPoints(position);
14123            }
14124
14125            position[0] += view.mLeft;
14126            position[1] += view.mTop;
14127
14128            viewParent = view.mParent;
14129         }
14130
14131        if (viewParent instanceof ViewRootImpl) {
14132            // *cough*
14133            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14134            position[1] -= vr.mCurScrollY;
14135        }
14136
14137        location[0] = (int) (position[0] + 0.5f);
14138        location[1] = (int) (position[1] + 0.5f);
14139    }
14140
14141    /**
14142     * {@hide}
14143     * @param id the id of the view to be found
14144     * @return the view of the specified id, null if cannot be found
14145     */
14146    protected View findViewTraversal(int id) {
14147        if (id == mID) {
14148            return this;
14149        }
14150        return null;
14151    }
14152
14153    /**
14154     * {@hide}
14155     * @param tag the tag of the view to be found
14156     * @return the view of specified tag, null if cannot be found
14157     */
14158    protected View findViewWithTagTraversal(Object tag) {
14159        if (tag != null && tag.equals(mTag)) {
14160            return this;
14161        }
14162        return null;
14163    }
14164
14165    /**
14166     * {@hide}
14167     * @param predicate The predicate to evaluate.
14168     * @param childToSkip If not null, ignores this child during the recursive traversal.
14169     * @return The first view that matches the predicate or null.
14170     */
14171    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14172        if (predicate.apply(this)) {
14173            return this;
14174        }
14175        return null;
14176    }
14177
14178    /**
14179     * Look for a child view with the given id.  If this view has the given
14180     * id, return this view.
14181     *
14182     * @param id The id to search for.
14183     * @return The view that has the given id in the hierarchy or null
14184     */
14185    public final View findViewById(int id) {
14186        if (id < 0) {
14187            return null;
14188        }
14189        return findViewTraversal(id);
14190    }
14191
14192    /**
14193     * Finds a view by its unuque and stable accessibility id.
14194     *
14195     * @param accessibilityId The searched accessibility id.
14196     * @return The found view.
14197     */
14198    final View findViewByAccessibilityId(int accessibilityId) {
14199        if (accessibilityId < 0) {
14200            return null;
14201        }
14202        return findViewByAccessibilityIdTraversal(accessibilityId);
14203    }
14204
14205    /**
14206     * Performs the traversal to find a view by its unuque and stable accessibility id.
14207     *
14208     * <strong>Note:</strong>This method does not stop at the root namespace
14209     * boundary since the user can touch the screen at an arbitrary location
14210     * potentially crossing the root namespace bounday which will send an
14211     * accessibility event to accessibility services and they should be able
14212     * to obtain the event source. Also accessibility ids are guaranteed to be
14213     * unique in the window.
14214     *
14215     * @param accessibilityId The accessibility id.
14216     * @return The found view.
14217     */
14218    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14219        if (getAccessibilityViewId() == accessibilityId) {
14220            return this;
14221        }
14222        return null;
14223    }
14224
14225    /**
14226     * Look for a child view with the given tag.  If this view has the given
14227     * tag, return this view.
14228     *
14229     * @param tag The tag to search for, using "tag.equals(getTag())".
14230     * @return The View that has the given tag in the hierarchy or null
14231     */
14232    public final View findViewWithTag(Object tag) {
14233        if (tag == null) {
14234            return null;
14235        }
14236        return findViewWithTagTraversal(tag);
14237    }
14238
14239    /**
14240     * {@hide}
14241     * Look for a child view that matches the specified predicate.
14242     * If this view matches the predicate, return this view.
14243     *
14244     * @param predicate The predicate to evaluate.
14245     * @return The first view that matches the predicate or null.
14246     */
14247    public final View findViewByPredicate(Predicate<View> predicate) {
14248        return findViewByPredicateTraversal(predicate, null);
14249    }
14250
14251    /**
14252     * {@hide}
14253     * Look for a child view that matches the specified predicate,
14254     * starting with the specified view and its descendents and then
14255     * recusively searching the ancestors and siblings of that view
14256     * until this view is reached.
14257     *
14258     * This method is useful in cases where the predicate does not match
14259     * a single unique view (perhaps multiple views use the same id)
14260     * and we are trying to find the view that is "closest" in scope to the
14261     * starting view.
14262     *
14263     * @param start The view to start from.
14264     * @param predicate The predicate to evaluate.
14265     * @return The first view that matches the predicate or null.
14266     */
14267    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14268        View childToSkip = null;
14269        for (;;) {
14270            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14271            if (view != null || start == this) {
14272                return view;
14273            }
14274
14275            ViewParent parent = start.getParent();
14276            if (parent == null || !(parent instanceof View)) {
14277                return null;
14278            }
14279
14280            childToSkip = start;
14281            start = (View) parent;
14282        }
14283    }
14284
14285    /**
14286     * Sets the identifier for this view. The identifier does not have to be
14287     * unique in this view's hierarchy. The identifier should be a positive
14288     * number.
14289     *
14290     * @see #NO_ID
14291     * @see #getId()
14292     * @see #findViewById(int)
14293     *
14294     * @param id a number used to identify the view
14295     *
14296     * @attr ref android.R.styleable#View_id
14297     */
14298    public void setId(int id) {
14299        mID = id;
14300    }
14301
14302    /**
14303     * {@hide}
14304     *
14305     * @param isRoot true if the view belongs to the root namespace, false
14306     *        otherwise
14307     */
14308    public void setIsRootNamespace(boolean isRoot) {
14309        if (isRoot) {
14310            mPrivateFlags |= IS_ROOT_NAMESPACE;
14311        } else {
14312            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14313        }
14314    }
14315
14316    /**
14317     * {@hide}
14318     *
14319     * @return true if the view belongs to the root namespace, false otherwise
14320     */
14321    public boolean isRootNamespace() {
14322        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14323    }
14324
14325    /**
14326     * Returns this view's identifier.
14327     *
14328     * @return a positive integer used to identify the view or {@link #NO_ID}
14329     *         if the view has no ID
14330     *
14331     * @see #setId(int)
14332     * @see #findViewById(int)
14333     * @attr ref android.R.styleable#View_id
14334     */
14335    @ViewDebug.CapturedViewProperty
14336    public int getId() {
14337        return mID;
14338    }
14339
14340    /**
14341     * Returns this view's tag.
14342     *
14343     * @return the Object stored in this view as a tag
14344     *
14345     * @see #setTag(Object)
14346     * @see #getTag(int)
14347     */
14348    @ViewDebug.ExportedProperty
14349    public Object getTag() {
14350        return mTag;
14351    }
14352
14353    /**
14354     * Sets the tag associated with this view. A tag can be used to mark
14355     * a view in its hierarchy and does not have to be unique within the
14356     * hierarchy. Tags can also be used to store data within a view without
14357     * resorting to another data structure.
14358     *
14359     * @param tag an Object to tag the view with
14360     *
14361     * @see #getTag()
14362     * @see #setTag(int, Object)
14363     */
14364    public void setTag(final Object tag) {
14365        mTag = tag;
14366    }
14367
14368    /**
14369     * Returns the tag associated with this view and the specified key.
14370     *
14371     * @param key The key identifying the tag
14372     *
14373     * @return the Object stored in this view as a tag
14374     *
14375     * @see #setTag(int, Object)
14376     * @see #getTag()
14377     */
14378    public Object getTag(int key) {
14379        if (mKeyedTags != null) return mKeyedTags.get(key);
14380        return null;
14381    }
14382
14383    /**
14384     * Sets a tag associated with this view and a key. A tag can be used
14385     * to mark a view in its hierarchy and does not have to be unique within
14386     * the hierarchy. Tags can also be used to store data within a view
14387     * without resorting to another data structure.
14388     *
14389     * The specified key should be an id declared in the resources of the
14390     * application to ensure it is unique (see the <a
14391     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14392     * Keys identified as belonging to
14393     * the Android framework or not associated with any package will cause
14394     * an {@link IllegalArgumentException} to be thrown.
14395     *
14396     * @param key The key identifying the tag
14397     * @param tag An Object to tag the view with
14398     *
14399     * @throws IllegalArgumentException If they specified key is not valid
14400     *
14401     * @see #setTag(Object)
14402     * @see #getTag(int)
14403     */
14404    public void setTag(int key, final Object tag) {
14405        // If the package id is 0x00 or 0x01, it's either an undefined package
14406        // or a framework id
14407        if ((key >>> 24) < 2) {
14408            throw new IllegalArgumentException("The key must be an application-specific "
14409                    + "resource id.");
14410        }
14411
14412        setKeyedTag(key, tag);
14413    }
14414
14415    /**
14416     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14417     * framework id.
14418     *
14419     * @hide
14420     */
14421    public void setTagInternal(int key, Object tag) {
14422        if ((key >>> 24) != 0x1) {
14423            throw new IllegalArgumentException("The key must be a framework-specific "
14424                    + "resource id.");
14425        }
14426
14427        setKeyedTag(key, tag);
14428    }
14429
14430    private void setKeyedTag(int key, Object tag) {
14431        if (mKeyedTags == null) {
14432            mKeyedTags = new SparseArray<Object>();
14433        }
14434
14435        mKeyedTags.put(key, tag);
14436    }
14437
14438    /**
14439     * @param consistency The type of consistency. See ViewDebug for more information.
14440     *
14441     * @hide
14442     */
14443    protected boolean dispatchConsistencyCheck(int consistency) {
14444        return onConsistencyCheck(consistency);
14445    }
14446
14447    /**
14448     * Method that subclasses should implement to check their consistency. The type of
14449     * consistency check is indicated by the bit field passed as a parameter.
14450     *
14451     * @param consistency The type of consistency. See ViewDebug for more information.
14452     *
14453     * @throws IllegalStateException if the view is in an inconsistent state.
14454     *
14455     * @hide
14456     */
14457    protected boolean onConsistencyCheck(int consistency) {
14458        boolean result = true;
14459
14460        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14461        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14462
14463        if (checkLayout) {
14464            if (getParent() == null) {
14465                result = false;
14466                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14467                        "View " + this + " does not have a parent.");
14468            }
14469
14470            if (mAttachInfo == null) {
14471                result = false;
14472                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14473                        "View " + this + " is not attached to a window.");
14474            }
14475        }
14476
14477        if (checkDrawing) {
14478            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14479            // from their draw() method
14480
14481            if ((mPrivateFlags & DRAWN) != DRAWN &&
14482                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14483                result = false;
14484                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14485                        "View " + this + " was invalidated but its drawing cache is valid.");
14486            }
14487        }
14488
14489        return result;
14490    }
14491
14492    /**
14493     * Prints information about this view in the log output, with the tag
14494     * {@link #VIEW_LOG_TAG}.
14495     *
14496     * @hide
14497     */
14498    public void debug() {
14499        debug(0);
14500    }
14501
14502    /**
14503     * Prints information about this view in the log output, with the tag
14504     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14505     * indentation defined by the <code>depth</code>.
14506     *
14507     * @param depth the indentation level
14508     *
14509     * @hide
14510     */
14511    protected void debug(int depth) {
14512        String output = debugIndent(depth - 1);
14513
14514        output += "+ " + this;
14515        int id = getId();
14516        if (id != -1) {
14517            output += " (id=" + id + ")";
14518        }
14519        Object tag = getTag();
14520        if (tag != null) {
14521            output += " (tag=" + tag + ")";
14522        }
14523        Log.d(VIEW_LOG_TAG, output);
14524
14525        if ((mPrivateFlags & FOCUSED) != 0) {
14526            output = debugIndent(depth) + " FOCUSED";
14527            Log.d(VIEW_LOG_TAG, output);
14528        }
14529
14530        output = debugIndent(depth);
14531        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14532                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14533                + "} ";
14534        Log.d(VIEW_LOG_TAG, output);
14535
14536        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14537                || mPaddingBottom != 0) {
14538            output = debugIndent(depth);
14539            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14540                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14541            Log.d(VIEW_LOG_TAG, output);
14542        }
14543
14544        output = debugIndent(depth);
14545        output += "mMeasureWidth=" + mMeasuredWidth +
14546                " mMeasureHeight=" + mMeasuredHeight;
14547        Log.d(VIEW_LOG_TAG, output);
14548
14549        output = debugIndent(depth);
14550        if (mLayoutParams == null) {
14551            output += "BAD! no layout params";
14552        } else {
14553            output = mLayoutParams.debug(output);
14554        }
14555        Log.d(VIEW_LOG_TAG, output);
14556
14557        output = debugIndent(depth);
14558        output += "flags={";
14559        output += View.printFlags(mViewFlags);
14560        output += "}";
14561        Log.d(VIEW_LOG_TAG, output);
14562
14563        output = debugIndent(depth);
14564        output += "privateFlags={";
14565        output += View.printPrivateFlags(mPrivateFlags);
14566        output += "}";
14567        Log.d(VIEW_LOG_TAG, output);
14568    }
14569
14570    /**
14571     * Creates a string of whitespaces used for indentation.
14572     *
14573     * @param depth the indentation level
14574     * @return a String containing (depth * 2 + 3) * 2 white spaces
14575     *
14576     * @hide
14577     */
14578    protected static String debugIndent(int depth) {
14579        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14580        for (int i = 0; i < (depth * 2) + 3; i++) {
14581            spaces.append(' ').append(' ');
14582        }
14583        return spaces.toString();
14584    }
14585
14586    /**
14587     * <p>Return the offset of the widget's text baseline from the widget's top
14588     * boundary. If this widget does not support baseline alignment, this
14589     * method returns -1. </p>
14590     *
14591     * @return the offset of the baseline within the widget's bounds or -1
14592     *         if baseline alignment is not supported
14593     */
14594    @ViewDebug.ExportedProperty(category = "layout")
14595    public int getBaseline() {
14596        return -1;
14597    }
14598
14599    /**
14600     * Call this when something has changed which has invalidated the
14601     * layout of this view. This will schedule a layout pass of the view
14602     * tree.
14603     */
14604    public void requestLayout() {
14605        if (ViewDebug.TRACE_HIERARCHY) {
14606            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14607        }
14608
14609        mPrivateFlags |= FORCE_LAYOUT;
14610        mPrivateFlags |= INVALIDATED;
14611
14612        if (mLayoutParams != null) {
14613            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14614        }
14615
14616        if (mParent != null && !mParent.isLayoutRequested()) {
14617            mParent.requestLayout();
14618        }
14619    }
14620
14621    /**
14622     * Forces this view to be laid out during the next layout pass.
14623     * This method does not call requestLayout() or forceLayout()
14624     * on the parent.
14625     */
14626    public void forceLayout() {
14627        mPrivateFlags |= FORCE_LAYOUT;
14628        mPrivateFlags |= INVALIDATED;
14629    }
14630
14631    /**
14632     * <p>
14633     * This is called to find out how big a view should be. The parent
14634     * supplies constraint information in the width and height parameters.
14635     * </p>
14636     *
14637     * <p>
14638     * The actual measurement work of a view is performed in
14639     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14640     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14641     * </p>
14642     *
14643     *
14644     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14645     *        parent
14646     * @param heightMeasureSpec Vertical space requirements as imposed by the
14647     *        parent
14648     *
14649     * @see #onMeasure(int, int)
14650     */
14651    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14652        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14653                widthMeasureSpec != mOldWidthMeasureSpec ||
14654                heightMeasureSpec != mOldHeightMeasureSpec) {
14655
14656            // first clears the measured dimension flag
14657            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14658
14659            if (ViewDebug.TRACE_HIERARCHY) {
14660                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
14661            }
14662
14663            // measure ourselves, this should set the measured dimension flag back
14664            onMeasure(widthMeasureSpec, heightMeasureSpec);
14665
14666            // flag not set, setMeasuredDimension() was not invoked, we raise
14667            // an exception to warn the developer
14668            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14669                throw new IllegalStateException("onMeasure() did not set the"
14670                        + " measured dimension by calling"
14671                        + " setMeasuredDimension()");
14672            }
14673
14674            mPrivateFlags |= LAYOUT_REQUIRED;
14675        }
14676
14677        mOldWidthMeasureSpec = widthMeasureSpec;
14678        mOldHeightMeasureSpec = heightMeasureSpec;
14679    }
14680
14681    /**
14682     * <p>
14683     * Measure the view and its content to determine the measured width and the
14684     * measured height. This method is invoked by {@link #measure(int, int)} and
14685     * should be overriden by subclasses to provide accurate and efficient
14686     * measurement of their contents.
14687     * </p>
14688     *
14689     * <p>
14690     * <strong>CONTRACT:</strong> When overriding this method, you
14691     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14692     * measured width and height of this view. Failure to do so will trigger an
14693     * <code>IllegalStateException</code>, thrown by
14694     * {@link #measure(int, int)}. Calling the superclass'
14695     * {@link #onMeasure(int, int)} is a valid use.
14696     * </p>
14697     *
14698     * <p>
14699     * The base class implementation of measure defaults to the background size,
14700     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14701     * override {@link #onMeasure(int, int)} to provide better measurements of
14702     * their content.
14703     * </p>
14704     *
14705     * <p>
14706     * If this method is overridden, it is the subclass's responsibility to make
14707     * sure the measured height and width are at least the view's minimum height
14708     * and width ({@link #getSuggestedMinimumHeight()} and
14709     * {@link #getSuggestedMinimumWidth()}).
14710     * </p>
14711     *
14712     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14713     *                         The requirements are encoded with
14714     *                         {@link android.view.View.MeasureSpec}.
14715     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14716     *                         The requirements are encoded with
14717     *                         {@link android.view.View.MeasureSpec}.
14718     *
14719     * @see #getMeasuredWidth()
14720     * @see #getMeasuredHeight()
14721     * @see #setMeasuredDimension(int, int)
14722     * @see #getSuggestedMinimumHeight()
14723     * @see #getSuggestedMinimumWidth()
14724     * @see android.view.View.MeasureSpec#getMode(int)
14725     * @see android.view.View.MeasureSpec#getSize(int)
14726     */
14727    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14728        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14729                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14730    }
14731
14732    /**
14733     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14734     * measured width and measured height. Failing to do so will trigger an
14735     * exception at measurement time.</p>
14736     *
14737     * @param measuredWidth The measured width of this view.  May be a complex
14738     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14739     * {@link #MEASURED_STATE_TOO_SMALL}.
14740     * @param measuredHeight The measured height of this view.  May be a complex
14741     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14742     * {@link #MEASURED_STATE_TOO_SMALL}.
14743     */
14744    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14745        mMeasuredWidth = measuredWidth;
14746        mMeasuredHeight = measuredHeight;
14747
14748        mPrivateFlags |= MEASURED_DIMENSION_SET;
14749    }
14750
14751    /**
14752     * Merge two states as returned by {@link #getMeasuredState()}.
14753     * @param curState The current state as returned from a view or the result
14754     * of combining multiple views.
14755     * @param newState The new view state to combine.
14756     * @return Returns a new integer reflecting the combination of the two
14757     * states.
14758     */
14759    public static int combineMeasuredStates(int curState, int newState) {
14760        return curState | newState;
14761    }
14762
14763    /**
14764     * Version of {@link #resolveSizeAndState(int, int, int)}
14765     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
14766     */
14767    public static int resolveSize(int size, int measureSpec) {
14768        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
14769    }
14770
14771    /**
14772     * Utility to reconcile a desired size and state, with constraints imposed
14773     * by a MeasureSpec.  Will take the desired size, unless a different size
14774     * is imposed by the constraints.  The returned value is a compound integer,
14775     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
14776     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
14777     * size is smaller than the size the view wants to be.
14778     *
14779     * @param size How big the view wants to be
14780     * @param measureSpec Constraints imposed by the parent
14781     * @return Size information bit mask as defined by
14782     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14783     */
14784    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
14785        int result = size;
14786        int specMode = MeasureSpec.getMode(measureSpec);
14787        int specSize =  MeasureSpec.getSize(measureSpec);
14788        switch (specMode) {
14789        case MeasureSpec.UNSPECIFIED:
14790            result = size;
14791            break;
14792        case MeasureSpec.AT_MOST:
14793            if (specSize < size) {
14794                result = specSize | MEASURED_STATE_TOO_SMALL;
14795            } else {
14796                result = size;
14797            }
14798            break;
14799        case MeasureSpec.EXACTLY:
14800            result = specSize;
14801            break;
14802        }
14803        return result | (childMeasuredState&MEASURED_STATE_MASK);
14804    }
14805
14806    /**
14807     * Utility to return a default size. Uses the supplied size if the
14808     * MeasureSpec imposed no constraints. Will get larger if allowed
14809     * by the MeasureSpec.
14810     *
14811     * @param size Default size for this view
14812     * @param measureSpec Constraints imposed by the parent
14813     * @return The size this view should be.
14814     */
14815    public static int getDefaultSize(int size, int measureSpec) {
14816        int result = size;
14817        int specMode = MeasureSpec.getMode(measureSpec);
14818        int specSize = MeasureSpec.getSize(measureSpec);
14819
14820        switch (specMode) {
14821        case MeasureSpec.UNSPECIFIED:
14822            result = size;
14823            break;
14824        case MeasureSpec.AT_MOST:
14825        case MeasureSpec.EXACTLY:
14826            result = specSize;
14827            break;
14828        }
14829        return result;
14830    }
14831
14832    /**
14833     * Returns the suggested minimum height that the view should use. This
14834     * returns the maximum of the view's minimum height
14835     * and the background's minimum height
14836     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
14837     * <p>
14838     * When being used in {@link #onMeasure(int, int)}, the caller should still
14839     * ensure the returned height is within the requirements of the parent.
14840     *
14841     * @return The suggested minimum height of the view.
14842     */
14843    protected int getSuggestedMinimumHeight() {
14844        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
14845
14846    }
14847
14848    /**
14849     * Returns the suggested minimum width that the view should use. This
14850     * returns the maximum of the view's minimum width)
14851     * and the background's minimum width
14852     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
14853     * <p>
14854     * When being used in {@link #onMeasure(int, int)}, the caller should still
14855     * ensure the returned width is within the requirements of the parent.
14856     *
14857     * @return The suggested minimum width of the view.
14858     */
14859    protected int getSuggestedMinimumWidth() {
14860        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
14861    }
14862
14863    /**
14864     * Returns the minimum height of the view.
14865     *
14866     * @return the minimum height the view will try to be.
14867     *
14868     * @see #setMinimumHeight(int)
14869     *
14870     * @attr ref android.R.styleable#View_minHeight
14871     */
14872    public int getMinimumHeight() {
14873        return mMinHeight;
14874    }
14875
14876    /**
14877     * Sets the minimum height of the view. It is not guaranteed the view will
14878     * be able to achieve this minimum height (for example, if its parent layout
14879     * constrains it with less available height).
14880     *
14881     * @param minHeight The minimum height the view will try to be.
14882     *
14883     * @see #getMinimumHeight()
14884     *
14885     * @attr ref android.R.styleable#View_minHeight
14886     */
14887    public void setMinimumHeight(int minHeight) {
14888        mMinHeight = minHeight;
14889        requestLayout();
14890    }
14891
14892    /**
14893     * Returns the minimum width of the view.
14894     *
14895     * @return the minimum width the view will try to be.
14896     *
14897     * @see #setMinimumWidth(int)
14898     *
14899     * @attr ref android.R.styleable#View_minWidth
14900     */
14901    public int getMinimumWidth() {
14902        return mMinWidth;
14903    }
14904
14905    /**
14906     * Sets the minimum width of the view. It is not guaranteed the view will
14907     * be able to achieve this minimum width (for example, if its parent layout
14908     * constrains it with less available width).
14909     *
14910     * @param minWidth The minimum width the view will try to be.
14911     *
14912     * @see #getMinimumWidth()
14913     *
14914     * @attr ref android.R.styleable#View_minWidth
14915     */
14916    public void setMinimumWidth(int minWidth) {
14917        mMinWidth = minWidth;
14918        requestLayout();
14919
14920    }
14921
14922    /**
14923     * Get the animation currently associated with this view.
14924     *
14925     * @return The animation that is currently playing or
14926     *         scheduled to play for this view.
14927     */
14928    public Animation getAnimation() {
14929        return mCurrentAnimation;
14930    }
14931
14932    /**
14933     * Start the specified animation now.
14934     *
14935     * @param animation the animation to start now
14936     */
14937    public void startAnimation(Animation animation) {
14938        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
14939        setAnimation(animation);
14940        invalidateParentCaches();
14941        invalidate(true);
14942    }
14943
14944    /**
14945     * Cancels any animations for this view.
14946     */
14947    public void clearAnimation() {
14948        if (mCurrentAnimation != null) {
14949            mCurrentAnimation.detach();
14950        }
14951        mCurrentAnimation = null;
14952        invalidateParentIfNeeded();
14953    }
14954
14955    /**
14956     * Sets the next animation to play for this view.
14957     * If you want the animation to play immediately, use
14958     * startAnimation. This method provides allows fine-grained
14959     * control over the start time and invalidation, but you
14960     * must make sure that 1) the animation has a start time set, and
14961     * 2) the view will be invalidated when the animation is supposed to
14962     * start.
14963     *
14964     * @param animation The next animation, or null.
14965     */
14966    public void setAnimation(Animation animation) {
14967        mCurrentAnimation = animation;
14968
14969        if (animation != null) {
14970            // If the screen is off assume the animation start time is now instead of
14971            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
14972            // would cause the animation to start when the screen turns back on
14973            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
14974                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
14975                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
14976            }
14977            animation.reset();
14978        }
14979    }
14980
14981    /**
14982     * Invoked by a parent ViewGroup to notify the start of the animation
14983     * currently associated with this view. If you override this method,
14984     * always call super.onAnimationStart();
14985     *
14986     * @see #setAnimation(android.view.animation.Animation)
14987     * @see #getAnimation()
14988     */
14989    protected void onAnimationStart() {
14990        mPrivateFlags |= ANIMATION_STARTED;
14991    }
14992
14993    /**
14994     * Invoked by a parent ViewGroup to notify the end of the animation
14995     * currently associated with this view. If you override this method,
14996     * always call super.onAnimationEnd();
14997     *
14998     * @see #setAnimation(android.view.animation.Animation)
14999     * @see #getAnimation()
15000     */
15001    protected void onAnimationEnd() {
15002        mPrivateFlags &= ~ANIMATION_STARTED;
15003    }
15004
15005    /**
15006     * Invoked if there is a Transform that involves alpha. Subclass that can
15007     * draw themselves with the specified alpha should return true, and then
15008     * respect that alpha when their onDraw() is called. If this returns false
15009     * then the view may be redirected to draw into an offscreen buffer to
15010     * fulfill the request, which will look fine, but may be slower than if the
15011     * subclass handles it internally. The default implementation returns false.
15012     *
15013     * @param alpha The alpha (0..255) to apply to the view's drawing
15014     * @return true if the view can draw with the specified alpha.
15015     */
15016    protected boolean onSetAlpha(int alpha) {
15017        return false;
15018    }
15019
15020    /**
15021     * This is used by the RootView to perform an optimization when
15022     * the view hierarchy contains one or several SurfaceView.
15023     * SurfaceView is always considered transparent, but its children are not,
15024     * therefore all View objects remove themselves from the global transparent
15025     * region (passed as a parameter to this function).
15026     *
15027     * @param region The transparent region for this ViewAncestor (window).
15028     *
15029     * @return Returns true if the effective visibility of the view at this
15030     * point is opaque, regardless of the transparent region; returns false
15031     * if it is possible for underlying windows to be seen behind the view.
15032     *
15033     * {@hide}
15034     */
15035    public boolean gatherTransparentRegion(Region region) {
15036        final AttachInfo attachInfo = mAttachInfo;
15037        if (region != null && attachInfo != null) {
15038            final int pflags = mPrivateFlags;
15039            if ((pflags & SKIP_DRAW) == 0) {
15040                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15041                // remove it from the transparent region.
15042                final int[] location = attachInfo.mTransparentLocation;
15043                getLocationInWindow(location);
15044                region.op(location[0], location[1], location[0] + mRight - mLeft,
15045                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15046            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15047                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15048                // exists, so we remove the background drawable's non-transparent
15049                // parts from this transparent region.
15050                applyDrawableToTransparentRegion(mBackground, region);
15051            }
15052        }
15053        return true;
15054    }
15055
15056    /**
15057     * Play a sound effect for this view.
15058     *
15059     * <p>The framework will play sound effects for some built in actions, such as
15060     * clicking, but you may wish to play these effects in your widget,
15061     * for instance, for internal navigation.
15062     *
15063     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15064     * {@link #isSoundEffectsEnabled()} is true.
15065     *
15066     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15067     */
15068    public void playSoundEffect(int soundConstant) {
15069        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15070            return;
15071        }
15072        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15073    }
15074
15075    /**
15076     * BZZZTT!!1!
15077     *
15078     * <p>Provide haptic feedback to the user for this view.
15079     *
15080     * <p>The framework will provide haptic feedback for some built in actions,
15081     * such as long presses, but you may wish to provide feedback for your
15082     * own widget.
15083     *
15084     * <p>The feedback will only be performed if
15085     * {@link #isHapticFeedbackEnabled()} is true.
15086     *
15087     * @param feedbackConstant One of the constants defined in
15088     * {@link HapticFeedbackConstants}
15089     */
15090    public boolean performHapticFeedback(int feedbackConstant) {
15091        return performHapticFeedback(feedbackConstant, 0);
15092    }
15093
15094    /**
15095     * BZZZTT!!1!
15096     *
15097     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15098     *
15099     * @param feedbackConstant One of the constants defined in
15100     * {@link HapticFeedbackConstants}
15101     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15102     */
15103    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15104        if (mAttachInfo == null) {
15105            return false;
15106        }
15107        //noinspection SimplifiableIfStatement
15108        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15109                && !isHapticFeedbackEnabled()) {
15110            return false;
15111        }
15112        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15113                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15114    }
15115
15116    /**
15117     * Request that the visibility of the status bar or other screen/window
15118     * decorations be changed.
15119     *
15120     * <p>This method is used to put the over device UI into temporary modes
15121     * where the user's attention is focused more on the application content,
15122     * by dimming or hiding surrounding system affordances.  This is typically
15123     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15124     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15125     * to be placed behind the action bar (and with these flags other system
15126     * affordances) so that smooth transitions between hiding and showing them
15127     * can be done.
15128     *
15129     * <p>Two representative examples of the use of system UI visibility is
15130     * implementing a content browsing application (like a magazine reader)
15131     * and a video playing application.
15132     *
15133     * <p>The first code shows a typical implementation of a View in a content
15134     * browsing application.  In this implementation, the application goes
15135     * into a content-oriented mode by hiding the status bar and action bar,
15136     * and putting the navigation elements into lights out mode.  The user can
15137     * then interact with content while in this mode.  Such an application should
15138     * provide an easy way for the user to toggle out of the mode (such as to
15139     * check information in the status bar or access notifications).  In the
15140     * implementation here, this is done simply by tapping on the content.
15141     *
15142     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15143     *      content}
15144     *
15145     * <p>This second code sample shows a typical implementation of a View
15146     * in a video playing application.  In this situation, while the video is
15147     * playing the application would like to go into a complete full-screen mode,
15148     * to use as much of the display as possible for the video.  When in this state
15149     * the user can not interact with the application; the system intercepts
15150     * touching on the screen to pop the UI out of full screen mode.
15151     *
15152     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15153     *      content}
15154     *
15155     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15156     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15157     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15158     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15159     */
15160    public void setSystemUiVisibility(int visibility) {
15161        if (visibility != mSystemUiVisibility) {
15162            mSystemUiVisibility = visibility;
15163            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15164                mParent.recomputeViewAttributes(this);
15165            }
15166        }
15167    }
15168
15169    /**
15170     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15171     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15172     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15173     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15174     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15175     */
15176    public int getSystemUiVisibility() {
15177        return mSystemUiVisibility;
15178    }
15179
15180    /**
15181     * Returns the current system UI visibility that is currently set for
15182     * the entire window.  This is the combination of the
15183     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15184     * views in the window.
15185     */
15186    public int getWindowSystemUiVisibility() {
15187        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15188    }
15189
15190    /**
15191     * Override to find out when the window's requested system UI visibility
15192     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15193     * This is different from the callbacks recieved through
15194     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15195     * in that this is only telling you about the local request of the window,
15196     * not the actual values applied by the system.
15197     */
15198    public void onWindowSystemUiVisibilityChanged(int visible) {
15199    }
15200
15201    /**
15202     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15203     * the view hierarchy.
15204     */
15205    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15206        onWindowSystemUiVisibilityChanged(visible);
15207    }
15208
15209    /**
15210     * Set a listener to receive callbacks when the visibility of the system bar changes.
15211     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15212     */
15213    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15214        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15215        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15216            mParent.recomputeViewAttributes(this);
15217        }
15218    }
15219
15220    /**
15221     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15222     * the view hierarchy.
15223     */
15224    public void dispatchSystemUiVisibilityChanged(int visibility) {
15225        ListenerInfo li = mListenerInfo;
15226        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15227            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15228                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15229        }
15230    }
15231
15232    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
15233        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15234        if (val != mSystemUiVisibility) {
15235            setSystemUiVisibility(val);
15236        }
15237    }
15238
15239    /** @hide */
15240    public void setDisabledSystemUiVisibility(int flags) {
15241        if (mAttachInfo != null) {
15242            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15243                mAttachInfo.mDisabledSystemUiVisibility = flags;
15244                if (mParent != null) {
15245                    mParent.recomputeViewAttributes(this);
15246                }
15247            }
15248        }
15249    }
15250
15251    /**
15252     * Creates an image that the system displays during the drag and drop
15253     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15254     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15255     * appearance as the given View. The default also positions the center of the drag shadow
15256     * directly under the touch point. If no View is provided (the constructor with no parameters
15257     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15258     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15259     * default is an invisible drag shadow.
15260     * <p>
15261     * You are not required to use the View you provide to the constructor as the basis of the
15262     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15263     * anything you want as the drag shadow.
15264     * </p>
15265     * <p>
15266     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15267     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15268     *  size and position of the drag shadow. It uses this data to construct a
15269     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15270     *  so that your application can draw the shadow image in the Canvas.
15271     * </p>
15272     *
15273     * <div class="special reference">
15274     * <h3>Developer Guides</h3>
15275     * <p>For a guide to implementing drag and drop features, read the
15276     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15277     * </div>
15278     */
15279    public static class DragShadowBuilder {
15280        private final WeakReference<View> mView;
15281
15282        /**
15283         * Constructs a shadow image builder based on a View. By default, the resulting drag
15284         * shadow will have the same appearance and dimensions as the View, with the touch point
15285         * over the center of the View.
15286         * @param view A View. Any View in scope can be used.
15287         */
15288        public DragShadowBuilder(View view) {
15289            mView = new WeakReference<View>(view);
15290        }
15291
15292        /**
15293         * Construct a shadow builder object with no associated View.  This
15294         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15295         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15296         * to supply the drag shadow's dimensions and appearance without
15297         * reference to any View object. If they are not overridden, then the result is an
15298         * invisible drag shadow.
15299         */
15300        public DragShadowBuilder() {
15301            mView = new WeakReference<View>(null);
15302        }
15303
15304        /**
15305         * Returns the View object that had been passed to the
15306         * {@link #View.DragShadowBuilder(View)}
15307         * constructor.  If that View parameter was {@code null} or if the
15308         * {@link #View.DragShadowBuilder()}
15309         * constructor was used to instantiate the builder object, this method will return
15310         * null.
15311         *
15312         * @return The View object associate with this builder object.
15313         */
15314        @SuppressWarnings({"JavadocReference"})
15315        final public View getView() {
15316            return mView.get();
15317        }
15318
15319        /**
15320         * Provides the metrics for the shadow image. These include the dimensions of
15321         * the shadow image, and the point within that shadow that should
15322         * be centered under the touch location while dragging.
15323         * <p>
15324         * The default implementation sets the dimensions of the shadow to be the
15325         * same as the dimensions of the View itself and centers the shadow under
15326         * the touch point.
15327         * </p>
15328         *
15329         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15330         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15331         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15332         * image.
15333         *
15334         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15335         * shadow image that should be underneath the touch point during the drag and drop
15336         * operation. Your application must set {@link android.graphics.Point#x} to the
15337         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15338         */
15339        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15340            final View view = mView.get();
15341            if (view != null) {
15342                shadowSize.set(view.getWidth(), view.getHeight());
15343                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15344            } else {
15345                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15346            }
15347        }
15348
15349        /**
15350         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15351         * based on the dimensions it received from the
15352         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15353         *
15354         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15355         */
15356        public void onDrawShadow(Canvas canvas) {
15357            final View view = mView.get();
15358            if (view != null) {
15359                view.draw(canvas);
15360            } else {
15361                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15362            }
15363        }
15364    }
15365
15366    /**
15367     * Starts a drag and drop operation. When your application calls this method, it passes a
15368     * {@link android.view.View.DragShadowBuilder} object to the system. The
15369     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15370     * to get metrics for the drag shadow, and then calls the object's
15371     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15372     * <p>
15373     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15374     *  drag events to all the View objects in your application that are currently visible. It does
15375     *  this either by calling the View object's drag listener (an implementation of
15376     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15377     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15378     *  Both are passed a {@link android.view.DragEvent} object that has a
15379     *  {@link android.view.DragEvent#getAction()} value of
15380     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15381     * </p>
15382     * <p>
15383     * Your application can invoke startDrag() on any attached View object. The View object does not
15384     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15385     * be related to the View the user selected for dragging.
15386     * </p>
15387     * @param data A {@link android.content.ClipData} object pointing to the data to be
15388     * transferred by the drag and drop operation.
15389     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15390     * drag shadow.
15391     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15392     * drop operation. This Object is put into every DragEvent object sent by the system during the
15393     * current drag.
15394     * <p>
15395     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15396     * to the target Views. For example, it can contain flags that differentiate between a
15397     * a copy operation and a move operation.
15398     * </p>
15399     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15400     * so the parameter should be set to 0.
15401     * @return {@code true} if the method completes successfully, or
15402     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15403     * do a drag, and so no drag operation is in progress.
15404     */
15405    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15406            Object myLocalState, int flags) {
15407        if (ViewDebug.DEBUG_DRAG) {
15408            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15409        }
15410        boolean okay = false;
15411
15412        Point shadowSize = new Point();
15413        Point shadowTouchPoint = new Point();
15414        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15415
15416        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15417                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15418            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15419        }
15420
15421        if (ViewDebug.DEBUG_DRAG) {
15422            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15423                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15424        }
15425        Surface surface = new Surface();
15426        try {
15427            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15428                    flags, shadowSize.x, shadowSize.y, surface);
15429            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15430                    + " surface=" + surface);
15431            if (token != null) {
15432                Canvas canvas = surface.lockCanvas(null);
15433                try {
15434                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15435                    shadowBuilder.onDrawShadow(canvas);
15436                } finally {
15437                    surface.unlockCanvasAndPost(canvas);
15438                }
15439
15440                final ViewRootImpl root = getViewRootImpl();
15441
15442                // Cache the local state object for delivery with DragEvents
15443                root.setLocalDragState(myLocalState);
15444
15445                // repurpose 'shadowSize' for the last touch point
15446                root.getLastTouchPoint(shadowSize);
15447
15448                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15449                        shadowSize.x, shadowSize.y,
15450                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15451                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15452
15453                // Off and running!  Release our local surface instance; the drag
15454                // shadow surface is now managed by the system process.
15455                surface.release();
15456            }
15457        } catch (Exception e) {
15458            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15459            surface.destroy();
15460        }
15461
15462        return okay;
15463    }
15464
15465    /**
15466     * Handles drag events sent by the system following a call to
15467     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15468     *<p>
15469     * When the system calls this method, it passes a
15470     * {@link android.view.DragEvent} object. A call to
15471     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15472     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15473     * operation.
15474     * @param event The {@link android.view.DragEvent} sent by the system.
15475     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15476     * in DragEvent, indicating the type of drag event represented by this object.
15477     * @return {@code true} if the method was successful, otherwise {@code false}.
15478     * <p>
15479     *  The method should return {@code true} in response to an action type of
15480     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15481     *  operation.
15482     * </p>
15483     * <p>
15484     *  The method should also return {@code true} in response to an action type of
15485     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15486     *  {@code false} if it didn't.
15487     * </p>
15488     */
15489    public boolean onDragEvent(DragEvent event) {
15490        return false;
15491    }
15492
15493    /**
15494     * Detects if this View is enabled and has a drag event listener.
15495     * If both are true, then it calls the drag event listener with the
15496     * {@link android.view.DragEvent} it received. If the drag event listener returns
15497     * {@code true}, then dispatchDragEvent() returns {@code true}.
15498     * <p>
15499     * For all other cases, the method calls the
15500     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15501     * method and returns its result.
15502     * </p>
15503     * <p>
15504     * This ensures that a drag event is always consumed, even if the View does not have a drag
15505     * event listener. However, if the View has a listener and the listener returns true, then
15506     * onDragEvent() is not called.
15507     * </p>
15508     */
15509    public boolean dispatchDragEvent(DragEvent event) {
15510        //noinspection SimplifiableIfStatement
15511        ListenerInfo li = mListenerInfo;
15512        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15513                && li.mOnDragListener.onDrag(this, event)) {
15514            return true;
15515        }
15516        return onDragEvent(event);
15517    }
15518
15519    boolean canAcceptDrag() {
15520        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15521    }
15522
15523    /**
15524     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15525     * it is ever exposed at all.
15526     * @hide
15527     */
15528    public void onCloseSystemDialogs(String reason) {
15529    }
15530
15531    /**
15532     * Given a Drawable whose bounds have been set to draw into this view,
15533     * update a Region being computed for
15534     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15535     * that any non-transparent parts of the Drawable are removed from the
15536     * given transparent region.
15537     *
15538     * @param dr The Drawable whose transparency is to be applied to the region.
15539     * @param region A Region holding the current transparency information,
15540     * where any parts of the region that are set are considered to be
15541     * transparent.  On return, this region will be modified to have the
15542     * transparency information reduced by the corresponding parts of the
15543     * Drawable that are not transparent.
15544     * {@hide}
15545     */
15546    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15547        if (DBG) {
15548            Log.i("View", "Getting transparent region for: " + this);
15549        }
15550        final Region r = dr.getTransparentRegion();
15551        final Rect db = dr.getBounds();
15552        final AttachInfo attachInfo = mAttachInfo;
15553        if (r != null && attachInfo != null) {
15554            final int w = getRight()-getLeft();
15555            final int h = getBottom()-getTop();
15556            if (db.left > 0) {
15557                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15558                r.op(0, 0, db.left, h, Region.Op.UNION);
15559            }
15560            if (db.right < w) {
15561                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15562                r.op(db.right, 0, w, h, Region.Op.UNION);
15563            }
15564            if (db.top > 0) {
15565                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15566                r.op(0, 0, w, db.top, Region.Op.UNION);
15567            }
15568            if (db.bottom < h) {
15569                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15570                r.op(0, db.bottom, w, h, Region.Op.UNION);
15571            }
15572            final int[] location = attachInfo.mTransparentLocation;
15573            getLocationInWindow(location);
15574            r.translate(location[0], location[1]);
15575            region.op(r, Region.Op.INTERSECT);
15576        } else {
15577            region.op(db, Region.Op.DIFFERENCE);
15578        }
15579    }
15580
15581    private void checkForLongClick(int delayOffset) {
15582        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15583            mHasPerformedLongPress = false;
15584
15585            if (mPendingCheckForLongPress == null) {
15586                mPendingCheckForLongPress = new CheckForLongPress();
15587            }
15588            mPendingCheckForLongPress.rememberWindowAttachCount();
15589            postDelayed(mPendingCheckForLongPress,
15590                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15591        }
15592    }
15593
15594    /**
15595     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15596     * LayoutInflater} class, which provides a full range of options for view inflation.
15597     *
15598     * @param context The Context object for your activity or application.
15599     * @param resource The resource ID to inflate
15600     * @param root A view group that will be the parent.  Used to properly inflate the
15601     * layout_* parameters.
15602     * @see LayoutInflater
15603     */
15604    public static View inflate(Context context, int resource, ViewGroup root) {
15605        LayoutInflater factory = LayoutInflater.from(context);
15606        return factory.inflate(resource, root);
15607    }
15608
15609    /**
15610     * Scroll the view with standard behavior for scrolling beyond the normal
15611     * content boundaries. Views that call this method should override
15612     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15613     * results of an over-scroll operation.
15614     *
15615     * Views can use this method to handle any touch or fling-based scrolling.
15616     *
15617     * @param deltaX Change in X in pixels
15618     * @param deltaY Change in Y in pixels
15619     * @param scrollX Current X scroll value in pixels before applying deltaX
15620     * @param scrollY Current Y scroll value in pixels before applying deltaY
15621     * @param scrollRangeX Maximum content scroll range along the X axis
15622     * @param scrollRangeY Maximum content scroll range along the Y axis
15623     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15624     *          along the X axis.
15625     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15626     *          along the Y axis.
15627     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15628     * @return true if scrolling was clamped to an over-scroll boundary along either
15629     *          axis, false otherwise.
15630     */
15631    @SuppressWarnings({"UnusedParameters"})
15632    protected boolean overScrollBy(int deltaX, int deltaY,
15633            int scrollX, int scrollY,
15634            int scrollRangeX, int scrollRangeY,
15635            int maxOverScrollX, int maxOverScrollY,
15636            boolean isTouchEvent) {
15637        final int overScrollMode = mOverScrollMode;
15638        final boolean canScrollHorizontal =
15639                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15640        final boolean canScrollVertical =
15641                computeVerticalScrollRange() > computeVerticalScrollExtent();
15642        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15643                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15644        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15645                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15646
15647        int newScrollX = scrollX + deltaX;
15648        if (!overScrollHorizontal) {
15649            maxOverScrollX = 0;
15650        }
15651
15652        int newScrollY = scrollY + deltaY;
15653        if (!overScrollVertical) {
15654            maxOverScrollY = 0;
15655        }
15656
15657        // Clamp values if at the limits and record
15658        final int left = -maxOverScrollX;
15659        final int right = maxOverScrollX + scrollRangeX;
15660        final int top = -maxOverScrollY;
15661        final int bottom = maxOverScrollY + scrollRangeY;
15662
15663        boolean clampedX = false;
15664        if (newScrollX > right) {
15665            newScrollX = right;
15666            clampedX = true;
15667        } else if (newScrollX < left) {
15668            newScrollX = left;
15669            clampedX = true;
15670        }
15671
15672        boolean clampedY = false;
15673        if (newScrollY > bottom) {
15674            newScrollY = bottom;
15675            clampedY = true;
15676        } else if (newScrollY < top) {
15677            newScrollY = top;
15678            clampedY = true;
15679        }
15680
15681        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15682
15683        return clampedX || clampedY;
15684    }
15685
15686    /**
15687     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15688     * respond to the results of an over-scroll operation.
15689     *
15690     * @param scrollX New X scroll value in pixels
15691     * @param scrollY New Y scroll value in pixels
15692     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15693     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15694     */
15695    protected void onOverScrolled(int scrollX, int scrollY,
15696            boolean clampedX, boolean clampedY) {
15697        // Intentionally empty.
15698    }
15699
15700    /**
15701     * Returns the over-scroll mode for this view. The result will be
15702     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15703     * (allow over-scrolling only if the view content is larger than the container),
15704     * or {@link #OVER_SCROLL_NEVER}.
15705     *
15706     * @return This view's over-scroll mode.
15707     */
15708    public int getOverScrollMode() {
15709        return mOverScrollMode;
15710    }
15711
15712    /**
15713     * Set the over-scroll mode for this view. Valid over-scroll modes are
15714     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15715     * (allow over-scrolling only if the view content is larger than the container),
15716     * or {@link #OVER_SCROLL_NEVER}.
15717     *
15718     * Setting the over-scroll mode of a view will have an effect only if the
15719     * view is capable of scrolling.
15720     *
15721     * @param overScrollMode The new over-scroll mode for this view.
15722     */
15723    public void setOverScrollMode(int overScrollMode) {
15724        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15725                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15726                overScrollMode != OVER_SCROLL_NEVER) {
15727            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15728        }
15729        mOverScrollMode = overScrollMode;
15730    }
15731
15732    /**
15733     * Gets a scale factor that determines the distance the view should scroll
15734     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15735     * @return The vertical scroll scale factor.
15736     * @hide
15737     */
15738    protected float getVerticalScrollFactor() {
15739        if (mVerticalScrollFactor == 0) {
15740            TypedValue outValue = new TypedValue();
15741            if (!mContext.getTheme().resolveAttribute(
15742                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15743                throw new IllegalStateException(
15744                        "Expected theme to define listPreferredItemHeight.");
15745            }
15746            mVerticalScrollFactor = outValue.getDimension(
15747                    mContext.getResources().getDisplayMetrics());
15748        }
15749        return mVerticalScrollFactor;
15750    }
15751
15752    /**
15753     * Gets a scale factor that determines the distance the view should scroll
15754     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
15755     * @return The horizontal scroll scale factor.
15756     * @hide
15757     */
15758    protected float getHorizontalScrollFactor() {
15759        // TODO: Should use something else.
15760        return getVerticalScrollFactor();
15761    }
15762
15763    /**
15764     * Return the value specifying the text direction or policy that was set with
15765     * {@link #setTextDirection(int)}.
15766     *
15767     * @return the defined text direction. It can be one of:
15768     *
15769     * {@link #TEXT_DIRECTION_INHERIT},
15770     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15771     * {@link #TEXT_DIRECTION_ANY_RTL},
15772     * {@link #TEXT_DIRECTION_LTR},
15773     * {@link #TEXT_DIRECTION_RTL},
15774     * {@link #TEXT_DIRECTION_LOCALE}
15775     * @hide
15776     */
15777    @ViewDebug.ExportedProperty(category = "text", mapping = {
15778            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
15779            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
15780            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
15781            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
15782            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
15783            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
15784    })
15785    public int getTextDirection() {
15786        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
15787    }
15788
15789    /**
15790     * Set the text direction.
15791     *
15792     * @param textDirection the direction to set. Should be one of:
15793     *
15794     * {@link #TEXT_DIRECTION_INHERIT},
15795     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15796     * {@link #TEXT_DIRECTION_ANY_RTL},
15797     * {@link #TEXT_DIRECTION_LTR},
15798     * {@link #TEXT_DIRECTION_RTL},
15799     * {@link #TEXT_DIRECTION_LOCALE}
15800     * @hide
15801     */
15802    public void setTextDirection(int textDirection) {
15803        if (getTextDirection() != textDirection) {
15804            // Reset the current text direction and the resolved one
15805            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
15806            resetResolvedTextDirection();
15807            // Set the new text direction
15808            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
15809            // Refresh
15810            requestLayout();
15811            invalidate(true);
15812        }
15813    }
15814
15815    /**
15816     * Return the resolved text direction.
15817     *
15818     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
15819     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
15820     * up the parent chain of the view. if there is no parent, then it will return the default
15821     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
15822     *
15823     * @return the resolved text direction. Returns one of:
15824     *
15825     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15826     * {@link #TEXT_DIRECTION_ANY_RTL},
15827     * {@link #TEXT_DIRECTION_LTR},
15828     * {@link #TEXT_DIRECTION_RTL},
15829     * {@link #TEXT_DIRECTION_LOCALE}
15830     * @hide
15831     */
15832    public int getResolvedTextDirection() {
15833        // The text direction will be resolved only if needed
15834        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
15835            resolveTextDirection();
15836        }
15837        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
15838    }
15839
15840    /**
15841     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
15842     * resolution is done.
15843     * @hide
15844     */
15845    public void resolveTextDirection() {
15846        // Reset any previous text direction resolution
15847        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15848
15849        if (hasRtlSupport()) {
15850            // Set resolved text direction flag depending on text direction flag
15851            final int textDirection = getTextDirection();
15852            switch(textDirection) {
15853                case TEXT_DIRECTION_INHERIT:
15854                    if (canResolveTextDirection()) {
15855                        ViewGroup viewGroup = ((ViewGroup) mParent);
15856
15857                        // Set current resolved direction to the same value as the parent's one
15858                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
15859                        switch (parentResolvedDirection) {
15860                            case TEXT_DIRECTION_FIRST_STRONG:
15861                            case TEXT_DIRECTION_ANY_RTL:
15862                            case TEXT_DIRECTION_LTR:
15863                            case TEXT_DIRECTION_RTL:
15864                            case TEXT_DIRECTION_LOCALE:
15865                                mPrivateFlags2 |=
15866                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15867                                break;
15868                            default:
15869                                // Default resolved direction is "first strong" heuristic
15870                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15871                        }
15872                    } else {
15873                        // We cannot do the resolution if there is no parent, so use the default one
15874                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15875                    }
15876                    break;
15877                case TEXT_DIRECTION_FIRST_STRONG:
15878                case TEXT_DIRECTION_ANY_RTL:
15879                case TEXT_DIRECTION_LTR:
15880                case TEXT_DIRECTION_RTL:
15881                case TEXT_DIRECTION_LOCALE:
15882                    // Resolved direction is the same as text direction
15883                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15884                    break;
15885                default:
15886                    // Default resolved direction is "first strong" heuristic
15887                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15888            }
15889        } else {
15890            // Default resolved direction is "first strong" heuristic
15891            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15892        }
15893
15894        // Set to resolved
15895        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
15896        onResolvedTextDirectionChanged();
15897    }
15898
15899    /**
15900     * Called when text direction has been resolved. Subclasses that care about text direction
15901     * resolution should override this method.
15902     *
15903     * The default implementation does nothing.
15904     * @hide
15905     */
15906    public void onResolvedTextDirectionChanged() {
15907    }
15908
15909    /**
15910     * Check if text direction resolution can be done.
15911     *
15912     * @return true if text direction resolution can be done otherwise return false.
15913     * @hide
15914     */
15915    public boolean canResolveTextDirection() {
15916        switch (getTextDirection()) {
15917            case TEXT_DIRECTION_INHERIT:
15918                return (mParent != null) && (mParent instanceof ViewGroup);
15919            default:
15920                return true;
15921        }
15922    }
15923
15924    /**
15925     * Reset resolved text direction. Text direction can be resolved with a call to
15926     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
15927     * reset is done.
15928     * @hide
15929     */
15930    public void resetResolvedTextDirection() {
15931        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15932        onResolvedTextDirectionReset();
15933    }
15934
15935    /**
15936     * Called when text direction is reset. Subclasses that care about text direction reset should
15937     * override this method and do a reset of the text direction of their children. The default
15938     * implementation does nothing.
15939     * @hide
15940     */
15941    public void onResolvedTextDirectionReset() {
15942    }
15943
15944    /**
15945     * Return the value specifying the text alignment or policy that was set with
15946     * {@link #setTextAlignment(int)}.
15947     *
15948     * @return the defined text alignment. It can be one of:
15949     *
15950     * {@link #TEXT_ALIGNMENT_INHERIT},
15951     * {@link #TEXT_ALIGNMENT_GRAVITY},
15952     * {@link #TEXT_ALIGNMENT_CENTER},
15953     * {@link #TEXT_ALIGNMENT_TEXT_START},
15954     * {@link #TEXT_ALIGNMENT_TEXT_END},
15955     * {@link #TEXT_ALIGNMENT_VIEW_START},
15956     * {@link #TEXT_ALIGNMENT_VIEW_END}
15957     * @hide
15958     */
15959    @ViewDebug.ExportedProperty(category = "text", mapping = {
15960            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15961            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15962            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15963            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15964            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15965            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15966            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15967    })
15968    public int getTextAlignment() {
15969        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
15970    }
15971
15972    /**
15973     * Set the text alignment.
15974     *
15975     * @param textAlignment The text alignment to set. Should be one of
15976     *
15977     * {@link #TEXT_ALIGNMENT_INHERIT},
15978     * {@link #TEXT_ALIGNMENT_GRAVITY},
15979     * {@link #TEXT_ALIGNMENT_CENTER},
15980     * {@link #TEXT_ALIGNMENT_TEXT_START},
15981     * {@link #TEXT_ALIGNMENT_TEXT_END},
15982     * {@link #TEXT_ALIGNMENT_VIEW_START},
15983     * {@link #TEXT_ALIGNMENT_VIEW_END}
15984     *
15985     * @attr ref android.R.styleable#View_textAlignment
15986     * @hide
15987     */
15988    public void setTextAlignment(int textAlignment) {
15989        if (textAlignment != getTextAlignment()) {
15990            // Reset the current and resolved text alignment
15991            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
15992            resetResolvedTextAlignment();
15993            // Set the new text alignment
15994            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
15995            // Refresh
15996            requestLayout();
15997            invalidate(true);
15998        }
15999    }
16000
16001    /**
16002     * Return the resolved text alignment.
16003     *
16004     * The resolved text alignment. This needs resolution if the value is
16005     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16006     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16007     *
16008     * @return the resolved text alignment. Returns one of:
16009     *
16010     * {@link #TEXT_ALIGNMENT_GRAVITY},
16011     * {@link #TEXT_ALIGNMENT_CENTER},
16012     * {@link #TEXT_ALIGNMENT_TEXT_START},
16013     * {@link #TEXT_ALIGNMENT_TEXT_END},
16014     * {@link #TEXT_ALIGNMENT_VIEW_START},
16015     * {@link #TEXT_ALIGNMENT_VIEW_END}
16016     * @hide
16017     */
16018    @ViewDebug.ExportedProperty(category = "text", mapping = {
16019            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16020            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16021            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16022            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16023            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16024            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16025            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16026    })
16027    public int getResolvedTextAlignment() {
16028        // If text alignment is not resolved, then resolve it
16029        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16030            resolveTextAlignment();
16031        }
16032        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16033    }
16034
16035    /**
16036     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16037     * resolution is done.
16038     * @hide
16039     */
16040    public void resolveTextAlignment() {
16041        // Reset any previous text alignment resolution
16042        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16043
16044        if (hasRtlSupport()) {
16045            // Set resolved text alignment flag depending on text alignment flag
16046            final int textAlignment = getTextAlignment();
16047            switch (textAlignment) {
16048                case TEXT_ALIGNMENT_INHERIT:
16049                    // Check if we can resolve the text alignment
16050                    if (canResolveLayoutDirection() && mParent instanceof View) {
16051                        View view = (View) mParent;
16052
16053                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16054                        switch (parentResolvedTextAlignment) {
16055                            case TEXT_ALIGNMENT_GRAVITY:
16056                            case TEXT_ALIGNMENT_TEXT_START:
16057                            case TEXT_ALIGNMENT_TEXT_END:
16058                            case TEXT_ALIGNMENT_CENTER:
16059                            case TEXT_ALIGNMENT_VIEW_START:
16060                            case TEXT_ALIGNMENT_VIEW_END:
16061                                // Resolved text alignment is the same as the parent resolved
16062                                // text alignment
16063                                mPrivateFlags2 |=
16064                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16065                                break;
16066                            default:
16067                                // Use default resolved text alignment
16068                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16069                        }
16070                    }
16071                    else {
16072                        // We cannot do the resolution if there is no parent so use the default
16073                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16074                    }
16075                    break;
16076                case TEXT_ALIGNMENT_GRAVITY:
16077                case TEXT_ALIGNMENT_TEXT_START:
16078                case TEXT_ALIGNMENT_TEXT_END:
16079                case TEXT_ALIGNMENT_CENTER:
16080                case TEXT_ALIGNMENT_VIEW_START:
16081                case TEXT_ALIGNMENT_VIEW_END:
16082                    // Resolved text alignment is the same as text alignment
16083                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16084                    break;
16085                default:
16086                    // Use default resolved text alignment
16087                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16088            }
16089        } else {
16090            // Use default resolved text alignment
16091            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16092        }
16093
16094        // Set the resolved
16095        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16096        onResolvedTextAlignmentChanged();
16097    }
16098
16099    /**
16100     * Check if text alignment resolution can be done.
16101     *
16102     * @return true if text alignment resolution can be done otherwise return false.
16103     * @hide
16104     */
16105    public boolean canResolveTextAlignment() {
16106        switch (getTextAlignment()) {
16107            case TEXT_DIRECTION_INHERIT:
16108                return (mParent != null);
16109            default:
16110                return true;
16111        }
16112    }
16113
16114    /**
16115     * Called when text alignment has been resolved. Subclasses that care about text alignment
16116     * resolution should override this method.
16117     *
16118     * The default implementation does nothing.
16119     * @hide
16120     */
16121    public void onResolvedTextAlignmentChanged() {
16122    }
16123
16124    /**
16125     * Reset resolved text alignment. Text alignment can be resolved with a call to
16126     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16127     * reset is done.
16128     * @hide
16129     */
16130    public void resetResolvedTextAlignment() {
16131        // Reset any previous text alignment resolution
16132        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16133        onResolvedTextAlignmentReset();
16134    }
16135
16136    /**
16137     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16138     * override this method and do a reset of the text alignment of their children. The default
16139     * implementation does nothing.
16140     * @hide
16141     */
16142    public void onResolvedTextAlignmentReset() {
16143    }
16144
16145    //
16146    // Properties
16147    //
16148    /**
16149     * A Property wrapper around the <code>alpha</code> functionality handled by the
16150     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16151     */
16152    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16153        @Override
16154        public void setValue(View object, float value) {
16155            object.setAlpha(value);
16156        }
16157
16158        @Override
16159        public Float get(View object) {
16160            return object.getAlpha();
16161        }
16162    };
16163
16164    /**
16165     * A Property wrapper around the <code>translationX</code> functionality handled by the
16166     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16167     */
16168    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16169        @Override
16170        public void setValue(View object, float value) {
16171            object.setTranslationX(value);
16172        }
16173
16174                @Override
16175        public Float get(View object) {
16176            return object.getTranslationX();
16177        }
16178    };
16179
16180    /**
16181     * A Property wrapper around the <code>translationY</code> functionality handled by the
16182     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16183     */
16184    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16185        @Override
16186        public void setValue(View object, float value) {
16187            object.setTranslationY(value);
16188        }
16189
16190        @Override
16191        public Float get(View object) {
16192            return object.getTranslationY();
16193        }
16194    };
16195
16196    /**
16197     * A Property wrapper around the <code>x</code> functionality handled by the
16198     * {@link View#setX(float)} and {@link View#getX()} methods.
16199     */
16200    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16201        @Override
16202        public void setValue(View object, float value) {
16203            object.setX(value);
16204        }
16205
16206        @Override
16207        public Float get(View object) {
16208            return object.getX();
16209        }
16210    };
16211
16212    /**
16213     * A Property wrapper around the <code>y</code> functionality handled by the
16214     * {@link View#setY(float)} and {@link View#getY()} methods.
16215     */
16216    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16217        @Override
16218        public void setValue(View object, float value) {
16219            object.setY(value);
16220        }
16221
16222        @Override
16223        public Float get(View object) {
16224            return object.getY();
16225        }
16226    };
16227
16228    /**
16229     * A Property wrapper around the <code>rotation</code> functionality handled by the
16230     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16231     */
16232    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16233        @Override
16234        public void setValue(View object, float value) {
16235            object.setRotation(value);
16236        }
16237
16238        @Override
16239        public Float get(View object) {
16240            return object.getRotation();
16241        }
16242    };
16243
16244    /**
16245     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16246     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16247     */
16248    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16249        @Override
16250        public void setValue(View object, float value) {
16251            object.setRotationX(value);
16252        }
16253
16254        @Override
16255        public Float get(View object) {
16256            return object.getRotationX();
16257        }
16258    };
16259
16260    /**
16261     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16262     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16263     */
16264    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16265        @Override
16266        public void setValue(View object, float value) {
16267            object.setRotationY(value);
16268        }
16269
16270        @Override
16271        public Float get(View object) {
16272            return object.getRotationY();
16273        }
16274    };
16275
16276    /**
16277     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16278     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16279     */
16280    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16281        @Override
16282        public void setValue(View object, float value) {
16283            object.setScaleX(value);
16284        }
16285
16286        @Override
16287        public Float get(View object) {
16288            return object.getScaleX();
16289        }
16290    };
16291
16292    /**
16293     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16294     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16295     */
16296    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16297        @Override
16298        public void setValue(View object, float value) {
16299            object.setScaleY(value);
16300        }
16301
16302        @Override
16303        public Float get(View object) {
16304            return object.getScaleY();
16305        }
16306    };
16307
16308    /**
16309     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16310     * Each MeasureSpec represents a requirement for either the width or the height.
16311     * A MeasureSpec is comprised of a size and a mode. There are three possible
16312     * modes:
16313     * <dl>
16314     * <dt>UNSPECIFIED</dt>
16315     * <dd>
16316     * The parent has not imposed any constraint on the child. It can be whatever size
16317     * it wants.
16318     * </dd>
16319     *
16320     * <dt>EXACTLY</dt>
16321     * <dd>
16322     * The parent has determined an exact size for the child. The child is going to be
16323     * given those bounds regardless of how big it wants to be.
16324     * </dd>
16325     *
16326     * <dt>AT_MOST</dt>
16327     * <dd>
16328     * The child can be as large as it wants up to the specified size.
16329     * </dd>
16330     * </dl>
16331     *
16332     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16333     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16334     */
16335    public static class MeasureSpec {
16336        private static final int MODE_SHIFT = 30;
16337        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16338
16339        /**
16340         * Measure specification mode: The parent has not imposed any constraint
16341         * on the child. It can be whatever size it wants.
16342         */
16343        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16344
16345        /**
16346         * Measure specification mode: The parent has determined an exact size
16347         * for the child. The child is going to be given those bounds regardless
16348         * of how big it wants to be.
16349         */
16350        public static final int EXACTLY     = 1 << MODE_SHIFT;
16351
16352        /**
16353         * Measure specification mode: The child can be as large as it wants up
16354         * to the specified size.
16355         */
16356        public static final int AT_MOST     = 2 << MODE_SHIFT;
16357
16358        /**
16359         * Creates a measure specification based on the supplied size and mode.
16360         *
16361         * The mode must always be one of the following:
16362         * <ul>
16363         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16364         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16365         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16366         * </ul>
16367         *
16368         * @param size the size of the measure specification
16369         * @param mode the mode of the measure specification
16370         * @return the measure specification based on size and mode
16371         */
16372        public static int makeMeasureSpec(int size, int mode) {
16373            return size + mode;
16374        }
16375
16376        /**
16377         * Extracts the mode from the supplied measure specification.
16378         *
16379         * @param measureSpec the measure specification to extract the mode from
16380         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16381         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16382         *         {@link android.view.View.MeasureSpec#EXACTLY}
16383         */
16384        public static int getMode(int measureSpec) {
16385            return (measureSpec & MODE_MASK);
16386        }
16387
16388        /**
16389         * Extracts the size from the supplied measure specification.
16390         *
16391         * @param measureSpec the measure specification to extract the size from
16392         * @return the size in pixels defined in the supplied measure specification
16393         */
16394        public static int getSize(int measureSpec) {
16395            return (measureSpec & ~MODE_MASK);
16396        }
16397
16398        /**
16399         * Returns a String representation of the specified measure
16400         * specification.
16401         *
16402         * @param measureSpec the measure specification to convert to a String
16403         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16404         */
16405        public static String toString(int measureSpec) {
16406            int mode = getMode(measureSpec);
16407            int size = getSize(measureSpec);
16408
16409            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16410
16411            if (mode == UNSPECIFIED)
16412                sb.append("UNSPECIFIED ");
16413            else if (mode == EXACTLY)
16414                sb.append("EXACTLY ");
16415            else if (mode == AT_MOST)
16416                sb.append("AT_MOST ");
16417            else
16418                sb.append(mode).append(" ");
16419
16420            sb.append(size);
16421            return sb.toString();
16422        }
16423    }
16424
16425    class CheckForLongPress implements Runnable {
16426
16427        private int mOriginalWindowAttachCount;
16428
16429        public void run() {
16430            if (isPressed() && (mParent != null)
16431                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16432                if (performLongClick()) {
16433                    mHasPerformedLongPress = true;
16434                }
16435            }
16436        }
16437
16438        public void rememberWindowAttachCount() {
16439            mOriginalWindowAttachCount = mWindowAttachCount;
16440        }
16441    }
16442
16443    private final class CheckForTap implements Runnable {
16444        public void run() {
16445            mPrivateFlags &= ~PREPRESSED;
16446            setPressed(true);
16447            checkForLongClick(ViewConfiguration.getTapTimeout());
16448        }
16449    }
16450
16451    private final class PerformClick implements Runnable {
16452        public void run() {
16453            performClick();
16454        }
16455    }
16456
16457    /** @hide */
16458    public void hackTurnOffWindowResizeAnim(boolean off) {
16459        mAttachInfo.mTurnOffWindowResizeAnim = off;
16460    }
16461
16462    /**
16463     * This method returns a ViewPropertyAnimator object, which can be used to animate
16464     * specific properties on this View.
16465     *
16466     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16467     */
16468    public ViewPropertyAnimator animate() {
16469        if (mAnimator == null) {
16470            mAnimator = new ViewPropertyAnimator(this);
16471        }
16472        return mAnimator;
16473    }
16474
16475    /**
16476     * Interface definition for a callback to be invoked when a key event is
16477     * dispatched to this view. The callback will be invoked before the key
16478     * event is given to the view.
16479     */
16480    public interface OnKeyListener {
16481        /**
16482         * Called when a key is dispatched to a view. This allows listeners to
16483         * get a chance to respond before the target view.
16484         *
16485         * @param v The view the key has been dispatched to.
16486         * @param keyCode The code for the physical key that was pressed
16487         * @param event The KeyEvent object containing full information about
16488         *        the event.
16489         * @return True if the listener has consumed the event, false otherwise.
16490         */
16491        boolean onKey(View v, int keyCode, KeyEvent event);
16492    }
16493
16494    /**
16495     * Interface definition for a callback to be invoked when a touch event is
16496     * dispatched to this view. The callback will be invoked before the touch
16497     * event is given to the view.
16498     */
16499    public interface OnTouchListener {
16500        /**
16501         * Called when a touch event is dispatched to a view. This allows listeners to
16502         * get a chance to respond before the target view.
16503         *
16504         * @param v The view the touch event has been dispatched to.
16505         * @param event The MotionEvent object containing full information about
16506         *        the event.
16507         * @return True if the listener has consumed the event, false otherwise.
16508         */
16509        boolean onTouch(View v, MotionEvent event);
16510    }
16511
16512    /**
16513     * Interface definition for a callback to be invoked when a hover event is
16514     * dispatched to this view. The callback will be invoked before the hover
16515     * event is given to the view.
16516     */
16517    public interface OnHoverListener {
16518        /**
16519         * Called when a hover event is dispatched to a view. This allows listeners to
16520         * get a chance to respond before the target view.
16521         *
16522         * @param v The view the hover event has been dispatched to.
16523         * @param event The MotionEvent object containing full information about
16524         *        the event.
16525         * @return True if the listener has consumed the event, false otherwise.
16526         */
16527        boolean onHover(View v, MotionEvent event);
16528    }
16529
16530    /**
16531     * Interface definition for a callback to be invoked when a generic motion event is
16532     * dispatched to this view. The callback will be invoked before the generic motion
16533     * event is given to the view.
16534     */
16535    public interface OnGenericMotionListener {
16536        /**
16537         * Called when a generic motion event is dispatched to a view. This allows listeners to
16538         * get a chance to respond before the target view.
16539         *
16540         * @param v The view the generic motion event has been dispatched to.
16541         * @param event The MotionEvent object containing full information about
16542         *        the event.
16543         * @return True if the listener has consumed the event, false otherwise.
16544         */
16545        boolean onGenericMotion(View v, MotionEvent event);
16546    }
16547
16548    /**
16549     * Interface definition for a callback to be invoked when a view has been clicked and held.
16550     */
16551    public interface OnLongClickListener {
16552        /**
16553         * Called when a view has been clicked and held.
16554         *
16555         * @param v The view that was clicked and held.
16556         *
16557         * @return true if the callback consumed the long click, false otherwise.
16558         */
16559        boolean onLongClick(View v);
16560    }
16561
16562    /**
16563     * Interface definition for a callback to be invoked when a drag is being dispatched
16564     * to this view.  The callback will be invoked before the hosting view's own
16565     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16566     * onDrag(event) behavior, it should return 'false' from this callback.
16567     *
16568     * <div class="special reference">
16569     * <h3>Developer Guides</h3>
16570     * <p>For a guide to implementing drag and drop features, read the
16571     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16572     * </div>
16573     */
16574    public interface OnDragListener {
16575        /**
16576         * Called when a drag event is dispatched to a view. This allows listeners
16577         * to get a chance to override base View behavior.
16578         *
16579         * @param v The View that received the drag event.
16580         * @param event The {@link android.view.DragEvent} object for the drag event.
16581         * @return {@code true} if the drag event was handled successfully, or {@code false}
16582         * if the drag event was not handled. Note that {@code false} will trigger the View
16583         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16584         */
16585        boolean onDrag(View v, DragEvent event);
16586    }
16587
16588    /**
16589     * Interface definition for a callback to be invoked when the focus state of
16590     * a view changed.
16591     */
16592    public interface OnFocusChangeListener {
16593        /**
16594         * Called when the focus state of a view has changed.
16595         *
16596         * @param v The view whose state has changed.
16597         * @param hasFocus The new focus state of v.
16598         */
16599        void onFocusChange(View v, boolean hasFocus);
16600    }
16601
16602    /**
16603     * Interface definition for a callback to be invoked when a view is clicked.
16604     */
16605    public interface OnClickListener {
16606        /**
16607         * Called when a view has been clicked.
16608         *
16609         * @param v The view that was clicked.
16610         */
16611        void onClick(View v);
16612    }
16613
16614    /**
16615     * Interface definition for a callback to be invoked when the context menu
16616     * for this view is being built.
16617     */
16618    public interface OnCreateContextMenuListener {
16619        /**
16620         * Called when the context menu for this view is being built. It is not
16621         * safe to hold onto the menu after this method returns.
16622         *
16623         * @param menu The context menu that is being built
16624         * @param v The view for which the context menu is being built
16625         * @param menuInfo Extra information about the item for which the
16626         *            context menu should be shown. This information will vary
16627         *            depending on the class of v.
16628         */
16629        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16630    }
16631
16632    /**
16633     * Interface definition for a callback to be invoked when the status bar changes
16634     * visibility.  This reports <strong>global</strong> changes to the system UI
16635     * state, not just what the application is requesting.
16636     *
16637     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16638     */
16639    public interface OnSystemUiVisibilityChangeListener {
16640        /**
16641         * Called when the status bar changes visibility because of a call to
16642         * {@link View#setSystemUiVisibility(int)}.
16643         *
16644         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
16645         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
16646         * <strong>global</strong> state of the UI visibility flags, not what your
16647         * app is currently applying.
16648         */
16649        public void onSystemUiVisibilityChange(int visibility);
16650    }
16651
16652    /**
16653     * Interface definition for a callback to be invoked when this view is attached
16654     * or detached from its window.
16655     */
16656    public interface OnAttachStateChangeListener {
16657        /**
16658         * Called when the view is attached to a window.
16659         * @param v The view that was attached
16660         */
16661        public void onViewAttachedToWindow(View v);
16662        /**
16663         * Called when the view is detached from a window.
16664         * @param v The view that was detached
16665         */
16666        public void onViewDetachedFromWindow(View v);
16667    }
16668
16669    private final class UnsetPressedState implements Runnable {
16670        public void run() {
16671            setPressed(false);
16672        }
16673    }
16674
16675    /**
16676     * Base class for derived classes that want to save and restore their own
16677     * state in {@link android.view.View#onSaveInstanceState()}.
16678     */
16679    public static class BaseSavedState extends AbsSavedState {
16680        /**
16681         * Constructor used when reading from a parcel. Reads the state of the superclass.
16682         *
16683         * @param source
16684         */
16685        public BaseSavedState(Parcel source) {
16686            super(source);
16687        }
16688
16689        /**
16690         * Constructor called by derived classes when creating their SavedState objects
16691         *
16692         * @param superState The state of the superclass of this view
16693         */
16694        public BaseSavedState(Parcelable superState) {
16695            super(superState);
16696        }
16697
16698        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16699                new Parcelable.Creator<BaseSavedState>() {
16700            public BaseSavedState createFromParcel(Parcel in) {
16701                return new BaseSavedState(in);
16702            }
16703
16704            public BaseSavedState[] newArray(int size) {
16705                return new BaseSavedState[size];
16706            }
16707        };
16708    }
16709
16710    /**
16711     * A set of information given to a view when it is attached to its parent
16712     * window.
16713     */
16714    static class AttachInfo {
16715        interface Callbacks {
16716            void playSoundEffect(int effectId);
16717            boolean performHapticFeedback(int effectId, boolean always);
16718        }
16719
16720        /**
16721         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
16722         * to a Handler. This class contains the target (View) to invalidate and
16723         * the coordinates of the dirty rectangle.
16724         *
16725         * For performance purposes, this class also implements a pool of up to
16726         * POOL_LIMIT objects that get reused. This reduces memory allocations
16727         * whenever possible.
16728         */
16729        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16730            private static final int POOL_LIMIT = 10;
16731            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16732                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16733                        public InvalidateInfo newInstance() {
16734                            return new InvalidateInfo();
16735                        }
16736
16737                        public void onAcquired(InvalidateInfo element) {
16738                        }
16739
16740                        public void onReleased(InvalidateInfo element) {
16741                            element.target = null;
16742                        }
16743                    }, POOL_LIMIT)
16744            );
16745
16746            private InvalidateInfo mNext;
16747            private boolean mIsPooled;
16748
16749            View target;
16750
16751            int left;
16752            int top;
16753            int right;
16754            int bottom;
16755
16756            public void setNextPoolable(InvalidateInfo element) {
16757                mNext = element;
16758            }
16759
16760            public InvalidateInfo getNextPoolable() {
16761                return mNext;
16762            }
16763
16764            static InvalidateInfo acquire() {
16765                return sPool.acquire();
16766            }
16767
16768            void release() {
16769                sPool.release(this);
16770            }
16771
16772            public boolean isPooled() {
16773                return mIsPooled;
16774            }
16775
16776            public void setPooled(boolean isPooled) {
16777                mIsPooled = isPooled;
16778            }
16779        }
16780
16781        final IWindowSession mSession;
16782
16783        final IWindow mWindow;
16784
16785        final IBinder mWindowToken;
16786
16787        final Callbacks mRootCallbacks;
16788
16789        HardwareCanvas mHardwareCanvas;
16790
16791        /**
16792         * The top view of the hierarchy.
16793         */
16794        View mRootView;
16795
16796        IBinder mPanelParentWindowToken;
16797        Surface mSurface;
16798
16799        boolean mHardwareAccelerated;
16800        boolean mHardwareAccelerationRequested;
16801        HardwareRenderer mHardwareRenderer;
16802
16803        boolean mScreenOn;
16804
16805        /**
16806         * Scale factor used by the compatibility mode
16807         */
16808        float mApplicationScale;
16809
16810        /**
16811         * Indicates whether the application is in compatibility mode
16812         */
16813        boolean mScalingRequired;
16814
16815        /**
16816         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
16817         */
16818        boolean mTurnOffWindowResizeAnim;
16819
16820        /**
16821         * Left position of this view's window
16822         */
16823        int mWindowLeft;
16824
16825        /**
16826         * Top position of this view's window
16827         */
16828        int mWindowTop;
16829
16830        /**
16831         * Indicates whether views need to use 32-bit drawing caches
16832         */
16833        boolean mUse32BitDrawingCache;
16834
16835        /**
16836         * Describes the parts of the window that are currently completely
16837         * obscured by system UI elements.
16838         */
16839        final Rect mSystemInsets = new Rect();
16840
16841        /**
16842         * For windows that are full-screen but using insets to layout inside
16843         * of the screen decorations, these are the current insets for the
16844         * content of the window.
16845         */
16846        final Rect mContentInsets = new Rect();
16847
16848        /**
16849         * For windows that are full-screen but using insets to layout inside
16850         * of the screen decorations, these are the current insets for the
16851         * actual visible parts of the window.
16852         */
16853        final Rect mVisibleInsets = new Rect();
16854
16855        /**
16856         * The internal insets given by this window.  This value is
16857         * supplied by the client (through
16858         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
16859         * be given to the window manager when changed to be used in laying
16860         * out windows behind it.
16861         */
16862        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
16863                = new ViewTreeObserver.InternalInsetsInfo();
16864
16865        /**
16866         * All views in the window's hierarchy that serve as scroll containers,
16867         * used to determine if the window can be resized or must be panned
16868         * to adjust for a soft input area.
16869         */
16870        final ArrayList<View> mScrollContainers = new ArrayList<View>();
16871
16872        final KeyEvent.DispatcherState mKeyDispatchState
16873                = new KeyEvent.DispatcherState();
16874
16875        /**
16876         * Indicates whether the view's window currently has the focus.
16877         */
16878        boolean mHasWindowFocus;
16879
16880        /**
16881         * The current visibility of the window.
16882         */
16883        int mWindowVisibility;
16884
16885        /**
16886         * Indicates the time at which drawing started to occur.
16887         */
16888        long mDrawingTime;
16889
16890        /**
16891         * Indicates whether or not ignoring the DIRTY_MASK flags.
16892         */
16893        boolean mIgnoreDirtyState;
16894
16895        /**
16896         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
16897         * to avoid clearing that flag prematurely.
16898         */
16899        boolean mSetIgnoreDirtyState = false;
16900
16901        /**
16902         * Indicates whether the view's window is currently in touch mode.
16903         */
16904        boolean mInTouchMode;
16905
16906        /**
16907         * Indicates that ViewAncestor should trigger a global layout change
16908         * the next time it performs a traversal
16909         */
16910        boolean mRecomputeGlobalAttributes;
16911
16912        /**
16913         * Always report new attributes at next traversal.
16914         */
16915        boolean mForceReportNewAttributes;
16916
16917        /**
16918         * Set during a traveral if any views want to keep the screen on.
16919         */
16920        boolean mKeepScreenOn;
16921
16922        /**
16923         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
16924         */
16925        int mSystemUiVisibility;
16926
16927        /**
16928         * Hack to force certain system UI visibility flags to be cleared.
16929         */
16930        int mDisabledSystemUiVisibility;
16931
16932        /**
16933         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
16934         * attached.
16935         */
16936        boolean mHasSystemUiListeners;
16937
16938        /**
16939         * Set if the visibility of any views has changed.
16940         */
16941        boolean mViewVisibilityChanged;
16942
16943        /**
16944         * Set to true if a view has been scrolled.
16945         */
16946        boolean mViewScrollChanged;
16947
16948        /**
16949         * Global to the view hierarchy used as a temporary for dealing with
16950         * x/y points in the transparent region computations.
16951         */
16952        final int[] mTransparentLocation = new int[2];
16953
16954        /**
16955         * Global to the view hierarchy used as a temporary for dealing with
16956         * x/y points in the ViewGroup.invalidateChild implementation.
16957         */
16958        final int[] mInvalidateChildLocation = new int[2];
16959
16960
16961        /**
16962         * Global to the view hierarchy used as a temporary for dealing with
16963         * x/y location when view is transformed.
16964         */
16965        final float[] mTmpTransformLocation = new float[2];
16966
16967        /**
16968         * The view tree observer used to dispatch global events like
16969         * layout, pre-draw, touch mode change, etc.
16970         */
16971        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
16972
16973        /**
16974         * A Canvas used by the view hierarchy to perform bitmap caching.
16975         */
16976        Canvas mCanvas;
16977
16978        /**
16979         * The view root impl.
16980         */
16981        final ViewRootImpl mViewRootImpl;
16982
16983        /**
16984         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
16985         * handler can be used to pump events in the UI events queue.
16986         */
16987        final Handler mHandler;
16988
16989        /**
16990         * Temporary for use in computing invalidate rectangles while
16991         * calling up the hierarchy.
16992         */
16993        final Rect mTmpInvalRect = new Rect();
16994
16995        /**
16996         * Temporary for use in computing hit areas with transformed views
16997         */
16998        final RectF mTmpTransformRect = new RectF();
16999
17000        /**
17001         * Temporary list for use in collecting focusable descendents of a view.
17002         */
17003        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17004
17005        /**
17006         * The id of the window for accessibility purposes.
17007         */
17008        int mAccessibilityWindowId = View.NO_ID;
17009
17010        /**
17011         * Whether to ingore not exposed for accessibility Views when
17012         * reporting the view tree to accessibility services.
17013         */
17014        boolean mIncludeNotImportantViews;
17015
17016        /**
17017         * The drawable for highlighting accessibility focus.
17018         */
17019        Drawable mAccessibilityFocusDrawable;
17020
17021        /**
17022         * Show where the margins, bounds and layout bounds are for each view.
17023         */
17024        final boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17025
17026        /**
17027         * Point used to compute visible regions.
17028         */
17029        final Point mPoint = new Point();
17030
17031        /**
17032         * Creates a new set of attachment information with the specified
17033         * events handler and thread.
17034         *
17035         * @param handler the events handler the view must use
17036         */
17037        AttachInfo(IWindowSession session, IWindow window,
17038                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17039            mSession = session;
17040            mWindow = window;
17041            mWindowToken = window.asBinder();
17042            mViewRootImpl = viewRootImpl;
17043            mHandler = handler;
17044            mRootCallbacks = effectPlayer;
17045        }
17046    }
17047
17048    /**
17049     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17050     * is supported. This avoids keeping too many unused fields in most
17051     * instances of View.</p>
17052     */
17053    private static class ScrollabilityCache implements Runnable {
17054
17055        /**
17056         * Scrollbars are not visible
17057         */
17058        public static final int OFF = 0;
17059
17060        /**
17061         * Scrollbars are visible
17062         */
17063        public static final int ON = 1;
17064
17065        /**
17066         * Scrollbars are fading away
17067         */
17068        public static final int FADING = 2;
17069
17070        public boolean fadeScrollBars;
17071
17072        public int fadingEdgeLength;
17073        public int scrollBarDefaultDelayBeforeFade;
17074        public int scrollBarFadeDuration;
17075
17076        public int scrollBarSize;
17077        public ScrollBarDrawable scrollBar;
17078        public float[] interpolatorValues;
17079        public View host;
17080
17081        public final Paint paint;
17082        public final Matrix matrix;
17083        public Shader shader;
17084
17085        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17086
17087        private static final float[] OPAQUE = { 255 };
17088        private static final float[] TRANSPARENT = { 0.0f };
17089
17090        /**
17091         * When fading should start. This time moves into the future every time
17092         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17093         */
17094        public long fadeStartTime;
17095
17096
17097        /**
17098         * The current state of the scrollbars: ON, OFF, or FADING
17099         */
17100        public int state = OFF;
17101
17102        private int mLastColor;
17103
17104        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17105            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17106            scrollBarSize = configuration.getScaledScrollBarSize();
17107            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17108            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17109
17110            paint = new Paint();
17111            matrix = new Matrix();
17112            // use use a height of 1, and then wack the matrix each time we
17113            // actually use it.
17114            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17115
17116            paint.setShader(shader);
17117            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17118            this.host = host;
17119        }
17120
17121        public void setFadeColor(int color) {
17122            if (color != 0 && color != mLastColor) {
17123                mLastColor = color;
17124                color |= 0xFF000000;
17125
17126                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17127                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17128
17129                paint.setShader(shader);
17130                // Restore the default transfer mode (src_over)
17131                paint.setXfermode(null);
17132            }
17133        }
17134
17135        public void run() {
17136            long now = AnimationUtils.currentAnimationTimeMillis();
17137            if (now >= fadeStartTime) {
17138
17139                // the animation fades the scrollbars out by changing
17140                // the opacity (alpha) from fully opaque to fully
17141                // transparent
17142                int nextFrame = (int) now;
17143                int framesCount = 0;
17144
17145                Interpolator interpolator = scrollBarInterpolator;
17146
17147                // Start opaque
17148                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17149
17150                // End transparent
17151                nextFrame += scrollBarFadeDuration;
17152                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17153
17154                state = FADING;
17155
17156                // Kick off the fade animation
17157                host.invalidate(true);
17158            }
17159        }
17160    }
17161
17162    /**
17163     * Resuable callback for sending
17164     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17165     */
17166    private class SendViewScrolledAccessibilityEvent implements Runnable {
17167        public volatile boolean mIsPending;
17168
17169        public void run() {
17170            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17171            mIsPending = false;
17172        }
17173    }
17174
17175    /**
17176     * <p>
17177     * This class represents a delegate that can be registered in a {@link View}
17178     * to enhance accessibility support via composition rather via inheritance.
17179     * It is specifically targeted to widget developers that extend basic View
17180     * classes i.e. classes in package android.view, that would like their
17181     * applications to be backwards compatible.
17182     * </p>
17183     * <div class="special reference">
17184     * <h3>Developer Guides</h3>
17185     * <p>For more information about making applications accessible, read the
17186     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17187     * developer guide.</p>
17188     * </div>
17189     * <p>
17190     * A scenario in which a developer would like to use an accessibility delegate
17191     * is overriding a method introduced in a later API version then the minimal API
17192     * version supported by the application. For example, the method
17193     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17194     * in API version 4 when the accessibility APIs were first introduced. If a
17195     * developer would like his application to run on API version 4 devices (assuming
17196     * all other APIs used by the application are version 4 or lower) and take advantage
17197     * of this method, instead of overriding the method which would break the application's
17198     * backwards compatibility, he can override the corresponding method in this
17199     * delegate and register the delegate in the target View if the API version of
17200     * the system is high enough i.e. the API version is same or higher to the API
17201     * version that introduced
17202     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17203     * </p>
17204     * <p>
17205     * Here is an example implementation:
17206     * </p>
17207     * <code><pre><p>
17208     * if (Build.VERSION.SDK_INT >= 14) {
17209     *     // If the API version is equal of higher than the version in
17210     *     // which onInitializeAccessibilityNodeInfo was introduced we
17211     *     // register a delegate with a customized implementation.
17212     *     View view = findViewById(R.id.view_id);
17213     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17214     *         public void onInitializeAccessibilityNodeInfo(View host,
17215     *                 AccessibilityNodeInfo info) {
17216     *             // Let the default implementation populate the info.
17217     *             super.onInitializeAccessibilityNodeInfo(host, info);
17218     *             // Set some other information.
17219     *             info.setEnabled(host.isEnabled());
17220     *         }
17221     *     });
17222     * }
17223     * </code></pre></p>
17224     * <p>
17225     * This delegate contains methods that correspond to the accessibility methods
17226     * in View. If a delegate has been specified the implementation in View hands
17227     * off handling to the corresponding method in this delegate. The default
17228     * implementation the delegate methods behaves exactly as the corresponding
17229     * method in View for the case of no accessibility delegate been set. Hence,
17230     * to customize the behavior of a View method, clients can override only the
17231     * corresponding delegate method without altering the behavior of the rest
17232     * accessibility related methods of the host view.
17233     * </p>
17234     */
17235    public static class AccessibilityDelegate {
17236
17237        /**
17238         * Sends an accessibility event of the given type. If accessibility is not
17239         * enabled this method has no effect.
17240         * <p>
17241         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17242         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17243         * been set.
17244         * </p>
17245         *
17246         * @param host The View hosting the delegate.
17247         * @param eventType The type of the event to send.
17248         *
17249         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17250         */
17251        public void sendAccessibilityEvent(View host, int eventType) {
17252            host.sendAccessibilityEventInternal(eventType);
17253        }
17254
17255        /**
17256         * Sends an accessibility event. This method behaves exactly as
17257         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17258         * empty {@link AccessibilityEvent} and does not perform a check whether
17259         * accessibility is enabled.
17260         * <p>
17261         * The default implementation behaves as
17262         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17263         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17264         * the case of no accessibility delegate been set.
17265         * </p>
17266         *
17267         * @param host The View hosting the delegate.
17268         * @param event The event to send.
17269         *
17270         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17271         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17272         */
17273        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17274            host.sendAccessibilityEventUncheckedInternal(event);
17275        }
17276
17277        /**
17278         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17279         * to its children for adding their text content to the event.
17280         * <p>
17281         * The default implementation behaves as
17282         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17283         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17284         * the case of no accessibility delegate been set.
17285         * </p>
17286         *
17287         * @param host The View hosting the delegate.
17288         * @param event The event.
17289         * @return True if the event population was completed.
17290         *
17291         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17292         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17293         */
17294        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17295            return host.dispatchPopulateAccessibilityEventInternal(event);
17296        }
17297
17298        /**
17299         * Gives a chance to the host View to populate the accessibility event with its
17300         * text content.
17301         * <p>
17302         * The default implementation behaves as
17303         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17304         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17305         * the case of no accessibility delegate been set.
17306         * </p>
17307         *
17308         * @param host The View hosting the delegate.
17309         * @param event The accessibility event which to populate.
17310         *
17311         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17312         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17313         */
17314        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17315            host.onPopulateAccessibilityEventInternal(event);
17316        }
17317
17318        /**
17319         * Initializes an {@link AccessibilityEvent} with information about the
17320         * the host View which is the event source.
17321         * <p>
17322         * The default implementation behaves as
17323         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17324         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17325         * the case of no accessibility delegate been set.
17326         * </p>
17327         *
17328         * @param host The View hosting the delegate.
17329         * @param event The event to initialize.
17330         *
17331         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17332         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17333         */
17334        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17335            host.onInitializeAccessibilityEventInternal(event);
17336        }
17337
17338        /**
17339         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17340         * <p>
17341         * The default implementation behaves as
17342         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17343         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17344         * the case of no accessibility delegate been set.
17345         * </p>
17346         *
17347         * @param host The View hosting the delegate.
17348         * @param info The instance to initialize.
17349         *
17350         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17351         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17352         */
17353        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17354            host.onInitializeAccessibilityNodeInfoInternal(info);
17355        }
17356
17357        /**
17358         * Called when a child of the host View has requested sending an
17359         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17360         * to augment the event.
17361         * <p>
17362         * The default implementation behaves as
17363         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17364         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17365         * the case of no accessibility delegate been set.
17366         * </p>
17367         *
17368         * @param host The View hosting the delegate.
17369         * @param child The child which requests sending the event.
17370         * @param event The event to be sent.
17371         * @return True if the event should be sent
17372         *
17373         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17374         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17375         */
17376        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17377                AccessibilityEvent event) {
17378            return host.onRequestSendAccessibilityEventInternal(child, event);
17379        }
17380
17381        /**
17382         * Gets the provider for managing a virtual view hierarchy rooted at this View
17383         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17384         * that explore the window content.
17385         * <p>
17386         * The default implementation behaves as
17387         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17388         * the case of no accessibility delegate been set.
17389         * </p>
17390         *
17391         * @return The provider.
17392         *
17393         * @see AccessibilityNodeProvider
17394         */
17395        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17396            return null;
17397        }
17398    }
17399}
17400