View.java revision aa6f3de253db6c0702de0cc40028750c1fcfb22c
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Interpolator;
28import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
32import android.graphics.Point;
33import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.Region;
38import android.graphics.Shader;
39import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Parcel;
44import android.os.Parcelable;
45import android.os.RemoteException;
46import android.os.SystemClock;
47import android.text.TextUtils;
48import android.util.AttributeSet;
49import android.util.FloatProperty;
50import android.util.LocaleUtil;
51import android.util.Log;
52import android.util.Pool;
53import android.util.Poolable;
54import android.util.PoolableManager;
55import android.util.Pools;
56import android.util.Property;
57import android.util.SparseArray;
58import android.util.TypedValue;
59import android.view.ContextMenu.ContextMenuInfo;
60import android.view.accessibility.AccessibilityEvent;
61import android.view.accessibility.AccessibilityEventSource;
62import android.view.accessibility.AccessibilityManager;
63import android.view.accessibility.AccessibilityNodeInfo;
64import android.view.accessibility.AccessibilityNodeProvider;
65import android.view.animation.Animation;
66import android.view.animation.AnimationUtils;
67import android.view.animation.Transformation;
68import android.view.inputmethod.EditorInfo;
69import android.view.inputmethod.InputConnection;
70import android.view.inputmethod.InputMethodManager;
71import android.widget.ScrollBarDrawable;
72
73import static android.os.Build.VERSION_CODES.*;
74import static java.lang.Math.max;
75
76import com.android.internal.R;
77import com.android.internal.util.Predicate;
78import com.android.internal.view.menu.MenuBuilder;
79
80import java.lang.ref.WeakReference;
81import java.lang.reflect.InvocationTargetException;
82import java.lang.reflect.Method;
83import java.util.ArrayList;
84import java.util.Arrays;
85import java.util.Locale;
86import java.util.concurrent.CopyOnWriteArrayList;
87
88/**
89 * <p>
90 * This class represents the basic building block for user interface components. A View
91 * occupies a rectangular area on the screen and is responsible for drawing and
92 * event handling. View is the base class for <em>widgets</em>, which are
93 * used to create interactive UI components (buttons, text fields, etc.). The
94 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
95 * are invisible containers that hold other Views (or other ViewGroups) and define
96 * their layout properties.
97 * </p>
98 *
99 * <div class="special reference">
100 * <h3>Developer Guides</h3>
101 * <p>For information about using this class to develop your application's user interface,
102 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
103 * </div>
104 *
105 * <a name="Using"></a>
106 * <h3>Using Views</h3>
107 * <p>
108 * All of the views in a window are arranged in a single tree. You can add views
109 * either from code or by specifying a tree of views in one or more XML layout
110 * files. There are many specialized subclasses of views that act as controls or
111 * are capable of displaying text, images, or other content.
112 * </p>
113 * <p>
114 * Once you have created a tree of views, there are typically a few types of
115 * common operations you may wish to perform:
116 * <ul>
117 * <li><strong>Set properties:</strong> for example setting the text of a
118 * {@link android.widget.TextView}. The available properties and the methods
119 * that set them will vary among the different subclasses of views. Note that
120 * properties that are known at build time can be set in the XML layout
121 * files.</li>
122 * <li><strong>Set focus:</strong> The framework will handled moving focus in
123 * response to user input. To force focus to a specific view, call
124 * {@link #requestFocus}.</li>
125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
126 * that will be notified when something interesting happens to the view. For
127 * example, all views will let you set a listener to be notified when the view
128 * gains or loses focus. You can register such a listener using
129 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
130 * Other view subclasses offer more specialized listeners. For example, a Button
131 * exposes a listener to notify clients when the button is clicked.</li>
132 * <li><strong>Set visibility:</strong> You can hide or show views using
133 * {@link #setVisibility(int)}.</li>
134 * </ul>
135 * </p>
136 * <p><em>
137 * Note: The Android framework is responsible for measuring, laying out and
138 * drawing views. You should not call methods that perform these actions on
139 * views yourself unless you are actually implementing a
140 * {@link android.view.ViewGroup}.
141 * </em></p>
142 *
143 * <a name="Lifecycle"></a>
144 * <h3>Implementing a Custom View</h3>
145 *
146 * <p>
147 * To implement a custom view, you will usually begin by providing overrides for
148 * some of the standard methods that the framework calls on all views. You do
149 * not need to override all of these methods. In fact, you can start by just
150 * overriding {@link #onDraw(android.graphics.Canvas)}.
151 * <table border="2" width="85%" align="center" cellpadding="5">
152 *     <thead>
153 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
154 *     </thead>
155 *
156 *     <tbody>
157 *     <tr>
158 *         <td rowspan="2">Creation</td>
159 *         <td>Constructors</td>
160 *         <td>There is a form of the constructor that are called when the view
161 *         is created from code and a form that is called when the view is
162 *         inflated from a layout file. The second form should parse and apply
163 *         any attributes defined in the layout file.
164 *         </td>
165 *     </tr>
166 *     <tr>
167 *         <td><code>{@link #onFinishInflate()}</code></td>
168 *         <td>Called after a view and all of its children has been inflated
169 *         from XML.</td>
170 *     </tr>
171 *
172 *     <tr>
173 *         <td rowspan="3">Layout</td>
174 *         <td><code>{@link #onMeasure(int, int)}</code></td>
175 *         <td>Called to determine the size requirements for this view and all
176 *         of its children.
177 *         </td>
178 *     </tr>
179 *     <tr>
180 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
181 *         <td>Called when this view should assign a size and position to all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
187 *         <td>Called when the size of this view has changed.
188 *         </td>
189 *     </tr>
190 *
191 *     <tr>
192 *         <td>Drawing</td>
193 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
194 *         <td>Called when the view should render its content.
195 *         </td>
196 *     </tr>
197 *
198 *     <tr>
199 *         <td rowspan="4">Event processing</td>
200 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
201 *         <td>Called when a new key event occurs.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
206 *         <td>Called when a key up event occurs.
207 *         </td>
208 *     </tr>
209 *     <tr>
210 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
211 *         <td>Called when a trackball motion event occurs.
212 *         </td>
213 *     </tr>
214 *     <tr>
215 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
216 *         <td>Called when a touch screen motion event occurs.
217 *         </td>
218 *     </tr>
219 *
220 *     <tr>
221 *         <td rowspan="2">Focus</td>
222 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
223 *         <td>Called when the view gains or loses focus.
224 *         </td>
225 *     </tr>
226 *
227 *     <tr>
228 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
229 *         <td>Called when the window containing the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td rowspan="3">Attaching</td>
235 *         <td><code>{@link #onAttachedToWindow()}</code></td>
236 *         <td>Called when the view is attached to a window.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td><code>{@link #onDetachedFromWindow}</code></td>
242 *         <td>Called when the view is detached from its window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
248 *         <td>Called when the visibility of the window containing the view
249 *         has changed.
250 *         </td>
251 *     </tr>
252 *     </tbody>
253 *
254 * </table>
255 * </p>
256 *
257 * <a name="IDs"></a>
258 * <h3>IDs</h3>
259 * Views may have an integer id associated with them. These ids are typically
260 * assigned in the layout XML files, and are used to find specific views within
261 * the view tree. A common pattern is to:
262 * <ul>
263 * <li>Define a Button in the layout file and assign it a unique ID.
264 * <pre>
265 * &lt;Button
266 *     android:id="@+id/my_button"
267 *     android:layout_width="wrap_content"
268 *     android:layout_height="wrap_content"
269 *     android:text="@string/my_button_text"/&gt;
270 * </pre></li>
271 * <li>From the onCreate method of an Activity, find the Button
272 * <pre class="prettyprint">
273 *      Button myButton = (Button) findViewById(R.id.my_button);
274 * </pre></li>
275 * </ul>
276 * <p>
277 * View IDs need not be unique throughout the tree, but it is good practice to
278 * ensure that they are at least unique within the part of the tree you are
279 * searching.
280 * </p>
281 *
282 * <a name="Position"></a>
283 * <h3>Position</h3>
284 * <p>
285 * The geometry of a view is that of a rectangle. A view has a location,
286 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
287 * two dimensions, expressed as a width and a height. The unit for location
288 * and dimensions is the pixel.
289 * </p>
290 *
291 * <p>
292 * It is possible to retrieve the location of a view by invoking the methods
293 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
294 * coordinate of the rectangle representing the view. The latter returns the
295 * top, or Y, coordinate of the rectangle representing the view. These methods
296 * both return the location of the view relative to its parent. For instance,
297 * when getLeft() returns 20, that means the view is located 20 pixels to the
298 * right of the left edge of its direct parent.
299 * </p>
300 *
301 * <p>
302 * In addition, several convenience methods are offered to avoid unnecessary
303 * computations, namely {@link #getRight()} and {@link #getBottom()}.
304 * These methods return the coordinates of the right and bottom edges of the
305 * rectangle representing the view. For instance, calling {@link #getRight()}
306 * is similar to the following computation: <code>getLeft() + getWidth()</code>
307 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
308 * </p>
309 *
310 * <a name="SizePaddingMargins"></a>
311 * <h3>Size, padding and margins</h3>
312 * <p>
313 * The size of a view is expressed with a width and a height. A view actually
314 * possess two pairs of width and height values.
315 * </p>
316 *
317 * <p>
318 * The first pair is known as <em>measured width</em> and
319 * <em>measured height</em>. These dimensions define how big a view wants to be
320 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
321 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
322 * and {@link #getMeasuredHeight()}.
323 * </p>
324 *
325 * <p>
326 * The second pair is simply known as <em>width</em> and <em>height</em>, or
327 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
328 * dimensions define the actual size of the view on screen, at drawing time and
329 * after layout. These values may, but do not have to, be different from the
330 * measured width and height. The width and height can be obtained by calling
331 * {@link #getWidth()} and {@link #getHeight()}.
332 * </p>
333 *
334 * <p>
335 * To measure its dimensions, a view takes into account its padding. The padding
336 * is expressed in pixels for the left, top, right and bottom parts of the view.
337 * Padding can be used to offset the content of the view by a specific amount of
338 * pixels. For instance, a left padding of 2 will push the view's content by
339 * 2 pixels to the right of the left edge. Padding can be set using the
340 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
341 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
342 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
343 * {@link #getPaddingEnd()}.
344 * </p>
345 *
346 * <p>
347 * Even though a view can define a padding, it does not provide any support for
348 * margins. However, view groups provide such a support. Refer to
349 * {@link android.view.ViewGroup} and
350 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
351 * </p>
352 *
353 * <a name="Layout"></a>
354 * <h3>Layout</h3>
355 * <p>
356 * Layout is a two pass process: a measure pass and a layout pass. The measuring
357 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
358 * of the view tree. Each view pushes dimension specifications down the tree
359 * during the recursion. At the end of the measure pass, every view has stored
360 * its measurements. The second pass happens in
361 * {@link #layout(int,int,int,int)} and is also top-down. During
362 * this pass each parent is responsible for positioning all of its children
363 * using the sizes computed in the measure pass.
364 * </p>
365 *
366 * <p>
367 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
368 * {@link #getMeasuredHeight()} values must be set, along with those for all of
369 * that view's descendants. A view's measured width and measured height values
370 * must respect the constraints imposed by the view's parents. This guarantees
371 * that at the end of the measure pass, all parents accept all of their
372 * children's measurements. A parent view may call measure() more than once on
373 * its children. For example, the parent may measure each child once with
374 * unspecified dimensions to find out how big they want to be, then call
375 * measure() on them again with actual numbers if the sum of all the children's
376 * unconstrained sizes is too big or too small.
377 * </p>
378 *
379 * <p>
380 * The measure pass uses two classes to communicate dimensions. The
381 * {@link MeasureSpec} class is used by views to tell their parents how they
382 * want to be measured and positioned. The base LayoutParams class just
383 * describes how big the view wants to be for both width and height. For each
384 * dimension, it can specify one of:
385 * <ul>
386 * <li> an exact number
387 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
388 * (minus padding)
389 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
390 * enclose its content (plus padding).
391 * </ul>
392 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
393 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
394 * an X and Y value.
395 * </p>
396 *
397 * <p>
398 * MeasureSpecs are used to push requirements down the tree from parent to
399 * child. A MeasureSpec can be in one of three modes:
400 * <ul>
401 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
402 * of a child view. For example, a LinearLayout may call measure() on its child
403 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
404 * tall the child view wants to be given a width of 240 pixels.
405 * <li>EXACTLY: This is used by the parent to impose an exact size on the
406 * child. The child must use this size, and guarantee that all of its
407 * descendants will fit within this size.
408 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
409 * child. The child must gurantee that it and all of its descendants will fit
410 * within this size.
411 * </ul>
412 * </p>
413 *
414 * <p>
415 * To intiate a layout, call {@link #requestLayout}. This method is typically
416 * called by a view on itself when it believes that is can no longer fit within
417 * its current bounds.
418 * </p>
419 *
420 * <a name="Drawing"></a>
421 * <h3>Drawing</h3>
422 * <p>
423 * Drawing is handled by walking the tree and rendering each view that
424 * intersects the invalid region. Because the tree is traversed in-order,
425 * this means that parents will draw before (i.e., behind) their children, with
426 * siblings drawn in the order they appear in the tree.
427 * If you set a background drawable for a View, then the View will draw it for you
428 * before calling back to its <code>onDraw()</code> method.
429 * </p>
430 *
431 * <p>
432 * Note that the framework will not draw views that are not in the invalid region.
433 * </p>
434 *
435 * <p>
436 * To force a view to draw, call {@link #invalidate()}.
437 * </p>
438 *
439 * <a name="EventHandlingThreading"></a>
440 * <h3>Event Handling and Threading</h3>
441 * <p>
442 * The basic cycle of a view is as follows:
443 * <ol>
444 * <li>An event comes in and is dispatched to the appropriate view. The view
445 * handles the event and notifies any listeners.</li>
446 * <li>If in the course of processing the event, the view's bounds may need
447 * to be changed, the view will call {@link #requestLayout()}.</li>
448 * <li>Similarly, if in the course of processing the event the view's appearance
449 * may need to be changed, the view will call {@link #invalidate()}.</li>
450 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
451 * the framework will take care of measuring, laying out, and drawing the tree
452 * as appropriate.</li>
453 * </ol>
454 * </p>
455 *
456 * <p><em>Note: The entire view tree is single threaded. You must always be on
457 * the UI thread when calling any method on any view.</em>
458 * If you are doing work on other threads and want to update the state of a view
459 * from that thread, you should use a {@link Handler}.
460 * </p>
461 *
462 * <a name="FocusHandling"></a>
463 * <h3>Focus Handling</h3>
464 * <p>
465 * The framework will handle routine focus movement in response to user input.
466 * This includes changing the focus as views are removed or hidden, or as new
467 * views become available. Views indicate their willingness to take focus
468 * through the {@link #isFocusable} method. To change whether a view can take
469 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
470 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
471 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
472 * </p>
473 * <p>
474 * Focus movement is based on an algorithm which finds the nearest neighbor in a
475 * given direction. In rare cases, the default algorithm may not match the
476 * intended behavior of the developer. In these situations, you can provide
477 * explicit overrides by using these XML attributes in the layout file:
478 * <pre>
479 * nextFocusDown
480 * nextFocusLeft
481 * nextFocusRight
482 * nextFocusUp
483 * </pre>
484 * </p>
485 *
486 *
487 * <p>
488 * To get a particular view to take focus, call {@link #requestFocus()}.
489 * </p>
490 *
491 * <a name="TouchMode"></a>
492 * <h3>Touch Mode</h3>
493 * <p>
494 * When a user is navigating a user interface via directional keys such as a D-pad, it is
495 * necessary to give focus to actionable items such as buttons so the user can see
496 * what will take input.  If the device has touch capabilities, however, and the user
497 * begins interacting with the interface by touching it, it is no longer necessary to
498 * always highlight, or give focus to, a particular view.  This motivates a mode
499 * for interaction named 'touch mode'.
500 * </p>
501 * <p>
502 * For a touch capable device, once the user touches the screen, the device
503 * will enter touch mode.  From this point onward, only views for which
504 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
505 * Other views that are touchable, like buttons, will not take focus when touched; they will
506 * only fire the on click listeners.
507 * </p>
508 * <p>
509 * Any time a user hits a directional key, such as a D-pad direction, the view device will
510 * exit touch mode, and find a view to take focus, so that the user may resume interacting
511 * with the user interface without touching the screen again.
512 * </p>
513 * <p>
514 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
515 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
516 * </p>
517 *
518 * <a name="Scrolling"></a>
519 * <h3>Scrolling</h3>
520 * <p>
521 * The framework provides basic support for views that wish to internally
522 * scroll their content. This includes keeping track of the X and Y scroll
523 * offset as well as mechanisms for drawing scrollbars. See
524 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
525 * {@link #awakenScrollBars()} for more details.
526 * </p>
527 *
528 * <a name="Tags"></a>
529 * <h3>Tags</h3>
530 * <p>
531 * Unlike IDs, tags are not used to identify views. Tags are essentially an
532 * extra piece of information that can be associated with a view. They are most
533 * often used as a convenience to store data related to views in the views
534 * themselves rather than by putting them in a separate structure.
535 * </p>
536 *
537 * <a name="Animation"></a>
538 * <h3>Animation</h3>
539 * <p>
540 * You can attach an {@link Animation} object to a view using
541 * {@link #setAnimation(Animation)} or
542 * {@link #startAnimation(Animation)}. The animation can alter the scale,
543 * rotation, translation and alpha of a view over time. If the animation is
544 * attached to a view that has children, the animation will affect the entire
545 * subtree rooted by that node. When an animation is started, the framework will
546 * take care of redrawing the appropriate views until the animation completes.
547 * </p>
548 * <p>
549 * Starting with Android 3.0, the preferred way of animating views is to use the
550 * {@link android.animation} package APIs.
551 * </p>
552 *
553 * <a name="Security"></a>
554 * <h3>Security</h3>
555 * <p>
556 * Sometimes it is essential that an application be able to verify that an action
557 * is being performed with the full knowledge and consent of the user, such as
558 * granting a permission request, making a purchase or clicking on an advertisement.
559 * Unfortunately, a malicious application could try to spoof the user into
560 * performing these actions, unaware, by concealing the intended purpose of the view.
561 * As a remedy, the framework offers a touch filtering mechanism that can be used to
562 * improve the security of views that provide access to sensitive functionality.
563 * </p><p>
564 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
565 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
566 * will discard touches that are received whenever the view's window is obscured by
567 * another visible window.  As a result, the view will not receive touches whenever a
568 * toast, dialog or other window appears above the view's window.
569 * </p><p>
570 * For more fine-grained control over security, consider overriding the
571 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
572 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
573 * </p>
574 *
575 * @attr ref android.R.styleable#View_alpha
576 * @attr ref android.R.styleable#View_background
577 * @attr ref android.R.styleable#View_clickable
578 * @attr ref android.R.styleable#View_contentDescription
579 * @attr ref android.R.styleable#View_drawingCacheQuality
580 * @attr ref android.R.styleable#View_duplicateParentState
581 * @attr ref android.R.styleable#View_id
582 * @attr ref android.R.styleable#View_requiresFadingEdge
583 * @attr ref android.R.styleable#View_fadeScrollbars
584 * @attr ref android.R.styleable#View_fadingEdgeLength
585 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
586 * @attr ref android.R.styleable#View_fitsSystemWindows
587 * @attr ref android.R.styleable#View_isScrollContainer
588 * @attr ref android.R.styleable#View_focusable
589 * @attr ref android.R.styleable#View_focusableInTouchMode
590 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
591 * @attr ref android.R.styleable#View_keepScreenOn
592 * @attr ref android.R.styleable#View_layerType
593 * @attr ref android.R.styleable#View_longClickable
594 * @attr ref android.R.styleable#View_minHeight
595 * @attr ref android.R.styleable#View_minWidth
596 * @attr ref android.R.styleable#View_nextFocusDown
597 * @attr ref android.R.styleable#View_nextFocusLeft
598 * @attr ref android.R.styleable#View_nextFocusRight
599 * @attr ref android.R.styleable#View_nextFocusUp
600 * @attr ref android.R.styleable#View_onClick
601 * @attr ref android.R.styleable#View_padding
602 * @attr ref android.R.styleable#View_paddingBottom
603 * @attr ref android.R.styleable#View_paddingLeft
604 * @attr ref android.R.styleable#View_paddingRight
605 * @attr ref android.R.styleable#View_paddingTop
606 * @attr ref android.R.styleable#View_paddingStart
607 * @attr ref android.R.styleable#View_paddingEnd
608 * @attr ref android.R.styleable#View_saveEnabled
609 * @attr ref android.R.styleable#View_rotation
610 * @attr ref android.R.styleable#View_rotationX
611 * @attr ref android.R.styleable#View_rotationY
612 * @attr ref android.R.styleable#View_scaleX
613 * @attr ref android.R.styleable#View_scaleY
614 * @attr ref android.R.styleable#View_scrollX
615 * @attr ref android.R.styleable#View_scrollY
616 * @attr ref android.R.styleable#View_scrollbarSize
617 * @attr ref android.R.styleable#View_scrollbarStyle
618 * @attr ref android.R.styleable#View_scrollbars
619 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
620 * @attr ref android.R.styleable#View_scrollbarFadeDuration
621 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
622 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
623 * @attr ref android.R.styleable#View_scrollbarThumbVertical
624 * @attr ref android.R.styleable#View_scrollbarTrackVertical
625 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
626 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
627 * @attr ref android.R.styleable#View_soundEffectsEnabled
628 * @attr ref android.R.styleable#View_tag
629 * @attr ref android.R.styleable#View_textAlignment
630 * @attr ref android.R.styleable#View_transformPivotX
631 * @attr ref android.R.styleable#View_transformPivotY
632 * @attr ref android.R.styleable#View_translationX
633 * @attr ref android.R.styleable#View_translationY
634 * @attr ref android.R.styleable#View_visibility
635 *
636 * @see android.view.ViewGroup
637 */
638public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
639        AccessibilityEventSource {
640    private static final boolean DBG = false;
641
642    /**
643     * The logging tag used by this class with android.util.Log.
644     */
645    protected static final String VIEW_LOG_TAG = "View";
646
647    /**
648     * Used to mark a View that has no ID.
649     */
650    public static final int NO_ID = -1;
651
652    /**
653     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
654     * calling setFlags.
655     */
656    private static final int NOT_FOCUSABLE = 0x00000000;
657
658    /**
659     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
660     * setFlags.
661     */
662    private static final int FOCUSABLE = 0x00000001;
663
664    /**
665     * Mask for use with setFlags indicating bits used for focus.
666     */
667    private static final int FOCUSABLE_MASK = 0x00000001;
668
669    /**
670     * This view will adjust its padding to fit sytem windows (e.g. status bar)
671     */
672    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
673
674    /**
675     * This view is visible.
676     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
677     * android:visibility}.
678     */
679    public static final int VISIBLE = 0x00000000;
680
681    /**
682     * This view is invisible, but it still takes up space for layout purposes.
683     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
684     * android:visibility}.
685     */
686    public static final int INVISIBLE = 0x00000004;
687
688    /**
689     * This view is invisible, and it doesn't take any space for layout
690     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
691     * android:visibility}.
692     */
693    public static final int GONE = 0x00000008;
694
695    /**
696     * Mask for use with setFlags indicating bits used for visibility.
697     * {@hide}
698     */
699    static final int VISIBILITY_MASK = 0x0000000C;
700
701    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
702
703    /**
704     * This view is enabled. Interpretation varies by subclass.
705     * Use with ENABLED_MASK when calling setFlags.
706     * {@hide}
707     */
708    static final int ENABLED = 0x00000000;
709
710    /**
711     * This view is disabled. Interpretation varies by subclass.
712     * Use with ENABLED_MASK when calling setFlags.
713     * {@hide}
714     */
715    static final int DISABLED = 0x00000020;
716
717   /**
718    * Mask for use with setFlags indicating bits used for indicating whether
719    * this view is enabled
720    * {@hide}
721    */
722    static final int ENABLED_MASK = 0x00000020;
723
724    /**
725     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
726     * called and further optimizations will be performed. It is okay to have
727     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
728     * {@hide}
729     */
730    static final int WILL_NOT_DRAW = 0x00000080;
731
732    /**
733     * Mask for use with setFlags indicating bits used for indicating whether
734     * this view is will draw
735     * {@hide}
736     */
737    static final int DRAW_MASK = 0x00000080;
738
739    /**
740     * <p>This view doesn't show scrollbars.</p>
741     * {@hide}
742     */
743    static final int SCROLLBARS_NONE = 0x00000000;
744
745    /**
746     * <p>This view shows horizontal scrollbars.</p>
747     * {@hide}
748     */
749    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
750
751    /**
752     * <p>This view shows vertical scrollbars.</p>
753     * {@hide}
754     */
755    static final int SCROLLBARS_VERTICAL = 0x00000200;
756
757    /**
758     * <p>Mask for use with setFlags indicating bits used for indicating which
759     * scrollbars are enabled.</p>
760     * {@hide}
761     */
762    static final int SCROLLBARS_MASK = 0x00000300;
763
764    /**
765     * Indicates that the view should filter touches when its window is obscured.
766     * Refer to the class comments for more information about this security feature.
767     * {@hide}
768     */
769    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
770
771    /**
772     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
773     * that they are optional and should be skipped if the window has
774     * requested system UI flags that ignore those insets for layout.
775     */
776    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
777
778    /**
779     * <p>This view doesn't show fading edges.</p>
780     * {@hide}
781     */
782    static final int FADING_EDGE_NONE = 0x00000000;
783
784    /**
785     * <p>This view shows horizontal fading edges.</p>
786     * {@hide}
787     */
788    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
789
790    /**
791     * <p>This view shows vertical fading edges.</p>
792     * {@hide}
793     */
794    static final int FADING_EDGE_VERTICAL = 0x00002000;
795
796    /**
797     * <p>Mask for use with setFlags indicating bits used for indicating which
798     * fading edges are enabled.</p>
799     * {@hide}
800     */
801    static final int FADING_EDGE_MASK = 0x00003000;
802
803    /**
804     * <p>Indicates this view can be clicked. When clickable, a View reacts
805     * to clicks by notifying the OnClickListener.<p>
806     * {@hide}
807     */
808    static final int CLICKABLE = 0x00004000;
809
810    /**
811     * <p>Indicates this view is caching its drawing into a bitmap.</p>
812     * {@hide}
813     */
814    static final int DRAWING_CACHE_ENABLED = 0x00008000;
815
816    /**
817     * <p>Indicates that no icicle should be saved for this view.<p>
818     * {@hide}
819     */
820    static final int SAVE_DISABLED = 0x000010000;
821
822    /**
823     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
824     * property.</p>
825     * {@hide}
826     */
827    static final int SAVE_DISABLED_MASK = 0x000010000;
828
829    /**
830     * <p>Indicates that no drawing cache should ever be created for this view.<p>
831     * {@hide}
832     */
833    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
834
835    /**
836     * <p>Indicates this view can take / keep focus when int touch mode.</p>
837     * {@hide}
838     */
839    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
840
841    /**
842     * <p>Enables low quality mode for the drawing cache.</p>
843     */
844    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
845
846    /**
847     * <p>Enables high quality mode for the drawing cache.</p>
848     */
849    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
850
851    /**
852     * <p>Enables automatic quality mode for the drawing cache.</p>
853     */
854    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
855
856    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
857            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
858    };
859
860    /**
861     * <p>Mask for use with setFlags indicating bits used for the cache
862     * quality property.</p>
863     * {@hide}
864     */
865    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
866
867    /**
868     * <p>
869     * Indicates this view can be long clicked. When long clickable, a View
870     * reacts to long clicks by notifying the OnLongClickListener or showing a
871     * context menu.
872     * </p>
873     * {@hide}
874     */
875    static final int LONG_CLICKABLE = 0x00200000;
876
877    /**
878     * <p>Indicates that this view gets its drawable states from its direct parent
879     * and ignores its original internal states.</p>
880     *
881     * @hide
882     */
883    static final int DUPLICATE_PARENT_STATE = 0x00400000;
884
885    /**
886     * The scrollbar style to display the scrollbars inside the content area,
887     * without increasing the padding. The scrollbars will be overlaid with
888     * translucency on the view's content.
889     */
890    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
891
892    /**
893     * The scrollbar style to display the scrollbars inside the padded area,
894     * increasing the padding of the view. The scrollbars will not overlap the
895     * content area of the view.
896     */
897    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
898
899    /**
900     * The scrollbar style to display the scrollbars at the edge of the view,
901     * without increasing the padding. The scrollbars will be overlaid with
902     * translucency.
903     */
904    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
905
906    /**
907     * The scrollbar style to display the scrollbars at the edge of the view,
908     * increasing the padding of the view. The scrollbars will only overlap the
909     * background, if any.
910     */
911    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
912
913    /**
914     * Mask to check if the scrollbar style is overlay or inset.
915     * {@hide}
916     */
917    static final int SCROLLBARS_INSET_MASK = 0x01000000;
918
919    /**
920     * Mask to check if the scrollbar style is inside or outside.
921     * {@hide}
922     */
923    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
924
925    /**
926     * Mask for scrollbar style.
927     * {@hide}
928     */
929    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
930
931    /**
932     * View flag indicating that the screen should remain on while the
933     * window containing this view is visible to the user.  This effectively
934     * takes care of automatically setting the WindowManager's
935     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
936     */
937    public static final int KEEP_SCREEN_ON = 0x04000000;
938
939    /**
940     * View flag indicating whether this view should have sound effects enabled
941     * for events such as clicking and touching.
942     */
943    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
944
945    /**
946     * View flag indicating whether this view should have haptic feedback
947     * enabled for events such as long presses.
948     */
949    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
950
951    /**
952     * <p>Indicates that the view hierarchy should stop saving state when
953     * it reaches this view.  If state saving is initiated immediately at
954     * the view, it will be allowed.
955     * {@hide}
956     */
957    static final int PARENT_SAVE_DISABLED = 0x20000000;
958
959    /**
960     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
961     * {@hide}
962     */
963    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
964
965    /**
966     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
967     * should add all focusable Views regardless if they are focusable in touch mode.
968     */
969    public static final int FOCUSABLES_ALL = 0x00000000;
970
971    /**
972     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
973     * should add only Views focusable in touch mode.
974     */
975    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
976
977    /**
978     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
979     * item.
980     */
981    public static final int FOCUS_BACKWARD = 0x00000001;
982
983    /**
984     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
985     * item.
986     */
987    public static final int FOCUS_FORWARD = 0x00000002;
988
989    /**
990     * Use with {@link #focusSearch(int)}. Move focus to the left.
991     */
992    public static final int FOCUS_LEFT = 0x00000011;
993
994    /**
995     * Use with {@link #focusSearch(int)}. Move focus up.
996     */
997    public static final int FOCUS_UP = 0x00000021;
998
999    /**
1000     * Use with {@link #focusSearch(int)}. Move focus to the right.
1001     */
1002    public static final int FOCUS_RIGHT = 0x00000042;
1003
1004    /**
1005     * Use with {@link #focusSearch(int)}. Move focus down.
1006     */
1007    public static final int FOCUS_DOWN = 0x00000082;
1008
1009    /**
1010     * Bits of {@link #getMeasuredWidthAndState()} and
1011     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1012     */
1013    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1014
1015    /**
1016     * Bits of {@link #getMeasuredWidthAndState()} and
1017     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1018     */
1019    public static final int MEASURED_STATE_MASK = 0xff000000;
1020
1021    /**
1022     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1023     * for functions that combine both width and height into a single int,
1024     * such as {@link #getMeasuredState()} and the childState argument of
1025     * {@link #resolveSizeAndState(int, int, int)}.
1026     */
1027    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1028
1029    /**
1030     * Bit of {@link #getMeasuredWidthAndState()} and
1031     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1032     * is smaller that the space the view would like to have.
1033     */
1034    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1035
1036    /**
1037     * Base View state sets
1038     */
1039    // Singles
1040    /**
1041     * Indicates the view has no states set. States are used with
1042     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1043     * view depending on its state.
1044     *
1045     * @see android.graphics.drawable.Drawable
1046     * @see #getDrawableState()
1047     */
1048    protected static final int[] EMPTY_STATE_SET;
1049    /**
1050     * Indicates the view is enabled. States are used with
1051     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1052     * view depending on its state.
1053     *
1054     * @see android.graphics.drawable.Drawable
1055     * @see #getDrawableState()
1056     */
1057    protected static final int[] ENABLED_STATE_SET;
1058    /**
1059     * Indicates the view is focused. States are used with
1060     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1061     * view depending on its state.
1062     *
1063     * @see android.graphics.drawable.Drawable
1064     * @see #getDrawableState()
1065     */
1066    protected static final int[] FOCUSED_STATE_SET;
1067    /**
1068     * Indicates the view is selected. States are used with
1069     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1070     * view depending on its state.
1071     *
1072     * @see android.graphics.drawable.Drawable
1073     * @see #getDrawableState()
1074     */
1075    protected static final int[] SELECTED_STATE_SET;
1076    /**
1077     * Indicates the view is pressed. States are used with
1078     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1079     * view depending on its state.
1080     *
1081     * @see android.graphics.drawable.Drawable
1082     * @see #getDrawableState()
1083     * @hide
1084     */
1085    protected static final int[] PRESSED_STATE_SET;
1086    /**
1087     * Indicates the view's window has focus. States are used with
1088     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1089     * view depending on its state.
1090     *
1091     * @see android.graphics.drawable.Drawable
1092     * @see #getDrawableState()
1093     */
1094    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1095    // Doubles
1096    /**
1097     * Indicates the view is enabled and has the focus.
1098     *
1099     * @see #ENABLED_STATE_SET
1100     * @see #FOCUSED_STATE_SET
1101     */
1102    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1103    /**
1104     * Indicates the view is enabled and selected.
1105     *
1106     * @see #ENABLED_STATE_SET
1107     * @see #SELECTED_STATE_SET
1108     */
1109    protected static final int[] ENABLED_SELECTED_STATE_SET;
1110    /**
1111     * Indicates the view is enabled and that its window has focus.
1112     *
1113     * @see #ENABLED_STATE_SET
1114     * @see #WINDOW_FOCUSED_STATE_SET
1115     */
1116    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1117    /**
1118     * Indicates the view is focused and selected.
1119     *
1120     * @see #FOCUSED_STATE_SET
1121     * @see #SELECTED_STATE_SET
1122     */
1123    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1124    /**
1125     * Indicates the view has the focus and that its window has the focus.
1126     *
1127     * @see #FOCUSED_STATE_SET
1128     * @see #WINDOW_FOCUSED_STATE_SET
1129     */
1130    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1131    /**
1132     * Indicates the view is selected and that its window has the focus.
1133     *
1134     * @see #SELECTED_STATE_SET
1135     * @see #WINDOW_FOCUSED_STATE_SET
1136     */
1137    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1138    // Triples
1139    /**
1140     * Indicates the view is enabled, focused and selected.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #FOCUSED_STATE_SET
1144     * @see #SELECTED_STATE_SET
1145     */
1146    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1147    /**
1148     * Indicates the view is enabled, focused and its window has the focus.
1149     *
1150     * @see #ENABLED_STATE_SET
1151     * @see #FOCUSED_STATE_SET
1152     * @see #WINDOW_FOCUSED_STATE_SET
1153     */
1154    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1155    /**
1156     * Indicates the view is enabled, selected and its window has the focus.
1157     *
1158     * @see #ENABLED_STATE_SET
1159     * @see #SELECTED_STATE_SET
1160     * @see #WINDOW_FOCUSED_STATE_SET
1161     */
1162    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1163    /**
1164     * Indicates the view is focused, selected and its window has the focus.
1165     *
1166     * @see #FOCUSED_STATE_SET
1167     * @see #SELECTED_STATE_SET
1168     * @see #WINDOW_FOCUSED_STATE_SET
1169     */
1170    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1171    /**
1172     * Indicates the view is enabled, focused, selected and its window
1173     * has the focus.
1174     *
1175     * @see #ENABLED_STATE_SET
1176     * @see #FOCUSED_STATE_SET
1177     * @see #SELECTED_STATE_SET
1178     * @see #WINDOW_FOCUSED_STATE_SET
1179     */
1180    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1181    /**
1182     * Indicates the view is pressed and its window has the focus.
1183     *
1184     * @see #PRESSED_STATE_SET
1185     * @see #WINDOW_FOCUSED_STATE_SET
1186     */
1187    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1188    /**
1189     * Indicates the view is pressed and selected.
1190     *
1191     * @see #PRESSED_STATE_SET
1192     * @see #SELECTED_STATE_SET
1193     */
1194    protected static final int[] PRESSED_SELECTED_STATE_SET;
1195    /**
1196     * Indicates the view is pressed, selected and its window has the focus.
1197     *
1198     * @see #PRESSED_STATE_SET
1199     * @see #SELECTED_STATE_SET
1200     * @see #WINDOW_FOCUSED_STATE_SET
1201     */
1202    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1203    /**
1204     * Indicates the view is pressed and focused.
1205     *
1206     * @see #PRESSED_STATE_SET
1207     * @see #FOCUSED_STATE_SET
1208     */
1209    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1210    /**
1211     * Indicates the view is pressed, focused and its window has the focus.
1212     *
1213     * @see #PRESSED_STATE_SET
1214     * @see #FOCUSED_STATE_SET
1215     * @see #WINDOW_FOCUSED_STATE_SET
1216     */
1217    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1218    /**
1219     * Indicates the view is pressed, focused and selected.
1220     *
1221     * @see #PRESSED_STATE_SET
1222     * @see #SELECTED_STATE_SET
1223     * @see #FOCUSED_STATE_SET
1224     */
1225    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1226    /**
1227     * Indicates the view is pressed, focused, selected and its window has the focus.
1228     *
1229     * @see #PRESSED_STATE_SET
1230     * @see #FOCUSED_STATE_SET
1231     * @see #SELECTED_STATE_SET
1232     * @see #WINDOW_FOCUSED_STATE_SET
1233     */
1234    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1235    /**
1236     * Indicates the view is pressed and enabled.
1237     *
1238     * @see #PRESSED_STATE_SET
1239     * @see #ENABLED_STATE_SET
1240     */
1241    protected static final int[] PRESSED_ENABLED_STATE_SET;
1242    /**
1243     * Indicates the view is pressed, enabled and its window has the focus.
1244     *
1245     * @see #PRESSED_STATE_SET
1246     * @see #ENABLED_STATE_SET
1247     * @see #WINDOW_FOCUSED_STATE_SET
1248     */
1249    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1250    /**
1251     * Indicates the view is pressed, enabled and selected.
1252     *
1253     * @see #PRESSED_STATE_SET
1254     * @see #ENABLED_STATE_SET
1255     * @see #SELECTED_STATE_SET
1256     */
1257    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1258    /**
1259     * Indicates the view is pressed, enabled, selected and its window has the
1260     * focus.
1261     *
1262     * @see #PRESSED_STATE_SET
1263     * @see #ENABLED_STATE_SET
1264     * @see #SELECTED_STATE_SET
1265     * @see #WINDOW_FOCUSED_STATE_SET
1266     */
1267    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1268    /**
1269     * Indicates the view is pressed, enabled and focused.
1270     *
1271     * @see #PRESSED_STATE_SET
1272     * @see #ENABLED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     */
1275    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1276    /**
1277     * Indicates the view is pressed, enabled, focused and its window has the
1278     * focus.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #ENABLED_STATE_SET
1282     * @see #FOCUSED_STATE_SET
1283     * @see #WINDOW_FOCUSED_STATE_SET
1284     */
1285    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1286    /**
1287     * Indicates the view is pressed, enabled, focused and selected.
1288     *
1289     * @see #PRESSED_STATE_SET
1290     * @see #ENABLED_STATE_SET
1291     * @see #SELECTED_STATE_SET
1292     * @see #FOCUSED_STATE_SET
1293     */
1294    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1295    /**
1296     * Indicates the view is pressed, enabled, focused, selected and its window
1297     * has the focus.
1298     *
1299     * @see #PRESSED_STATE_SET
1300     * @see #ENABLED_STATE_SET
1301     * @see #SELECTED_STATE_SET
1302     * @see #FOCUSED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1306
1307    /**
1308     * The order here is very important to {@link #getDrawableState()}
1309     */
1310    private static final int[][] VIEW_STATE_SETS;
1311
1312    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1313    static final int VIEW_STATE_SELECTED = 1 << 1;
1314    static final int VIEW_STATE_FOCUSED = 1 << 2;
1315    static final int VIEW_STATE_ENABLED = 1 << 3;
1316    static final int VIEW_STATE_PRESSED = 1 << 4;
1317    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1318    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1319    static final int VIEW_STATE_HOVERED = 1 << 7;
1320    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1321    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1322
1323    static final int[] VIEW_STATE_IDS = new int[] {
1324        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1325        R.attr.state_selected,          VIEW_STATE_SELECTED,
1326        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1327        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1328        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1329        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1330        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1331        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1332        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1333        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1334    };
1335
1336    static {
1337        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1338            throw new IllegalStateException(
1339                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1340        }
1341        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1342        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1343            int viewState = R.styleable.ViewDrawableStates[i];
1344            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1345                if (VIEW_STATE_IDS[j] == viewState) {
1346                    orderedIds[i * 2] = viewState;
1347                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1348                }
1349            }
1350        }
1351        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1352        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1353        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1354            int numBits = Integer.bitCount(i);
1355            int[] set = new int[numBits];
1356            int pos = 0;
1357            for (int j = 0; j < orderedIds.length; j += 2) {
1358                if ((i & orderedIds[j+1]) != 0) {
1359                    set[pos++] = orderedIds[j];
1360                }
1361            }
1362            VIEW_STATE_SETS[i] = set;
1363        }
1364
1365        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1366        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1367        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1368        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1369                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1370        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1371        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1372                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1373        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1374                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1375        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1376                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1377                | VIEW_STATE_FOCUSED];
1378        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1379        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1380                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1381        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1382                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1383        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1384                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1385                | VIEW_STATE_ENABLED];
1386        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1387                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1388        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1389                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1390                | VIEW_STATE_ENABLED];
1391        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1392                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1393                | VIEW_STATE_ENABLED];
1394        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1395                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1396                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1397
1398        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1399        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1400                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1401        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1402                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1403        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1404                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1405                | VIEW_STATE_PRESSED];
1406        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1408        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1409                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1410                | VIEW_STATE_PRESSED];
1411        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1413                | VIEW_STATE_PRESSED];
1414        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1416                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1417        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1419        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1421                | VIEW_STATE_PRESSED];
1422        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1424                | VIEW_STATE_PRESSED];
1425        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1427                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1428        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1430                | VIEW_STATE_PRESSED];
1431        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1434        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1437        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1439                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1440                | VIEW_STATE_PRESSED];
1441    }
1442
1443    /**
1444     * Accessibility event types that are dispatched for text population.
1445     */
1446    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1447            AccessibilityEvent.TYPE_VIEW_CLICKED
1448            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1449            | AccessibilityEvent.TYPE_VIEW_SELECTED
1450            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1451            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1452            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1453            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1454            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1455            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
1456
1457    /**
1458     * Temporary Rect currently for use in setBackground().  This will probably
1459     * be extended in the future to hold our own class with more than just
1460     * a Rect. :)
1461     */
1462    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1463
1464    /**
1465     * Temporary flag, used to enable processing of View properties in the native DisplayList
1466     * object instead of during draw(). Soon to be enabled by default for hardware-accelerated
1467     * apps.
1468     * @hide
1469     */
1470    public static final boolean USE_DISPLAY_LIST_PROPERTIES = true;
1471
1472    /**
1473     * Map used to store views' tags.
1474     */
1475    private SparseArray<Object> mKeyedTags;
1476
1477    /**
1478     * The next available accessiiblity id.
1479     */
1480    private static int sNextAccessibilityViewId;
1481
1482    /**
1483     * The animation currently associated with this view.
1484     * @hide
1485     */
1486    protected Animation mCurrentAnimation = null;
1487
1488    /**
1489     * Width as measured during measure pass.
1490     * {@hide}
1491     */
1492    @ViewDebug.ExportedProperty(category = "measurement")
1493    int mMeasuredWidth;
1494
1495    /**
1496     * Height as measured during measure pass.
1497     * {@hide}
1498     */
1499    @ViewDebug.ExportedProperty(category = "measurement")
1500    int mMeasuredHeight;
1501
1502    /**
1503     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1504     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1505     * its display list. This flag, used only when hw accelerated, allows us to clear the
1506     * flag while retaining this information until it's needed (at getDisplayList() time and
1507     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1508     *
1509     * {@hide}
1510     */
1511    boolean mRecreateDisplayList = false;
1512
1513    /**
1514     * The view's identifier.
1515     * {@hide}
1516     *
1517     * @see #setId(int)
1518     * @see #getId()
1519     */
1520    @ViewDebug.ExportedProperty(resolveId = true)
1521    int mID = NO_ID;
1522
1523    /**
1524     * The stable ID of this view for accessibility purposes.
1525     */
1526    int mAccessibilityViewId = NO_ID;
1527
1528    /**
1529     * The view's tag.
1530     * {@hide}
1531     *
1532     * @see #setTag(Object)
1533     * @see #getTag()
1534     */
1535    protected Object mTag;
1536
1537    // for mPrivateFlags:
1538    /** {@hide} */
1539    static final int WANTS_FOCUS                    = 0x00000001;
1540    /** {@hide} */
1541    static final int FOCUSED                        = 0x00000002;
1542    /** {@hide} */
1543    static final int SELECTED                       = 0x00000004;
1544    /** {@hide} */
1545    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1546    /** {@hide} */
1547    static final int HAS_BOUNDS                     = 0x00000010;
1548    /** {@hide} */
1549    static final int DRAWN                          = 0x00000020;
1550    /**
1551     * When this flag is set, this view is running an animation on behalf of its
1552     * children and should therefore not cancel invalidate requests, even if they
1553     * lie outside of this view's bounds.
1554     *
1555     * {@hide}
1556     */
1557    static final int DRAW_ANIMATION                 = 0x00000040;
1558    /** {@hide} */
1559    static final int SKIP_DRAW                      = 0x00000080;
1560    /** {@hide} */
1561    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1562    /** {@hide} */
1563    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1564    /** {@hide} */
1565    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1566    /** {@hide} */
1567    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1568    /** {@hide} */
1569    static final int FORCE_LAYOUT                   = 0x00001000;
1570    /** {@hide} */
1571    static final int LAYOUT_REQUIRED                = 0x00002000;
1572
1573    private static final int PRESSED                = 0x00004000;
1574
1575    /** {@hide} */
1576    static final int DRAWING_CACHE_VALID            = 0x00008000;
1577    /**
1578     * Flag used to indicate that this view should be drawn once more (and only once
1579     * more) after its animation has completed.
1580     * {@hide}
1581     */
1582    static final int ANIMATION_STARTED              = 0x00010000;
1583
1584    private static final int SAVE_STATE_CALLED      = 0x00020000;
1585
1586    /**
1587     * Indicates that the View returned true when onSetAlpha() was called and that
1588     * the alpha must be restored.
1589     * {@hide}
1590     */
1591    static final int ALPHA_SET                      = 0x00040000;
1592
1593    /**
1594     * Set by {@link #setScrollContainer(boolean)}.
1595     */
1596    static final int SCROLL_CONTAINER               = 0x00080000;
1597
1598    /**
1599     * Set by {@link #setScrollContainer(boolean)}.
1600     */
1601    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1602
1603    /**
1604     * View flag indicating whether this view was invalidated (fully or partially.)
1605     *
1606     * @hide
1607     */
1608    static final int DIRTY                          = 0x00200000;
1609
1610    /**
1611     * View flag indicating whether this view was invalidated by an opaque
1612     * invalidate request.
1613     *
1614     * @hide
1615     */
1616    static final int DIRTY_OPAQUE                   = 0x00400000;
1617
1618    /**
1619     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1620     *
1621     * @hide
1622     */
1623    static final int DIRTY_MASK                     = 0x00600000;
1624
1625    /**
1626     * Indicates whether the background is opaque.
1627     *
1628     * @hide
1629     */
1630    static final int OPAQUE_BACKGROUND              = 0x00800000;
1631
1632    /**
1633     * Indicates whether the scrollbars are opaque.
1634     *
1635     * @hide
1636     */
1637    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1638
1639    /**
1640     * Indicates whether the view is opaque.
1641     *
1642     * @hide
1643     */
1644    static final int OPAQUE_MASK                    = 0x01800000;
1645
1646    /**
1647     * Indicates a prepressed state;
1648     * the short time between ACTION_DOWN and recognizing
1649     * a 'real' press. Prepressed is used to recognize quick taps
1650     * even when they are shorter than ViewConfiguration.getTapTimeout().
1651     *
1652     * @hide
1653     */
1654    private static final int PREPRESSED             = 0x02000000;
1655
1656    /**
1657     * Indicates whether the view is temporarily detached.
1658     *
1659     * @hide
1660     */
1661    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1662
1663    /**
1664     * Indicates that we should awaken scroll bars once attached
1665     *
1666     * @hide
1667     */
1668    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1669
1670    /**
1671     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1672     * @hide
1673     */
1674    private static final int HOVERED              = 0x10000000;
1675
1676    /**
1677     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1678     * for transform operations
1679     *
1680     * @hide
1681     */
1682    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1683
1684    /** {@hide} */
1685    static final int ACTIVATED                    = 0x40000000;
1686
1687    /**
1688     * Indicates that this view was specifically invalidated, not just dirtied because some
1689     * child view was invalidated. The flag is used to determine when we need to recreate
1690     * a view's display list (as opposed to just returning a reference to its existing
1691     * display list).
1692     *
1693     * @hide
1694     */
1695    static final int INVALIDATED                  = 0x80000000;
1696
1697    /* Masks for mPrivateFlags2 */
1698
1699    /**
1700     * Indicates that this view has reported that it can accept the current drag's content.
1701     * Cleared when the drag operation concludes.
1702     * @hide
1703     */
1704    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1705
1706    /**
1707     * Indicates that this view is currently directly under the drag location in a
1708     * drag-and-drop operation involving content that it can accept.  Cleared when
1709     * the drag exits the view, or when the drag operation concludes.
1710     * @hide
1711     */
1712    static final int DRAG_HOVERED                 = 0x00000002;
1713
1714    /**
1715     * Horizontal layout direction of this view is from Left to Right.
1716     * Use with {@link #setLayoutDirection}.
1717     */
1718    public static final int LAYOUT_DIRECTION_LTR = 0;
1719
1720    /**
1721     * Horizontal layout direction of this view is from Right to Left.
1722     * Use with {@link #setLayoutDirection}.
1723     */
1724    public static final int LAYOUT_DIRECTION_RTL = 1;
1725
1726    /**
1727     * Horizontal layout direction of this view is inherited from its parent.
1728     * Use with {@link #setLayoutDirection}.
1729     */
1730    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1731
1732    /**
1733     * Horizontal layout direction of this view is from deduced from the default language
1734     * script for the locale. Use with {@link #setLayoutDirection}.
1735     */
1736    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1737
1738    /**
1739     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1740     * @hide
1741     */
1742    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1743
1744    /**
1745     * Mask for use with private flags indicating bits used for horizontal layout direction.
1746     * @hide
1747     */
1748    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1749
1750    /**
1751     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1752     * right-to-left direction.
1753     * @hide
1754     */
1755    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1756
1757    /**
1758     * Indicates whether the view horizontal layout direction has been resolved.
1759     * @hide
1760     */
1761    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1762
1763    /**
1764     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1765     * @hide
1766     */
1767    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1768
1769    /*
1770     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1771     * flag value.
1772     * @hide
1773     */
1774    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1775            LAYOUT_DIRECTION_LTR,
1776            LAYOUT_DIRECTION_RTL,
1777            LAYOUT_DIRECTION_INHERIT,
1778            LAYOUT_DIRECTION_LOCALE
1779    };
1780
1781    /**
1782     * Default horizontal layout direction.
1783     * @hide
1784     */
1785    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1786
1787
1788    /**
1789     * Indicates that the view is tracking some sort of transient state
1790     * that the app should not need to be aware of, but that the framework
1791     * should take special care to preserve.
1792     *
1793     * @hide
1794     */
1795    static final int HAS_TRANSIENT_STATE = 0x00000100;
1796
1797
1798    /**
1799     * Text direction is inherited thru {@link ViewGroup}
1800     */
1801    public static final int TEXT_DIRECTION_INHERIT = 0;
1802
1803    /**
1804     * Text direction is using "first strong algorithm". The first strong directional character
1805     * determines the paragraph direction. If there is no strong directional character, the
1806     * paragraph direction is the view's resolved layout direction.
1807     */
1808    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1809
1810    /**
1811     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1812     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1813     * If there are neither, the paragraph direction is the view's resolved layout direction.
1814     */
1815    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1816
1817    /**
1818     * Text direction is forced to LTR.
1819     */
1820    public static final int TEXT_DIRECTION_LTR = 3;
1821
1822    /**
1823     * Text direction is forced to RTL.
1824     */
1825    public static final int TEXT_DIRECTION_RTL = 4;
1826
1827    /**
1828     * Text direction is coming from the system Locale.
1829     */
1830    public static final int TEXT_DIRECTION_LOCALE = 5;
1831
1832    /**
1833     * Default text direction is inherited
1834     */
1835    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1836
1837    /**
1838     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1839     * @hide
1840     */
1841    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1842
1843    /**
1844     * Mask for use with private flags indicating bits used for text direction.
1845     * @hide
1846     */
1847    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1848
1849    /**
1850     * Array of text direction flags for mapping attribute "textDirection" to correct
1851     * flag value.
1852     * @hide
1853     */
1854    private static final int[] TEXT_DIRECTION_FLAGS = {
1855            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1856            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1857            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1858            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1859            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1860            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1861    };
1862
1863    /**
1864     * Indicates whether the view text direction has been resolved.
1865     * @hide
1866     */
1867    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1868
1869    /**
1870     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1871     * @hide
1872     */
1873    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1874
1875    /**
1876     * Mask for use with private flags indicating bits used for resolved text direction.
1877     * @hide
1878     */
1879    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1880
1881    /**
1882     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1883     * @hide
1884     */
1885    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1886            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1887
1888    /*
1889     * Default text alignment. The text alignment of this View is inherited from its parent.
1890     * Use with {@link #setTextAlignment(int)}
1891     */
1892    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1893
1894    /**
1895     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1896     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1897     *
1898     * Use with {@link #setTextAlignment(int)}
1899     */
1900    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1901
1902    /**
1903     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1904     *
1905     * Use with {@link #setTextAlignment(int)}
1906     */
1907    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1908
1909    /**
1910     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1911     *
1912     * Use with {@link #setTextAlignment(int)}
1913     */
1914    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1915
1916    /**
1917     * Center the paragraph, e.g. ALIGN_CENTER.
1918     *
1919     * Use with {@link #setTextAlignment(int)}
1920     */
1921    public static final int TEXT_ALIGNMENT_CENTER = 4;
1922
1923    /**
1924     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
1925     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
1926     *
1927     * Use with {@link #setTextAlignment(int)}
1928     */
1929    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
1930
1931    /**
1932     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
1933     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
1934     *
1935     * Use with {@link #setTextAlignment(int)}
1936     */
1937    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
1938
1939    /**
1940     * Default text alignment is inherited
1941     */
1942    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
1943
1944    /**
1945      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1946      * @hide
1947      */
1948    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
1949
1950    /**
1951      * Mask for use with private flags indicating bits used for text alignment.
1952      * @hide
1953      */
1954    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
1955
1956    /**
1957     * Array of text direction flags for mapping attribute "textAlignment" to correct
1958     * flag value.
1959     * @hide
1960     */
1961    private static final int[] TEXT_ALIGNMENT_FLAGS = {
1962            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
1963            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
1964            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
1965            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
1966            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
1967            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
1968            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
1969    };
1970
1971    /**
1972     * Indicates whether the view text alignment has been resolved.
1973     * @hide
1974     */
1975    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
1976
1977    /**
1978     * Bit shift to get the resolved text alignment.
1979     * @hide
1980     */
1981    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
1982
1983    /**
1984     * Mask for use with private flags indicating bits used for text alignment.
1985     * @hide
1986     */
1987    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
1988
1989    /**
1990     * Indicates whether if the view text alignment has been resolved to gravity
1991     */
1992    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
1993            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
1994
1995
1996    /* End of masks for mPrivateFlags2 */
1997
1998    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1999
2000    /**
2001     * Always allow a user to over-scroll this view, provided it is a
2002     * view that can scroll.
2003     *
2004     * @see #getOverScrollMode()
2005     * @see #setOverScrollMode(int)
2006     */
2007    public static final int OVER_SCROLL_ALWAYS = 0;
2008
2009    /**
2010     * Allow a user to over-scroll this view only if the content is large
2011     * enough to meaningfully scroll, provided it is a view that can scroll.
2012     *
2013     * @see #getOverScrollMode()
2014     * @see #setOverScrollMode(int)
2015     */
2016    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2017
2018    /**
2019     * Never allow a user to over-scroll this view.
2020     *
2021     * @see #getOverScrollMode()
2022     * @see #setOverScrollMode(int)
2023     */
2024    public static final int OVER_SCROLL_NEVER = 2;
2025
2026    /**
2027     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2028     * requested the system UI (status bar) to be visible (the default).
2029     *
2030     * @see #setSystemUiVisibility(int)
2031     */
2032    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2033
2034    /**
2035     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2036     * system UI to enter an unobtrusive "low profile" mode.
2037     *
2038     * <p>This is for use in games, book readers, video players, or any other
2039     * "immersive" application where the usual system chrome is deemed too distracting.
2040     *
2041     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2042     *
2043     * @see #setSystemUiVisibility(int)
2044     */
2045    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2046
2047    /**
2048     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2049     * system navigation be temporarily hidden.
2050     *
2051     * <p>This is an even less obtrusive state than that called for by
2052     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2053     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2054     * those to disappear. This is useful (in conjunction with the
2055     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2056     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2057     * window flags) for displaying content using every last pixel on the display.
2058     *
2059     * <p>There is a limitation: because navigation controls are so important, the least user
2060     * interaction will cause them to reappear immediately.  When this happens, both
2061     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2062     * so that both elements reappear at the same time.
2063     *
2064     * @see #setSystemUiVisibility(int)
2065     */
2066    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2067
2068    /**
2069     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2070     * into the normal fullscreen mode so that its content can take over the screen
2071     * while still allowing the user to interact with the application.
2072     *
2073     * <p>This has the same visual effect as
2074     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2075     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2076     * meaning that non-critical screen decorations (such as the status bar) will be
2077     * hidden while the user is in the View's window, focusing the experience on
2078     * that content.  Unlike the window flag, if you are using ActionBar in
2079     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2080     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2081     * hide the action bar.
2082     *
2083     * <p>This approach to going fullscreen is best used over the window flag when
2084     * it is a transient state -- that is, the application does this at certain
2085     * points in its user interaction where it wants to allow the user to focus
2086     * on content, but not as a continuous state.  For situations where the application
2087     * would like to simply stay full screen the entire time (such as a game that
2088     * wants to take over the screen), the
2089     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2090     * is usually a better approach.  The state set here will be removed by the system
2091     * in various situations (such as the user moving to another application) like
2092     * the other system UI states.
2093     *
2094     * <p>When using this flag, the application should provide some easy facility
2095     * for the user to go out of it.  A common example would be in an e-book
2096     * reader, where tapping on the screen brings back whatever screen and UI
2097     * decorations that had been hidden while the user was immersed in reading
2098     * the book.
2099     *
2100     * @see #setSystemUiVisibility(int)
2101     */
2102    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2103
2104    /**
2105     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2106     * flags, we would like a stable view of the content insets given to
2107     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2108     * will always represent the worst case that the application can expect
2109     * as a continue state.  In practice this means with any of system bar,
2110     * nav bar, and status bar shown, but not the space that would be needed
2111     * for an input method.
2112     *
2113     * <p>If you are using ActionBar in
2114     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2115     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2116     * insets it adds to those given to the application.
2117     */
2118    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2119
2120    /**
2121     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2122     * to be layed out as if it has requested
2123     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2124     * allows it to avoid artifacts when switching in and out of that mode, at
2125     * the expense that some of its user interface may be covered by screen
2126     * decorations when they are shown.  You can perform layout of your inner
2127     * UI elements to account for the navagation system UI through the
2128     * {@link #fitSystemWindows(Rect)} method.
2129     */
2130    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2131
2132    /**
2133     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2134     * to be layed out as if it has requested
2135     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2136     * allows it to avoid artifacts when switching in and out of that mode, at
2137     * the expense that some of its user interface may be covered by screen
2138     * decorations when they are shown.  You can perform layout of your inner
2139     * UI elements to account for non-fullscreen system UI through the
2140     * {@link #fitSystemWindows(Rect)} method.
2141     */
2142    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2143
2144    /**
2145     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2146     */
2147    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2148
2149    /**
2150     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2151     */
2152    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2153
2154    /**
2155     * @hide
2156     *
2157     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2158     * out of the public fields to keep the undefined bits out of the developer's way.
2159     *
2160     * Flag to make the status bar not expandable.  Unless you also
2161     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2162     */
2163    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2164
2165    /**
2166     * @hide
2167     *
2168     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2169     * out of the public fields to keep the undefined bits out of the developer's way.
2170     *
2171     * Flag to hide notification icons and scrolling ticker text.
2172     */
2173    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2174
2175    /**
2176     * @hide
2177     *
2178     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2179     * out of the public fields to keep the undefined bits out of the developer's way.
2180     *
2181     * Flag to disable incoming notification alerts.  This will not block
2182     * icons, but it will block sound, vibrating and other visual or aural notifications.
2183     */
2184    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2185
2186    /**
2187     * @hide
2188     *
2189     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2190     * out of the public fields to keep the undefined bits out of the developer's way.
2191     *
2192     * Flag to hide only the scrolling ticker.  Note that
2193     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2194     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2195     */
2196    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2197
2198    /**
2199     * @hide
2200     *
2201     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2202     * out of the public fields to keep the undefined bits out of the developer's way.
2203     *
2204     * Flag to hide the center system info area.
2205     */
2206    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2207
2208    /**
2209     * @hide
2210     *
2211     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2212     * out of the public fields to keep the undefined bits out of the developer's way.
2213     *
2214     * Flag to hide only the home button.  Don't use this
2215     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2216     */
2217    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2218
2219    /**
2220     * @hide
2221     *
2222     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2223     * out of the public fields to keep the undefined bits out of the developer's way.
2224     *
2225     * Flag to hide only the back button. Don't use this
2226     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2227     */
2228    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2229
2230    /**
2231     * @hide
2232     *
2233     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2234     * out of the public fields to keep the undefined bits out of the developer's way.
2235     *
2236     * Flag to hide only the clock.  You might use this if your activity has
2237     * its own clock making the status bar's clock redundant.
2238     */
2239    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2240
2241    /**
2242     * @hide
2243     *
2244     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2245     * out of the public fields to keep the undefined bits out of the developer's way.
2246     *
2247     * Flag to hide only the recent apps button. Don't use this
2248     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2249     */
2250    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2251
2252    /**
2253     * @hide
2254     */
2255    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2256
2257    /**
2258     * These are the system UI flags that can be cleared by events outside
2259     * of an application.  Currently this is just the ability to tap on the
2260     * screen while hiding the navigation bar to have it return.
2261     * @hide
2262     */
2263    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2264            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2265            | SYSTEM_UI_FLAG_FULLSCREEN;
2266
2267    /**
2268     * Flags that can impact the layout in relation to system UI.
2269     */
2270    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2271            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2272            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2273
2274    /**
2275     * Find views that render the specified text.
2276     *
2277     * @see #findViewsWithText(ArrayList, CharSequence, int)
2278     */
2279    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2280
2281    /**
2282     * Find find views that contain the specified content description.
2283     *
2284     * @see #findViewsWithText(ArrayList, CharSequence, int)
2285     */
2286    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2287
2288    /**
2289     * Find views that contain {@link AccessibilityNodeProvider}. Such
2290     * a View is a root of virtual view hierarchy and may contain the searched
2291     * text. If this flag is set Views with providers are automatically
2292     * added and it is a responsibility of the client to call the APIs of
2293     * the provider to determine whether the virtual tree rooted at this View
2294     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2295     * represeting the virtual views with this text.
2296     *
2297     * @see #findViewsWithText(ArrayList, CharSequence, int)
2298     *
2299     * @hide
2300     */
2301    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2302
2303    /**
2304     * Indicates that the screen has changed state and is now off.
2305     *
2306     * @see #onScreenStateChanged(int)
2307     */
2308    public static final int SCREEN_STATE_OFF = 0x0;
2309
2310    /**
2311     * Indicates that the screen has changed state and is now on.
2312     *
2313     * @see #onScreenStateChanged(int)
2314     */
2315    public static final int SCREEN_STATE_ON = 0x1;
2316
2317    /**
2318     * Controls the over-scroll mode for this view.
2319     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2320     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2321     * and {@link #OVER_SCROLL_NEVER}.
2322     */
2323    private int mOverScrollMode;
2324
2325    /**
2326     * The parent this view is attached to.
2327     * {@hide}
2328     *
2329     * @see #getParent()
2330     */
2331    protected ViewParent mParent;
2332
2333    /**
2334     * {@hide}
2335     */
2336    AttachInfo mAttachInfo;
2337
2338    /**
2339     * {@hide}
2340     */
2341    @ViewDebug.ExportedProperty(flagMapping = {
2342        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2343                name = "FORCE_LAYOUT"),
2344        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2345                name = "LAYOUT_REQUIRED"),
2346        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2347            name = "DRAWING_CACHE_INVALID", outputIf = false),
2348        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2349        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2350        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2351        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2352    })
2353    int mPrivateFlags;
2354    int mPrivateFlags2;
2355
2356    /**
2357     * This view's request for the visibility of the status bar.
2358     * @hide
2359     */
2360    @ViewDebug.ExportedProperty(flagMapping = {
2361        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2362                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2363                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2364        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2365                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2366                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2367        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2368                                equals = SYSTEM_UI_FLAG_VISIBLE,
2369                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2370    })
2371    int mSystemUiVisibility;
2372
2373    /**
2374     * Count of how many windows this view has been attached to.
2375     */
2376    int mWindowAttachCount;
2377
2378    /**
2379     * The layout parameters associated with this view and used by the parent
2380     * {@link android.view.ViewGroup} to determine how this view should be
2381     * laid out.
2382     * {@hide}
2383     */
2384    protected ViewGroup.LayoutParams mLayoutParams;
2385
2386    /**
2387     * The view flags hold various views states.
2388     * {@hide}
2389     */
2390    @ViewDebug.ExportedProperty
2391    int mViewFlags;
2392
2393    static class TransformationInfo {
2394        /**
2395         * The transform matrix for the View. This transform is calculated internally
2396         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2397         * is used by default. Do *not* use this variable directly; instead call
2398         * getMatrix(), which will automatically recalculate the matrix if necessary
2399         * to get the correct matrix based on the latest rotation and scale properties.
2400         */
2401        private final Matrix mMatrix = new Matrix();
2402
2403        /**
2404         * The transform matrix for the View. This transform is calculated internally
2405         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2406         * is used by default. Do *not* use this variable directly; instead call
2407         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2408         * to get the correct matrix based on the latest rotation and scale properties.
2409         */
2410        private Matrix mInverseMatrix;
2411
2412        /**
2413         * An internal variable that tracks whether we need to recalculate the
2414         * transform matrix, based on whether the rotation or scaleX/Y properties
2415         * have changed since the matrix was last calculated.
2416         */
2417        boolean mMatrixDirty = false;
2418
2419        /**
2420         * An internal variable that tracks whether we need to recalculate the
2421         * transform matrix, based on whether the rotation or scaleX/Y properties
2422         * have changed since the matrix was last calculated.
2423         */
2424        private boolean mInverseMatrixDirty = true;
2425
2426        /**
2427         * A variable that tracks whether we need to recalculate the
2428         * transform matrix, based on whether the rotation or scaleX/Y properties
2429         * have changed since the matrix was last calculated. This variable
2430         * is only valid after a call to updateMatrix() or to a function that
2431         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2432         */
2433        private boolean mMatrixIsIdentity = true;
2434
2435        /**
2436         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2437         */
2438        private Camera mCamera = null;
2439
2440        /**
2441         * This matrix is used when computing the matrix for 3D rotations.
2442         */
2443        private Matrix matrix3D = null;
2444
2445        /**
2446         * These prev values are used to recalculate a centered pivot point when necessary. The
2447         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2448         * set), so thes values are only used then as well.
2449         */
2450        private int mPrevWidth = -1;
2451        private int mPrevHeight = -1;
2452
2453        /**
2454         * The degrees rotation around the vertical axis through the pivot point.
2455         */
2456        @ViewDebug.ExportedProperty
2457        float mRotationY = 0f;
2458
2459        /**
2460         * The degrees rotation around the horizontal axis through the pivot point.
2461         */
2462        @ViewDebug.ExportedProperty
2463        float mRotationX = 0f;
2464
2465        /**
2466         * The degrees rotation around the pivot point.
2467         */
2468        @ViewDebug.ExportedProperty
2469        float mRotation = 0f;
2470
2471        /**
2472         * The amount of translation of the object away from its left property (post-layout).
2473         */
2474        @ViewDebug.ExportedProperty
2475        float mTranslationX = 0f;
2476
2477        /**
2478         * The amount of translation of the object away from its top property (post-layout).
2479         */
2480        @ViewDebug.ExportedProperty
2481        float mTranslationY = 0f;
2482
2483        /**
2484         * The amount of scale in the x direction around the pivot point. A
2485         * value of 1 means no scaling is applied.
2486         */
2487        @ViewDebug.ExportedProperty
2488        float mScaleX = 1f;
2489
2490        /**
2491         * The amount of scale in the y direction around the pivot point. A
2492         * value of 1 means no scaling is applied.
2493         */
2494        @ViewDebug.ExportedProperty
2495        float mScaleY = 1f;
2496
2497        /**
2498         * The x location of the point around which the view is rotated and scaled.
2499         */
2500        @ViewDebug.ExportedProperty
2501        float mPivotX = 0f;
2502
2503        /**
2504         * The y location of the point around which the view is rotated and scaled.
2505         */
2506        @ViewDebug.ExportedProperty
2507        float mPivotY = 0f;
2508
2509        /**
2510         * The opacity of the View. This is a value from 0 to 1, where 0 means
2511         * completely transparent and 1 means completely opaque.
2512         */
2513        @ViewDebug.ExportedProperty
2514        float mAlpha = 1f;
2515    }
2516
2517    TransformationInfo mTransformationInfo;
2518
2519    private boolean mLastIsOpaque;
2520
2521    /**
2522     * Convenience value to check for float values that are close enough to zero to be considered
2523     * zero.
2524     */
2525    private static final float NONZERO_EPSILON = .001f;
2526
2527    /**
2528     * The distance in pixels from the left edge of this view's parent
2529     * to the left edge of this view.
2530     * {@hide}
2531     */
2532    @ViewDebug.ExportedProperty(category = "layout")
2533    protected int mLeft;
2534    /**
2535     * The distance in pixels from the left edge of this view's parent
2536     * to the right edge of this view.
2537     * {@hide}
2538     */
2539    @ViewDebug.ExportedProperty(category = "layout")
2540    protected int mRight;
2541    /**
2542     * The distance in pixels from the top edge of this view's parent
2543     * to the top edge of this view.
2544     * {@hide}
2545     */
2546    @ViewDebug.ExportedProperty(category = "layout")
2547    protected int mTop;
2548    /**
2549     * The distance in pixels from the top edge of this view's parent
2550     * to the bottom edge of this view.
2551     * {@hide}
2552     */
2553    @ViewDebug.ExportedProperty(category = "layout")
2554    protected int mBottom;
2555
2556    /**
2557     * The offset, in pixels, by which the content of this view is scrolled
2558     * horizontally.
2559     * {@hide}
2560     */
2561    @ViewDebug.ExportedProperty(category = "scrolling")
2562    protected int mScrollX;
2563    /**
2564     * The offset, in pixels, by which the content of this view is scrolled
2565     * vertically.
2566     * {@hide}
2567     */
2568    @ViewDebug.ExportedProperty(category = "scrolling")
2569    protected int mScrollY;
2570
2571    /**
2572     * The left padding in pixels, that is the distance in pixels between the
2573     * left edge of this view and the left edge of its content.
2574     * {@hide}
2575     */
2576    @ViewDebug.ExportedProperty(category = "padding")
2577    protected int mPaddingLeft;
2578    /**
2579     * The right padding in pixels, that is the distance in pixels between the
2580     * right edge of this view and the right edge of its content.
2581     * {@hide}
2582     */
2583    @ViewDebug.ExportedProperty(category = "padding")
2584    protected int mPaddingRight;
2585    /**
2586     * The top padding in pixels, that is the distance in pixels between the
2587     * top edge of this view and the top edge of its content.
2588     * {@hide}
2589     */
2590    @ViewDebug.ExportedProperty(category = "padding")
2591    protected int mPaddingTop;
2592    /**
2593     * The bottom padding in pixels, that is the distance in pixels between the
2594     * bottom edge of this view and the bottom edge of its content.
2595     * {@hide}
2596     */
2597    @ViewDebug.ExportedProperty(category = "padding")
2598    protected int mPaddingBottom;
2599
2600    /**
2601     * Briefly describes the view and is primarily used for accessibility support.
2602     */
2603    private CharSequence mContentDescription;
2604
2605    /**
2606     * Cache the paddingRight set by the user to append to the scrollbar's size.
2607     *
2608     * @hide
2609     */
2610    @ViewDebug.ExportedProperty(category = "padding")
2611    protected int mUserPaddingRight;
2612
2613    /**
2614     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2615     *
2616     * @hide
2617     */
2618    @ViewDebug.ExportedProperty(category = "padding")
2619    protected int mUserPaddingBottom;
2620
2621    /**
2622     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2623     *
2624     * @hide
2625     */
2626    @ViewDebug.ExportedProperty(category = "padding")
2627    protected int mUserPaddingLeft;
2628
2629    /**
2630     * Cache if the user padding is relative.
2631     *
2632     */
2633    @ViewDebug.ExportedProperty(category = "padding")
2634    boolean mUserPaddingRelative;
2635
2636    /**
2637     * Cache the paddingStart set by the user to append to the scrollbar's size.
2638     *
2639     */
2640    @ViewDebug.ExportedProperty(category = "padding")
2641    int mUserPaddingStart;
2642
2643    /**
2644     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2645     *
2646     */
2647    @ViewDebug.ExportedProperty(category = "padding")
2648    int mUserPaddingEnd;
2649
2650    /**
2651     * @hide
2652     */
2653    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2654    /**
2655     * @hide
2656     */
2657    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2658
2659    private Drawable mBackground;
2660
2661    private int mBackgroundResource;
2662    private boolean mBackgroundSizeChanged;
2663
2664    static class ListenerInfo {
2665        /**
2666         * Listener used to dispatch focus change events.
2667         * This field should be made private, so it is hidden from the SDK.
2668         * {@hide}
2669         */
2670        protected OnFocusChangeListener mOnFocusChangeListener;
2671
2672        /**
2673         * Listeners for layout change events.
2674         */
2675        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2676
2677        /**
2678         * Listeners for attach events.
2679         */
2680        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2681
2682        /**
2683         * Listener used to dispatch click events.
2684         * This field should be made private, so it is hidden from the SDK.
2685         * {@hide}
2686         */
2687        public OnClickListener mOnClickListener;
2688
2689        /**
2690         * Listener used to dispatch long click events.
2691         * This field should be made private, so it is hidden from the SDK.
2692         * {@hide}
2693         */
2694        protected OnLongClickListener mOnLongClickListener;
2695
2696        /**
2697         * Listener used to build the context menu.
2698         * This field should be made private, so it is hidden from the SDK.
2699         * {@hide}
2700         */
2701        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2702
2703        private OnKeyListener mOnKeyListener;
2704
2705        private OnTouchListener mOnTouchListener;
2706
2707        private OnHoverListener mOnHoverListener;
2708
2709        private OnGenericMotionListener mOnGenericMotionListener;
2710
2711        private OnDragListener mOnDragListener;
2712
2713        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2714    }
2715
2716    ListenerInfo mListenerInfo;
2717
2718    /**
2719     * The application environment this view lives in.
2720     * This field should be made private, so it is hidden from the SDK.
2721     * {@hide}
2722     */
2723    protected Context mContext;
2724
2725    private final Resources mResources;
2726
2727    private ScrollabilityCache mScrollCache;
2728
2729    private int[] mDrawableState = null;
2730
2731    /**
2732     * Set to true when drawing cache is enabled and cannot be created.
2733     *
2734     * @hide
2735     */
2736    public boolean mCachingFailed;
2737
2738    private Bitmap mDrawingCache;
2739    private Bitmap mUnscaledDrawingCache;
2740    private HardwareLayer mHardwareLayer;
2741    DisplayList mDisplayList;
2742
2743    /**
2744     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2745     * the user may specify which view to go to next.
2746     */
2747    private int mNextFocusLeftId = View.NO_ID;
2748
2749    /**
2750     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2751     * the user may specify which view to go to next.
2752     */
2753    private int mNextFocusRightId = View.NO_ID;
2754
2755    /**
2756     * When this view has focus and the next focus is {@link #FOCUS_UP},
2757     * the user may specify which view to go to next.
2758     */
2759    private int mNextFocusUpId = View.NO_ID;
2760
2761    /**
2762     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2763     * the user may specify which view to go to next.
2764     */
2765    private int mNextFocusDownId = View.NO_ID;
2766
2767    /**
2768     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2769     * the user may specify which view to go to next.
2770     */
2771    int mNextFocusForwardId = View.NO_ID;
2772
2773    private CheckForLongPress mPendingCheckForLongPress;
2774    private CheckForTap mPendingCheckForTap = null;
2775    private PerformClick mPerformClick;
2776    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2777
2778    private UnsetPressedState mUnsetPressedState;
2779
2780    /**
2781     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2782     * up event while a long press is invoked as soon as the long press duration is reached, so
2783     * a long press could be performed before the tap is checked, in which case the tap's action
2784     * should not be invoked.
2785     */
2786    private boolean mHasPerformedLongPress;
2787
2788    /**
2789     * The minimum height of the view. We'll try our best to have the height
2790     * of this view to at least this amount.
2791     */
2792    @ViewDebug.ExportedProperty(category = "measurement")
2793    private int mMinHeight;
2794
2795    /**
2796     * The minimum width of the view. We'll try our best to have the width
2797     * of this view to at least this amount.
2798     */
2799    @ViewDebug.ExportedProperty(category = "measurement")
2800    private int mMinWidth;
2801
2802    /**
2803     * The delegate to handle touch events that are physically in this view
2804     * but should be handled by another view.
2805     */
2806    private TouchDelegate mTouchDelegate = null;
2807
2808    /**
2809     * Solid color to use as a background when creating the drawing cache. Enables
2810     * the cache to use 16 bit bitmaps instead of 32 bit.
2811     */
2812    private int mDrawingCacheBackgroundColor = 0;
2813
2814    /**
2815     * Special tree observer used when mAttachInfo is null.
2816     */
2817    private ViewTreeObserver mFloatingTreeObserver;
2818
2819    /**
2820     * Cache the touch slop from the context that created the view.
2821     */
2822    private int mTouchSlop;
2823
2824    /**
2825     * Object that handles automatic animation of view properties.
2826     */
2827    private ViewPropertyAnimator mAnimator = null;
2828
2829    /**
2830     * Flag indicating that a drag can cross window boundaries.  When
2831     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2832     * with this flag set, all visible applications will be able to participate
2833     * in the drag operation and receive the dragged content.
2834     *
2835     * @hide
2836     */
2837    public static final int DRAG_FLAG_GLOBAL = 1;
2838
2839    /**
2840     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2841     */
2842    private float mVerticalScrollFactor;
2843
2844    /**
2845     * Position of the vertical scroll bar.
2846     */
2847    private int mVerticalScrollbarPosition;
2848
2849    /**
2850     * Position the scroll bar at the default position as determined by the system.
2851     */
2852    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2853
2854    /**
2855     * Position the scroll bar along the left edge.
2856     */
2857    public static final int SCROLLBAR_POSITION_LEFT = 1;
2858
2859    /**
2860     * Position the scroll bar along the right edge.
2861     */
2862    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2863
2864    /**
2865     * Indicates that the view does not have a layer.
2866     *
2867     * @see #getLayerType()
2868     * @see #setLayerType(int, android.graphics.Paint)
2869     * @see #LAYER_TYPE_SOFTWARE
2870     * @see #LAYER_TYPE_HARDWARE
2871     */
2872    public static final int LAYER_TYPE_NONE = 0;
2873
2874    /**
2875     * <p>Indicates that the view has a software layer. A software layer is backed
2876     * by a bitmap and causes the view to be rendered using Android's software
2877     * rendering pipeline, even if hardware acceleration is enabled.</p>
2878     *
2879     * <p>Software layers have various usages:</p>
2880     * <p>When the application is not using hardware acceleration, a software layer
2881     * is useful to apply a specific color filter and/or blending mode and/or
2882     * translucency to a view and all its children.</p>
2883     * <p>When the application is using hardware acceleration, a software layer
2884     * is useful to render drawing primitives not supported by the hardware
2885     * accelerated pipeline. It can also be used to cache a complex view tree
2886     * into a texture and reduce the complexity of drawing operations. For instance,
2887     * when animating a complex view tree with a translation, a software layer can
2888     * be used to render the view tree only once.</p>
2889     * <p>Software layers should be avoided when the affected view tree updates
2890     * often. Every update will require to re-render the software layer, which can
2891     * potentially be slow (particularly when hardware acceleration is turned on
2892     * since the layer will have to be uploaded into a hardware texture after every
2893     * update.)</p>
2894     *
2895     * @see #getLayerType()
2896     * @see #setLayerType(int, android.graphics.Paint)
2897     * @see #LAYER_TYPE_NONE
2898     * @see #LAYER_TYPE_HARDWARE
2899     */
2900    public static final int LAYER_TYPE_SOFTWARE = 1;
2901
2902    /**
2903     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2904     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2905     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2906     * rendering pipeline, but only if hardware acceleration is turned on for the
2907     * view hierarchy. When hardware acceleration is turned off, hardware layers
2908     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2909     *
2910     * <p>A hardware layer is useful to apply a specific color filter and/or
2911     * blending mode and/or translucency to a view and all its children.</p>
2912     * <p>A hardware layer can be used to cache a complex view tree into a
2913     * texture and reduce the complexity of drawing operations. For instance,
2914     * when animating a complex view tree with a translation, a hardware layer can
2915     * be used to render the view tree only once.</p>
2916     * <p>A hardware layer can also be used to increase the rendering quality when
2917     * rotation transformations are applied on a view. It can also be used to
2918     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2919     *
2920     * @see #getLayerType()
2921     * @see #setLayerType(int, android.graphics.Paint)
2922     * @see #LAYER_TYPE_NONE
2923     * @see #LAYER_TYPE_SOFTWARE
2924     */
2925    public static final int LAYER_TYPE_HARDWARE = 2;
2926
2927    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2928            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2929            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2930            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2931    })
2932    int mLayerType = LAYER_TYPE_NONE;
2933    Paint mLayerPaint;
2934    Rect mLocalDirtyRect;
2935
2936    /**
2937     * Set to true when the view is sending hover accessibility events because it
2938     * is the innermost hovered view.
2939     */
2940    private boolean mSendingHoverAccessibilityEvents;
2941
2942    /**
2943     * Simple constructor to use when creating a view from code.
2944     *
2945     * @param context The Context the view is running in, through which it can
2946     *        access the current theme, resources, etc.
2947     */
2948    public View(Context context) {
2949        mContext = context;
2950        mResources = context != null ? context.getResources() : null;
2951        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
2952        // Set layout and text direction defaults
2953        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
2954                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
2955                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT);
2956        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2957        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2958        mUserPaddingStart = -1;
2959        mUserPaddingEnd = -1;
2960        mUserPaddingRelative = false;
2961    }
2962
2963    /**
2964     * Delegate for injecting accessiblity functionality.
2965     */
2966    AccessibilityDelegate mAccessibilityDelegate;
2967
2968    /**
2969     * Consistency verifier for debugging purposes.
2970     * @hide
2971     */
2972    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2973            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2974                    new InputEventConsistencyVerifier(this, 0) : null;
2975
2976    /**
2977     * Constructor that is called when inflating a view from XML. This is called
2978     * when a view is being constructed from an XML file, supplying attributes
2979     * that were specified in the XML file. This version uses a default style of
2980     * 0, so the only attribute values applied are those in the Context's Theme
2981     * and the given AttributeSet.
2982     *
2983     * <p>
2984     * The method onFinishInflate() will be called after all children have been
2985     * added.
2986     *
2987     * @param context The Context the view is running in, through which it can
2988     *        access the current theme, resources, etc.
2989     * @param attrs The attributes of the XML tag that is inflating the view.
2990     * @see #View(Context, AttributeSet, int)
2991     */
2992    public View(Context context, AttributeSet attrs) {
2993        this(context, attrs, 0);
2994    }
2995
2996    /**
2997     * Perform inflation from XML and apply a class-specific base style. This
2998     * constructor of View allows subclasses to use their own base style when
2999     * they are inflating. For example, a Button class's constructor would call
3000     * this version of the super class constructor and supply
3001     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3002     * the theme's button style to modify all of the base view attributes (in
3003     * particular its background) as well as the Button class's attributes.
3004     *
3005     * @param context The Context the view is running in, through which it can
3006     *        access the current theme, resources, etc.
3007     * @param attrs The attributes of the XML tag that is inflating the view.
3008     * @param defStyle The default style to apply to this view. If 0, no style
3009     *        will be applied (beyond what is included in the theme). This may
3010     *        either be an attribute resource, whose value will be retrieved
3011     *        from the current theme, or an explicit style resource.
3012     * @see #View(Context, AttributeSet)
3013     */
3014    public View(Context context, AttributeSet attrs, int defStyle) {
3015        this(context);
3016
3017        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3018                defStyle, 0);
3019
3020        Drawable background = null;
3021
3022        int leftPadding = -1;
3023        int topPadding = -1;
3024        int rightPadding = -1;
3025        int bottomPadding = -1;
3026        int startPadding = -1;
3027        int endPadding = -1;
3028
3029        int padding = -1;
3030
3031        int viewFlagValues = 0;
3032        int viewFlagMasks = 0;
3033
3034        boolean setScrollContainer = false;
3035
3036        int x = 0;
3037        int y = 0;
3038
3039        float tx = 0;
3040        float ty = 0;
3041        float rotation = 0;
3042        float rotationX = 0;
3043        float rotationY = 0;
3044        float sx = 1f;
3045        float sy = 1f;
3046        boolean transformSet = false;
3047
3048        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3049
3050        int overScrollMode = mOverScrollMode;
3051        final int N = a.getIndexCount();
3052        for (int i = 0; i < N; i++) {
3053            int attr = a.getIndex(i);
3054            switch (attr) {
3055                case com.android.internal.R.styleable.View_background:
3056                    background = a.getDrawable(attr);
3057                    break;
3058                case com.android.internal.R.styleable.View_padding:
3059                    padding = a.getDimensionPixelSize(attr, -1);
3060                    break;
3061                 case com.android.internal.R.styleable.View_paddingLeft:
3062                    leftPadding = a.getDimensionPixelSize(attr, -1);
3063                    break;
3064                case com.android.internal.R.styleable.View_paddingTop:
3065                    topPadding = a.getDimensionPixelSize(attr, -1);
3066                    break;
3067                case com.android.internal.R.styleable.View_paddingRight:
3068                    rightPadding = a.getDimensionPixelSize(attr, -1);
3069                    break;
3070                case com.android.internal.R.styleable.View_paddingBottom:
3071                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3072                    break;
3073                case com.android.internal.R.styleable.View_paddingStart:
3074                    startPadding = a.getDimensionPixelSize(attr, -1);
3075                    break;
3076                case com.android.internal.R.styleable.View_paddingEnd:
3077                    endPadding = a.getDimensionPixelSize(attr, -1);
3078                    break;
3079                case com.android.internal.R.styleable.View_scrollX:
3080                    x = a.getDimensionPixelOffset(attr, 0);
3081                    break;
3082                case com.android.internal.R.styleable.View_scrollY:
3083                    y = a.getDimensionPixelOffset(attr, 0);
3084                    break;
3085                case com.android.internal.R.styleable.View_alpha:
3086                    setAlpha(a.getFloat(attr, 1f));
3087                    break;
3088                case com.android.internal.R.styleable.View_transformPivotX:
3089                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3090                    break;
3091                case com.android.internal.R.styleable.View_transformPivotY:
3092                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3093                    break;
3094                case com.android.internal.R.styleable.View_translationX:
3095                    tx = a.getDimensionPixelOffset(attr, 0);
3096                    transformSet = true;
3097                    break;
3098                case com.android.internal.R.styleable.View_translationY:
3099                    ty = a.getDimensionPixelOffset(attr, 0);
3100                    transformSet = true;
3101                    break;
3102                case com.android.internal.R.styleable.View_rotation:
3103                    rotation = a.getFloat(attr, 0);
3104                    transformSet = true;
3105                    break;
3106                case com.android.internal.R.styleable.View_rotationX:
3107                    rotationX = a.getFloat(attr, 0);
3108                    transformSet = true;
3109                    break;
3110                case com.android.internal.R.styleable.View_rotationY:
3111                    rotationY = a.getFloat(attr, 0);
3112                    transformSet = true;
3113                    break;
3114                case com.android.internal.R.styleable.View_scaleX:
3115                    sx = a.getFloat(attr, 1f);
3116                    transformSet = true;
3117                    break;
3118                case com.android.internal.R.styleable.View_scaleY:
3119                    sy = a.getFloat(attr, 1f);
3120                    transformSet = true;
3121                    break;
3122                case com.android.internal.R.styleable.View_id:
3123                    mID = a.getResourceId(attr, NO_ID);
3124                    break;
3125                case com.android.internal.R.styleable.View_tag:
3126                    mTag = a.getText(attr);
3127                    break;
3128                case com.android.internal.R.styleable.View_fitsSystemWindows:
3129                    if (a.getBoolean(attr, false)) {
3130                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3131                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3132                    }
3133                    break;
3134                case com.android.internal.R.styleable.View_focusable:
3135                    if (a.getBoolean(attr, false)) {
3136                        viewFlagValues |= FOCUSABLE;
3137                        viewFlagMasks |= FOCUSABLE_MASK;
3138                    }
3139                    break;
3140                case com.android.internal.R.styleable.View_focusableInTouchMode:
3141                    if (a.getBoolean(attr, false)) {
3142                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3143                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3144                    }
3145                    break;
3146                case com.android.internal.R.styleable.View_clickable:
3147                    if (a.getBoolean(attr, false)) {
3148                        viewFlagValues |= CLICKABLE;
3149                        viewFlagMasks |= CLICKABLE;
3150                    }
3151                    break;
3152                case com.android.internal.R.styleable.View_longClickable:
3153                    if (a.getBoolean(attr, false)) {
3154                        viewFlagValues |= LONG_CLICKABLE;
3155                        viewFlagMasks |= LONG_CLICKABLE;
3156                    }
3157                    break;
3158                case com.android.internal.R.styleable.View_saveEnabled:
3159                    if (!a.getBoolean(attr, true)) {
3160                        viewFlagValues |= SAVE_DISABLED;
3161                        viewFlagMasks |= SAVE_DISABLED_MASK;
3162                    }
3163                    break;
3164                case com.android.internal.R.styleable.View_duplicateParentState:
3165                    if (a.getBoolean(attr, false)) {
3166                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3167                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3168                    }
3169                    break;
3170                case com.android.internal.R.styleable.View_visibility:
3171                    final int visibility = a.getInt(attr, 0);
3172                    if (visibility != 0) {
3173                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3174                        viewFlagMasks |= VISIBILITY_MASK;
3175                    }
3176                    break;
3177                case com.android.internal.R.styleable.View_layoutDirection:
3178                    // Clear any layout direction flags (included resolved bits) already set
3179                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3180                    // Set the layout direction flags depending on the value of the attribute
3181                    final int layoutDirection = a.getInt(attr, -1);
3182                    final int value = (layoutDirection != -1) ?
3183                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3184                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3185                    break;
3186                case com.android.internal.R.styleable.View_drawingCacheQuality:
3187                    final int cacheQuality = a.getInt(attr, 0);
3188                    if (cacheQuality != 0) {
3189                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3190                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3191                    }
3192                    break;
3193                case com.android.internal.R.styleable.View_contentDescription:
3194                    mContentDescription = a.getString(attr);
3195                    break;
3196                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3197                    if (!a.getBoolean(attr, true)) {
3198                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3199                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3200                    }
3201                    break;
3202                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3203                    if (!a.getBoolean(attr, true)) {
3204                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3205                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3206                    }
3207                    break;
3208                case R.styleable.View_scrollbars:
3209                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3210                    if (scrollbars != SCROLLBARS_NONE) {
3211                        viewFlagValues |= scrollbars;
3212                        viewFlagMasks |= SCROLLBARS_MASK;
3213                        initializeScrollbars(a);
3214                    }
3215                    break;
3216                //noinspection deprecation
3217                case R.styleable.View_fadingEdge:
3218                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3219                        // Ignore the attribute starting with ICS
3220                        break;
3221                    }
3222                    // With builds < ICS, fall through and apply fading edges
3223                case R.styleable.View_requiresFadingEdge:
3224                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3225                    if (fadingEdge != FADING_EDGE_NONE) {
3226                        viewFlagValues |= fadingEdge;
3227                        viewFlagMasks |= FADING_EDGE_MASK;
3228                        initializeFadingEdge(a);
3229                    }
3230                    break;
3231                case R.styleable.View_scrollbarStyle:
3232                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3233                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3234                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3235                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3236                    }
3237                    break;
3238                case R.styleable.View_isScrollContainer:
3239                    setScrollContainer = true;
3240                    if (a.getBoolean(attr, false)) {
3241                        setScrollContainer(true);
3242                    }
3243                    break;
3244                case com.android.internal.R.styleable.View_keepScreenOn:
3245                    if (a.getBoolean(attr, false)) {
3246                        viewFlagValues |= KEEP_SCREEN_ON;
3247                        viewFlagMasks |= KEEP_SCREEN_ON;
3248                    }
3249                    break;
3250                case R.styleable.View_filterTouchesWhenObscured:
3251                    if (a.getBoolean(attr, false)) {
3252                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3253                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3254                    }
3255                    break;
3256                case R.styleable.View_nextFocusLeft:
3257                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3258                    break;
3259                case R.styleable.View_nextFocusRight:
3260                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3261                    break;
3262                case R.styleable.View_nextFocusUp:
3263                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3264                    break;
3265                case R.styleable.View_nextFocusDown:
3266                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3267                    break;
3268                case R.styleable.View_nextFocusForward:
3269                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3270                    break;
3271                case R.styleable.View_minWidth:
3272                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3273                    break;
3274                case R.styleable.View_minHeight:
3275                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3276                    break;
3277                case R.styleable.View_onClick:
3278                    if (context.isRestricted()) {
3279                        throw new IllegalStateException("The android:onClick attribute cannot "
3280                                + "be used within a restricted context");
3281                    }
3282
3283                    final String handlerName = a.getString(attr);
3284                    if (handlerName != null) {
3285                        setOnClickListener(new OnClickListener() {
3286                            private Method mHandler;
3287
3288                            public void onClick(View v) {
3289                                if (mHandler == null) {
3290                                    try {
3291                                        mHandler = getContext().getClass().getMethod(handlerName,
3292                                                View.class);
3293                                    } catch (NoSuchMethodException e) {
3294                                        int id = getId();
3295                                        String idText = id == NO_ID ? "" : " with id '"
3296                                                + getContext().getResources().getResourceEntryName(
3297                                                    id) + "'";
3298                                        throw new IllegalStateException("Could not find a method " +
3299                                                handlerName + "(View) in the activity "
3300                                                + getContext().getClass() + " for onClick handler"
3301                                                + " on view " + View.this.getClass() + idText, e);
3302                                    }
3303                                }
3304
3305                                try {
3306                                    mHandler.invoke(getContext(), View.this);
3307                                } catch (IllegalAccessException e) {
3308                                    throw new IllegalStateException("Could not execute non "
3309                                            + "public method of the activity", e);
3310                                } catch (InvocationTargetException e) {
3311                                    throw new IllegalStateException("Could not execute "
3312                                            + "method of the activity", e);
3313                                }
3314                            }
3315                        });
3316                    }
3317                    break;
3318                case R.styleable.View_overScrollMode:
3319                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3320                    break;
3321                case R.styleable.View_verticalScrollbarPosition:
3322                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3323                    break;
3324                case R.styleable.View_layerType:
3325                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3326                    break;
3327                case R.styleable.View_textDirection:
3328                    // Clear any text direction flag already set
3329                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3330                    // Set the text direction flags depending on the value of the attribute
3331                    final int textDirection = a.getInt(attr, -1);
3332                    if (textDirection != -1) {
3333                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3334                    }
3335                    break;
3336                case R.styleable.View_textAlignment:
3337                    // Clear any text alignment flag already set
3338                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3339                    // Set the text alignment flag depending on the value of the attribute
3340                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3341                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3342                    break;
3343            }
3344        }
3345
3346        a.recycle();
3347
3348        setOverScrollMode(overScrollMode);
3349
3350        if (background != null) {
3351            setBackground(background);
3352        }
3353
3354        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3355        // layout direction). Those cached values will be used later during padding resolution.
3356        mUserPaddingStart = startPadding;
3357        mUserPaddingEnd = endPadding;
3358
3359        updateUserPaddingRelative();
3360
3361        if (padding >= 0) {
3362            leftPadding = padding;
3363            topPadding = padding;
3364            rightPadding = padding;
3365            bottomPadding = padding;
3366        }
3367
3368        // If the user specified the padding (either with android:padding or
3369        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3370        // use the default padding or the padding from the background drawable
3371        // (stored at this point in mPadding*)
3372        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3373                topPadding >= 0 ? topPadding : mPaddingTop,
3374                rightPadding >= 0 ? rightPadding : mPaddingRight,
3375                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3376
3377        if (viewFlagMasks != 0) {
3378            setFlags(viewFlagValues, viewFlagMasks);
3379        }
3380
3381        // Needs to be called after mViewFlags is set
3382        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3383            recomputePadding();
3384        }
3385
3386        if (x != 0 || y != 0) {
3387            scrollTo(x, y);
3388        }
3389
3390        if (transformSet) {
3391            setTranslationX(tx);
3392            setTranslationY(ty);
3393            setRotation(rotation);
3394            setRotationX(rotationX);
3395            setRotationY(rotationY);
3396            setScaleX(sx);
3397            setScaleY(sy);
3398        }
3399
3400        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3401            setScrollContainer(true);
3402        }
3403
3404        computeOpaqueFlags();
3405    }
3406
3407    private void updateUserPaddingRelative() {
3408        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3409    }
3410
3411    /**
3412     * Non-public constructor for use in testing
3413     */
3414    View() {
3415        mResources = null;
3416    }
3417
3418    /**
3419     * <p>
3420     * Initializes the fading edges from a given set of styled attributes. This
3421     * method should be called by subclasses that need fading edges and when an
3422     * instance of these subclasses is created programmatically rather than
3423     * being inflated from XML. This method is automatically called when the XML
3424     * is inflated.
3425     * </p>
3426     *
3427     * @param a the styled attributes set to initialize the fading edges from
3428     */
3429    protected void initializeFadingEdge(TypedArray a) {
3430        initScrollCache();
3431
3432        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3433                R.styleable.View_fadingEdgeLength,
3434                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3435    }
3436
3437    /**
3438     * Returns the size of the vertical faded edges used to indicate that more
3439     * content in this view is visible.
3440     *
3441     * @return The size in pixels of the vertical faded edge or 0 if vertical
3442     *         faded edges are not enabled for this view.
3443     * @attr ref android.R.styleable#View_fadingEdgeLength
3444     */
3445    public int getVerticalFadingEdgeLength() {
3446        if (isVerticalFadingEdgeEnabled()) {
3447            ScrollabilityCache cache = mScrollCache;
3448            if (cache != null) {
3449                return cache.fadingEdgeLength;
3450            }
3451        }
3452        return 0;
3453    }
3454
3455    /**
3456     * Set the size of the faded edge used to indicate that more content in this
3457     * view is available.  Will not change whether the fading edge is enabled; use
3458     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3459     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3460     * for the vertical or horizontal fading edges.
3461     *
3462     * @param length The size in pixels of the faded edge used to indicate that more
3463     *        content in this view is visible.
3464     */
3465    public void setFadingEdgeLength(int length) {
3466        initScrollCache();
3467        mScrollCache.fadingEdgeLength = length;
3468    }
3469
3470    /**
3471     * Returns the size of the horizontal faded edges used to indicate that more
3472     * content in this view is visible.
3473     *
3474     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3475     *         faded edges are not enabled for this view.
3476     * @attr ref android.R.styleable#View_fadingEdgeLength
3477     */
3478    public int getHorizontalFadingEdgeLength() {
3479        if (isHorizontalFadingEdgeEnabled()) {
3480            ScrollabilityCache cache = mScrollCache;
3481            if (cache != null) {
3482                return cache.fadingEdgeLength;
3483            }
3484        }
3485        return 0;
3486    }
3487
3488    /**
3489     * Returns the width of the vertical scrollbar.
3490     *
3491     * @return The width in pixels of the vertical scrollbar or 0 if there
3492     *         is no vertical scrollbar.
3493     */
3494    public int getVerticalScrollbarWidth() {
3495        ScrollabilityCache cache = mScrollCache;
3496        if (cache != null) {
3497            ScrollBarDrawable scrollBar = cache.scrollBar;
3498            if (scrollBar != null) {
3499                int size = scrollBar.getSize(true);
3500                if (size <= 0) {
3501                    size = cache.scrollBarSize;
3502                }
3503                return size;
3504            }
3505            return 0;
3506        }
3507        return 0;
3508    }
3509
3510    /**
3511     * Returns the height of the horizontal scrollbar.
3512     *
3513     * @return The height in pixels of the horizontal scrollbar or 0 if
3514     *         there is no horizontal scrollbar.
3515     */
3516    protected int getHorizontalScrollbarHeight() {
3517        ScrollabilityCache cache = mScrollCache;
3518        if (cache != null) {
3519            ScrollBarDrawable scrollBar = cache.scrollBar;
3520            if (scrollBar != null) {
3521                int size = scrollBar.getSize(false);
3522                if (size <= 0) {
3523                    size = cache.scrollBarSize;
3524                }
3525                return size;
3526            }
3527            return 0;
3528        }
3529        return 0;
3530    }
3531
3532    /**
3533     * <p>
3534     * Initializes the scrollbars from a given set of styled attributes. This
3535     * method should be called by subclasses that need scrollbars and when an
3536     * instance of these subclasses is created programmatically rather than
3537     * being inflated from XML. This method is automatically called when the XML
3538     * is inflated.
3539     * </p>
3540     *
3541     * @param a the styled attributes set to initialize the scrollbars from
3542     */
3543    protected void initializeScrollbars(TypedArray a) {
3544        initScrollCache();
3545
3546        final ScrollabilityCache scrollabilityCache = mScrollCache;
3547
3548        if (scrollabilityCache.scrollBar == null) {
3549            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3550        }
3551
3552        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3553
3554        if (!fadeScrollbars) {
3555            scrollabilityCache.state = ScrollabilityCache.ON;
3556        }
3557        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3558
3559
3560        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3561                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3562                        .getScrollBarFadeDuration());
3563        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3564                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3565                ViewConfiguration.getScrollDefaultDelay());
3566
3567
3568        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3569                com.android.internal.R.styleable.View_scrollbarSize,
3570                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3571
3572        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3573        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3574
3575        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3576        if (thumb != null) {
3577            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3578        }
3579
3580        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3581                false);
3582        if (alwaysDraw) {
3583            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3584        }
3585
3586        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3587        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3588
3589        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3590        if (thumb != null) {
3591            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3592        }
3593
3594        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3595                false);
3596        if (alwaysDraw) {
3597            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3598        }
3599
3600        // Re-apply user/background padding so that scrollbar(s) get added
3601        resolvePadding();
3602    }
3603
3604    /**
3605     * <p>
3606     * Initalizes the scrollability cache if necessary.
3607     * </p>
3608     */
3609    private void initScrollCache() {
3610        if (mScrollCache == null) {
3611            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3612        }
3613    }
3614
3615    private ScrollabilityCache getScrollCache() {
3616        initScrollCache();
3617        return mScrollCache;
3618    }
3619
3620    /**
3621     * Set the position of the vertical scroll bar. Should be one of
3622     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3623     * {@link #SCROLLBAR_POSITION_RIGHT}.
3624     *
3625     * @param position Where the vertical scroll bar should be positioned.
3626     */
3627    public void setVerticalScrollbarPosition(int position) {
3628        if (mVerticalScrollbarPosition != position) {
3629            mVerticalScrollbarPosition = position;
3630            computeOpaqueFlags();
3631            resolvePadding();
3632        }
3633    }
3634
3635    /**
3636     * @return The position where the vertical scroll bar will show, if applicable.
3637     * @see #setVerticalScrollbarPosition(int)
3638     */
3639    public int getVerticalScrollbarPosition() {
3640        return mVerticalScrollbarPosition;
3641    }
3642
3643    ListenerInfo getListenerInfo() {
3644        if (mListenerInfo != null) {
3645            return mListenerInfo;
3646        }
3647        mListenerInfo = new ListenerInfo();
3648        return mListenerInfo;
3649    }
3650
3651    /**
3652     * Register a callback to be invoked when focus of this view changed.
3653     *
3654     * @param l The callback that will run.
3655     */
3656    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3657        getListenerInfo().mOnFocusChangeListener = l;
3658    }
3659
3660    /**
3661     * Add a listener that will be called when the bounds of the view change due to
3662     * layout processing.
3663     *
3664     * @param listener The listener that will be called when layout bounds change.
3665     */
3666    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3667        ListenerInfo li = getListenerInfo();
3668        if (li.mOnLayoutChangeListeners == null) {
3669            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3670        }
3671        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3672            li.mOnLayoutChangeListeners.add(listener);
3673        }
3674    }
3675
3676    /**
3677     * Remove a listener for layout changes.
3678     *
3679     * @param listener The listener for layout bounds change.
3680     */
3681    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3682        ListenerInfo li = mListenerInfo;
3683        if (li == null || li.mOnLayoutChangeListeners == null) {
3684            return;
3685        }
3686        li.mOnLayoutChangeListeners.remove(listener);
3687    }
3688
3689    /**
3690     * Add a listener for attach state changes.
3691     *
3692     * This listener will be called whenever this view is attached or detached
3693     * from a window. Remove the listener using
3694     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3695     *
3696     * @param listener Listener to attach
3697     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3698     */
3699    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3700        ListenerInfo li = getListenerInfo();
3701        if (li.mOnAttachStateChangeListeners == null) {
3702            li.mOnAttachStateChangeListeners
3703                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3704        }
3705        li.mOnAttachStateChangeListeners.add(listener);
3706    }
3707
3708    /**
3709     * Remove a listener for attach state changes. The listener will receive no further
3710     * notification of window attach/detach events.
3711     *
3712     * @param listener Listener to remove
3713     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3714     */
3715    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3716        ListenerInfo li = mListenerInfo;
3717        if (li == null || li.mOnAttachStateChangeListeners == null) {
3718            return;
3719        }
3720        li.mOnAttachStateChangeListeners.remove(listener);
3721    }
3722
3723    /**
3724     * Returns the focus-change callback registered for this view.
3725     *
3726     * @return The callback, or null if one is not registered.
3727     */
3728    public OnFocusChangeListener getOnFocusChangeListener() {
3729        ListenerInfo li = mListenerInfo;
3730        return li != null ? li.mOnFocusChangeListener : null;
3731    }
3732
3733    /**
3734     * Register a callback to be invoked when this view is clicked. If this view is not
3735     * clickable, it becomes clickable.
3736     *
3737     * @param l The callback that will run
3738     *
3739     * @see #setClickable(boolean)
3740     */
3741    public void setOnClickListener(OnClickListener l) {
3742        if (!isClickable()) {
3743            setClickable(true);
3744        }
3745        getListenerInfo().mOnClickListener = l;
3746    }
3747
3748    /**
3749     * Return whether this view has an attached OnClickListener.  Returns
3750     * true if there is a listener, false if there is none.
3751     */
3752    public boolean hasOnClickListeners() {
3753        ListenerInfo li = mListenerInfo;
3754        return (li != null && li.mOnClickListener != null);
3755    }
3756
3757    /**
3758     * Register a callback to be invoked when this view is clicked and held. If this view is not
3759     * long clickable, it becomes long clickable.
3760     *
3761     * @param l The callback that will run
3762     *
3763     * @see #setLongClickable(boolean)
3764     */
3765    public void setOnLongClickListener(OnLongClickListener l) {
3766        if (!isLongClickable()) {
3767            setLongClickable(true);
3768        }
3769        getListenerInfo().mOnLongClickListener = l;
3770    }
3771
3772    /**
3773     * Register a callback to be invoked when the context menu for this view is
3774     * being built. If this view is not long clickable, it becomes long clickable.
3775     *
3776     * @param l The callback that will run
3777     *
3778     */
3779    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3780        if (!isLongClickable()) {
3781            setLongClickable(true);
3782        }
3783        getListenerInfo().mOnCreateContextMenuListener = l;
3784    }
3785
3786    /**
3787     * Call this view's OnClickListener, if it is defined.  Performs all normal
3788     * actions associated with clicking: reporting accessibility event, playing
3789     * a sound, etc.
3790     *
3791     * @return True there was an assigned OnClickListener that was called, false
3792     *         otherwise is returned.
3793     */
3794    public boolean performClick() {
3795        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3796
3797        ListenerInfo li = mListenerInfo;
3798        if (li != null && li.mOnClickListener != null) {
3799            playSoundEffect(SoundEffectConstants.CLICK);
3800            li.mOnClickListener.onClick(this);
3801            return true;
3802        }
3803
3804        return false;
3805    }
3806
3807    /**
3808     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3809     * this only calls the listener, and does not do any associated clicking
3810     * actions like reporting an accessibility event.
3811     *
3812     * @return True there was an assigned OnClickListener that was called, false
3813     *         otherwise is returned.
3814     */
3815    public boolean callOnClick() {
3816        ListenerInfo li = mListenerInfo;
3817        if (li != null && li.mOnClickListener != null) {
3818            li.mOnClickListener.onClick(this);
3819            return true;
3820        }
3821        return false;
3822    }
3823
3824    /**
3825     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3826     * OnLongClickListener did not consume the event.
3827     *
3828     * @return True if one of the above receivers consumed the event, false otherwise.
3829     */
3830    public boolean performLongClick() {
3831        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3832
3833        boolean handled = false;
3834        ListenerInfo li = mListenerInfo;
3835        if (li != null && li.mOnLongClickListener != null) {
3836            handled = li.mOnLongClickListener.onLongClick(View.this);
3837        }
3838        if (!handled) {
3839            handled = showContextMenu();
3840        }
3841        if (handled) {
3842            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3843        }
3844        return handled;
3845    }
3846
3847    /**
3848     * Performs button-related actions during a touch down event.
3849     *
3850     * @param event The event.
3851     * @return True if the down was consumed.
3852     *
3853     * @hide
3854     */
3855    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3856        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3857            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3858                return true;
3859            }
3860        }
3861        return false;
3862    }
3863
3864    /**
3865     * Bring up the context menu for this view.
3866     *
3867     * @return Whether a context menu was displayed.
3868     */
3869    public boolean showContextMenu() {
3870        return getParent().showContextMenuForChild(this);
3871    }
3872
3873    /**
3874     * Bring up the context menu for this view, referring to the item under the specified point.
3875     *
3876     * @param x The referenced x coordinate.
3877     * @param y The referenced y coordinate.
3878     * @param metaState The keyboard modifiers that were pressed.
3879     * @return Whether a context menu was displayed.
3880     *
3881     * @hide
3882     */
3883    public boolean showContextMenu(float x, float y, int metaState) {
3884        return showContextMenu();
3885    }
3886
3887    /**
3888     * Start an action mode.
3889     *
3890     * @param callback Callback that will control the lifecycle of the action mode
3891     * @return The new action mode if it is started, null otherwise
3892     *
3893     * @see ActionMode
3894     */
3895    public ActionMode startActionMode(ActionMode.Callback callback) {
3896        ViewParent parent = getParent();
3897        if (parent == null) return null;
3898        return parent.startActionModeForChild(this, callback);
3899    }
3900
3901    /**
3902     * Register a callback to be invoked when a key is pressed in this view.
3903     * @param l the key listener to attach to this view
3904     */
3905    public void setOnKeyListener(OnKeyListener l) {
3906        getListenerInfo().mOnKeyListener = l;
3907    }
3908
3909    /**
3910     * Register a callback to be invoked when a touch event is sent to this view.
3911     * @param l the touch listener to attach to this view
3912     */
3913    public void setOnTouchListener(OnTouchListener l) {
3914        getListenerInfo().mOnTouchListener = l;
3915    }
3916
3917    /**
3918     * Register a callback to be invoked when a generic motion event is sent to this view.
3919     * @param l the generic motion listener to attach to this view
3920     */
3921    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3922        getListenerInfo().mOnGenericMotionListener = l;
3923    }
3924
3925    /**
3926     * Register a callback to be invoked when a hover event is sent to this view.
3927     * @param l the hover listener to attach to this view
3928     */
3929    public void setOnHoverListener(OnHoverListener l) {
3930        getListenerInfo().mOnHoverListener = l;
3931    }
3932
3933    /**
3934     * Register a drag event listener callback object for this View. The parameter is
3935     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3936     * View, the system calls the
3937     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3938     * @param l An implementation of {@link android.view.View.OnDragListener}.
3939     */
3940    public void setOnDragListener(OnDragListener l) {
3941        getListenerInfo().mOnDragListener = l;
3942    }
3943
3944    /**
3945     * Give this view focus. This will cause
3946     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3947     *
3948     * Note: this does not check whether this {@link View} should get focus, it just
3949     * gives it focus no matter what.  It should only be called internally by framework
3950     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3951     *
3952     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3953     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3954     *        focus moved when requestFocus() is called. It may not always
3955     *        apply, in which case use the default View.FOCUS_DOWN.
3956     * @param previouslyFocusedRect The rectangle of the view that had focus
3957     *        prior in this View's coordinate system.
3958     */
3959    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3960        if (DBG) {
3961            System.out.println(this + " requestFocus()");
3962        }
3963
3964        if ((mPrivateFlags & FOCUSED) == 0) {
3965            mPrivateFlags |= FOCUSED;
3966
3967            if (mParent != null) {
3968                mParent.requestChildFocus(this, this);
3969            }
3970
3971            onFocusChanged(true, direction, previouslyFocusedRect);
3972            refreshDrawableState();
3973        }
3974    }
3975
3976    /**
3977     * Request that a rectangle of this view be visible on the screen,
3978     * scrolling if necessary just enough.
3979     *
3980     * <p>A View should call this if it maintains some notion of which part
3981     * of its content is interesting.  For example, a text editing view
3982     * should call this when its cursor moves.
3983     *
3984     * @param rectangle The rectangle.
3985     * @return Whether any parent scrolled.
3986     */
3987    public boolean requestRectangleOnScreen(Rect rectangle) {
3988        return requestRectangleOnScreen(rectangle, false);
3989    }
3990
3991    /**
3992     * Request that a rectangle of this view be visible on the screen,
3993     * scrolling if necessary just enough.
3994     *
3995     * <p>A View should call this if it maintains some notion of which part
3996     * of its content is interesting.  For example, a text editing view
3997     * should call this when its cursor moves.
3998     *
3999     * <p>When <code>immediate</code> is set to true, scrolling will not be
4000     * animated.
4001     *
4002     * @param rectangle The rectangle.
4003     * @param immediate True to forbid animated scrolling, false otherwise
4004     * @return Whether any parent scrolled.
4005     */
4006    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4007        View child = this;
4008        ViewParent parent = mParent;
4009        boolean scrolled = false;
4010        while (parent != null) {
4011            scrolled |= parent.requestChildRectangleOnScreen(child,
4012                    rectangle, immediate);
4013
4014            // offset rect so next call has the rectangle in the
4015            // coordinate system of its direct child.
4016            rectangle.offset(child.getLeft(), child.getTop());
4017            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4018
4019            if (!(parent instanceof View)) {
4020                break;
4021            }
4022
4023            child = (View) parent;
4024            parent = child.getParent();
4025        }
4026        return scrolled;
4027    }
4028
4029    /**
4030     * Called when this view wants to give up focus. If focus is cleared
4031     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4032     * <p>
4033     * <strong>Note:</strong> When a View clears focus the framework is trying
4034     * to give focus to the first focusable View from the top. Hence, if this
4035     * View is the first from the top that can take focus, then all callbacks
4036     * related to clearing focus will be invoked after wich the framework will
4037     * give focus to this view.
4038     * </p>
4039     */
4040    public void clearFocus() {
4041        if (DBG) {
4042            System.out.println(this + " clearFocus()");
4043        }
4044
4045        if ((mPrivateFlags & FOCUSED) != 0) {
4046            mPrivateFlags &= ~FOCUSED;
4047
4048            if (mParent != null) {
4049                mParent.clearChildFocus(this);
4050            }
4051
4052            onFocusChanged(false, 0, null);
4053            refreshDrawableState();
4054
4055            ensureInputFocusOnFirstFocusable();
4056        }
4057    }
4058
4059    void ensureInputFocusOnFirstFocusable() {
4060        View root = getRootView();
4061        if (root != null) {
4062            root.requestFocus(FOCUS_FORWARD);
4063        }
4064    }
4065
4066    /**
4067     * Called internally by the view system when a new view is getting focus.
4068     * This is what clears the old focus.
4069     */
4070    void unFocus() {
4071        if (DBG) {
4072            System.out.println(this + " unFocus()");
4073        }
4074
4075        if ((mPrivateFlags & FOCUSED) != 0) {
4076            mPrivateFlags &= ~FOCUSED;
4077
4078            onFocusChanged(false, 0, null);
4079            refreshDrawableState();
4080        }
4081    }
4082
4083    /**
4084     * Returns true if this view has focus iteself, or is the ancestor of the
4085     * view that has focus.
4086     *
4087     * @return True if this view has or contains focus, false otherwise.
4088     */
4089    @ViewDebug.ExportedProperty(category = "focus")
4090    public boolean hasFocus() {
4091        return (mPrivateFlags & FOCUSED) != 0;
4092    }
4093
4094    /**
4095     * Returns true if this view is focusable or if it contains a reachable View
4096     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4097     * is a View whose parents do not block descendants focus.
4098     *
4099     * Only {@link #VISIBLE} views are considered focusable.
4100     *
4101     * @return True if the view is focusable or if the view contains a focusable
4102     *         View, false otherwise.
4103     *
4104     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4105     */
4106    public boolean hasFocusable() {
4107        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4108    }
4109
4110    /**
4111     * Called by the view system when the focus state of this view changes.
4112     * When the focus change event is caused by directional navigation, direction
4113     * and previouslyFocusedRect provide insight into where the focus is coming from.
4114     * When overriding, be sure to call up through to the super class so that
4115     * the standard focus handling will occur.
4116     *
4117     * @param gainFocus True if the View has focus; false otherwise.
4118     * @param direction The direction focus has moved when requestFocus()
4119     *                  is called to give this view focus. Values are
4120     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4121     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4122     *                  It may not always apply, in which case use the default.
4123     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4124     *        system, of the previously focused view.  If applicable, this will be
4125     *        passed in as finer grained information about where the focus is coming
4126     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4127     */
4128    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4129        if (gainFocus) {
4130            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4131        }
4132
4133        InputMethodManager imm = InputMethodManager.peekInstance();
4134        if (!gainFocus) {
4135            if (isPressed()) {
4136                setPressed(false);
4137            }
4138            if (imm != null && mAttachInfo != null
4139                    && mAttachInfo.mHasWindowFocus) {
4140                imm.focusOut(this);
4141            }
4142            onFocusLost();
4143        } else if (imm != null && mAttachInfo != null
4144                && mAttachInfo.mHasWindowFocus) {
4145            imm.focusIn(this);
4146        }
4147
4148        invalidate(true);
4149        ListenerInfo li = mListenerInfo;
4150        if (li != null && li.mOnFocusChangeListener != null) {
4151            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4152        }
4153
4154        if (mAttachInfo != null) {
4155            mAttachInfo.mKeyDispatchState.reset(this);
4156        }
4157    }
4158
4159    /**
4160     * Sends an accessibility event of the given type. If accessiiblity is
4161     * not enabled this method has no effect. The default implementation calls
4162     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4163     * to populate information about the event source (this View), then calls
4164     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4165     * populate the text content of the event source including its descendants,
4166     * and last calls
4167     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4168     * on its parent to resuest sending of the event to interested parties.
4169     * <p>
4170     * If an {@link AccessibilityDelegate} has been specified via calling
4171     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4172     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4173     * responsible for handling this call.
4174     * </p>
4175     *
4176     * @param eventType The type of the event to send, as defined by several types from
4177     * {@link android.view.accessibility.AccessibilityEvent}, such as
4178     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4179     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4180     *
4181     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4182     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4183     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4184     * @see AccessibilityDelegate
4185     */
4186    public void sendAccessibilityEvent(int eventType) {
4187        if (mAccessibilityDelegate != null) {
4188            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4189        } else {
4190            sendAccessibilityEventInternal(eventType);
4191        }
4192    }
4193
4194    /**
4195     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4196     * {@link AccessibilityEvent} to make an announcement which is related to some
4197     * sort of a context change for which none of the events representing UI transitions
4198     * is a good fit. For example, announcing a new page in a book. If accessibility
4199     * is not enabled this method does nothing.
4200     *
4201     * @param text The announcement text.
4202     */
4203    public void announceForAccessibility(CharSequence text) {
4204        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4205            AccessibilityEvent event = AccessibilityEvent.obtain(
4206                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4207            event.getText().add(text);
4208            sendAccessibilityEventUnchecked(event);
4209        }
4210    }
4211
4212    /**
4213     * @see #sendAccessibilityEvent(int)
4214     *
4215     * Note: Called from the default {@link AccessibilityDelegate}.
4216     */
4217    void sendAccessibilityEventInternal(int eventType) {
4218        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4219            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4220        }
4221    }
4222
4223    /**
4224     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4225     * takes as an argument an empty {@link AccessibilityEvent} and does not
4226     * perform a check whether accessibility is enabled.
4227     * <p>
4228     * If an {@link AccessibilityDelegate} has been specified via calling
4229     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4230     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4231     * is responsible for handling this call.
4232     * </p>
4233     *
4234     * @param event The event to send.
4235     *
4236     * @see #sendAccessibilityEvent(int)
4237     */
4238    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4239        if (mAccessibilityDelegate != null) {
4240           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4241        } else {
4242            sendAccessibilityEventUncheckedInternal(event);
4243        }
4244    }
4245
4246    /**
4247     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4248     *
4249     * Note: Called from the default {@link AccessibilityDelegate}.
4250     */
4251    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4252        if (!isShown()) {
4253            return;
4254        }
4255        onInitializeAccessibilityEvent(event);
4256        // Only a subset of accessibility events populates text content.
4257        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4258            dispatchPopulateAccessibilityEvent(event);
4259        }
4260        // In the beginning we called #isShown(), so we know that getParent() is not null.
4261        getParent().requestSendAccessibilityEvent(this, event);
4262    }
4263
4264    /**
4265     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4266     * to its children for adding their text content to the event. Note that the
4267     * event text is populated in a separate dispatch path since we add to the
4268     * event not only the text of the source but also the text of all its descendants.
4269     * A typical implementation will call
4270     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4271     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4272     * on each child. Override this method if custom population of the event text
4273     * content is required.
4274     * <p>
4275     * If an {@link AccessibilityDelegate} has been specified via calling
4276     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4277     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4278     * is responsible for handling this call.
4279     * </p>
4280     * <p>
4281     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4282     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4283     * </p>
4284     *
4285     * @param event The event.
4286     *
4287     * @return True if the event population was completed.
4288     */
4289    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4290        if (mAccessibilityDelegate != null) {
4291            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4292        } else {
4293            return dispatchPopulateAccessibilityEventInternal(event);
4294        }
4295    }
4296
4297    /**
4298     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4299     *
4300     * Note: Called from the default {@link AccessibilityDelegate}.
4301     */
4302    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4303        onPopulateAccessibilityEvent(event);
4304        return false;
4305    }
4306
4307    /**
4308     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4309     * giving a chance to this View to populate the accessibility event with its
4310     * text content. While this method is free to modify event
4311     * attributes other than text content, doing so should normally be performed in
4312     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4313     * <p>
4314     * Example: Adding formatted date string to an accessibility event in addition
4315     *          to the text added by the super implementation:
4316     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4317     *     super.onPopulateAccessibilityEvent(event);
4318     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4319     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4320     *         mCurrentDate.getTimeInMillis(), flags);
4321     *     event.getText().add(selectedDateUtterance);
4322     * }</pre>
4323     * <p>
4324     * If an {@link AccessibilityDelegate} has been specified via calling
4325     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4326     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4327     * is responsible for handling this call.
4328     * </p>
4329     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4330     * information to the event, in case the default implementation has basic information to add.
4331     * </p>
4332     *
4333     * @param event The accessibility event which to populate.
4334     *
4335     * @see #sendAccessibilityEvent(int)
4336     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4337     */
4338    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4339        if (mAccessibilityDelegate != null) {
4340            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4341        } else {
4342            onPopulateAccessibilityEventInternal(event);
4343        }
4344    }
4345
4346    /**
4347     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4348     *
4349     * Note: Called from the default {@link AccessibilityDelegate}.
4350     */
4351    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4352
4353    }
4354
4355    /**
4356     * Initializes an {@link AccessibilityEvent} with information about
4357     * this View which is the event source. In other words, the source of
4358     * an accessibility event is the view whose state change triggered firing
4359     * the event.
4360     * <p>
4361     * Example: Setting the password property of an event in addition
4362     *          to properties set by the super implementation:
4363     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4364     *     super.onInitializeAccessibilityEvent(event);
4365     *     event.setPassword(true);
4366     * }</pre>
4367     * <p>
4368     * If an {@link AccessibilityDelegate} has been specified via calling
4369     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4370     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4371     * is responsible for handling this call.
4372     * </p>
4373     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4374     * information to the event, in case the default implementation has basic information to add.
4375     * </p>
4376     * @param event The event to initialize.
4377     *
4378     * @see #sendAccessibilityEvent(int)
4379     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4380     */
4381    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4382        if (mAccessibilityDelegate != null) {
4383            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4384        } else {
4385            onInitializeAccessibilityEventInternal(event);
4386        }
4387    }
4388
4389    /**
4390     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4391     *
4392     * Note: Called from the default {@link AccessibilityDelegate}.
4393     */
4394    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4395        event.setSource(this);
4396        event.setClassName(View.class.getName());
4397        event.setPackageName(getContext().getPackageName());
4398        event.setEnabled(isEnabled());
4399        event.setContentDescription(mContentDescription);
4400
4401        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4402            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4403            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4404                    FOCUSABLES_ALL);
4405            event.setItemCount(focusablesTempList.size());
4406            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4407            focusablesTempList.clear();
4408        }
4409    }
4410
4411    /**
4412     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4413     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4414     * This method is responsible for obtaining an accessibility node info from a
4415     * pool of reusable instances and calling
4416     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4417     * initialize the former.
4418     * <p>
4419     * Note: The client is responsible for recycling the obtained instance by calling
4420     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4421     * </p>
4422     *
4423     * @return A populated {@link AccessibilityNodeInfo}.
4424     *
4425     * @see AccessibilityNodeInfo
4426     */
4427    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4428        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4429        if (provider != null) {
4430            return provider.createAccessibilityNodeInfo(View.NO_ID);
4431        } else {
4432            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4433            onInitializeAccessibilityNodeInfo(info);
4434            return info;
4435        }
4436    }
4437
4438    /**
4439     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4440     * The base implementation sets:
4441     * <ul>
4442     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4443     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4444     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4445     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4446     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4447     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4448     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4449     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4450     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4451     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4452     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4453     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4454     * </ul>
4455     * <p>
4456     * Subclasses should override this method, call the super implementation,
4457     * and set additional attributes.
4458     * </p>
4459     * <p>
4460     * If an {@link AccessibilityDelegate} has been specified via calling
4461     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4462     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4463     * is responsible for handling this call.
4464     * </p>
4465     *
4466     * @param info The instance to initialize.
4467     */
4468    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4469        if (mAccessibilityDelegate != null) {
4470            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4471        } else {
4472            onInitializeAccessibilityNodeInfoInternal(info);
4473        }
4474    }
4475
4476    /**
4477     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4478     *
4479     * Note: Called from the default {@link AccessibilityDelegate}.
4480     */
4481    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4482        Rect bounds = mAttachInfo.mTmpInvalRect;
4483        getDrawingRect(bounds);
4484        info.setBoundsInParent(bounds);
4485
4486        getGlobalVisibleRect(bounds);
4487        bounds.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4488        info.setBoundsInScreen(bounds);
4489
4490        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4491            ViewParent parent = getParent();
4492            if (parent instanceof View) {
4493                View parentView = (View) parent;
4494                info.setParent(parentView);
4495            }
4496        }
4497
4498        info.setPackageName(mContext.getPackageName());
4499        info.setClassName(View.class.getName());
4500        info.setContentDescription(getContentDescription());
4501
4502        info.setEnabled(isEnabled());
4503        info.setClickable(isClickable());
4504        info.setFocusable(isFocusable());
4505        info.setFocused(isFocused());
4506        info.setSelected(isSelected());
4507        info.setLongClickable(isLongClickable());
4508
4509        // TODO: These make sense only if we are in an AdapterView but all
4510        // views can be selected. Maybe from accessiiblity perspective
4511        // we should report as selectable view in an AdapterView.
4512        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4513        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4514
4515        if (isFocusable()) {
4516            if (isFocused()) {
4517                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4518            } else {
4519                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4520            }
4521        }
4522    }
4523
4524    /**
4525     * Sets a delegate for implementing accessibility support via compositon as
4526     * opposed to inheritance. The delegate's primary use is for implementing
4527     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4528     *
4529     * @param delegate The delegate instance.
4530     *
4531     * @see AccessibilityDelegate
4532     */
4533    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4534        mAccessibilityDelegate = delegate;
4535    }
4536
4537    /**
4538     * Gets the provider for managing a virtual view hierarchy rooted at this View
4539     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4540     * that explore the window content.
4541     * <p>
4542     * If this method returns an instance, this instance is responsible for managing
4543     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4544     * View including the one representing the View itself. Similarly the returned
4545     * instance is responsible for performing accessibility actions on any virtual
4546     * view or the root view itself.
4547     * </p>
4548     * <p>
4549     * If an {@link AccessibilityDelegate} has been specified via calling
4550     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4551     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4552     * is responsible for handling this call.
4553     * </p>
4554     *
4555     * @return The provider.
4556     *
4557     * @see AccessibilityNodeProvider
4558     */
4559    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4560        if (mAccessibilityDelegate != null) {
4561            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4562        } else {
4563            return null;
4564        }
4565    }
4566
4567    /**
4568     * Gets the unique identifier of this view on the screen for accessibility purposes.
4569     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4570     *
4571     * @return The view accessibility id.
4572     *
4573     * @hide
4574     */
4575    public int getAccessibilityViewId() {
4576        if (mAccessibilityViewId == NO_ID) {
4577            mAccessibilityViewId = sNextAccessibilityViewId++;
4578        }
4579        return mAccessibilityViewId;
4580    }
4581
4582    /**
4583     * Gets the unique identifier of the window in which this View reseides.
4584     *
4585     * @return The window accessibility id.
4586     *
4587     * @hide
4588     */
4589    public int getAccessibilityWindowId() {
4590        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4591    }
4592
4593    /**
4594     * Gets the {@link View} description. It briefly describes the view and is
4595     * primarily used for accessibility support. Set this property to enable
4596     * better accessibility support for your application. This is especially
4597     * true for views that do not have textual representation (For example,
4598     * ImageButton).
4599     *
4600     * @return The content descriptiopn.
4601     *
4602     * @attr ref android.R.styleable#View_contentDescription
4603     */
4604    public CharSequence getContentDescription() {
4605        return mContentDescription;
4606    }
4607
4608    /**
4609     * Sets the {@link View} description. It briefly describes the view and is
4610     * primarily used for accessibility support. Set this property to enable
4611     * better accessibility support for your application. This is especially
4612     * true for views that do not have textual representation (For example,
4613     * ImageButton).
4614     *
4615     * @param contentDescription The content description.
4616     *
4617     * @attr ref android.R.styleable#View_contentDescription
4618     */
4619    @RemotableViewMethod
4620    public void setContentDescription(CharSequence contentDescription) {
4621        mContentDescription = contentDescription;
4622    }
4623
4624    /**
4625     * Invoked whenever this view loses focus, either by losing window focus or by losing
4626     * focus within its window. This method can be used to clear any state tied to the
4627     * focus. For instance, if a button is held pressed with the trackball and the window
4628     * loses focus, this method can be used to cancel the press.
4629     *
4630     * Subclasses of View overriding this method should always call super.onFocusLost().
4631     *
4632     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4633     * @see #onWindowFocusChanged(boolean)
4634     *
4635     * @hide pending API council approval
4636     */
4637    protected void onFocusLost() {
4638        resetPressedState();
4639    }
4640
4641    private void resetPressedState() {
4642        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4643            return;
4644        }
4645
4646        if (isPressed()) {
4647            setPressed(false);
4648
4649            if (!mHasPerformedLongPress) {
4650                removeLongPressCallback();
4651            }
4652        }
4653    }
4654
4655    /**
4656     * Returns true if this view has focus
4657     *
4658     * @return True if this view has focus, false otherwise.
4659     */
4660    @ViewDebug.ExportedProperty(category = "focus")
4661    public boolean isFocused() {
4662        return (mPrivateFlags & FOCUSED) != 0;
4663    }
4664
4665    /**
4666     * Find the view in the hierarchy rooted at this view that currently has
4667     * focus.
4668     *
4669     * @return The view that currently has focus, or null if no focused view can
4670     *         be found.
4671     */
4672    public View findFocus() {
4673        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4674    }
4675
4676    /**
4677     * Indicates whether this view is one of the set of scrollable containers in
4678     * its window.
4679     *
4680     * @return whether this view is one of the set of scrollable containers in
4681     * its window
4682     *
4683     * @attr ref android.R.styleable#View_isScrollContainer
4684     */
4685    public boolean isScrollContainer() {
4686        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4687    }
4688
4689    /**
4690     * Change whether this view is one of the set of scrollable containers in
4691     * its window.  This will be used to determine whether the window can
4692     * resize or must pan when a soft input area is open -- scrollable
4693     * containers allow the window to use resize mode since the container
4694     * will appropriately shrink.
4695     *
4696     * @attr ref android.R.styleable#View_isScrollContainer
4697     */
4698    public void setScrollContainer(boolean isScrollContainer) {
4699        if (isScrollContainer) {
4700            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4701                mAttachInfo.mScrollContainers.add(this);
4702                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4703            }
4704            mPrivateFlags |= SCROLL_CONTAINER;
4705        } else {
4706            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4707                mAttachInfo.mScrollContainers.remove(this);
4708            }
4709            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4710        }
4711    }
4712
4713    /**
4714     * Returns the quality of the drawing cache.
4715     *
4716     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4717     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4718     *
4719     * @see #setDrawingCacheQuality(int)
4720     * @see #setDrawingCacheEnabled(boolean)
4721     * @see #isDrawingCacheEnabled()
4722     *
4723     * @attr ref android.R.styleable#View_drawingCacheQuality
4724     */
4725    public int getDrawingCacheQuality() {
4726        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4727    }
4728
4729    /**
4730     * Set the drawing cache quality of this view. This value is used only when the
4731     * drawing cache is enabled
4732     *
4733     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4734     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4735     *
4736     * @see #getDrawingCacheQuality()
4737     * @see #setDrawingCacheEnabled(boolean)
4738     * @see #isDrawingCacheEnabled()
4739     *
4740     * @attr ref android.R.styleable#View_drawingCacheQuality
4741     */
4742    public void setDrawingCacheQuality(int quality) {
4743        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4744    }
4745
4746    /**
4747     * Returns whether the screen should remain on, corresponding to the current
4748     * value of {@link #KEEP_SCREEN_ON}.
4749     *
4750     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4751     *
4752     * @see #setKeepScreenOn(boolean)
4753     *
4754     * @attr ref android.R.styleable#View_keepScreenOn
4755     */
4756    public boolean getKeepScreenOn() {
4757        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4758    }
4759
4760    /**
4761     * Controls whether the screen should remain on, modifying the
4762     * value of {@link #KEEP_SCREEN_ON}.
4763     *
4764     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4765     *
4766     * @see #getKeepScreenOn()
4767     *
4768     * @attr ref android.R.styleable#View_keepScreenOn
4769     */
4770    public void setKeepScreenOn(boolean keepScreenOn) {
4771        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4772    }
4773
4774    /**
4775     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4776     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4777     *
4778     * @attr ref android.R.styleable#View_nextFocusLeft
4779     */
4780    public int getNextFocusLeftId() {
4781        return mNextFocusLeftId;
4782    }
4783
4784    /**
4785     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4786     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4787     * decide automatically.
4788     *
4789     * @attr ref android.R.styleable#View_nextFocusLeft
4790     */
4791    public void setNextFocusLeftId(int nextFocusLeftId) {
4792        mNextFocusLeftId = nextFocusLeftId;
4793    }
4794
4795    /**
4796     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4797     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4798     *
4799     * @attr ref android.R.styleable#View_nextFocusRight
4800     */
4801    public int getNextFocusRightId() {
4802        return mNextFocusRightId;
4803    }
4804
4805    /**
4806     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4807     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4808     * decide automatically.
4809     *
4810     * @attr ref android.R.styleable#View_nextFocusRight
4811     */
4812    public void setNextFocusRightId(int nextFocusRightId) {
4813        mNextFocusRightId = nextFocusRightId;
4814    }
4815
4816    /**
4817     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4818     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4819     *
4820     * @attr ref android.R.styleable#View_nextFocusUp
4821     */
4822    public int getNextFocusUpId() {
4823        return mNextFocusUpId;
4824    }
4825
4826    /**
4827     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4828     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4829     * decide automatically.
4830     *
4831     * @attr ref android.R.styleable#View_nextFocusUp
4832     */
4833    public void setNextFocusUpId(int nextFocusUpId) {
4834        mNextFocusUpId = nextFocusUpId;
4835    }
4836
4837    /**
4838     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4839     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4840     *
4841     * @attr ref android.R.styleable#View_nextFocusDown
4842     */
4843    public int getNextFocusDownId() {
4844        return mNextFocusDownId;
4845    }
4846
4847    /**
4848     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4849     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4850     * decide automatically.
4851     *
4852     * @attr ref android.R.styleable#View_nextFocusDown
4853     */
4854    public void setNextFocusDownId(int nextFocusDownId) {
4855        mNextFocusDownId = nextFocusDownId;
4856    }
4857
4858    /**
4859     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4860     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4861     *
4862     * @attr ref android.R.styleable#View_nextFocusForward
4863     */
4864    public int getNextFocusForwardId() {
4865        return mNextFocusForwardId;
4866    }
4867
4868    /**
4869     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4870     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4871     * decide automatically.
4872     *
4873     * @attr ref android.R.styleable#View_nextFocusForward
4874     */
4875    public void setNextFocusForwardId(int nextFocusForwardId) {
4876        mNextFocusForwardId = nextFocusForwardId;
4877    }
4878
4879    /**
4880     * Returns the visibility of this view and all of its ancestors
4881     *
4882     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4883     */
4884    public boolean isShown() {
4885        View current = this;
4886        //noinspection ConstantConditions
4887        do {
4888            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4889                return false;
4890            }
4891            ViewParent parent = current.mParent;
4892            if (parent == null) {
4893                return false; // We are not attached to the view root
4894            }
4895            if (!(parent instanceof View)) {
4896                return true;
4897            }
4898            current = (View) parent;
4899        } while (current != null);
4900
4901        return false;
4902    }
4903
4904    /**
4905     * Called by the view hierarchy when the content insets for a window have
4906     * changed, to allow it to adjust its content to fit within those windows.
4907     * The content insets tell you the space that the status bar, input method,
4908     * and other system windows infringe on the application's window.
4909     *
4910     * <p>You do not normally need to deal with this function, since the default
4911     * window decoration given to applications takes care of applying it to the
4912     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
4913     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
4914     * and your content can be placed under those system elements.  You can then
4915     * use this method within your view hierarchy if you have parts of your UI
4916     * which you would like to ensure are not being covered.
4917     *
4918     * <p>The default implementation of this method simply applies the content
4919     * inset's to the view's padding.  This can be enabled through
4920     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
4921     * the method and handle the insets however you would like.  Note that the
4922     * insets provided by the framework are always relative to the far edges
4923     * of the window, not accounting for the location of the called view within
4924     * that window.  (In fact when this method is called you do not yet know
4925     * where the layout will place the view, as it is done before layout happens.)
4926     *
4927     * <p>Note: unlike many View methods, there is no dispatch phase to this
4928     * call.  If you are overriding it in a ViewGroup and want to allow the
4929     * call to continue to your children, you must be sure to call the super
4930     * implementation.
4931     *
4932     * @param insets Current content insets of the window.  Prior to
4933     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
4934     * the insets or else you and Android will be unhappy.
4935     *
4936     * @return Return true if this view applied the insets and it should not
4937     * continue propagating further down the hierarchy, false otherwise.
4938     */
4939    protected boolean fitSystemWindows(Rect insets) {
4940        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4941            mUserPaddingStart = -1;
4942            mUserPaddingEnd = -1;
4943            mUserPaddingRelative = false;
4944            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
4945                    || mAttachInfo == null
4946                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
4947                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
4948                return true;
4949            } else {
4950                internalSetPadding(0, 0, 0, 0);
4951                return false;
4952            }
4953        }
4954        return false;
4955    }
4956
4957    /**
4958     * Set whether or not this view should account for system screen decorations
4959     * such as the status bar and inset its content. This allows this view to be
4960     * positioned in absolute screen coordinates and remain visible to the user.
4961     *
4962     * <p>This should only be used by top-level window decor views.
4963     *
4964     * @param fitSystemWindows true to inset content for system screen decorations, false for
4965     *                         default behavior.
4966     *
4967     * @attr ref android.R.styleable#View_fitsSystemWindows
4968     */
4969    public void setFitsSystemWindows(boolean fitSystemWindows) {
4970        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4971    }
4972
4973    /**
4974     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4975     * will account for system screen decorations such as the status bar and inset its
4976     * content. This allows the view to be positioned in absolute screen coordinates
4977     * and remain visible to the user.
4978     *
4979     * @return true if this view will adjust its content bounds for system screen decorations.
4980     *
4981     * @attr ref android.R.styleable#View_fitsSystemWindows
4982     */
4983    public boolean fitsSystemWindows() {
4984        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4985    }
4986
4987    /**
4988     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
4989     */
4990    public void requestFitSystemWindows() {
4991        if (mParent != null) {
4992            mParent.requestFitSystemWindows();
4993        }
4994    }
4995
4996    /**
4997     * For use by PhoneWindow to make its own system window fitting optional.
4998     * @hide
4999     */
5000    public void makeOptionalFitsSystemWindows() {
5001        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5002    }
5003
5004    /**
5005     * Returns the visibility status for this view.
5006     *
5007     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5008     * @attr ref android.R.styleable#View_visibility
5009     */
5010    @ViewDebug.ExportedProperty(mapping = {
5011        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5012        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5013        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5014    })
5015    public int getVisibility() {
5016        return mViewFlags & VISIBILITY_MASK;
5017    }
5018
5019    /**
5020     * Set the enabled state of this view.
5021     *
5022     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5023     * @attr ref android.R.styleable#View_visibility
5024     */
5025    @RemotableViewMethod
5026    public void setVisibility(int visibility) {
5027        setFlags(visibility, VISIBILITY_MASK);
5028        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5029    }
5030
5031    /**
5032     * Returns the enabled status for this view. The interpretation of the
5033     * enabled state varies by subclass.
5034     *
5035     * @return True if this view is enabled, false otherwise.
5036     */
5037    @ViewDebug.ExportedProperty
5038    public boolean isEnabled() {
5039        return (mViewFlags & ENABLED_MASK) == ENABLED;
5040    }
5041
5042    /**
5043     * Set the enabled state of this view. The interpretation of the enabled
5044     * state varies by subclass.
5045     *
5046     * @param enabled True if this view is enabled, false otherwise.
5047     */
5048    @RemotableViewMethod
5049    public void setEnabled(boolean enabled) {
5050        if (enabled == isEnabled()) return;
5051
5052        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5053
5054        /*
5055         * The View most likely has to change its appearance, so refresh
5056         * the drawable state.
5057         */
5058        refreshDrawableState();
5059
5060        // Invalidate too, since the default behavior for views is to be
5061        // be drawn at 50% alpha rather than to change the drawable.
5062        invalidate(true);
5063    }
5064
5065    /**
5066     * Set whether this view can receive the focus.
5067     *
5068     * Setting this to false will also ensure that this view is not focusable
5069     * in touch mode.
5070     *
5071     * @param focusable If true, this view can receive the focus.
5072     *
5073     * @see #setFocusableInTouchMode(boolean)
5074     * @attr ref android.R.styleable#View_focusable
5075     */
5076    public void setFocusable(boolean focusable) {
5077        if (!focusable) {
5078            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5079        }
5080        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5081    }
5082
5083    /**
5084     * Set whether this view can receive focus while in touch mode.
5085     *
5086     * Setting this to true will also ensure that this view is focusable.
5087     *
5088     * @param focusableInTouchMode If true, this view can receive the focus while
5089     *   in touch mode.
5090     *
5091     * @see #setFocusable(boolean)
5092     * @attr ref android.R.styleable#View_focusableInTouchMode
5093     */
5094    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5095        // Focusable in touch mode should always be set before the focusable flag
5096        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5097        // which, in touch mode, will not successfully request focus on this view
5098        // because the focusable in touch mode flag is not set
5099        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5100        if (focusableInTouchMode) {
5101            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5102        }
5103    }
5104
5105    /**
5106     * Set whether this view should have sound effects enabled for events such as
5107     * clicking and touching.
5108     *
5109     * <p>You may wish to disable sound effects for a view if you already play sounds,
5110     * for instance, a dial key that plays dtmf tones.
5111     *
5112     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5113     * @see #isSoundEffectsEnabled()
5114     * @see #playSoundEffect(int)
5115     * @attr ref android.R.styleable#View_soundEffectsEnabled
5116     */
5117    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5118        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5119    }
5120
5121    /**
5122     * @return whether this view should have sound effects enabled for events such as
5123     *     clicking and touching.
5124     *
5125     * @see #setSoundEffectsEnabled(boolean)
5126     * @see #playSoundEffect(int)
5127     * @attr ref android.R.styleable#View_soundEffectsEnabled
5128     */
5129    @ViewDebug.ExportedProperty
5130    public boolean isSoundEffectsEnabled() {
5131        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5132    }
5133
5134    /**
5135     * Set whether this view should have haptic feedback for events such as
5136     * long presses.
5137     *
5138     * <p>You may wish to disable haptic feedback if your view already controls
5139     * its own haptic feedback.
5140     *
5141     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5142     * @see #isHapticFeedbackEnabled()
5143     * @see #performHapticFeedback(int)
5144     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5145     */
5146    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5147        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5148    }
5149
5150    /**
5151     * @return whether this view should have haptic feedback enabled for events
5152     * long presses.
5153     *
5154     * @see #setHapticFeedbackEnabled(boolean)
5155     * @see #performHapticFeedback(int)
5156     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5157     */
5158    @ViewDebug.ExportedProperty
5159    public boolean isHapticFeedbackEnabled() {
5160        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5161    }
5162
5163    /**
5164     * Returns the layout direction for this view.
5165     *
5166     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5167     *   {@link #LAYOUT_DIRECTION_RTL},
5168     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5169     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5170     * @attr ref android.R.styleable#View_layoutDirection
5171     */
5172    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5173        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5174        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5175        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5176        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5177    })
5178    public int getLayoutDirection() {
5179        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5180    }
5181
5182    /**
5183     * Set the layout direction for this view. This will propagate a reset of layout direction
5184     * resolution to the view's children and resolve layout direction for this view.
5185     *
5186     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5187     *   {@link #LAYOUT_DIRECTION_RTL},
5188     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5189     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5190     *
5191     * @attr ref android.R.styleable#View_layoutDirection
5192     */
5193    @RemotableViewMethod
5194    public void setLayoutDirection(int layoutDirection) {
5195        if (getLayoutDirection() != layoutDirection) {
5196            // Reset the current layout direction and the resolved one
5197            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5198            resetResolvedLayoutDirection();
5199            // Set the new layout direction (filtered) and ask for a layout pass
5200            mPrivateFlags2 |=
5201                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5202            requestLayout();
5203        }
5204    }
5205
5206    /**
5207     * Returns the resolved layout direction for this view.
5208     *
5209     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5210     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5211     */
5212    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5213        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5214        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5215    })
5216    public int getResolvedLayoutDirection() {
5217        // The layout diretion will be resolved only if needed
5218        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5219            resolveLayoutDirection();
5220        }
5221        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5222                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5223    }
5224
5225    /**
5226     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5227     * layout attribute and/or the inherited value from the parent
5228     *
5229     * @return true if the layout is right-to-left.
5230     */
5231    @ViewDebug.ExportedProperty(category = "layout")
5232    public boolean isLayoutRtl() {
5233        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5234    }
5235
5236    /**
5237     * Indicates whether the view is currently tracking transient state that the
5238     * app should not need to concern itself with saving and restoring, but that
5239     * the framework should take special note to preserve when possible.
5240     *
5241     * @return true if the view has transient state
5242     */
5243    @ViewDebug.ExportedProperty(category = "layout")
5244    public boolean hasTransientState() {
5245        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5246    }
5247
5248    /**
5249     * Set whether this view is currently tracking transient state that the
5250     * framework should attempt to preserve when possible.
5251     *
5252     * @param hasTransientState true if this view has transient state
5253     */
5254    public void setHasTransientState(boolean hasTransientState) {
5255        if (hasTransientState() == hasTransientState) return;
5256
5257        mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5258                (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5259        if (mParent != null) {
5260            try {
5261                mParent.childHasTransientStateChanged(this, hasTransientState);
5262            } catch (AbstractMethodError e) {
5263                Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5264                        " does not fully implement ViewParent", e);
5265            }
5266        }
5267    }
5268
5269    /**
5270     * If this view doesn't do any drawing on its own, set this flag to
5271     * allow further optimizations. By default, this flag is not set on
5272     * View, but could be set on some View subclasses such as ViewGroup.
5273     *
5274     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5275     * you should clear this flag.
5276     *
5277     * @param willNotDraw whether or not this View draw on its own
5278     */
5279    public void setWillNotDraw(boolean willNotDraw) {
5280        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5281    }
5282
5283    /**
5284     * Returns whether or not this View draws on its own.
5285     *
5286     * @return true if this view has nothing to draw, false otherwise
5287     */
5288    @ViewDebug.ExportedProperty(category = "drawing")
5289    public boolean willNotDraw() {
5290        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5291    }
5292
5293    /**
5294     * When a View's drawing cache is enabled, drawing is redirected to an
5295     * offscreen bitmap. Some views, like an ImageView, must be able to
5296     * bypass this mechanism if they already draw a single bitmap, to avoid
5297     * unnecessary usage of the memory.
5298     *
5299     * @param willNotCacheDrawing true if this view does not cache its
5300     *        drawing, false otherwise
5301     */
5302    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5303        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5304    }
5305
5306    /**
5307     * Returns whether or not this View can cache its drawing or not.
5308     *
5309     * @return true if this view does not cache its drawing, false otherwise
5310     */
5311    @ViewDebug.ExportedProperty(category = "drawing")
5312    public boolean willNotCacheDrawing() {
5313        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5314    }
5315
5316    /**
5317     * Indicates whether this view reacts to click events or not.
5318     *
5319     * @return true if the view is clickable, false otherwise
5320     *
5321     * @see #setClickable(boolean)
5322     * @attr ref android.R.styleable#View_clickable
5323     */
5324    @ViewDebug.ExportedProperty
5325    public boolean isClickable() {
5326        return (mViewFlags & CLICKABLE) == CLICKABLE;
5327    }
5328
5329    /**
5330     * Enables or disables click events for this view. When a view
5331     * is clickable it will change its state to "pressed" on every click.
5332     * Subclasses should set the view clickable to visually react to
5333     * user's clicks.
5334     *
5335     * @param clickable true to make the view clickable, false otherwise
5336     *
5337     * @see #isClickable()
5338     * @attr ref android.R.styleable#View_clickable
5339     */
5340    public void setClickable(boolean clickable) {
5341        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5342    }
5343
5344    /**
5345     * Indicates whether this view reacts to long click events or not.
5346     *
5347     * @return true if the view is long clickable, false otherwise
5348     *
5349     * @see #setLongClickable(boolean)
5350     * @attr ref android.R.styleable#View_longClickable
5351     */
5352    public boolean isLongClickable() {
5353        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5354    }
5355
5356    /**
5357     * Enables or disables long click events for this view. When a view is long
5358     * clickable it reacts to the user holding down the button for a longer
5359     * duration than a tap. This event can either launch the listener or a
5360     * context menu.
5361     *
5362     * @param longClickable true to make the view long clickable, false otherwise
5363     * @see #isLongClickable()
5364     * @attr ref android.R.styleable#View_longClickable
5365     */
5366    public void setLongClickable(boolean longClickable) {
5367        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5368    }
5369
5370    /**
5371     * Sets the pressed state for this view.
5372     *
5373     * @see #isClickable()
5374     * @see #setClickable(boolean)
5375     *
5376     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5377     *        the View's internal state from a previously set "pressed" state.
5378     */
5379    public void setPressed(boolean pressed) {
5380        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5381
5382        if (pressed) {
5383            mPrivateFlags |= PRESSED;
5384        } else {
5385            mPrivateFlags &= ~PRESSED;
5386        }
5387
5388        if (needsRefresh) {
5389            refreshDrawableState();
5390        }
5391        dispatchSetPressed(pressed);
5392    }
5393
5394    /**
5395     * Dispatch setPressed to all of this View's children.
5396     *
5397     * @see #setPressed(boolean)
5398     *
5399     * @param pressed The new pressed state
5400     */
5401    protected void dispatchSetPressed(boolean pressed) {
5402    }
5403
5404    /**
5405     * Indicates whether the view is currently in pressed state. Unless
5406     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5407     * the pressed state.
5408     *
5409     * @see #setPressed(boolean)
5410     * @see #isClickable()
5411     * @see #setClickable(boolean)
5412     *
5413     * @return true if the view is currently pressed, false otherwise
5414     */
5415    public boolean isPressed() {
5416        return (mPrivateFlags & PRESSED) == PRESSED;
5417    }
5418
5419    /**
5420     * Indicates whether this view will save its state (that is,
5421     * whether its {@link #onSaveInstanceState} method will be called).
5422     *
5423     * @return Returns true if the view state saving is enabled, else false.
5424     *
5425     * @see #setSaveEnabled(boolean)
5426     * @attr ref android.R.styleable#View_saveEnabled
5427     */
5428    public boolean isSaveEnabled() {
5429        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5430    }
5431
5432    /**
5433     * Controls whether the saving of this view's state is
5434     * enabled (that is, whether its {@link #onSaveInstanceState} method
5435     * will be called).  Note that even if freezing is enabled, the
5436     * view still must have an id assigned to it (via {@link #setId(int)})
5437     * for its state to be saved.  This flag can only disable the
5438     * saving of this view; any child views may still have their state saved.
5439     *
5440     * @param enabled Set to false to <em>disable</em> state saving, or true
5441     * (the default) to allow it.
5442     *
5443     * @see #isSaveEnabled()
5444     * @see #setId(int)
5445     * @see #onSaveInstanceState()
5446     * @attr ref android.R.styleable#View_saveEnabled
5447     */
5448    public void setSaveEnabled(boolean enabled) {
5449        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5450    }
5451
5452    /**
5453     * Gets whether the framework should discard touches when the view's
5454     * window is obscured by another visible window.
5455     * Refer to the {@link View} security documentation for more details.
5456     *
5457     * @return True if touch filtering is enabled.
5458     *
5459     * @see #setFilterTouchesWhenObscured(boolean)
5460     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5461     */
5462    @ViewDebug.ExportedProperty
5463    public boolean getFilterTouchesWhenObscured() {
5464        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5465    }
5466
5467    /**
5468     * Sets whether the framework should discard touches when the view's
5469     * window is obscured by another visible window.
5470     * Refer to the {@link View} security documentation for more details.
5471     *
5472     * @param enabled True if touch filtering should be enabled.
5473     *
5474     * @see #getFilterTouchesWhenObscured
5475     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5476     */
5477    public void setFilterTouchesWhenObscured(boolean enabled) {
5478        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5479                FILTER_TOUCHES_WHEN_OBSCURED);
5480    }
5481
5482    /**
5483     * Indicates whether the entire hierarchy under this view will save its
5484     * state when a state saving traversal occurs from its parent.  The default
5485     * is true; if false, these views will not be saved unless
5486     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5487     *
5488     * @return Returns true if the view state saving from parent is enabled, else false.
5489     *
5490     * @see #setSaveFromParentEnabled(boolean)
5491     */
5492    public boolean isSaveFromParentEnabled() {
5493        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5494    }
5495
5496    /**
5497     * Controls whether the entire hierarchy under this view will save its
5498     * state when a state saving traversal occurs from its parent.  The default
5499     * is true; if false, these views will not be saved unless
5500     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5501     *
5502     * @param enabled Set to false to <em>disable</em> state saving, or true
5503     * (the default) to allow it.
5504     *
5505     * @see #isSaveFromParentEnabled()
5506     * @see #setId(int)
5507     * @see #onSaveInstanceState()
5508     */
5509    public void setSaveFromParentEnabled(boolean enabled) {
5510        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5511    }
5512
5513
5514    /**
5515     * Returns whether this View is able to take focus.
5516     *
5517     * @return True if this view can take focus, or false otherwise.
5518     * @attr ref android.R.styleable#View_focusable
5519     */
5520    @ViewDebug.ExportedProperty(category = "focus")
5521    public final boolean isFocusable() {
5522        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5523    }
5524
5525    /**
5526     * When a view is focusable, it may not want to take focus when in touch mode.
5527     * For example, a button would like focus when the user is navigating via a D-pad
5528     * so that the user can click on it, but once the user starts touching the screen,
5529     * the button shouldn't take focus
5530     * @return Whether the view is focusable in touch mode.
5531     * @attr ref android.R.styleable#View_focusableInTouchMode
5532     */
5533    @ViewDebug.ExportedProperty
5534    public final boolean isFocusableInTouchMode() {
5535        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5536    }
5537
5538    /**
5539     * Find the nearest view in the specified direction that can take focus.
5540     * This does not actually give focus to that view.
5541     *
5542     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5543     *
5544     * @return The nearest focusable in the specified direction, or null if none
5545     *         can be found.
5546     */
5547    public View focusSearch(int direction) {
5548        if (mParent != null) {
5549            return mParent.focusSearch(this, direction);
5550        } else {
5551            return null;
5552        }
5553    }
5554
5555    /**
5556     * This method is the last chance for the focused view and its ancestors to
5557     * respond to an arrow key. This is called when the focused view did not
5558     * consume the key internally, nor could the view system find a new view in
5559     * the requested direction to give focus to.
5560     *
5561     * @param focused The currently focused view.
5562     * @param direction The direction focus wants to move. One of FOCUS_UP,
5563     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5564     * @return True if the this view consumed this unhandled move.
5565     */
5566    public boolean dispatchUnhandledMove(View focused, int direction) {
5567        return false;
5568    }
5569
5570    /**
5571     * If a user manually specified the next view id for a particular direction,
5572     * use the root to look up the view.
5573     * @param root The root view of the hierarchy containing this view.
5574     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5575     * or FOCUS_BACKWARD.
5576     * @return The user specified next view, or null if there is none.
5577     */
5578    View findUserSetNextFocus(View root, int direction) {
5579        switch (direction) {
5580            case FOCUS_LEFT:
5581                if (mNextFocusLeftId == View.NO_ID) return null;
5582                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5583            case FOCUS_RIGHT:
5584                if (mNextFocusRightId == View.NO_ID) return null;
5585                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5586            case FOCUS_UP:
5587                if (mNextFocusUpId == View.NO_ID) return null;
5588                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5589            case FOCUS_DOWN:
5590                if (mNextFocusDownId == View.NO_ID) return null;
5591                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5592            case FOCUS_FORWARD:
5593                if (mNextFocusForwardId == View.NO_ID) return null;
5594                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5595            case FOCUS_BACKWARD: {
5596                if (mID == View.NO_ID) return null;
5597                final int id = mID;
5598                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5599                    @Override
5600                    public boolean apply(View t) {
5601                        return t.mNextFocusForwardId == id;
5602                    }
5603                });
5604            }
5605        }
5606        return null;
5607    }
5608
5609    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5610        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5611            @Override
5612            public boolean apply(View t) {
5613                return t.mID == childViewId;
5614            }
5615        });
5616
5617        if (result == null) {
5618            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5619                    + "by user for id " + childViewId);
5620        }
5621        return result;
5622    }
5623
5624    /**
5625     * Find and return all focusable views that are descendants of this view,
5626     * possibly including this view if it is focusable itself.
5627     *
5628     * @param direction The direction of the focus
5629     * @return A list of focusable views
5630     */
5631    public ArrayList<View> getFocusables(int direction) {
5632        ArrayList<View> result = new ArrayList<View>(24);
5633        addFocusables(result, direction);
5634        return result;
5635    }
5636
5637    /**
5638     * Add any focusable views that are descendants of this view (possibly
5639     * including this view if it is focusable itself) to views.  If we are in touch mode,
5640     * only add views that are also focusable in touch mode.
5641     *
5642     * @param views Focusable views found so far
5643     * @param direction The direction of the focus
5644     */
5645    public void addFocusables(ArrayList<View> views, int direction) {
5646        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5647    }
5648
5649    /**
5650     * Adds any focusable views that are descendants of this view (possibly
5651     * including this view if it is focusable itself) to views. This method
5652     * adds all focusable views regardless if we are in touch mode or
5653     * only views focusable in touch mode if we are in touch mode depending on
5654     * the focusable mode paramater.
5655     *
5656     * @param views Focusable views found so far or null if all we are interested is
5657     *        the number of focusables.
5658     * @param direction The direction of the focus.
5659     * @param focusableMode The type of focusables to be added.
5660     *
5661     * @see #FOCUSABLES_ALL
5662     * @see #FOCUSABLES_TOUCH_MODE
5663     */
5664    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5665        if (!isFocusable()) {
5666            return;
5667        }
5668
5669        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5670                isInTouchMode() && !isFocusableInTouchMode()) {
5671            return;
5672        }
5673
5674        if (views != null) {
5675            views.add(this);
5676        }
5677    }
5678
5679    /**
5680     * Finds the Views that contain given text. The containment is case insensitive.
5681     * The search is performed by either the text that the View renders or the content
5682     * description that describes the view for accessibility purposes and the view does
5683     * not render or both. Clients can specify how the search is to be performed via
5684     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5685     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5686     *
5687     * @param outViews The output list of matching Views.
5688     * @param searched The text to match against.
5689     *
5690     * @see #FIND_VIEWS_WITH_TEXT
5691     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5692     * @see #setContentDescription(CharSequence)
5693     */
5694    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5695        if (getAccessibilityNodeProvider() != null) {
5696            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5697                outViews.add(this);
5698            }
5699        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5700                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5701            String searchedLowerCase = searched.toString().toLowerCase();
5702            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5703            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5704                outViews.add(this);
5705            }
5706        }
5707    }
5708
5709    /**
5710     * Find and return all touchable views that are descendants of this view,
5711     * possibly including this view if it is touchable itself.
5712     *
5713     * @return A list of touchable views
5714     */
5715    public ArrayList<View> getTouchables() {
5716        ArrayList<View> result = new ArrayList<View>();
5717        addTouchables(result);
5718        return result;
5719    }
5720
5721    /**
5722     * Add any touchable views that are descendants of this view (possibly
5723     * including this view if it is touchable itself) to views.
5724     *
5725     * @param views Touchable views found so far
5726     */
5727    public void addTouchables(ArrayList<View> views) {
5728        final int viewFlags = mViewFlags;
5729
5730        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5731                && (viewFlags & ENABLED_MASK) == ENABLED) {
5732            views.add(this);
5733        }
5734    }
5735
5736    /**
5737     * Call this to try to give focus to a specific view or to one of its
5738     * descendants.
5739     *
5740     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5741     * false), or if it is focusable and it is not focusable in touch mode
5742     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5743     *
5744     * See also {@link #focusSearch(int)}, which is what you call to say that you
5745     * have focus, and you want your parent to look for the next one.
5746     *
5747     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5748     * {@link #FOCUS_DOWN} and <code>null</code>.
5749     *
5750     * @return Whether this view or one of its descendants actually took focus.
5751     */
5752    public final boolean requestFocus() {
5753        return requestFocus(View.FOCUS_DOWN);
5754    }
5755
5756
5757    /**
5758     * Call this to try to give focus to a specific view or to one of its
5759     * descendants and give it a hint about what direction focus is heading.
5760     *
5761     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5762     * false), or if it is focusable and it is not focusable in touch mode
5763     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5764     *
5765     * See also {@link #focusSearch(int)}, which is what you call to say that you
5766     * have focus, and you want your parent to look for the next one.
5767     *
5768     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5769     * <code>null</code> set for the previously focused rectangle.
5770     *
5771     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5772     * @return Whether this view or one of its descendants actually took focus.
5773     */
5774    public final boolean requestFocus(int direction) {
5775        return requestFocus(direction, null);
5776    }
5777
5778    /**
5779     * Call this to try to give focus to a specific view or to one of its descendants
5780     * and give it hints about the direction and a specific rectangle that the focus
5781     * is coming from.  The rectangle can help give larger views a finer grained hint
5782     * about where focus is coming from, and therefore, where to show selection, or
5783     * forward focus change internally.
5784     *
5785     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5786     * false), or if it is focusable and it is not focusable in touch mode
5787     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5788     *
5789     * A View will not take focus if it is not visible.
5790     *
5791     * A View will not take focus if one of its parents has
5792     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5793     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5794     *
5795     * See also {@link #focusSearch(int)}, which is what you call to say that you
5796     * have focus, and you want your parent to look for the next one.
5797     *
5798     * You may wish to override this method if your custom {@link View} has an internal
5799     * {@link View} that it wishes to forward the request to.
5800     *
5801     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5802     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5803     *        to give a finer grained hint about where focus is coming from.  May be null
5804     *        if there is no hint.
5805     * @return Whether this view or one of its descendants actually took focus.
5806     */
5807    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5808        // need to be focusable
5809        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5810                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5811            return false;
5812        }
5813
5814        // need to be focusable in touch mode if in touch mode
5815        if (isInTouchMode() &&
5816            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5817               return false;
5818        }
5819
5820        // need to not have any parents blocking us
5821        if (hasAncestorThatBlocksDescendantFocus()) {
5822            return false;
5823        }
5824
5825        handleFocusGainInternal(direction, previouslyFocusedRect);
5826        return true;
5827    }
5828
5829    /**
5830     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5831     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5832     * touch mode to request focus when they are touched.
5833     *
5834     * @return Whether this view or one of its descendants actually took focus.
5835     *
5836     * @see #isInTouchMode()
5837     *
5838     */
5839    public final boolean requestFocusFromTouch() {
5840        // Leave touch mode if we need to
5841        if (isInTouchMode()) {
5842            ViewRootImpl viewRoot = getViewRootImpl();
5843            if (viewRoot != null) {
5844                viewRoot.ensureTouchMode(false);
5845            }
5846        }
5847        return requestFocus(View.FOCUS_DOWN);
5848    }
5849
5850    /**
5851     * @return Whether any ancestor of this view blocks descendant focus.
5852     */
5853    private boolean hasAncestorThatBlocksDescendantFocus() {
5854        ViewParent ancestor = mParent;
5855        while (ancestor instanceof ViewGroup) {
5856            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5857            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5858                return true;
5859            } else {
5860                ancestor = vgAncestor.getParent();
5861            }
5862        }
5863        return false;
5864    }
5865
5866    /**
5867     * @hide
5868     */
5869    public void dispatchStartTemporaryDetach() {
5870        onStartTemporaryDetach();
5871    }
5872
5873    /**
5874     * This is called when a container is going to temporarily detach a child, with
5875     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5876     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5877     * {@link #onDetachedFromWindow()} when the container is done.
5878     */
5879    public void onStartTemporaryDetach() {
5880        removeUnsetPressCallback();
5881        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5882    }
5883
5884    /**
5885     * @hide
5886     */
5887    public void dispatchFinishTemporaryDetach() {
5888        onFinishTemporaryDetach();
5889    }
5890
5891    /**
5892     * Called after {@link #onStartTemporaryDetach} when the container is done
5893     * changing the view.
5894     */
5895    public void onFinishTemporaryDetach() {
5896    }
5897
5898    /**
5899     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5900     * for this view's window.  Returns null if the view is not currently attached
5901     * to the window.  Normally you will not need to use this directly, but
5902     * just use the standard high-level event callbacks like
5903     * {@link #onKeyDown(int, KeyEvent)}.
5904     */
5905    public KeyEvent.DispatcherState getKeyDispatcherState() {
5906        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5907    }
5908
5909    /**
5910     * Dispatch a key event before it is processed by any input method
5911     * associated with the view hierarchy.  This can be used to intercept
5912     * key events in special situations before the IME consumes them; a
5913     * typical example would be handling the BACK key to update the application's
5914     * UI instead of allowing the IME to see it and close itself.
5915     *
5916     * @param event The key event to be dispatched.
5917     * @return True if the event was handled, false otherwise.
5918     */
5919    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5920        return onKeyPreIme(event.getKeyCode(), event);
5921    }
5922
5923    /**
5924     * Dispatch a key event to the next view on the focus path. This path runs
5925     * from the top of the view tree down to the currently focused view. If this
5926     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5927     * the next node down the focus path. This method also fires any key
5928     * listeners.
5929     *
5930     * @param event The key event to be dispatched.
5931     * @return True if the event was handled, false otherwise.
5932     */
5933    public boolean dispatchKeyEvent(KeyEvent event) {
5934        if (mInputEventConsistencyVerifier != null) {
5935            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5936        }
5937
5938        // Give any attached key listener a first crack at the event.
5939        //noinspection SimplifiableIfStatement
5940        ListenerInfo li = mListenerInfo;
5941        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5942                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5943            return true;
5944        }
5945
5946        if (event.dispatch(this, mAttachInfo != null
5947                ? mAttachInfo.mKeyDispatchState : null, this)) {
5948            return true;
5949        }
5950
5951        if (mInputEventConsistencyVerifier != null) {
5952            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5953        }
5954        return false;
5955    }
5956
5957    /**
5958     * Dispatches a key shortcut event.
5959     *
5960     * @param event The key event to be dispatched.
5961     * @return True if the event was handled by the view, false otherwise.
5962     */
5963    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5964        return onKeyShortcut(event.getKeyCode(), event);
5965    }
5966
5967    /**
5968     * Pass the touch screen motion event down to the target view, or this
5969     * view if it is the target.
5970     *
5971     * @param event The motion event to be dispatched.
5972     * @return True if the event was handled by the view, false otherwise.
5973     */
5974    public boolean dispatchTouchEvent(MotionEvent event) {
5975        if (mInputEventConsistencyVerifier != null) {
5976            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5977        }
5978
5979        if (onFilterTouchEventForSecurity(event)) {
5980            //noinspection SimplifiableIfStatement
5981            ListenerInfo li = mListenerInfo;
5982            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5983                    && li.mOnTouchListener.onTouch(this, event)) {
5984                return true;
5985            }
5986
5987            if (onTouchEvent(event)) {
5988                return true;
5989            }
5990        }
5991
5992        if (mInputEventConsistencyVerifier != null) {
5993            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5994        }
5995        return false;
5996    }
5997
5998    /**
5999     * Filter the touch event to apply security policies.
6000     *
6001     * @param event The motion event to be filtered.
6002     * @return True if the event should be dispatched, false if the event should be dropped.
6003     *
6004     * @see #getFilterTouchesWhenObscured
6005     */
6006    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6007        //noinspection RedundantIfStatement
6008        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6009                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6010            // Window is obscured, drop this touch.
6011            return false;
6012        }
6013        return true;
6014    }
6015
6016    /**
6017     * Pass a trackball motion event down to the focused view.
6018     *
6019     * @param event The motion event to be dispatched.
6020     * @return True if the event was handled by the view, false otherwise.
6021     */
6022    public boolean dispatchTrackballEvent(MotionEvent event) {
6023        if (mInputEventConsistencyVerifier != null) {
6024            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6025        }
6026
6027        return onTrackballEvent(event);
6028    }
6029
6030    /**
6031     * Dispatch a generic motion event.
6032     * <p>
6033     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6034     * are delivered to the view under the pointer.  All other generic motion events are
6035     * delivered to the focused view.  Hover events are handled specially and are delivered
6036     * to {@link #onHoverEvent(MotionEvent)}.
6037     * </p>
6038     *
6039     * @param event The motion event to be dispatched.
6040     * @return True if the event was handled by the view, false otherwise.
6041     */
6042    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6043        if (mInputEventConsistencyVerifier != null) {
6044            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6045        }
6046
6047        final int source = event.getSource();
6048        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6049            final int action = event.getAction();
6050            if (action == MotionEvent.ACTION_HOVER_ENTER
6051                    || action == MotionEvent.ACTION_HOVER_MOVE
6052                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6053                if (dispatchHoverEvent(event)) {
6054                    return true;
6055                }
6056            } else if (dispatchGenericPointerEvent(event)) {
6057                return true;
6058            }
6059        } else if (dispatchGenericFocusedEvent(event)) {
6060            return true;
6061        }
6062
6063        if (dispatchGenericMotionEventInternal(event)) {
6064            return true;
6065        }
6066
6067        if (mInputEventConsistencyVerifier != null) {
6068            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6069        }
6070        return false;
6071    }
6072
6073    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6074        //noinspection SimplifiableIfStatement
6075        ListenerInfo li = mListenerInfo;
6076        if (li != null && li.mOnGenericMotionListener != null
6077                && (mViewFlags & ENABLED_MASK) == ENABLED
6078                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6079            return true;
6080        }
6081
6082        if (onGenericMotionEvent(event)) {
6083            return true;
6084        }
6085
6086        if (mInputEventConsistencyVerifier != null) {
6087            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6088        }
6089        return false;
6090    }
6091
6092    /**
6093     * Dispatch a hover event.
6094     * <p>
6095     * Do not call this method directly.
6096     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6097     * </p>
6098     *
6099     * @param event The motion event to be dispatched.
6100     * @return True if the event was handled by the view, false otherwise.
6101     */
6102    protected boolean dispatchHoverEvent(MotionEvent event) {
6103        //noinspection SimplifiableIfStatement
6104        ListenerInfo li = mListenerInfo;
6105        if (li != null && li.mOnHoverListener != null
6106                && (mViewFlags & ENABLED_MASK) == ENABLED
6107                && li.mOnHoverListener.onHover(this, event)) {
6108            return true;
6109        }
6110
6111        return onHoverEvent(event);
6112    }
6113
6114    /**
6115     * Returns true if the view has a child to which it has recently sent
6116     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
6117     * it does not have a hovered child, then it must be the innermost hovered view.
6118     * @hide
6119     */
6120    protected boolean hasHoveredChild() {
6121        return false;
6122    }
6123
6124    /**
6125     * Dispatch a generic motion event to the view under the first pointer.
6126     * <p>
6127     * Do not call this method directly.
6128     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6129     * </p>
6130     *
6131     * @param event The motion event to be dispatched.
6132     * @return True if the event was handled by the view, false otherwise.
6133     */
6134    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
6135        return false;
6136    }
6137
6138    /**
6139     * Dispatch a generic motion event to the currently focused view.
6140     * <p>
6141     * Do not call this method directly.
6142     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6143     * </p>
6144     *
6145     * @param event The motion event to be dispatched.
6146     * @return True if the event was handled by the view, false otherwise.
6147     */
6148    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
6149        return false;
6150    }
6151
6152    /**
6153     * Dispatch a pointer event.
6154     * <p>
6155     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
6156     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
6157     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
6158     * and should not be expected to handle other pointing device features.
6159     * </p>
6160     *
6161     * @param event The motion event to be dispatched.
6162     * @return True if the event was handled by the view, false otherwise.
6163     * @hide
6164     */
6165    public final boolean dispatchPointerEvent(MotionEvent event) {
6166        if (event.isTouchEvent()) {
6167            return dispatchTouchEvent(event);
6168        } else {
6169            return dispatchGenericMotionEvent(event);
6170        }
6171    }
6172
6173    /**
6174     * Called when the window containing this view gains or loses window focus.
6175     * ViewGroups should override to route to their children.
6176     *
6177     * @param hasFocus True if the window containing this view now has focus,
6178     *        false otherwise.
6179     */
6180    public void dispatchWindowFocusChanged(boolean hasFocus) {
6181        onWindowFocusChanged(hasFocus);
6182    }
6183
6184    /**
6185     * Called when the window containing this view gains or loses focus.  Note
6186     * that this is separate from view focus: to receive key events, both
6187     * your view and its window must have focus.  If a window is displayed
6188     * on top of yours that takes input focus, then your own window will lose
6189     * focus but the view focus will remain unchanged.
6190     *
6191     * @param hasWindowFocus True if the window containing this view now has
6192     *        focus, false otherwise.
6193     */
6194    public void onWindowFocusChanged(boolean hasWindowFocus) {
6195        InputMethodManager imm = InputMethodManager.peekInstance();
6196        if (!hasWindowFocus) {
6197            if (isPressed()) {
6198                setPressed(false);
6199            }
6200            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6201                imm.focusOut(this);
6202            }
6203            removeLongPressCallback();
6204            removeTapCallback();
6205            onFocusLost();
6206        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6207            imm.focusIn(this);
6208        }
6209        refreshDrawableState();
6210    }
6211
6212    /**
6213     * Returns true if this view is in a window that currently has window focus.
6214     * Note that this is not the same as the view itself having focus.
6215     *
6216     * @return True if this view is in a window that currently has window focus.
6217     */
6218    public boolean hasWindowFocus() {
6219        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
6220    }
6221
6222    /**
6223     * Dispatch a view visibility change down the view hierarchy.
6224     * ViewGroups should override to route to their children.
6225     * @param changedView The view whose visibility changed. Could be 'this' or
6226     * an ancestor view.
6227     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6228     * {@link #INVISIBLE} or {@link #GONE}.
6229     */
6230    protected void dispatchVisibilityChanged(View changedView, int visibility) {
6231        onVisibilityChanged(changedView, visibility);
6232    }
6233
6234    /**
6235     * Called when the visibility of the view or an ancestor of the view is changed.
6236     * @param changedView The view whose visibility changed. Could be 'this' or
6237     * an ancestor view.
6238     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6239     * {@link #INVISIBLE} or {@link #GONE}.
6240     */
6241    protected void onVisibilityChanged(View changedView, int visibility) {
6242        if (visibility == VISIBLE) {
6243            if (mAttachInfo != null) {
6244                initialAwakenScrollBars();
6245            } else {
6246                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
6247            }
6248        }
6249    }
6250
6251    /**
6252     * Dispatch a hint about whether this view is displayed. For instance, when
6253     * a View moves out of the screen, it might receives a display hint indicating
6254     * the view is not displayed. Applications should not <em>rely</em> on this hint
6255     * as there is no guarantee that they will receive one.
6256     *
6257     * @param hint A hint about whether or not this view is displayed:
6258     * {@link #VISIBLE} or {@link #INVISIBLE}.
6259     */
6260    public void dispatchDisplayHint(int hint) {
6261        onDisplayHint(hint);
6262    }
6263
6264    /**
6265     * Gives this view a hint about whether is displayed or not. For instance, when
6266     * a View moves out of the screen, it might receives a display hint indicating
6267     * the view is not displayed. Applications should not <em>rely</em> on this hint
6268     * as there is no guarantee that they will receive one.
6269     *
6270     * @param hint A hint about whether or not this view is displayed:
6271     * {@link #VISIBLE} or {@link #INVISIBLE}.
6272     */
6273    protected void onDisplayHint(int hint) {
6274    }
6275
6276    /**
6277     * Dispatch a window visibility change down the view hierarchy.
6278     * ViewGroups should override to route to their children.
6279     *
6280     * @param visibility The new visibility of the window.
6281     *
6282     * @see #onWindowVisibilityChanged(int)
6283     */
6284    public void dispatchWindowVisibilityChanged(int visibility) {
6285        onWindowVisibilityChanged(visibility);
6286    }
6287
6288    /**
6289     * Called when the window containing has change its visibility
6290     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
6291     * that this tells you whether or not your window is being made visible
6292     * to the window manager; this does <em>not</em> tell you whether or not
6293     * your window is obscured by other windows on the screen, even if it
6294     * is itself visible.
6295     *
6296     * @param visibility The new visibility of the window.
6297     */
6298    protected void onWindowVisibilityChanged(int visibility) {
6299        if (visibility == VISIBLE) {
6300            initialAwakenScrollBars();
6301        }
6302    }
6303
6304    /**
6305     * Returns the current visibility of the window this view is attached to
6306     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6307     *
6308     * @return Returns the current visibility of the view's window.
6309     */
6310    public int getWindowVisibility() {
6311        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6312    }
6313
6314    /**
6315     * Retrieve the overall visible display size in which the window this view is
6316     * attached to has been positioned in.  This takes into account screen
6317     * decorations above the window, for both cases where the window itself
6318     * is being position inside of them or the window is being placed under
6319     * then and covered insets are used for the window to position its content
6320     * inside.  In effect, this tells you the available area where content can
6321     * be placed and remain visible to users.
6322     *
6323     * <p>This function requires an IPC back to the window manager to retrieve
6324     * the requested information, so should not be used in performance critical
6325     * code like drawing.
6326     *
6327     * @param outRect Filled in with the visible display frame.  If the view
6328     * is not attached to a window, this is simply the raw display size.
6329     */
6330    public void getWindowVisibleDisplayFrame(Rect outRect) {
6331        if (mAttachInfo != null) {
6332            try {
6333                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6334            } catch (RemoteException e) {
6335                return;
6336            }
6337            // XXX This is really broken, and probably all needs to be done
6338            // in the window manager, and we need to know more about whether
6339            // we want the area behind or in front of the IME.
6340            final Rect insets = mAttachInfo.mVisibleInsets;
6341            outRect.left += insets.left;
6342            outRect.top += insets.top;
6343            outRect.right -= insets.right;
6344            outRect.bottom -= insets.bottom;
6345            return;
6346        }
6347        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6348        d.getRectSize(outRect);
6349    }
6350
6351    /**
6352     * Dispatch a notification about a resource configuration change down
6353     * the view hierarchy.
6354     * ViewGroups should override to route to their children.
6355     *
6356     * @param newConfig The new resource configuration.
6357     *
6358     * @see #onConfigurationChanged(android.content.res.Configuration)
6359     */
6360    public void dispatchConfigurationChanged(Configuration newConfig) {
6361        onConfigurationChanged(newConfig);
6362    }
6363
6364    /**
6365     * Called when the current configuration of the resources being used
6366     * by the application have changed.  You can use this to decide when
6367     * to reload resources that can changed based on orientation and other
6368     * configuration characterstics.  You only need to use this if you are
6369     * not relying on the normal {@link android.app.Activity} mechanism of
6370     * recreating the activity instance upon a configuration change.
6371     *
6372     * @param newConfig The new resource configuration.
6373     */
6374    protected void onConfigurationChanged(Configuration newConfig) {
6375    }
6376
6377    /**
6378     * Private function to aggregate all per-view attributes in to the view
6379     * root.
6380     */
6381    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6382        performCollectViewAttributes(attachInfo, visibility);
6383    }
6384
6385    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6386        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
6387            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6388                attachInfo.mKeepScreenOn = true;
6389            }
6390            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6391            ListenerInfo li = mListenerInfo;
6392            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6393                attachInfo.mHasSystemUiListeners = true;
6394            }
6395        }
6396    }
6397
6398    void needGlobalAttributesUpdate(boolean force) {
6399        final AttachInfo ai = mAttachInfo;
6400        if (ai != null) {
6401            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6402                    || ai.mHasSystemUiListeners) {
6403                ai.mRecomputeGlobalAttributes = true;
6404            }
6405        }
6406    }
6407
6408    /**
6409     * Returns whether the device is currently in touch mode.  Touch mode is entered
6410     * once the user begins interacting with the device by touch, and affects various
6411     * things like whether focus is always visible to the user.
6412     *
6413     * @return Whether the device is in touch mode.
6414     */
6415    @ViewDebug.ExportedProperty
6416    public boolean isInTouchMode() {
6417        if (mAttachInfo != null) {
6418            return mAttachInfo.mInTouchMode;
6419        } else {
6420            return ViewRootImpl.isInTouchMode();
6421        }
6422    }
6423
6424    /**
6425     * Returns the context the view is running in, through which it can
6426     * access the current theme, resources, etc.
6427     *
6428     * @return The view's Context.
6429     */
6430    @ViewDebug.CapturedViewProperty
6431    public final Context getContext() {
6432        return mContext;
6433    }
6434
6435    /**
6436     * Handle a key event before it is processed by any input method
6437     * associated with the view hierarchy.  This can be used to intercept
6438     * key events in special situations before the IME consumes them; a
6439     * typical example would be handling the BACK key to update the application's
6440     * UI instead of allowing the IME to see it and close itself.
6441     *
6442     * @param keyCode The value in event.getKeyCode().
6443     * @param event Description of the key event.
6444     * @return If you handled the event, return true. If you want to allow the
6445     *         event to be handled by the next receiver, return false.
6446     */
6447    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6448        return false;
6449    }
6450
6451    /**
6452     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6453     * KeyEvent.Callback.onKeyDown()}: perform press of the view
6454     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
6455     * is released, if the view is enabled and clickable.
6456     *
6457     * @param keyCode A key code that represents the button pressed, from
6458     *                {@link android.view.KeyEvent}.
6459     * @param event   The KeyEvent object that defines the button action.
6460     */
6461    public boolean onKeyDown(int keyCode, KeyEvent event) {
6462        boolean result = false;
6463
6464        switch (keyCode) {
6465            case KeyEvent.KEYCODE_DPAD_CENTER:
6466            case KeyEvent.KEYCODE_ENTER: {
6467                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6468                    return true;
6469                }
6470                // Long clickable items don't necessarily have to be clickable
6471                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
6472                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
6473                        (event.getRepeatCount() == 0)) {
6474                    setPressed(true);
6475                    checkForLongClick(0);
6476                    return true;
6477                }
6478                break;
6479            }
6480        }
6481        return result;
6482    }
6483
6484    /**
6485     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
6486     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
6487     * the event).
6488     */
6489    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
6490        return false;
6491    }
6492
6493    /**
6494     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
6495     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
6496     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
6497     * {@link KeyEvent#KEYCODE_ENTER} is released.
6498     *
6499     * @param keyCode A key code that represents the button pressed, from
6500     *                {@link android.view.KeyEvent}.
6501     * @param event   The KeyEvent object that defines the button action.
6502     */
6503    public boolean onKeyUp(int keyCode, KeyEvent event) {
6504        boolean result = false;
6505
6506        switch (keyCode) {
6507            case KeyEvent.KEYCODE_DPAD_CENTER:
6508            case KeyEvent.KEYCODE_ENTER: {
6509                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6510                    return true;
6511                }
6512                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
6513                    setPressed(false);
6514
6515                    if (!mHasPerformedLongPress) {
6516                        // This is a tap, so remove the longpress check
6517                        removeLongPressCallback();
6518
6519                        result = performClick();
6520                    }
6521                }
6522                break;
6523            }
6524        }
6525        return result;
6526    }
6527
6528    /**
6529     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6530     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6531     * the event).
6532     *
6533     * @param keyCode     A key code that represents the button pressed, from
6534     *                    {@link android.view.KeyEvent}.
6535     * @param repeatCount The number of times the action was made.
6536     * @param event       The KeyEvent object that defines the button action.
6537     */
6538    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6539        return false;
6540    }
6541
6542    /**
6543     * Called on the focused view when a key shortcut event is not handled.
6544     * Override this method to implement local key shortcuts for the View.
6545     * Key shortcuts can also be implemented by setting the
6546     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6547     *
6548     * @param keyCode The value in event.getKeyCode().
6549     * @param event Description of the key event.
6550     * @return If you handled the event, return true. If you want to allow the
6551     *         event to be handled by the next receiver, return false.
6552     */
6553    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6554        return false;
6555    }
6556
6557    /**
6558     * Check whether the called view is a text editor, in which case it
6559     * would make sense to automatically display a soft input window for
6560     * it.  Subclasses should override this if they implement
6561     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6562     * a call on that method would return a non-null InputConnection, and
6563     * they are really a first-class editor that the user would normally
6564     * start typing on when the go into a window containing your view.
6565     *
6566     * <p>The default implementation always returns false.  This does
6567     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6568     * will not be called or the user can not otherwise perform edits on your
6569     * view; it is just a hint to the system that this is not the primary
6570     * purpose of this view.
6571     *
6572     * @return Returns true if this view is a text editor, else false.
6573     */
6574    public boolean onCheckIsTextEditor() {
6575        return false;
6576    }
6577
6578    /**
6579     * Create a new InputConnection for an InputMethod to interact
6580     * with the view.  The default implementation returns null, since it doesn't
6581     * support input methods.  You can override this to implement such support.
6582     * This is only needed for views that take focus and text input.
6583     *
6584     * <p>When implementing this, you probably also want to implement
6585     * {@link #onCheckIsTextEditor()} to indicate you will return a
6586     * non-null InputConnection.
6587     *
6588     * @param outAttrs Fill in with attribute information about the connection.
6589     */
6590    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6591        return null;
6592    }
6593
6594    /**
6595     * Called by the {@link android.view.inputmethod.InputMethodManager}
6596     * when a view who is not the current
6597     * input connection target is trying to make a call on the manager.  The
6598     * default implementation returns false; you can override this to return
6599     * true for certain views if you are performing InputConnection proxying
6600     * to them.
6601     * @param view The View that is making the InputMethodManager call.
6602     * @return Return true to allow the call, false to reject.
6603     */
6604    public boolean checkInputConnectionProxy(View view) {
6605        return false;
6606    }
6607
6608    /**
6609     * Show the context menu for this view. It is not safe to hold on to the
6610     * menu after returning from this method.
6611     *
6612     * You should normally not overload this method. Overload
6613     * {@link #onCreateContextMenu(ContextMenu)} or define an
6614     * {@link OnCreateContextMenuListener} to add items to the context menu.
6615     *
6616     * @param menu The context menu to populate
6617     */
6618    public void createContextMenu(ContextMenu menu) {
6619        ContextMenuInfo menuInfo = getContextMenuInfo();
6620
6621        // Sets the current menu info so all items added to menu will have
6622        // my extra info set.
6623        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6624
6625        onCreateContextMenu(menu);
6626        ListenerInfo li = mListenerInfo;
6627        if (li != null && li.mOnCreateContextMenuListener != null) {
6628            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6629        }
6630
6631        // Clear the extra information so subsequent items that aren't mine don't
6632        // have my extra info.
6633        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6634
6635        if (mParent != null) {
6636            mParent.createContextMenu(menu);
6637        }
6638    }
6639
6640    /**
6641     * Views should implement this if they have extra information to associate
6642     * with the context menu. The return result is supplied as a parameter to
6643     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6644     * callback.
6645     *
6646     * @return Extra information about the item for which the context menu
6647     *         should be shown. This information will vary across different
6648     *         subclasses of View.
6649     */
6650    protected ContextMenuInfo getContextMenuInfo() {
6651        return null;
6652    }
6653
6654    /**
6655     * Views should implement this if the view itself is going to add items to
6656     * the context menu.
6657     *
6658     * @param menu the context menu to populate
6659     */
6660    protected void onCreateContextMenu(ContextMenu menu) {
6661    }
6662
6663    /**
6664     * Implement this method to handle trackball motion events.  The
6665     * <em>relative</em> movement of the trackball since the last event
6666     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6667     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6668     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6669     * they will often be fractional values, representing the more fine-grained
6670     * movement information available from a trackball).
6671     *
6672     * @param event The motion event.
6673     * @return True if the event was handled, false otherwise.
6674     */
6675    public boolean onTrackballEvent(MotionEvent event) {
6676        return false;
6677    }
6678
6679    /**
6680     * Implement this method to handle generic motion events.
6681     * <p>
6682     * Generic motion events describe joystick movements, mouse hovers, track pad
6683     * touches, scroll wheel movements and other input events.  The
6684     * {@link MotionEvent#getSource() source} of the motion event specifies
6685     * the class of input that was received.  Implementations of this method
6686     * must examine the bits in the source before processing the event.
6687     * The following code example shows how this is done.
6688     * </p><p>
6689     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6690     * are delivered to the view under the pointer.  All other generic motion events are
6691     * delivered to the focused view.
6692     * </p>
6693     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
6694     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6695     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6696     *             // process the joystick movement...
6697     *             return true;
6698     *         }
6699     *     }
6700     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6701     *         switch (event.getAction()) {
6702     *             case MotionEvent.ACTION_HOVER_MOVE:
6703     *                 // process the mouse hover movement...
6704     *                 return true;
6705     *             case MotionEvent.ACTION_SCROLL:
6706     *                 // process the scroll wheel movement...
6707     *                 return true;
6708     *         }
6709     *     }
6710     *     return super.onGenericMotionEvent(event);
6711     * }</pre>
6712     *
6713     * @param event The generic motion event being processed.
6714     * @return True if the event was handled, false otherwise.
6715     */
6716    public boolean onGenericMotionEvent(MotionEvent event) {
6717        return false;
6718    }
6719
6720    /**
6721     * Implement this method to handle hover events.
6722     * <p>
6723     * This method is called whenever a pointer is hovering into, over, or out of the
6724     * bounds of a view and the view is not currently being touched.
6725     * Hover events are represented as pointer events with action
6726     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6727     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6728     * </p>
6729     * <ul>
6730     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6731     * when the pointer enters the bounds of the view.</li>
6732     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6733     * when the pointer has already entered the bounds of the view and has moved.</li>
6734     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6735     * when the pointer has exited the bounds of the view or when the pointer is
6736     * about to go down due to a button click, tap, or similar user action that
6737     * causes the view to be touched.</li>
6738     * </ul>
6739     * <p>
6740     * The view should implement this method to return true to indicate that it is
6741     * handling the hover event, such as by changing its drawable state.
6742     * </p><p>
6743     * The default implementation calls {@link #setHovered} to update the hovered state
6744     * of the view when a hover enter or hover exit event is received, if the view
6745     * is enabled and is clickable.  The default implementation also sends hover
6746     * accessibility events.
6747     * </p>
6748     *
6749     * @param event The motion event that describes the hover.
6750     * @return True if the view handled the hover event.
6751     *
6752     * @see #isHovered
6753     * @see #setHovered
6754     * @see #onHoverChanged
6755     */
6756    public boolean onHoverEvent(MotionEvent event) {
6757        // The root view may receive hover (or touch) events that are outside the bounds of
6758        // the window.  This code ensures that we only send accessibility events for
6759        // hovers that are actually within the bounds of the root view.
6760        final int action = event.getAction();
6761        if (!mSendingHoverAccessibilityEvents) {
6762            if ((action == MotionEvent.ACTION_HOVER_ENTER
6763                    || action == MotionEvent.ACTION_HOVER_MOVE)
6764                    && !hasHoveredChild()
6765                    && pointInView(event.getX(), event.getY())) {
6766                mSendingHoverAccessibilityEvents = true;
6767                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6768            }
6769        } else {
6770            if (action == MotionEvent.ACTION_HOVER_EXIT
6771                    || (action == MotionEvent.ACTION_HOVER_MOVE
6772                            && !pointInView(event.getX(), event.getY()))) {
6773                mSendingHoverAccessibilityEvents = false;
6774                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6775            }
6776        }
6777
6778        if (isHoverable()) {
6779            switch (action) {
6780                case MotionEvent.ACTION_HOVER_ENTER:
6781                    setHovered(true);
6782                    break;
6783                case MotionEvent.ACTION_HOVER_EXIT:
6784                    setHovered(false);
6785                    break;
6786            }
6787
6788            // Dispatch the event to onGenericMotionEvent before returning true.
6789            // This is to provide compatibility with existing applications that
6790            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6791            // break because of the new default handling for hoverable views
6792            // in onHoverEvent.
6793            // Note that onGenericMotionEvent will be called by default when
6794            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6795            dispatchGenericMotionEventInternal(event);
6796            return true;
6797        }
6798        return false;
6799    }
6800
6801    /**
6802     * Returns true if the view should handle {@link #onHoverEvent}
6803     * by calling {@link #setHovered} to change its hovered state.
6804     *
6805     * @return True if the view is hoverable.
6806     */
6807    private boolean isHoverable() {
6808        final int viewFlags = mViewFlags;
6809        //noinspection SimplifiableIfStatement
6810        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6811            return false;
6812        }
6813
6814        return (viewFlags & CLICKABLE) == CLICKABLE
6815                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6816    }
6817
6818    /**
6819     * Returns true if the view is currently hovered.
6820     *
6821     * @return True if the view is currently hovered.
6822     *
6823     * @see #setHovered
6824     * @see #onHoverChanged
6825     */
6826    @ViewDebug.ExportedProperty
6827    public boolean isHovered() {
6828        return (mPrivateFlags & HOVERED) != 0;
6829    }
6830
6831    /**
6832     * Sets whether the view is currently hovered.
6833     * <p>
6834     * Calling this method also changes the drawable state of the view.  This
6835     * enables the view to react to hover by using different drawable resources
6836     * to change its appearance.
6837     * </p><p>
6838     * The {@link #onHoverChanged} method is called when the hovered state changes.
6839     * </p>
6840     *
6841     * @param hovered True if the view is hovered.
6842     *
6843     * @see #isHovered
6844     * @see #onHoverChanged
6845     */
6846    public void setHovered(boolean hovered) {
6847        if (hovered) {
6848            if ((mPrivateFlags & HOVERED) == 0) {
6849                mPrivateFlags |= HOVERED;
6850                refreshDrawableState();
6851                onHoverChanged(true);
6852            }
6853        } else {
6854            if ((mPrivateFlags & HOVERED) != 0) {
6855                mPrivateFlags &= ~HOVERED;
6856                refreshDrawableState();
6857                onHoverChanged(false);
6858            }
6859        }
6860    }
6861
6862    /**
6863     * Implement this method to handle hover state changes.
6864     * <p>
6865     * This method is called whenever the hover state changes as a result of a
6866     * call to {@link #setHovered}.
6867     * </p>
6868     *
6869     * @param hovered The current hover state, as returned by {@link #isHovered}.
6870     *
6871     * @see #isHovered
6872     * @see #setHovered
6873     */
6874    public void onHoverChanged(boolean hovered) {
6875    }
6876
6877    /**
6878     * Implement this method to handle touch screen motion events.
6879     *
6880     * @param event The motion event.
6881     * @return True if the event was handled, false otherwise.
6882     */
6883    public boolean onTouchEvent(MotionEvent event) {
6884        final int viewFlags = mViewFlags;
6885
6886        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6887            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6888                setPressed(false);
6889            }
6890            // A disabled view that is clickable still consumes the touch
6891            // events, it just doesn't respond to them.
6892            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6893                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6894        }
6895
6896        if (mTouchDelegate != null) {
6897            if (mTouchDelegate.onTouchEvent(event)) {
6898                return true;
6899            }
6900        }
6901
6902        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6903                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6904            switch (event.getAction()) {
6905                case MotionEvent.ACTION_UP:
6906                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6907                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6908                        // take focus if we don't have it already and we should in
6909                        // touch mode.
6910                        boolean focusTaken = false;
6911                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6912                            focusTaken = requestFocus();
6913                        }
6914
6915                        if (prepressed) {
6916                            // The button is being released before we actually
6917                            // showed it as pressed.  Make it show the pressed
6918                            // state now (before scheduling the click) to ensure
6919                            // the user sees it.
6920                            setPressed(true);
6921                       }
6922
6923                        if (!mHasPerformedLongPress) {
6924                            // This is a tap, so remove the longpress check
6925                            removeLongPressCallback();
6926
6927                            // Only perform take click actions if we were in the pressed state
6928                            if (!focusTaken) {
6929                                // Use a Runnable and post this rather than calling
6930                                // performClick directly. This lets other visual state
6931                                // of the view update before click actions start.
6932                                if (mPerformClick == null) {
6933                                    mPerformClick = new PerformClick();
6934                                }
6935                                if (!post(mPerformClick)) {
6936                                    performClick();
6937                                }
6938                            }
6939                        }
6940
6941                        if (mUnsetPressedState == null) {
6942                            mUnsetPressedState = new UnsetPressedState();
6943                        }
6944
6945                        if (prepressed) {
6946                            postDelayed(mUnsetPressedState,
6947                                    ViewConfiguration.getPressedStateDuration());
6948                        } else if (!post(mUnsetPressedState)) {
6949                            // If the post failed, unpress right now
6950                            mUnsetPressedState.run();
6951                        }
6952                        removeTapCallback();
6953                    }
6954                    break;
6955
6956                case MotionEvent.ACTION_DOWN:
6957                    mHasPerformedLongPress = false;
6958
6959                    if (performButtonActionOnTouchDown(event)) {
6960                        break;
6961                    }
6962
6963                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6964                    boolean isInScrollingContainer = isInScrollingContainer();
6965
6966                    // For views inside a scrolling container, delay the pressed feedback for
6967                    // a short period in case this is a scroll.
6968                    if (isInScrollingContainer) {
6969                        mPrivateFlags |= PREPRESSED;
6970                        if (mPendingCheckForTap == null) {
6971                            mPendingCheckForTap = new CheckForTap();
6972                        }
6973                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6974                    } else {
6975                        // Not inside a scrolling container, so show the feedback right away
6976                        setPressed(true);
6977                        checkForLongClick(0);
6978                    }
6979                    break;
6980
6981                case MotionEvent.ACTION_CANCEL:
6982                    setPressed(false);
6983                    removeTapCallback();
6984                    break;
6985
6986                case MotionEvent.ACTION_MOVE:
6987                    final int x = (int) event.getX();
6988                    final int y = (int) event.getY();
6989
6990                    // Be lenient about moving outside of buttons
6991                    if (!pointInView(x, y, mTouchSlop)) {
6992                        // Outside button
6993                        removeTapCallback();
6994                        if ((mPrivateFlags & PRESSED) != 0) {
6995                            // Remove any future long press/tap checks
6996                            removeLongPressCallback();
6997
6998                            setPressed(false);
6999                        }
7000                    }
7001                    break;
7002            }
7003            return true;
7004        }
7005
7006        return false;
7007    }
7008
7009    /**
7010     * @hide
7011     */
7012    public boolean isInScrollingContainer() {
7013        ViewParent p = getParent();
7014        while (p != null && p instanceof ViewGroup) {
7015            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7016                return true;
7017            }
7018            p = p.getParent();
7019        }
7020        return false;
7021    }
7022
7023    /**
7024     * Remove the longpress detection timer.
7025     */
7026    private void removeLongPressCallback() {
7027        if (mPendingCheckForLongPress != null) {
7028          removeCallbacks(mPendingCheckForLongPress);
7029        }
7030    }
7031
7032    /**
7033     * Remove the pending click action
7034     */
7035    private void removePerformClickCallback() {
7036        if (mPerformClick != null) {
7037            removeCallbacks(mPerformClick);
7038        }
7039    }
7040
7041    /**
7042     * Remove the prepress detection timer.
7043     */
7044    private void removeUnsetPressCallback() {
7045        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7046            setPressed(false);
7047            removeCallbacks(mUnsetPressedState);
7048        }
7049    }
7050
7051    /**
7052     * Remove the tap detection timer.
7053     */
7054    private void removeTapCallback() {
7055        if (mPendingCheckForTap != null) {
7056            mPrivateFlags &= ~PREPRESSED;
7057            removeCallbacks(mPendingCheckForTap);
7058        }
7059    }
7060
7061    /**
7062     * Cancels a pending long press.  Your subclass can use this if you
7063     * want the context menu to come up if the user presses and holds
7064     * at the same place, but you don't want it to come up if they press
7065     * and then move around enough to cause scrolling.
7066     */
7067    public void cancelLongPress() {
7068        removeLongPressCallback();
7069
7070        /*
7071         * The prepressed state handled by the tap callback is a display
7072         * construct, but the tap callback will post a long press callback
7073         * less its own timeout. Remove it here.
7074         */
7075        removeTapCallback();
7076    }
7077
7078    /**
7079     * Remove the pending callback for sending a
7080     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7081     */
7082    private void removeSendViewScrolledAccessibilityEventCallback() {
7083        if (mSendViewScrolledAccessibilityEvent != null) {
7084            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7085        }
7086    }
7087
7088    /**
7089     * Sets the TouchDelegate for this View.
7090     */
7091    public void setTouchDelegate(TouchDelegate delegate) {
7092        mTouchDelegate = delegate;
7093    }
7094
7095    /**
7096     * Gets the TouchDelegate for this View.
7097     */
7098    public TouchDelegate getTouchDelegate() {
7099        return mTouchDelegate;
7100    }
7101
7102    /**
7103     * Set flags controlling behavior of this view.
7104     *
7105     * @param flags Constant indicating the value which should be set
7106     * @param mask Constant indicating the bit range that should be changed
7107     */
7108    void setFlags(int flags, int mask) {
7109        int old = mViewFlags;
7110        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
7111
7112        int changed = mViewFlags ^ old;
7113        if (changed == 0) {
7114            return;
7115        }
7116        int privateFlags = mPrivateFlags;
7117
7118        /* Check if the FOCUSABLE bit has changed */
7119        if (((changed & FOCUSABLE_MASK) != 0) &&
7120                ((privateFlags & HAS_BOUNDS) !=0)) {
7121            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
7122                    && ((privateFlags & FOCUSED) != 0)) {
7123                /* Give up focus if we are no longer focusable */
7124                clearFocus();
7125            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
7126                    && ((privateFlags & FOCUSED) == 0)) {
7127                /*
7128                 * Tell the view system that we are now available to take focus
7129                 * if no one else already has it.
7130                 */
7131                if (mParent != null) mParent.focusableViewAvailable(this);
7132            }
7133        }
7134
7135        if ((flags & VISIBILITY_MASK) == VISIBLE) {
7136            if ((changed & VISIBILITY_MASK) != 0) {
7137                /*
7138                 * If this view is becoming visible, invalidate it in case it changed while
7139                 * it was not visible. Marking it drawn ensures that the invalidation will
7140                 * go through.
7141                 */
7142                mPrivateFlags |= DRAWN;
7143                invalidate(true);
7144
7145                needGlobalAttributesUpdate(true);
7146
7147                // a view becoming visible is worth notifying the parent
7148                // about in case nothing has focus.  even if this specific view
7149                // isn't focusable, it may contain something that is, so let
7150                // the root view try to give this focus if nothing else does.
7151                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
7152                    mParent.focusableViewAvailable(this);
7153                }
7154            }
7155        }
7156
7157        /* Check if the GONE bit has changed */
7158        if ((changed & GONE) != 0) {
7159            needGlobalAttributesUpdate(false);
7160            requestLayout();
7161
7162            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
7163                if (hasFocus()) clearFocus();
7164                destroyDrawingCache();
7165                if (mParent instanceof View) {
7166                    // GONE views noop invalidation, so invalidate the parent
7167                    ((View) mParent).invalidate(true);
7168                }
7169                // Mark the view drawn to ensure that it gets invalidated properly the next
7170                // time it is visible and gets invalidated
7171                mPrivateFlags |= DRAWN;
7172            }
7173            if (mAttachInfo != null) {
7174                mAttachInfo.mViewVisibilityChanged = true;
7175            }
7176        }
7177
7178        /* Check if the VISIBLE bit has changed */
7179        if ((changed & INVISIBLE) != 0) {
7180            needGlobalAttributesUpdate(false);
7181            /*
7182             * If this view is becoming invisible, set the DRAWN flag so that
7183             * the next invalidate() will not be skipped.
7184             */
7185            mPrivateFlags |= DRAWN;
7186
7187            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
7188                // root view becoming invisible shouldn't clear focus
7189                if (getRootView() != this) {
7190                    clearFocus();
7191                }
7192            }
7193            if (mAttachInfo != null) {
7194                mAttachInfo.mViewVisibilityChanged = true;
7195            }
7196        }
7197
7198        if ((changed & VISIBILITY_MASK) != 0) {
7199            if (mParent instanceof ViewGroup) {
7200                ((ViewGroup) mParent).onChildVisibilityChanged(this,
7201                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
7202                ((View) mParent).invalidate(true);
7203            } else if (mParent != null) {
7204                mParent.invalidateChild(this, null);
7205            }
7206            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
7207        }
7208
7209        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
7210            destroyDrawingCache();
7211        }
7212
7213        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
7214            destroyDrawingCache();
7215            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7216            invalidateParentCaches();
7217        }
7218
7219        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
7220            destroyDrawingCache();
7221            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7222        }
7223
7224        if ((changed & DRAW_MASK) != 0) {
7225            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
7226                if (mBackground != null) {
7227                    mPrivateFlags &= ~SKIP_DRAW;
7228                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7229                } else {
7230                    mPrivateFlags |= SKIP_DRAW;
7231                }
7232            } else {
7233                mPrivateFlags &= ~SKIP_DRAW;
7234            }
7235            requestLayout();
7236            invalidate(true);
7237        }
7238
7239        if ((changed & KEEP_SCREEN_ON) != 0) {
7240            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
7241                mParent.recomputeViewAttributes(this);
7242            }
7243        }
7244    }
7245
7246    /**
7247     * Change the view's z order in the tree, so it's on top of other sibling
7248     * views
7249     */
7250    public void bringToFront() {
7251        if (mParent != null) {
7252            mParent.bringChildToFront(this);
7253        }
7254    }
7255
7256    /**
7257     * This is called in response to an internal scroll in this view (i.e., the
7258     * view scrolled its own contents). This is typically as a result of
7259     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
7260     * called.
7261     *
7262     * @param l Current horizontal scroll origin.
7263     * @param t Current vertical scroll origin.
7264     * @param oldl Previous horizontal scroll origin.
7265     * @param oldt Previous vertical scroll origin.
7266     */
7267    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
7268        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7269            postSendViewScrolledAccessibilityEventCallback();
7270        }
7271
7272        mBackgroundSizeChanged = true;
7273
7274        final AttachInfo ai = mAttachInfo;
7275        if (ai != null) {
7276            ai.mViewScrollChanged = true;
7277        }
7278    }
7279
7280    /**
7281     * Interface definition for a callback to be invoked when the layout bounds of a view
7282     * changes due to layout processing.
7283     */
7284    public interface OnLayoutChangeListener {
7285        /**
7286         * Called when the focus state of a view has changed.
7287         *
7288         * @param v The view whose state has changed.
7289         * @param left The new value of the view's left property.
7290         * @param top The new value of the view's top property.
7291         * @param right The new value of the view's right property.
7292         * @param bottom The new value of the view's bottom property.
7293         * @param oldLeft The previous value of the view's left property.
7294         * @param oldTop The previous value of the view's top property.
7295         * @param oldRight The previous value of the view's right property.
7296         * @param oldBottom The previous value of the view's bottom property.
7297         */
7298        void onLayoutChange(View v, int left, int top, int right, int bottom,
7299            int oldLeft, int oldTop, int oldRight, int oldBottom);
7300    }
7301
7302    /**
7303     * This is called during layout when the size of this view has changed. If
7304     * you were just added to the view hierarchy, you're called with the old
7305     * values of 0.
7306     *
7307     * @param w Current width of this view.
7308     * @param h Current height of this view.
7309     * @param oldw Old width of this view.
7310     * @param oldh Old height of this view.
7311     */
7312    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7313    }
7314
7315    /**
7316     * Called by draw to draw the child views. This may be overridden
7317     * by derived classes to gain control just before its children are drawn
7318     * (but after its own view has been drawn).
7319     * @param canvas the canvas on which to draw the view
7320     */
7321    protected void dispatchDraw(Canvas canvas) {
7322    }
7323
7324    /**
7325     * Gets the parent of this view. Note that the parent is a
7326     * ViewParent and not necessarily a View.
7327     *
7328     * @return Parent of this view.
7329     */
7330    public final ViewParent getParent() {
7331        return mParent;
7332    }
7333
7334    /**
7335     * Set the horizontal scrolled position of your view. This will cause a call to
7336     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7337     * invalidated.
7338     * @param value the x position to scroll to
7339     */
7340    public void setScrollX(int value) {
7341        scrollTo(value, mScrollY);
7342    }
7343
7344    /**
7345     * Set the vertical scrolled position of your view. This will cause a call to
7346     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7347     * invalidated.
7348     * @param value the y position to scroll to
7349     */
7350    public void setScrollY(int value) {
7351        scrollTo(mScrollX, value);
7352    }
7353
7354    /**
7355     * Return the scrolled left position of this view. This is the left edge of
7356     * the displayed part of your view. You do not need to draw any pixels
7357     * farther left, since those are outside of the frame of your view on
7358     * screen.
7359     *
7360     * @return The left edge of the displayed part of your view, in pixels.
7361     */
7362    public final int getScrollX() {
7363        return mScrollX;
7364    }
7365
7366    /**
7367     * Return the scrolled top position of this view. This is the top edge of
7368     * the displayed part of your view. You do not need to draw any pixels above
7369     * it, since those are outside of the frame of your view on screen.
7370     *
7371     * @return The top edge of the displayed part of your view, in pixels.
7372     */
7373    public final int getScrollY() {
7374        return mScrollY;
7375    }
7376
7377    /**
7378     * Return the width of the your view.
7379     *
7380     * @return The width of your view, in pixels.
7381     */
7382    @ViewDebug.ExportedProperty(category = "layout")
7383    public final int getWidth() {
7384        return mRight - mLeft;
7385    }
7386
7387    /**
7388     * Return the height of your view.
7389     *
7390     * @return The height of your view, in pixels.
7391     */
7392    @ViewDebug.ExportedProperty(category = "layout")
7393    public final int getHeight() {
7394        return mBottom - mTop;
7395    }
7396
7397    /**
7398     * Return the visible drawing bounds of your view. Fills in the output
7399     * rectangle with the values from getScrollX(), getScrollY(),
7400     * getWidth(), and getHeight().
7401     *
7402     * @param outRect The (scrolled) drawing bounds of the view.
7403     */
7404    public void getDrawingRect(Rect outRect) {
7405        outRect.left = mScrollX;
7406        outRect.top = mScrollY;
7407        outRect.right = mScrollX + (mRight - mLeft);
7408        outRect.bottom = mScrollY + (mBottom - mTop);
7409    }
7410
7411    /**
7412     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7413     * raw width component (that is the result is masked by
7414     * {@link #MEASURED_SIZE_MASK}).
7415     *
7416     * @return The raw measured width of this view.
7417     */
7418    public final int getMeasuredWidth() {
7419        return mMeasuredWidth & MEASURED_SIZE_MASK;
7420    }
7421
7422    /**
7423     * Return the full width measurement information for this view as computed
7424     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7425     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7426     * This should be used during measurement and layout calculations only. Use
7427     * {@link #getWidth()} to see how wide a view is after layout.
7428     *
7429     * @return The measured width of this view as a bit mask.
7430     */
7431    public final int getMeasuredWidthAndState() {
7432        return mMeasuredWidth;
7433    }
7434
7435    /**
7436     * Like {@link #getMeasuredHeightAndState()}, but only returns the
7437     * raw width component (that is the result is masked by
7438     * {@link #MEASURED_SIZE_MASK}).
7439     *
7440     * @return The raw measured height of this view.
7441     */
7442    public final int getMeasuredHeight() {
7443        return mMeasuredHeight & MEASURED_SIZE_MASK;
7444    }
7445
7446    /**
7447     * Return the full height measurement information for this view as computed
7448     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7449     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7450     * This should be used during measurement and layout calculations only. Use
7451     * {@link #getHeight()} to see how wide a view is after layout.
7452     *
7453     * @return The measured width of this view as a bit mask.
7454     */
7455    public final int getMeasuredHeightAndState() {
7456        return mMeasuredHeight;
7457    }
7458
7459    /**
7460     * Return only the state bits of {@link #getMeasuredWidthAndState()}
7461     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
7462     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
7463     * and the height component is at the shifted bits
7464     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
7465     */
7466    public final int getMeasuredState() {
7467        return (mMeasuredWidth&MEASURED_STATE_MASK)
7468                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
7469                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
7470    }
7471
7472    /**
7473     * The transform matrix of this view, which is calculated based on the current
7474     * roation, scale, and pivot properties.
7475     *
7476     * @see #getRotation()
7477     * @see #getScaleX()
7478     * @see #getScaleY()
7479     * @see #getPivotX()
7480     * @see #getPivotY()
7481     * @return The current transform matrix for the view
7482     */
7483    public Matrix getMatrix() {
7484        if (mTransformationInfo != null) {
7485            updateMatrix();
7486            return mTransformationInfo.mMatrix;
7487        }
7488        return Matrix.IDENTITY_MATRIX;
7489    }
7490
7491    /**
7492     * Utility function to determine if the value is far enough away from zero to be
7493     * considered non-zero.
7494     * @param value A floating point value to check for zero-ness
7495     * @return whether the passed-in value is far enough away from zero to be considered non-zero
7496     */
7497    private static boolean nonzero(float value) {
7498        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
7499    }
7500
7501    /**
7502     * Returns true if the transform matrix is the identity matrix.
7503     * Recomputes the matrix if necessary.
7504     *
7505     * @return True if the transform matrix is the identity matrix, false otherwise.
7506     */
7507    final boolean hasIdentityMatrix() {
7508        if (mTransformationInfo != null) {
7509            updateMatrix();
7510            return mTransformationInfo.mMatrixIsIdentity;
7511        }
7512        return true;
7513    }
7514
7515    void ensureTransformationInfo() {
7516        if (mTransformationInfo == null) {
7517            mTransformationInfo = new TransformationInfo();
7518        }
7519    }
7520
7521    /**
7522     * Recomputes the transform matrix if necessary.
7523     */
7524    private void updateMatrix() {
7525        final TransformationInfo info = mTransformationInfo;
7526        if (info == null) {
7527            return;
7528        }
7529        if (info.mMatrixDirty) {
7530            // transform-related properties have changed since the last time someone
7531            // asked for the matrix; recalculate it with the current values
7532
7533            // Figure out if we need to update the pivot point
7534            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7535                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7536                    info.mPrevWidth = mRight - mLeft;
7537                    info.mPrevHeight = mBottom - mTop;
7538                    info.mPivotX = info.mPrevWidth / 2f;
7539                    info.mPivotY = info.mPrevHeight / 2f;
7540                }
7541            }
7542            info.mMatrix.reset();
7543            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7544                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7545                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7546                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7547            } else {
7548                if (info.mCamera == null) {
7549                    info.mCamera = new Camera();
7550                    info.matrix3D = new Matrix();
7551                }
7552                info.mCamera.save();
7553                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7554                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7555                info.mCamera.getMatrix(info.matrix3D);
7556                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7557                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7558                        info.mPivotY + info.mTranslationY);
7559                info.mMatrix.postConcat(info.matrix3D);
7560                info.mCamera.restore();
7561            }
7562            info.mMatrixDirty = false;
7563            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7564            info.mInverseMatrixDirty = true;
7565        }
7566    }
7567
7568    /**
7569     * Utility method to retrieve the inverse of the current mMatrix property.
7570     * We cache the matrix to avoid recalculating it when transform properties
7571     * have not changed.
7572     *
7573     * @return The inverse of the current matrix of this view.
7574     */
7575    final Matrix getInverseMatrix() {
7576        final TransformationInfo info = mTransformationInfo;
7577        if (info != null) {
7578            updateMatrix();
7579            if (info.mInverseMatrixDirty) {
7580                if (info.mInverseMatrix == null) {
7581                    info.mInverseMatrix = new Matrix();
7582                }
7583                info.mMatrix.invert(info.mInverseMatrix);
7584                info.mInverseMatrixDirty = false;
7585            }
7586            return info.mInverseMatrix;
7587        }
7588        return Matrix.IDENTITY_MATRIX;
7589    }
7590
7591    /**
7592     * Gets the distance along the Z axis from the camera to this view.
7593     *
7594     * @see #setCameraDistance(float)
7595     *
7596     * @return The distance along the Z axis.
7597     */
7598    public float getCameraDistance() {
7599        ensureTransformationInfo();
7600        final float dpi = mResources.getDisplayMetrics().densityDpi;
7601        final TransformationInfo info = mTransformationInfo;
7602        if (info.mCamera == null) {
7603            info.mCamera = new Camera();
7604            info.matrix3D = new Matrix();
7605        }
7606        return -(info.mCamera.getLocationZ() * dpi);
7607    }
7608
7609    /**
7610     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7611     * views are drawn) from the camera to this view. The camera's distance
7612     * affects 3D transformations, for instance rotations around the X and Y
7613     * axis. If the rotationX or rotationY properties are changed and this view is
7614     * large (more than half the size of the screen), it is recommended to always
7615     * use a camera distance that's greater than the height (X axis rotation) or
7616     * the width (Y axis rotation) of this view.</p>
7617     *
7618     * <p>The distance of the camera from the view plane can have an affect on the
7619     * perspective distortion of the view when it is rotated around the x or y axis.
7620     * For example, a large distance will result in a large viewing angle, and there
7621     * will not be much perspective distortion of the view as it rotates. A short
7622     * distance may cause much more perspective distortion upon rotation, and can
7623     * also result in some drawing artifacts if the rotated view ends up partially
7624     * behind the camera (which is why the recommendation is to use a distance at
7625     * least as far as the size of the view, if the view is to be rotated.)</p>
7626     *
7627     * <p>The distance is expressed in "depth pixels." The default distance depends
7628     * on the screen density. For instance, on a medium density display, the
7629     * default distance is 1280. On a high density display, the default distance
7630     * is 1920.</p>
7631     *
7632     * <p>If you want to specify a distance that leads to visually consistent
7633     * results across various densities, use the following formula:</p>
7634     * <pre>
7635     * float scale = context.getResources().getDisplayMetrics().density;
7636     * view.setCameraDistance(distance * scale);
7637     * </pre>
7638     *
7639     * <p>The density scale factor of a high density display is 1.5,
7640     * and 1920 = 1280 * 1.5.</p>
7641     *
7642     * @param distance The distance in "depth pixels", if negative the opposite
7643     *        value is used
7644     *
7645     * @see #setRotationX(float)
7646     * @see #setRotationY(float)
7647     */
7648    public void setCameraDistance(float distance) {
7649        invalidateViewProperty(true, false);
7650
7651        ensureTransformationInfo();
7652        final float dpi = mResources.getDisplayMetrics().densityDpi;
7653        final TransformationInfo info = mTransformationInfo;
7654        if (info.mCamera == null) {
7655            info.mCamera = new Camera();
7656            info.matrix3D = new Matrix();
7657        }
7658
7659        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7660        info.mMatrixDirty = true;
7661
7662        invalidateViewProperty(false, false);
7663        if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7664            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
7665        }
7666    }
7667
7668    /**
7669     * The degrees that the view is rotated around the pivot point.
7670     *
7671     * @see #setRotation(float)
7672     * @see #getPivotX()
7673     * @see #getPivotY()
7674     *
7675     * @return The degrees of rotation.
7676     */
7677    @ViewDebug.ExportedProperty(category = "drawing")
7678    public float getRotation() {
7679        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7680    }
7681
7682    /**
7683     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7684     * result in clockwise rotation.
7685     *
7686     * @param rotation The degrees of rotation.
7687     *
7688     * @see #getRotation()
7689     * @see #getPivotX()
7690     * @see #getPivotY()
7691     * @see #setRotationX(float)
7692     * @see #setRotationY(float)
7693     *
7694     * @attr ref android.R.styleable#View_rotation
7695     */
7696    public void setRotation(float rotation) {
7697        ensureTransformationInfo();
7698        final TransformationInfo info = mTransformationInfo;
7699        if (info.mRotation != rotation) {
7700            // Double-invalidation is necessary to capture view's old and new areas
7701            invalidateViewProperty(true, false);
7702            info.mRotation = rotation;
7703            info.mMatrixDirty = true;
7704            invalidateViewProperty(false, true);
7705            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7706                mDisplayList.setRotation(rotation);
7707            }
7708        }
7709    }
7710
7711    /**
7712     * The degrees that the view is rotated around the vertical axis through the pivot point.
7713     *
7714     * @see #getPivotX()
7715     * @see #getPivotY()
7716     * @see #setRotationY(float)
7717     *
7718     * @return The degrees of Y rotation.
7719     */
7720    @ViewDebug.ExportedProperty(category = "drawing")
7721    public float getRotationY() {
7722        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7723    }
7724
7725    /**
7726     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7727     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7728     * down the y axis.
7729     *
7730     * When rotating large views, it is recommended to adjust the camera distance
7731     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7732     *
7733     * @param rotationY The degrees of Y rotation.
7734     *
7735     * @see #getRotationY()
7736     * @see #getPivotX()
7737     * @see #getPivotY()
7738     * @see #setRotation(float)
7739     * @see #setRotationX(float)
7740     * @see #setCameraDistance(float)
7741     *
7742     * @attr ref android.R.styleable#View_rotationY
7743     */
7744    public void setRotationY(float rotationY) {
7745        ensureTransformationInfo();
7746        final TransformationInfo info = mTransformationInfo;
7747        if (info.mRotationY != rotationY) {
7748            invalidateViewProperty(true, false);
7749            info.mRotationY = rotationY;
7750            info.mMatrixDirty = true;
7751            invalidateViewProperty(false, true);
7752            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7753                mDisplayList.setRotationY(rotationY);
7754            }
7755        }
7756    }
7757
7758    /**
7759     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7760     *
7761     * @see #getPivotX()
7762     * @see #getPivotY()
7763     * @see #setRotationX(float)
7764     *
7765     * @return The degrees of X rotation.
7766     */
7767    @ViewDebug.ExportedProperty(category = "drawing")
7768    public float getRotationX() {
7769        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7770    }
7771
7772    /**
7773     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7774     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7775     * x axis.
7776     *
7777     * When rotating large views, it is recommended to adjust the camera distance
7778     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7779     *
7780     * @param rotationX The degrees of X rotation.
7781     *
7782     * @see #getRotationX()
7783     * @see #getPivotX()
7784     * @see #getPivotY()
7785     * @see #setRotation(float)
7786     * @see #setRotationY(float)
7787     * @see #setCameraDistance(float)
7788     *
7789     * @attr ref android.R.styleable#View_rotationX
7790     */
7791    public void setRotationX(float rotationX) {
7792        ensureTransformationInfo();
7793        final TransformationInfo info = mTransformationInfo;
7794        if (info.mRotationX != rotationX) {
7795            invalidateViewProperty(true, false);
7796            info.mRotationX = rotationX;
7797            info.mMatrixDirty = true;
7798            invalidateViewProperty(false, true);
7799            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7800                mDisplayList.setRotationX(rotationX);
7801            }
7802        }
7803    }
7804
7805    /**
7806     * The amount that the view is scaled in x around the pivot point, as a proportion of
7807     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7808     *
7809     * <p>By default, this is 1.0f.
7810     *
7811     * @see #getPivotX()
7812     * @see #getPivotY()
7813     * @return The scaling factor.
7814     */
7815    @ViewDebug.ExportedProperty(category = "drawing")
7816    public float getScaleX() {
7817        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7818    }
7819
7820    /**
7821     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7822     * the view's unscaled width. A value of 1 means that no scaling is applied.
7823     *
7824     * @param scaleX The scaling factor.
7825     * @see #getPivotX()
7826     * @see #getPivotY()
7827     *
7828     * @attr ref android.R.styleable#View_scaleX
7829     */
7830    public void setScaleX(float scaleX) {
7831        ensureTransformationInfo();
7832        final TransformationInfo info = mTransformationInfo;
7833        if (info.mScaleX != scaleX) {
7834            invalidateViewProperty(true, false);
7835            info.mScaleX = scaleX;
7836            info.mMatrixDirty = true;
7837            invalidateViewProperty(false, true);
7838            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7839                mDisplayList.setScaleX(scaleX);
7840            }
7841        }
7842    }
7843
7844    /**
7845     * The amount that the view is scaled in y around the pivot point, as a proportion of
7846     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7847     *
7848     * <p>By default, this is 1.0f.
7849     *
7850     * @see #getPivotX()
7851     * @see #getPivotY()
7852     * @return The scaling factor.
7853     */
7854    @ViewDebug.ExportedProperty(category = "drawing")
7855    public float getScaleY() {
7856        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7857    }
7858
7859    /**
7860     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7861     * the view's unscaled width. A value of 1 means that no scaling is applied.
7862     *
7863     * @param scaleY The scaling factor.
7864     * @see #getPivotX()
7865     * @see #getPivotY()
7866     *
7867     * @attr ref android.R.styleable#View_scaleY
7868     */
7869    public void setScaleY(float scaleY) {
7870        ensureTransformationInfo();
7871        final TransformationInfo info = mTransformationInfo;
7872        if (info.mScaleY != scaleY) {
7873            invalidateViewProperty(true, false);
7874            info.mScaleY = scaleY;
7875            info.mMatrixDirty = true;
7876            invalidateViewProperty(false, true);
7877            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7878                mDisplayList.setScaleY(scaleY);
7879            }
7880        }
7881    }
7882
7883    /**
7884     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7885     * and {@link #setScaleX(float) scaled}.
7886     *
7887     * @see #getRotation()
7888     * @see #getScaleX()
7889     * @see #getScaleY()
7890     * @see #getPivotY()
7891     * @return The x location of the pivot point.
7892     *
7893     * @attr ref android.R.styleable#View_transformPivotX
7894     */
7895    @ViewDebug.ExportedProperty(category = "drawing")
7896    public float getPivotX() {
7897        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7898    }
7899
7900    /**
7901     * Sets the x location of the point around which the view is
7902     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7903     * By default, the pivot point is centered on the object.
7904     * Setting this property disables this behavior and causes the view to use only the
7905     * explicitly set pivotX and pivotY values.
7906     *
7907     * @param pivotX The x location of the pivot point.
7908     * @see #getRotation()
7909     * @see #getScaleX()
7910     * @see #getScaleY()
7911     * @see #getPivotY()
7912     *
7913     * @attr ref android.R.styleable#View_transformPivotX
7914     */
7915    public void setPivotX(float pivotX) {
7916        ensureTransformationInfo();
7917        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7918        final TransformationInfo info = mTransformationInfo;
7919        if (info.mPivotX != pivotX) {
7920            invalidateViewProperty(true, false);
7921            info.mPivotX = pivotX;
7922            info.mMatrixDirty = true;
7923            invalidateViewProperty(false, true);
7924            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7925                mDisplayList.setPivotX(pivotX);
7926            }
7927        }
7928    }
7929
7930    /**
7931     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7932     * and {@link #setScaleY(float) scaled}.
7933     *
7934     * @see #getRotation()
7935     * @see #getScaleX()
7936     * @see #getScaleY()
7937     * @see #getPivotY()
7938     * @return The y location of the pivot point.
7939     *
7940     * @attr ref android.R.styleable#View_transformPivotY
7941     */
7942    @ViewDebug.ExportedProperty(category = "drawing")
7943    public float getPivotY() {
7944        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7945    }
7946
7947    /**
7948     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7949     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7950     * Setting this property disables this behavior and causes the view to use only the
7951     * explicitly set pivotX and pivotY values.
7952     *
7953     * @param pivotY The y location of the pivot point.
7954     * @see #getRotation()
7955     * @see #getScaleX()
7956     * @see #getScaleY()
7957     * @see #getPivotY()
7958     *
7959     * @attr ref android.R.styleable#View_transformPivotY
7960     */
7961    public void setPivotY(float pivotY) {
7962        ensureTransformationInfo();
7963        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7964        final TransformationInfo info = mTransformationInfo;
7965        if (info.mPivotY != pivotY) {
7966            invalidateViewProperty(true, false);
7967            info.mPivotY = pivotY;
7968            info.mMatrixDirty = true;
7969            invalidateViewProperty(false, true);
7970            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7971                mDisplayList.setPivotY(pivotY);
7972            }
7973        }
7974    }
7975
7976    /**
7977     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7978     * completely transparent and 1 means the view is completely opaque.
7979     *
7980     * <p>By default this is 1.0f.
7981     * @return The opacity of the view.
7982     */
7983    @ViewDebug.ExportedProperty(category = "drawing")
7984    public float getAlpha() {
7985        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7986    }
7987
7988    /**
7989     * Returns whether this View has content which overlaps. This function, intended to be
7990     * overridden by specific View types, is an optimization when alpha is set on a view. If
7991     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
7992     * and then composited it into place, which can be expensive. If the view has no overlapping
7993     * rendering, the view can draw each primitive with the appropriate alpha value directly.
7994     * An example of overlapping rendering is a TextView with a background image, such as a
7995     * Button. An example of non-overlapping rendering is a TextView with no background, or
7996     * an ImageView with only the foreground image. The default implementation returns true;
7997     * subclasses should override if they have cases which can be optimized.
7998     *
7999     * @return true if the content in this view might overlap, false otherwise.
8000     */
8001    public boolean hasOverlappingRendering() {
8002        return true;
8003    }
8004
8005    /**
8006     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8007     * completely transparent and 1 means the view is completely opaque.</p>
8008     *
8009     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8010     * responsible for applying the opacity itself. Otherwise, calling this method is
8011     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8012     * setting a hardware layer.</p>
8013     *
8014     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8015     * performance implications. It is generally best to use the alpha property sparingly and
8016     * transiently, as in the case of fading animations.</p>
8017     *
8018     * @param alpha The opacity of the view.
8019     *
8020     * @see #setLayerType(int, android.graphics.Paint)
8021     *
8022     * @attr ref android.R.styleable#View_alpha
8023     */
8024    public void setAlpha(float alpha) {
8025        ensureTransformationInfo();
8026        if (mTransformationInfo.mAlpha != alpha) {
8027            mTransformationInfo.mAlpha = alpha;
8028            if (onSetAlpha((int) (alpha * 255))) {
8029                mPrivateFlags |= ALPHA_SET;
8030                // subclass is handling alpha - don't optimize rendering cache invalidation
8031                invalidateParentCaches();
8032                invalidate(true);
8033            } else {
8034                mPrivateFlags &= ~ALPHA_SET;
8035                invalidateViewProperty(true, false);
8036                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8037                    mDisplayList.setAlpha(alpha);
8038                }
8039            }
8040        }
8041    }
8042
8043    /**
8044     * Faster version of setAlpha() which performs the same steps except there are
8045     * no calls to invalidate(). The caller of this function should perform proper invalidation
8046     * on the parent and this object. The return value indicates whether the subclass handles
8047     * alpha (the return value for onSetAlpha()).
8048     *
8049     * @param alpha The new value for the alpha property
8050     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
8051     *         the new value for the alpha property is different from the old value
8052     */
8053    boolean setAlphaNoInvalidation(float alpha) {
8054        ensureTransformationInfo();
8055        if (mTransformationInfo.mAlpha != alpha) {
8056            mTransformationInfo.mAlpha = alpha;
8057            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
8058            if (subclassHandlesAlpha) {
8059                mPrivateFlags |= ALPHA_SET;
8060                return true;
8061            } else {
8062                mPrivateFlags &= ~ALPHA_SET;
8063                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8064                    mDisplayList.setAlpha(alpha);
8065                }
8066            }
8067        }
8068        return false;
8069    }
8070
8071    /**
8072     * Top position of this view relative to its parent.
8073     *
8074     * @return The top of this view, in pixels.
8075     */
8076    @ViewDebug.CapturedViewProperty
8077    public final int getTop() {
8078        return mTop;
8079    }
8080
8081    /**
8082     * Sets the top position of this view relative to its parent. This method is meant to be called
8083     * by the layout system and should not generally be called otherwise, because the property
8084     * may be changed at any time by the layout.
8085     *
8086     * @param top The top of this view, in pixels.
8087     */
8088    public final void setTop(int top) {
8089        if (top != mTop) {
8090            updateMatrix();
8091            final boolean matrixIsIdentity = mTransformationInfo == null
8092                    || mTransformationInfo.mMatrixIsIdentity;
8093            if (matrixIsIdentity) {
8094                if (mAttachInfo != null) {
8095                    int minTop;
8096                    int yLoc;
8097                    if (top < mTop) {
8098                        minTop = top;
8099                        yLoc = top - mTop;
8100                    } else {
8101                        minTop = mTop;
8102                        yLoc = 0;
8103                    }
8104                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
8105                }
8106            } else {
8107                // Double-invalidation is necessary to capture view's old and new areas
8108                invalidate(true);
8109            }
8110
8111            int width = mRight - mLeft;
8112            int oldHeight = mBottom - mTop;
8113
8114            mTop = top;
8115            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8116                mDisplayList.setTop(mTop);
8117            }
8118
8119            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8120
8121            if (!matrixIsIdentity) {
8122                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8123                    // A change in dimension means an auto-centered pivot point changes, too
8124                    mTransformationInfo.mMatrixDirty = true;
8125                }
8126                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8127                invalidate(true);
8128            }
8129            mBackgroundSizeChanged = true;
8130            invalidateParentIfNeeded();
8131        }
8132    }
8133
8134    /**
8135     * Bottom position of this view relative to its parent.
8136     *
8137     * @return The bottom of this view, in pixels.
8138     */
8139    @ViewDebug.CapturedViewProperty
8140    public final int getBottom() {
8141        return mBottom;
8142    }
8143
8144    /**
8145     * True if this view has changed since the last time being drawn.
8146     *
8147     * @return The dirty state of this view.
8148     */
8149    public boolean isDirty() {
8150        return (mPrivateFlags & DIRTY_MASK) != 0;
8151    }
8152
8153    /**
8154     * Sets the bottom position of this view relative to its parent. This method is meant to be
8155     * called by the layout system and should not generally be called otherwise, because the
8156     * property may be changed at any time by the layout.
8157     *
8158     * @param bottom The bottom of this view, in pixels.
8159     */
8160    public final void setBottom(int bottom) {
8161        if (bottom != mBottom) {
8162            updateMatrix();
8163            final boolean matrixIsIdentity = mTransformationInfo == null
8164                    || mTransformationInfo.mMatrixIsIdentity;
8165            if (matrixIsIdentity) {
8166                if (mAttachInfo != null) {
8167                    int maxBottom;
8168                    if (bottom < mBottom) {
8169                        maxBottom = mBottom;
8170                    } else {
8171                        maxBottom = bottom;
8172                    }
8173                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
8174                }
8175            } else {
8176                // Double-invalidation is necessary to capture view's old and new areas
8177                invalidate(true);
8178            }
8179
8180            int width = mRight - mLeft;
8181            int oldHeight = mBottom - mTop;
8182
8183            mBottom = bottom;
8184            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8185                mDisplayList.setBottom(mBottom);
8186            }
8187
8188            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8189
8190            if (!matrixIsIdentity) {
8191                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8192                    // A change in dimension means an auto-centered pivot point changes, too
8193                    mTransformationInfo.mMatrixDirty = true;
8194                }
8195                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8196                invalidate(true);
8197            }
8198            mBackgroundSizeChanged = true;
8199            invalidateParentIfNeeded();
8200        }
8201    }
8202
8203    /**
8204     * Left position of this view relative to its parent.
8205     *
8206     * @return The left edge of this view, in pixels.
8207     */
8208    @ViewDebug.CapturedViewProperty
8209    public final int getLeft() {
8210        return mLeft;
8211    }
8212
8213    /**
8214     * Sets the left position of this view relative to its parent. This method is meant to be called
8215     * by the layout system and should not generally be called otherwise, because the property
8216     * may be changed at any time by the layout.
8217     *
8218     * @param left The bottom of this view, in pixels.
8219     */
8220    public final void setLeft(int left) {
8221        if (left != mLeft) {
8222            updateMatrix();
8223            final boolean matrixIsIdentity = mTransformationInfo == null
8224                    || mTransformationInfo.mMatrixIsIdentity;
8225            if (matrixIsIdentity) {
8226                if (mAttachInfo != null) {
8227                    int minLeft;
8228                    int xLoc;
8229                    if (left < mLeft) {
8230                        minLeft = left;
8231                        xLoc = left - mLeft;
8232                    } else {
8233                        minLeft = mLeft;
8234                        xLoc = 0;
8235                    }
8236                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
8237                }
8238            } else {
8239                // Double-invalidation is necessary to capture view's old and new areas
8240                invalidate(true);
8241            }
8242
8243            int oldWidth = mRight - mLeft;
8244            int height = mBottom - mTop;
8245
8246            mLeft = left;
8247            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8248                mDisplayList.setLeft(left);
8249            }
8250
8251            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8252
8253            if (!matrixIsIdentity) {
8254                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8255                    // A change in dimension means an auto-centered pivot point changes, too
8256                    mTransformationInfo.mMatrixDirty = true;
8257                }
8258                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8259                invalidate(true);
8260            }
8261            mBackgroundSizeChanged = true;
8262            invalidateParentIfNeeded();
8263            if (USE_DISPLAY_LIST_PROPERTIES) {
8264
8265            }
8266        }
8267    }
8268
8269    /**
8270     * Right position of this view relative to its parent.
8271     *
8272     * @return The right edge of this view, in pixels.
8273     */
8274    @ViewDebug.CapturedViewProperty
8275    public final int getRight() {
8276        return mRight;
8277    }
8278
8279    /**
8280     * Sets the right position of this view relative to its parent. This method is meant to be called
8281     * by the layout system and should not generally be called otherwise, because the property
8282     * may be changed at any time by the layout.
8283     *
8284     * @param right The bottom of this view, in pixels.
8285     */
8286    public final void setRight(int right) {
8287        if (right != mRight) {
8288            updateMatrix();
8289            final boolean matrixIsIdentity = mTransformationInfo == null
8290                    || mTransformationInfo.mMatrixIsIdentity;
8291            if (matrixIsIdentity) {
8292                if (mAttachInfo != null) {
8293                    int maxRight;
8294                    if (right < mRight) {
8295                        maxRight = mRight;
8296                    } else {
8297                        maxRight = right;
8298                    }
8299                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
8300                }
8301            } else {
8302                // Double-invalidation is necessary to capture view's old and new areas
8303                invalidate(true);
8304            }
8305
8306            int oldWidth = mRight - mLeft;
8307            int height = mBottom - mTop;
8308
8309            mRight = right;
8310            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8311                mDisplayList.setRight(mRight);
8312            }
8313
8314            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8315
8316            if (!matrixIsIdentity) {
8317                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8318                    // A change in dimension means an auto-centered pivot point changes, too
8319                    mTransformationInfo.mMatrixDirty = true;
8320                }
8321                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8322                invalidate(true);
8323            }
8324            mBackgroundSizeChanged = true;
8325            invalidateParentIfNeeded();
8326        }
8327    }
8328
8329    /**
8330     * The visual x position of this view, in pixels. This is equivalent to the
8331     * {@link #setTranslationX(float) translationX} property plus the current
8332     * {@link #getLeft() left} property.
8333     *
8334     * @return The visual x position of this view, in pixels.
8335     */
8336    @ViewDebug.ExportedProperty(category = "drawing")
8337    public float getX() {
8338        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8339    }
8340
8341    /**
8342     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8343     * {@link #setTranslationX(float) translationX} property to be the difference between
8344     * the x value passed in and the current {@link #getLeft() left} property.
8345     *
8346     * @param x The visual x position of this view, in pixels.
8347     */
8348    public void setX(float x) {
8349        setTranslationX(x - mLeft);
8350    }
8351
8352    /**
8353     * The visual y position of this view, in pixels. This is equivalent to the
8354     * {@link #setTranslationY(float) translationY} property plus the current
8355     * {@link #getTop() top} property.
8356     *
8357     * @return The visual y position of this view, in pixels.
8358     */
8359    @ViewDebug.ExportedProperty(category = "drawing")
8360    public float getY() {
8361        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
8362    }
8363
8364    /**
8365     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
8366     * {@link #setTranslationY(float) translationY} property to be the difference between
8367     * the y value passed in and the current {@link #getTop() top} property.
8368     *
8369     * @param y The visual y position of this view, in pixels.
8370     */
8371    public void setY(float y) {
8372        setTranslationY(y - mTop);
8373    }
8374
8375
8376    /**
8377     * The horizontal location of this view relative to its {@link #getLeft() left} position.
8378     * This position is post-layout, in addition to wherever the object's
8379     * layout placed it.
8380     *
8381     * @return The horizontal position of this view relative to its left position, in pixels.
8382     */
8383    @ViewDebug.ExportedProperty(category = "drawing")
8384    public float getTranslationX() {
8385        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
8386    }
8387
8388    /**
8389     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
8390     * This effectively positions the object post-layout, in addition to wherever the object's
8391     * layout placed it.
8392     *
8393     * @param translationX The horizontal position of this view relative to its left position,
8394     * in pixels.
8395     *
8396     * @attr ref android.R.styleable#View_translationX
8397     */
8398    public void setTranslationX(float translationX) {
8399        ensureTransformationInfo();
8400        final TransformationInfo info = mTransformationInfo;
8401        if (info.mTranslationX != translationX) {
8402            // Double-invalidation is necessary to capture view's old and new areas
8403            invalidateViewProperty(true, false);
8404            info.mTranslationX = translationX;
8405            info.mMatrixDirty = true;
8406            invalidateViewProperty(false, true);
8407            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8408                mDisplayList.setTranslationX(translationX);
8409            }
8410        }
8411    }
8412
8413    /**
8414     * The horizontal location of this view relative to its {@link #getTop() top} position.
8415     * This position is post-layout, in addition to wherever the object's
8416     * layout placed it.
8417     *
8418     * @return The vertical position of this view relative to its top position,
8419     * in pixels.
8420     */
8421    @ViewDebug.ExportedProperty(category = "drawing")
8422    public float getTranslationY() {
8423        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
8424    }
8425
8426    /**
8427     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
8428     * This effectively positions the object post-layout, in addition to wherever the object's
8429     * layout placed it.
8430     *
8431     * @param translationY The vertical position of this view relative to its top position,
8432     * in pixels.
8433     *
8434     * @attr ref android.R.styleable#View_translationY
8435     */
8436    public void setTranslationY(float translationY) {
8437        ensureTransformationInfo();
8438        final TransformationInfo info = mTransformationInfo;
8439        if (info.mTranslationY != translationY) {
8440            invalidateViewProperty(true, false);
8441            info.mTranslationY = translationY;
8442            info.mMatrixDirty = true;
8443            invalidateViewProperty(false, true);
8444            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8445                mDisplayList.setTranslationY(translationY);
8446            }
8447        }
8448    }
8449
8450    /**
8451     * Hit rectangle in parent's coordinates
8452     *
8453     * @param outRect The hit rectangle of the view.
8454     */
8455    public void getHitRect(Rect outRect) {
8456        updateMatrix();
8457        final TransformationInfo info = mTransformationInfo;
8458        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
8459            outRect.set(mLeft, mTop, mRight, mBottom);
8460        } else {
8461            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
8462            tmpRect.set(-info.mPivotX, -info.mPivotY,
8463                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
8464            info.mMatrix.mapRect(tmpRect);
8465            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
8466                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
8467        }
8468    }
8469
8470    /**
8471     * Determines whether the given point, in local coordinates is inside the view.
8472     */
8473    /*package*/ final boolean pointInView(float localX, float localY) {
8474        return localX >= 0 && localX < (mRight - mLeft)
8475                && localY >= 0 && localY < (mBottom - mTop);
8476    }
8477
8478    /**
8479     * Utility method to determine whether the given point, in local coordinates,
8480     * is inside the view, where the area of the view is expanded by the slop factor.
8481     * This method is called while processing touch-move events to determine if the event
8482     * is still within the view.
8483     */
8484    private boolean pointInView(float localX, float localY, float slop) {
8485        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
8486                localY < ((mBottom - mTop) + slop);
8487    }
8488
8489    /**
8490     * When a view has focus and the user navigates away from it, the next view is searched for
8491     * starting from the rectangle filled in by this method.
8492     *
8493     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
8494     * of the view.  However, if your view maintains some idea of internal selection,
8495     * such as a cursor, or a selected row or column, you should override this method and
8496     * fill in a more specific rectangle.
8497     *
8498     * @param r The rectangle to fill in, in this view's coordinates.
8499     */
8500    public void getFocusedRect(Rect r) {
8501        getDrawingRect(r);
8502    }
8503
8504    /**
8505     * If some part of this view is not clipped by any of its parents, then
8506     * return that area in r in global (root) coordinates. To convert r to local
8507     * coordinates (without taking possible View rotations into account), offset
8508     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
8509     * If the view is completely clipped or translated out, return false.
8510     *
8511     * @param r If true is returned, r holds the global coordinates of the
8512     *        visible portion of this view.
8513     * @param globalOffset If true is returned, globalOffset holds the dx,dy
8514     *        between this view and its root. globalOffet may be null.
8515     * @return true if r is non-empty (i.e. part of the view is visible at the
8516     *         root level.
8517     */
8518    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
8519        int width = mRight - mLeft;
8520        int height = mBottom - mTop;
8521        if (width > 0 && height > 0) {
8522            r.set(0, 0, width, height);
8523            if (globalOffset != null) {
8524                globalOffset.set(-mScrollX, -mScrollY);
8525            }
8526            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8527        }
8528        return false;
8529    }
8530
8531    public final boolean getGlobalVisibleRect(Rect r) {
8532        return getGlobalVisibleRect(r, null);
8533    }
8534
8535    public final boolean getLocalVisibleRect(Rect r) {
8536        Point offset = new Point();
8537        if (getGlobalVisibleRect(r, offset)) {
8538            r.offset(-offset.x, -offset.y); // make r local
8539            return true;
8540        }
8541        return false;
8542    }
8543
8544    /**
8545     * Offset this view's vertical location by the specified number of pixels.
8546     *
8547     * @param offset the number of pixels to offset the view by
8548     */
8549    public void offsetTopAndBottom(int offset) {
8550        if (offset != 0) {
8551            updateMatrix();
8552            final boolean matrixIsIdentity = mTransformationInfo == null
8553                    || mTransformationInfo.mMatrixIsIdentity;
8554            if (matrixIsIdentity) {
8555                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8556                    invalidateViewProperty(false, false);
8557                } else {
8558                    final ViewParent p = mParent;
8559                    if (p != null && mAttachInfo != null) {
8560                        final Rect r = mAttachInfo.mTmpInvalRect;
8561                        int minTop;
8562                        int maxBottom;
8563                        int yLoc;
8564                        if (offset < 0) {
8565                            minTop = mTop + offset;
8566                            maxBottom = mBottom;
8567                            yLoc = offset;
8568                        } else {
8569                            minTop = mTop;
8570                            maxBottom = mBottom + offset;
8571                            yLoc = 0;
8572                        }
8573                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8574                        p.invalidateChild(this, r);
8575                    }
8576                }
8577            } else {
8578                invalidateViewProperty(false, false);
8579            }
8580
8581            mTop += offset;
8582            mBottom += offset;
8583            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8584                mDisplayList.offsetTopBottom(offset);
8585                invalidateViewProperty(false, false);
8586            } else {
8587                if (!matrixIsIdentity) {
8588                    invalidateViewProperty(false, true);
8589                }
8590                invalidateParentIfNeeded();
8591            }
8592        }
8593    }
8594
8595    /**
8596     * Offset this view's horizontal location by the specified amount of pixels.
8597     *
8598     * @param offset the numer of pixels to offset the view by
8599     */
8600    public void offsetLeftAndRight(int offset) {
8601        if (offset != 0) {
8602            updateMatrix();
8603            final boolean matrixIsIdentity = mTransformationInfo == null
8604                    || mTransformationInfo.mMatrixIsIdentity;
8605            if (matrixIsIdentity) {
8606                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8607                    invalidateViewProperty(false, false);
8608                } else {
8609                    final ViewParent p = mParent;
8610                    if (p != null && mAttachInfo != null) {
8611                        final Rect r = mAttachInfo.mTmpInvalRect;
8612                        int minLeft;
8613                        int maxRight;
8614                        if (offset < 0) {
8615                            minLeft = mLeft + offset;
8616                            maxRight = mRight;
8617                        } else {
8618                            minLeft = mLeft;
8619                            maxRight = mRight + offset;
8620                        }
8621                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8622                        p.invalidateChild(this, r);
8623                    }
8624                }
8625            } else {
8626                invalidateViewProperty(false, false);
8627            }
8628
8629            mLeft += offset;
8630            mRight += offset;
8631            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8632                mDisplayList.offsetLeftRight(offset);
8633                invalidateViewProperty(false, false);
8634            } else {
8635                if (!matrixIsIdentity) {
8636                    invalidateViewProperty(false, true);
8637                }
8638                invalidateParentIfNeeded();
8639            }
8640        }
8641    }
8642
8643    /**
8644     * Get the LayoutParams associated with this view. All views should have
8645     * layout parameters. These supply parameters to the <i>parent</i> of this
8646     * view specifying how it should be arranged. There are many subclasses of
8647     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8648     * of ViewGroup that are responsible for arranging their children.
8649     *
8650     * This method may return null if this View is not attached to a parent
8651     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8652     * was not invoked successfully. When a View is attached to a parent
8653     * ViewGroup, this method must not return null.
8654     *
8655     * @return The LayoutParams associated with this view, or null if no
8656     *         parameters have been set yet
8657     */
8658    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8659    public ViewGroup.LayoutParams getLayoutParams() {
8660        return mLayoutParams;
8661    }
8662
8663    /**
8664     * Set the layout parameters associated with this view. These supply
8665     * parameters to the <i>parent</i> of this view specifying how it should be
8666     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8667     * correspond to the different subclasses of ViewGroup that are responsible
8668     * for arranging their children.
8669     *
8670     * @param params The layout parameters for this view, cannot be null
8671     */
8672    public void setLayoutParams(ViewGroup.LayoutParams params) {
8673        if (params == null) {
8674            throw new NullPointerException("Layout parameters cannot be null");
8675        }
8676        mLayoutParams = params;
8677        if (mParent instanceof ViewGroup) {
8678            ((ViewGroup) mParent).onSetLayoutParams(this, params);
8679        }
8680        requestLayout();
8681    }
8682
8683    /**
8684     * Set the scrolled position of your view. This will cause a call to
8685     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8686     * invalidated.
8687     * @param x the x position to scroll to
8688     * @param y the y position to scroll to
8689     */
8690    public void scrollTo(int x, int y) {
8691        if (mScrollX != x || mScrollY != y) {
8692            int oldX = mScrollX;
8693            int oldY = mScrollY;
8694            mScrollX = x;
8695            mScrollY = y;
8696            invalidateParentCaches();
8697            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8698            if (!awakenScrollBars()) {
8699                invalidate(true);
8700            }
8701        }
8702    }
8703
8704    /**
8705     * Move the scrolled position of your view. This will cause a call to
8706     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8707     * invalidated.
8708     * @param x the amount of pixels to scroll by horizontally
8709     * @param y the amount of pixels to scroll by vertically
8710     */
8711    public void scrollBy(int x, int y) {
8712        scrollTo(mScrollX + x, mScrollY + y);
8713    }
8714
8715    /**
8716     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8717     * animation to fade the scrollbars out after a default delay. If a subclass
8718     * provides animated scrolling, the start delay should equal the duration
8719     * of the scrolling animation.</p>
8720     *
8721     * <p>The animation starts only if at least one of the scrollbars is
8722     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8723     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8724     * this method returns true, and false otherwise. If the animation is
8725     * started, this method calls {@link #invalidate()}; in that case the
8726     * caller should not call {@link #invalidate()}.</p>
8727     *
8728     * <p>This method should be invoked every time a subclass directly updates
8729     * the scroll parameters.</p>
8730     *
8731     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8732     * and {@link #scrollTo(int, int)}.</p>
8733     *
8734     * @return true if the animation is played, false otherwise
8735     *
8736     * @see #awakenScrollBars(int)
8737     * @see #scrollBy(int, int)
8738     * @see #scrollTo(int, int)
8739     * @see #isHorizontalScrollBarEnabled()
8740     * @see #isVerticalScrollBarEnabled()
8741     * @see #setHorizontalScrollBarEnabled(boolean)
8742     * @see #setVerticalScrollBarEnabled(boolean)
8743     */
8744    protected boolean awakenScrollBars() {
8745        return mScrollCache != null &&
8746                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8747    }
8748
8749    /**
8750     * Trigger the scrollbars to draw.
8751     * This method differs from awakenScrollBars() only in its default duration.
8752     * initialAwakenScrollBars() will show the scroll bars for longer than
8753     * usual to give the user more of a chance to notice them.
8754     *
8755     * @return true if the animation is played, false otherwise.
8756     */
8757    private boolean initialAwakenScrollBars() {
8758        return mScrollCache != null &&
8759                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8760    }
8761
8762    /**
8763     * <p>
8764     * Trigger the scrollbars to draw. When invoked this method starts an
8765     * animation to fade the scrollbars out after a fixed delay. If a subclass
8766     * provides animated scrolling, the start delay should equal the duration of
8767     * the scrolling animation.
8768     * </p>
8769     *
8770     * <p>
8771     * The animation starts only if at least one of the scrollbars is enabled,
8772     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8773     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8774     * this method returns true, and false otherwise. If the animation is
8775     * started, this method calls {@link #invalidate()}; in that case the caller
8776     * should not call {@link #invalidate()}.
8777     * </p>
8778     *
8779     * <p>
8780     * This method should be invoked everytime a subclass directly updates the
8781     * scroll parameters.
8782     * </p>
8783     *
8784     * @param startDelay the delay, in milliseconds, after which the animation
8785     *        should start; when the delay is 0, the animation starts
8786     *        immediately
8787     * @return true if the animation is played, false otherwise
8788     *
8789     * @see #scrollBy(int, int)
8790     * @see #scrollTo(int, int)
8791     * @see #isHorizontalScrollBarEnabled()
8792     * @see #isVerticalScrollBarEnabled()
8793     * @see #setHorizontalScrollBarEnabled(boolean)
8794     * @see #setVerticalScrollBarEnabled(boolean)
8795     */
8796    protected boolean awakenScrollBars(int startDelay) {
8797        return awakenScrollBars(startDelay, true);
8798    }
8799
8800    /**
8801     * <p>
8802     * Trigger the scrollbars to draw. When invoked this method starts an
8803     * animation to fade the scrollbars out after a fixed delay. If a subclass
8804     * provides animated scrolling, the start delay should equal the duration of
8805     * the scrolling animation.
8806     * </p>
8807     *
8808     * <p>
8809     * The animation starts only if at least one of the scrollbars is enabled,
8810     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8811     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8812     * this method returns true, and false otherwise. If the animation is
8813     * started, this method calls {@link #invalidate()} if the invalidate parameter
8814     * is set to true; in that case the caller
8815     * should not call {@link #invalidate()}.
8816     * </p>
8817     *
8818     * <p>
8819     * This method should be invoked everytime a subclass directly updates the
8820     * scroll parameters.
8821     * </p>
8822     *
8823     * @param startDelay the delay, in milliseconds, after which the animation
8824     *        should start; when the delay is 0, the animation starts
8825     *        immediately
8826     *
8827     * @param invalidate Wheter this method should call invalidate
8828     *
8829     * @return true if the animation is played, false otherwise
8830     *
8831     * @see #scrollBy(int, int)
8832     * @see #scrollTo(int, int)
8833     * @see #isHorizontalScrollBarEnabled()
8834     * @see #isVerticalScrollBarEnabled()
8835     * @see #setHorizontalScrollBarEnabled(boolean)
8836     * @see #setVerticalScrollBarEnabled(boolean)
8837     */
8838    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8839        final ScrollabilityCache scrollCache = mScrollCache;
8840
8841        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8842            return false;
8843        }
8844
8845        if (scrollCache.scrollBar == null) {
8846            scrollCache.scrollBar = new ScrollBarDrawable();
8847        }
8848
8849        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8850
8851            if (invalidate) {
8852                // Invalidate to show the scrollbars
8853                invalidate(true);
8854            }
8855
8856            if (scrollCache.state == ScrollabilityCache.OFF) {
8857                // FIXME: this is copied from WindowManagerService.
8858                // We should get this value from the system when it
8859                // is possible to do so.
8860                final int KEY_REPEAT_FIRST_DELAY = 750;
8861                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8862            }
8863
8864            // Tell mScrollCache when we should start fading. This may
8865            // extend the fade start time if one was already scheduled
8866            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8867            scrollCache.fadeStartTime = fadeStartTime;
8868            scrollCache.state = ScrollabilityCache.ON;
8869
8870            // Schedule our fader to run, unscheduling any old ones first
8871            if (mAttachInfo != null) {
8872                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8873                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8874            }
8875
8876            return true;
8877        }
8878
8879        return false;
8880    }
8881
8882    /**
8883     * Do not invalidate views which are not visible and which are not running an animation. They
8884     * will not get drawn and they should not set dirty flags as if they will be drawn
8885     */
8886    private boolean skipInvalidate() {
8887        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8888                (!(mParent instanceof ViewGroup) ||
8889                        !((ViewGroup) mParent).isViewTransitioning(this));
8890    }
8891    /**
8892     * Mark the area defined by dirty as needing to be drawn. If the view is
8893     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8894     * in the future. This must be called from a UI thread. To call from a non-UI
8895     * thread, call {@link #postInvalidate()}.
8896     *
8897     * WARNING: This method is destructive to dirty.
8898     * @param dirty the rectangle representing the bounds of the dirty region
8899     */
8900    public void invalidate(Rect dirty) {
8901        if (ViewDebug.TRACE_HIERARCHY) {
8902            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8903        }
8904
8905        if (skipInvalidate()) {
8906            return;
8907        }
8908        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8909                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8910                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8911            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8912            mPrivateFlags |= INVALIDATED;
8913            mPrivateFlags |= DIRTY;
8914            final ViewParent p = mParent;
8915            final AttachInfo ai = mAttachInfo;
8916            //noinspection PointlessBooleanExpression,ConstantConditions
8917            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8918                if (p != null && ai != null && ai.mHardwareAccelerated) {
8919                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8920                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8921                    p.invalidateChild(this, null);
8922                    return;
8923                }
8924            }
8925            if (p != null && ai != null) {
8926                final int scrollX = mScrollX;
8927                final int scrollY = mScrollY;
8928                final Rect r = ai.mTmpInvalRect;
8929                r.set(dirty.left - scrollX, dirty.top - scrollY,
8930                        dirty.right - scrollX, dirty.bottom - scrollY);
8931                mParent.invalidateChild(this, r);
8932            }
8933        }
8934    }
8935
8936    /**
8937     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
8938     * The coordinates of the dirty rect are relative to the view.
8939     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8940     * will be called at some point in the future. This must be called from
8941     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8942     * @param l the left position of the dirty region
8943     * @param t the top position of the dirty region
8944     * @param r the right position of the dirty region
8945     * @param b the bottom position of the dirty region
8946     */
8947    public void invalidate(int l, int t, int r, int b) {
8948        if (ViewDebug.TRACE_HIERARCHY) {
8949            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8950        }
8951
8952        if (skipInvalidate()) {
8953            return;
8954        }
8955        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8956                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8957                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8958            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8959            mPrivateFlags |= INVALIDATED;
8960            mPrivateFlags |= DIRTY;
8961            final ViewParent p = mParent;
8962            final AttachInfo ai = mAttachInfo;
8963            //noinspection PointlessBooleanExpression,ConstantConditions
8964            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8965                if (p != null && ai != null && ai.mHardwareAccelerated) {
8966                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8967                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8968                    p.invalidateChild(this, null);
8969                    return;
8970                }
8971            }
8972            if (p != null && ai != null && l < r && t < b) {
8973                final int scrollX = mScrollX;
8974                final int scrollY = mScrollY;
8975                final Rect tmpr = ai.mTmpInvalRect;
8976                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8977                p.invalidateChild(this, tmpr);
8978            }
8979        }
8980    }
8981
8982    /**
8983     * Invalidate the whole view. If the view is visible,
8984     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8985     * the future. This must be called from a UI thread. To call from a non-UI thread,
8986     * call {@link #postInvalidate()}.
8987     */
8988    public void invalidate() {
8989        invalidate(true);
8990    }
8991
8992    /**
8993     * This is where the invalidate() work actually happens. A full invalidate()
8994     * causes the drawing cache to be invalidated, but this function can be called with
8995     * invalidateCache set to false to skip that invalidation step for cases that do not
8996     * need it (for example, a component that remains at the same dimensions with the same
8997     * content).
8998     *
8999     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9000     * well. This is usually true for a full invalidate, but may be set to false if the
9001     * View's contents or dimensions have not changed.
9002     */
9003    void invalidate(boolean invalidateCache) {
9004        if (ViewDebug.TRACE_HIERARCHY) {
9005            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9006        }
9007
9008        if (skipInvalidate()) {
9009            return;
9010        }
9011        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9012                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9013                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9014            mLastIsOpaque = isOpaque();
9015            mPrivateFlags &= ~DRAWN;
9016            mPrivateFlags |= DIRTY;
9017            if (invalidateCache) {
9018                mPrivateFlags |= INVALIDATED;
9019                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9020            }
9021            final AttachInfo ai = mAttachInfo;
9022            final ViewParent p = mParent;
9023            //noinspection PointlessBooleanExpression,ConstantConditions
9024            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9025                if (p != null && ai != null && ai.mHardwareAccelerated) {
9026                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9027                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9028                    p.invalidateChild(this, null);
9029                    return;
9030                }
9031            }
9032
9033            if (p != null && ai != null) {
9034                final Rect r = ai.mTmpInvalRect;
9035                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9036                // Don't call invalidate -- we don't want to internally scroll
9037                // our own bounds
9038                p.invalidateChild(this, r);
9039            }
9040        }
9041    }
9042
9043    /**
9044     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
9045     * set any flags or handle all of the cases handled by the default invalidation methods.
9046     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
9047     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
9048     * walk up the hierarchy, transforming the dirty rect as necessary.
9049     *
9050     * The method also handles normal invalidation logic if display list properties are not
9051     * being used in this view. The invalidateParent and forceRedraw flags are used by that
9052     * backup approach, to handle these cases used in the various property-setting methods.
9053     *
9054     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
9055     * are not being used in this view
9056     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
9057     * list properties are not being used in this view
9058     */
9059    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
9060        if (!USE_DISPLAY_LIST_PROPERTIES || mDisplayList == null ||
9061                (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
9062            if (invalidateParent) {
9063                invalidateParentCaches();
9064            }
9065            if (forceRedraw) {
9066                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9067            }
9068            invalidate(false);
9069        } else {
9070            final AttachInfo ai = mAttachInfo;
9071            final ViewParent p = mParent;
9072            if (p != null && ai != null) {
9073                final Rect r = ai.mTmpInvalRect;
9074                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9075                if (mParent instanceof ViewGroup) {
9076                    ((ViewGroup) mParent).invalidateChildFast(this, r);
9077                } else {
9078                    mParent.invalidateChild(this, r);
9079                }
9080            }
9081        }
9082    }
9083
9084    /**
9085     * Utility method to transform a given Rect by the current matrix of this view.
9086     */
9087    void transformRect(final Rect rect) {
9088        if (!getMatrix().isIdentity()) {
9089            RectF boundingRect = mAttachInfo.mTmpTransformRect;
9090            boundingRect.set(rect);
9091            getMatrix().mapRect(boundingRect);
9092            rect.set((int) (boundingRect.left - 0.5f),
9093                    (int) (boundingRect.top - 0.5f),
9094                    (int) (boundingRect.right + 0.5f),
9095                    (int) (boundingRect.bottom + 0.5f));
9096        }
9097    }
9098
9099    /**
9100     * Used to indicate that the parent of this view should clear its caches. This functionality
9101     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9102     * which is necessary when various parent-managed properties of the view change, such as
9103     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
9104     * clears the parent caches and does not causes an invalidate event.
9105     *
9106     * @hide
9107     */
9108    protected void invalidateParentCaches() {
9109        if (mParent instanceof View) {
9110            ((View) mParent).mPrivateFlags |= INVALIDATED;
9111        }
9112    }
9113
9114    /**
9115     * Used to indicate that the parent of this view should be invalidated. This functionality
9116     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9117     * which is necessary when various parent-managed properties of the view change, such as
9118     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
9119     * an invalidation event to the parent.
9120     *
9121     * @hide
9122     */
9123    protected void invalidateParentIfNeeded() {
9124        if (isHardwareAccelerated() && mParent instanceof View) {
9125            ((View) mParent).invalidate(true);
9126        }
9127    }
9128
9129    /**
9130     * Indicates whether this View is opaque. An opaque View guarantees that it will
9131     * draw all the pixels overlapping its bounds using a fully opaque color.
9132     *
9133     * Subclasses of View should override this method whenever possible to indicate
9134     * whether an instance is opaque. Opaque Views are treated in a special way by
9135     * the View hierarchy, possibly allowing it to perform optimizations during
9136     * invalidate/draw passes.
9137     *
9138     * @return True if this View is guaranteed to be fully opaque, false otherwise.
9139     */
9140    @ViewDebug.ExportedProperty(category = "drawing")
9141    public boolean isOpaque() {
9142        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
9143                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
9144                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
9145    }
9146
9147    /**
9148     * @hide
9149     */
9150    protected void computeOpaqueFlags() {
9151        // Opaque if:
9152        //   - Has a background
9153        //   - Background is opaque
9154        //   - Doesn't have scrollbars or scrollbars are inside overlay
9155
9156        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
9157            mPrivateFlags |= OPAQUE_BACKGROUND;
9158        } else {
9159            mPrivateFlags &= ~OPAQUE_BACKGROUND;
9160        }
9161
9162        final int flags = mViewFlags;
9163        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
9164                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
9165            mPrivateFlags |= OPAQUE_SCROLLBARS;
9166        } else {
9167            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
9168        }
9169    }
9170
9171    /**
9172     * @hide
9173     */
9174    protected boolean hasOpaqueScrollbars() {
9175        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
9176    }
9177
9178    /**
9179     * @return A handler associated with the thread running the View. This
9180     * handler can be used to pump events in the UI events queue.
9181     */
9182    public Handler getHandler() {
9183        if (mAttachInfo != null) {
9184            return mAttachInfo.mHandler;
9185        }
9186        return null;
9187    }
9188
9189    /**
9190     * Gets the view root associated with the View.
9191     * @return The view root, or null if none.
9192     * @hide
9193     */
9194    public ViewRootImpl getViewRootImpl() {
9195        if (mAttachInfo != null) {
9196            return mAttachInfo.mViewRootImpl;
9197        }
9198        return null;
9199    }
9200
9201    /**
9202     * <p>Causes the Runnable to be added to the message queue.
9203     * The runnable will be run on the user interface thread.</p>
9204     *
9205     * <p>This method can be invoked from outside of the UI thread
9206     * only when this View is attached to a window.</p>
9207     *
9208     * @param action The Runnable that will be executed.
9209     *
9210     * @return Returns true if the Runnable was successfully placed in to the
9211     *         message queue.  Returns false on failure, usually because the
9212     *         looper processing the message queue is exiting.
9213     */
9214    public boolean post(Runnable action) {
9215        final AttachInfo attachInfo = mAttachInfo;
9216        if (attachInfo != null) {
9217            return attachInfo.mHandler.post(action);
9218        }
9219        // Assume that post will succeed later
9220        ViewRootImpl.getRunQueue().post(action);
9221        return true;
9222    }
9223
9224    /**
9225     * <p>Causes the Runnable to be added to the message queue, to be run
9226     * after the specified amount of time elapses.
9227     * The runnable will be run on the user interface thread.</p>
9228     *
9229     * <p>This method can be invoked from outside of the UI thread
9230     * only when this View is attached to a window.</p>
9231     *
9232     * @param action The Runnable that will be executed.
9233     * @param delayMillis The delay (in milliseconds) until the Runnable
9234     *        will be executed.
9235     *
9236     * @return true if the Runnable was successfully placed in to the
9237     *         message queue.  Returns false on failure, usually because the
9238     *         looper processing the message queue is exiting.  Note that a
9239     *         result of true does not mean the Runnable will be processed --
9240     *         if the looper is quit before the delivery time of the message
9241     *         occurs then the message will be dropped.
9242     */
9243    public boolean postDelayed(Runnable action, long delayMillis) {
9244        final AttachInfo attachInfo = mAttachInfo;
9245        if (attachInfo != null) {
9246            return attachInfo.mHandler.postDelayed(action, delayMillis);
9247        }
9248        // Assume that post will succeed later
9249        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9250        return true;
9251    }
9252
9253    /**
9254     * <p>Causes the Runnable to execute on the next animation time step.
9255     * The runnable will be run on the user interface thread.</p>
9256     *
9257     * <p>This method can be invoked from outside of the UI thread
9258     * only when this View is attached to a window.</p>
9259     *
9260     * @param action The Runnable that will be executed.
9261     *
9262     * @hide
9263     */
9264    public void postOnAnimation(Runnable action) {
9265        final AttachInfo attachInfo = mAttachInfo;
9266        if (attachInfo != null) {
9267            attachInfo.mViewRootImpl.mChoreographer.postCallback(
9268                    Choreographer.CALLBACK_ANIMATION, action, null);
9269        } else {
9270            // Assume that post will succeed later
9271            ViewRootImpl.getRunQueue().post(action);
9272        }
9273    }
9274
9275    /**
9276     * <p>Causes the Runnable to execute on the next animation time step,
9277     * after the specified amount of time elapses.
9278     * The runnable will be run on the user interface thread.</p>
9279     *
9280     * <p>This method can be invoked from outside of the UI thread
9281     * only when this View is attached to a window.</p>
9282     *
9283     * @param action The Runnable that will be executed.
9284     * @param delayMillis The delay (in milliseconds) until the Runnable
9285     *        will be executed.
9286     *
9287     * @hide
9288     */
9289    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
9290        final AttachInfo attachInfo = mAttachInfo;
9291        if (attachInfo != null) {
9292            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
9293                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
9294        } else {
9295            // Assume that post will succeed later
9296            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9297        }
9298    }
9299
9300    /**
9301     * <p>Removes the specified Runnable from the message queue.</p>
9302     *
9303     * <p>This method can be invoked from outside of the UI thread
9304     * only when this View is attached to a window.</p>
9305     *
9306     * @param action The Runnable to remove from the message handling queue
9307     *
9308     * @return true if this view could ask the Handler to remove the Runnable,
9309     *         false otherwise. When the returned value is true, the Runnable
9310     *         may or may not have been actually removed from the message queue
9311     *         (for instance, if the Runnable was not in the queue already.)
9312     */
9313    public boolean removeCallbacks(Runnable action) {
9314        if (action != null) {
9315            final AttachInfo attachInfo = mAttachInfo;
9316            if (attachInfo != null) {
9317                attachInfo.mHandler.removeCallbacks(action);
9318                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
9319                        Choreographer.CALLBACK_ANIMATION, action, null);
9320            } else {
9321                // Assume that post will succeed later
9322                ViewRootImpl.getRunQueue().removeCallbacks(action);
9323            }
9324        }
9325        return true;
9326    }
9327
9328    /**
9329     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
9330     * Use this to invalidate the View from a non-UI thread.</p>
9331     *
9332     * <p>This method can be invoked from outside of the UI thread
9333     * only when this View is attached to a window.</p>
9334     *
9335     * @see #invalidate()
9336     */
9337    public void postInvalidate() {
9338        postInvalidateDelayed(0);
9339    }
9340
9341    /**
9342     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9343     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
9344     *
9345     * <p>This method can be invoked from outside of the UI thread
9346     * only when this View is attached to a window.</p>
9347     *
9348     * @param left The left coordinate of the rectangle to invalidate.
9349     * @param top The top coordinate of the rectangle to invalidate.
9350     * @param right The right coordinate of the rectangle to invalidate.
9351     * @param bottom The bottom coordinate of the rectangle to invalidate.
9352     *
9353     * @see #invalidate(int, int, int, int)
9354     * @see #invalidate(Rect)
9355     */
9356    public void postInvalidate(int left, int top, int right, int bottom) {
9357        postInvalidateDelayed(0, left, top, right, bottom);
9358    }
9359
9360    /**
9361     * <p>Cause an invalidate to happen on a subsequent cycle through the event
9362     * loop. Waits for the specified amount of time.</p>
9363     *
9364     * <p>This method can be invoked from outside of the UI thread
9365     * only when this View is attached to a window.</p>
9366     *
9367     * @param delayMilliseconds the duration in milliseconds to delay the
9368     *         invalidation by
9369     */
9370    public void postInvalidateDelayed(long delayMilliseconds) {
9371        // We try only with the AttachInfo because there's no point in invalidating
9372        // if we are not attached to our window
9373        final AttachInfo attachInfo = mAttachInfo;
9374        if (attachInfo != null) {
9375            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
9376        }
9377    }
9378
9379    /**
9380     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9381     * through the event loop. Waits for the specified amount of time.</p>
9382     *
9383     * <p>This method can be invoked from outside of the UI thread
9384     * only when this View is attached to a window.</p>
9385     *
9386     * @param delayMilliseconds the duration in milliseconds to delay the
9387     *         invalidation by
9388     * @param left The left coordinate of the rectangle to invalidate.
9389     * @param top The top coordinate of the rectangle to invalidate.
9390     * @param right The right coordinate of the rectangle to invalidate.
9391     * @param bottom The bottom coordinate of the rectangle to invalidate.
9392     */
9393    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
9394            int right, int bottom) {
9395
9396        // We try only with the AttachInfo because there's no point in invalidating
9397        // if we are not attached to our window
9398        final AttachInfo attachInfo = mAttachInfo;
9399        if (attachInfo != null) {
9400            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9401            info.target = this;
9402            info.left = left;
9403            info.top = top;
9404            info.right = right;
9405            info.bottom = bottom;
9406
9407            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
9408        }
9409    }
9410
9411    /**
9412     * <p>Cause an invalidate to happen on the next animation time step, typically the
9413     * next display frame.</p>
9414     *
9415     * <p>This method can be invoked from outside of the UI thread
9416     * only when this View is attached to a window.</p>
9417     *
9418     * @hide
9419     */
9420    public void postInvalidateOnAnimation() {
9421        // We try only with the AttachInfo because there's no point in invalidating
9422        // if we are not attached to our window
9423        final AttachInfo attachInfo = mAttachInfo;
9424        if (attachInfo != null) {
9425            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
9426        }
9427    }
9428
9429    /**
9430     * <p>Cause an invalidate of the specified area to happen on the next animation
9431     * time step, typically the next display frame.</p>
9432     *
9433     * <p>This method can be invoked from outside of the UI thread
9434     * only when this View is attached to a window.</p>
9435     *
9436     * @param left The left coordinate of the rectangle to invalidate.
9437     * @param top The top coordinate of the rectangle to invalidate.
9438     * @param right The right coordinate of the rectangle to invalidate.
9439     * @param bottom The bottom coordinate of the rectangle to invalidate.
9440     *
9441     * @hide
9442     */
9443    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
9444        // We try only with the AttachInfo because there's no point in invalidating
9445        // if we are not attached to our window
9446        final AttachInfo attachInfo = mAttachInfo;
9447        if (attachInfo != null) {
9448            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9449            info.target = this;
9450            info.left = left;
9451            info.top = top;
9452            info.right = right;
9453            info.bottom = bottom;
9454
9455            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
9456        }
9457    }
9458
9459    /**
9460     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
9461     * This event is sent at most once every
9462     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
9463     */
9464    private void postSendViewScrolledAccessibilityEventCallback() {
9465        if (mSendViewScrolledAccessibilityEvent == null) {
9466            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
9467        }
9468        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
9469            mSendViewScrolledAccessibilityEvent.mIsPending = true;
9470            postDelayed(mSendViewScrolledAccessibilityEvent,
9471                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
9472        }
9473    }
9474
9475    /**
9476     * Called by a parent to request that a child update its values for mScrollX
9477     * and mScrollY if necessary. This will typically be done if the child is
9478     * animating a scroll using a {@link android.widget.Scroller Scroller}
9479     * object.
9480     */
9481    public void computeScroll() {
9482    }
9483
9484    /**
9485     * <p>Indicate whether the horizontal edges are faded when the view is
9486     * scrolled horizontally.</p>
9487     *
9488     * @return true if the horizontal edges should are faded on scroll, false
9489     *         otherwise
9490     *
9491     * @see #setHorizontalFadingEdgeEnabled(boolean)
9492     *
9493     * @attr ref android.R.styleable#View_requiresFadingEdge
9494     */
9495    public boolean isHorizontalFadingEdgeEnabled() {
9496        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
9497    }
9498
9499    /**
9500     * <p>Define whether the horizontal edges should be faded when this view
9501     * is scrolled horizontally.</p>
9502     *
9503     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
9504     *                                    be faded when the view is scrolled
9505     *                                    horizontally
9506     *
9507     * @see #isHorizontalFadingEdgeEnabled()
9508     *
9509     * @attr ref android.R.styleable#View_requiresFadingEdge
9510     */
9511    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
9512        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
9513            if (horizontalFadingEdgeEnabled) {
9514                initScrollCache();
9515            }
9516
9517            mViewFlags ^= FADING_EDGE_HORIZONTAL;
9518        }
9519    }
9520
9521    /**
9522     * <p>Indicate whether the vertical edges are faded when the view is
9523     * scrolled horizontally.</p>
9524     *
9525     * @return true if the vertical edges should are faded on scroll, false
9526     *         otherwise
9527     *
9528     * @see #setVerticalFadingEdgeEnabled(boolean)
9529     *
9530     * @attr ref android.R.styleable#View_requiresFadingEdge
9531     */
9532    public boolean isVerticalFadingEdgeEnabled() {
9533        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
9534    }
9535
9536    /**
9537     * <p>Define whether the vertical edges should be faded when this view
9538     * is scrolled vertically.</p>
9539     *
9540     * @param verticalFadingEdgeEnabled true if the vertical edges should
9541     *                                  be faded when the view is scrolled
9542     *                                  vertically
9543     *
9544     * @see #isVerticalFadingEdgeEnabled()
9545     *
9546     * @attr ref android.R.styleable#View_requiresFadingEdge
9547     */
9548    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
9549        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
9550            if (verticalFadingEdgeEnabled) {
9551                initScrollCache();
9552            }
9553
9554            mViewFlags ^= FADING_EDGE_VERTICAL;
9555        }
9556    }
9557
9558    /**
9559     * Returns the strength, or intensity, of the top faded edge. The strength is
9560     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9561     * returns 0.0 or 1.0 but no value in between.
9562     *
9563     * Subclasses should override this method to provide a smoother fade transition
9564     * when scrolling occurs.
9565     *
9566     * @return the intensity of the top fade as a float between 0.0f and 1.0f
9567     */
9568    protected float getTopFadingEdgeStrength() {
9569        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
9570    }
9571
9572    /**
9573     * Returns the strength, or intensity, of the bottom faded edge. The strength is
9574     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9575     * returns 0.0 or 1.0 but no value in between.
9576     *
9577     * Subclasses should override this method to provide a smoother fade transition
9578     * when scrolling occurs.
9579     *
9580     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
9581     */
9582    protected float getBottomFadingEdgeStrength() {
9583        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
9584                computeVerticalScrollRange() ? 1.0f : 0.0f;
9585    }
9586
9587    /**
9588     * Returns the strength, or intensity, of the left faded edge. The strength is
9589     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9590     * returns 0.0 or 1.0 but no value in between.
9591     *
9592     * Subclasses should override this method to provide a smoother fade transition
9593     * when scrolling occurs.
9594     *
9595     * @return the intensity of the left fade as a float between 0.0f and 1.0f
9596     */
9597    protected float getLeftFadingEdgeStrength() {
9598        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
9599    }
9600
9601    /**
9602     * Returns the strength, or intensity, of the right faded edge. The strength is
9603     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9604     * returns 0.0 or 1.0 but no value in between.
9605     *
9606     * Subclasses should override this method to provide a smoother fade transition
9607     * when scrolling occurs.
9608     *
9609     * @return the intensity of the right fade as a float between 0.0f and 1.0f
9610     */
9611    protected float getRightFadingEdgeStrength() {
9612        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
9613                computeHorizontalScrollRange() ? 1.0f : 0.0f;
9614    }
9615
9616    /**
9617     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
9618     * scrollbar is not drawn by default.</p>
9619     *
9620     * @return true if the horizontal scrollbar should be painted, false
9621     *         otherwise
9622     *
9623     * @see #setHorizontalScrollBarEnabled(boolean)
9624     */
9625    public boolean isHorizontalScrollBarEnabled() {
9626        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9627    }
9628
9629    /**
9630     * <p>Define whether the horizontal scrollbar should be drawn or not. The
9631     * scrollbar is not drawn by default.</p>
9632     *
9633     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
9634     *                                   be painted
9635     *
9636     * @see #isHorizontalScrollBarEnabled()
9637     */
9638    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
9639        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
9640            mViewFlags ^= SCROLLBARS_HORIZONTAL;
9641            computeOpaqueFlags();
9642            resolvePadding();
9643        }
9644    }
9645
9646    /**
9647     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
9648     * scrollbar is not drawn by default.</p>
9649     *
9650     * @return true if the vertical scrollbar should be painted, false
9651     *         otherwise
9652     *
9653     * @see #setVerticalScrollBarEnabled(boolean)
9654     */
9655    public boolean isVerticalScrollBarEnabled() {
9656        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
9657    }
9658
9659    /**
9660     * <p>Define whether the vertical scrollbar should be drawn or not. The
9661     * scrollbar is not drawn by default.</p>
9662     *
9663     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9664     *                                 be painted
9665     *
9666     * @see #isVerticalScrollBarEnabled()
9667     */
9668    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9669        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9670            mViewFlags ^= SCROLLBARS_VERTICAL;
9671            computeOpaqueFlags();
9672            resolvePadding();
9673        }
9674    }
9675
9676    /**
9677     * @hide
9678     */
9679    protected void recomputePadding() {
9680        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9681    }
9682
9683    /**
9684     * Define whether scrollbars will fade when the view is not scrolling.
9685     *
9686     * @param fadeScrollbars wheter to enable fading
9687     *
9688     * @attr ref android.R.styleable#View_fadeScrollbars
9689     */
9690    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9691        initScrollCache();
9692        final ScrollabilityCache scrollabilityCache = mScrollCache;
9693        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9694        if (fadeScrollbars) {
9695            scrollabilityCache.state = ScrollabilityCache.OFF;
9696        } else {
9697            scrollabilityCache.state = ScrollabilityCache.ON;
9698        }
9699    }
9700
9701    /**
9702     *
9703     * Returns true if scrollbars will fade when this view is not scrolling
9704     *
9705     * @return true if scrollbar fading is enabled
9706     *
9707     * @attr ref android.R.styleable#View_fadeScrollbars
9708     */
9709    public boolean isScrollbarFadingEnabled() {
9710        return mScrollCache != null && mScrollCache.fadeScrollBars;
9711    }
9712
9713    /**
9714     *
9715     * Returns the delay before scrollbars fade.
9716     *
9717     * @return the delay before scrollbars fade
9718     *
9719     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
9720     */
9721    public int getScrollBarDefaultDelayBeforeFade() {
9722        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
9723                mScrollCache.scrollBarDefaultDelayBeforeFade;
9724    }
9725
9726    /**
9727     * Define the delay before scrollbars fade.
9728     *
9729     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
9730     *
9731     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
9732     */
9733    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
9734        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
9735    }
9736
9737    /**
9738     *
9739     * Returns the scrollbar fade duration.
9740     *
9741     * @return the scrollbar fade duration
9742     *
9743     * @attr ref android.R.styleable#View_scrollbarFadeDuration
9744     */
9745    public int getScrollBarFadeDuration() {
9746        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
9747                mScrollCache.scrollBarFadeDuration;
9748    }
9749
9750    /**
9751     * Define the scrollbar fade duration.
9752     *
9753     * @param scrollBarFadeDuration - the scrollbar fade duration
9754     *
9755     * @attr ref android.R.styleable#View_scrollbarFadeDuration
9756     */
9757    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
9758        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
9759    }
9760
9761    /**
9762     *
9763     * Returns the scrollbar size.
9764     *
9765     * @return the scrollbar size
9766     *
9767     * @attr ref android.R.styleable#View_scrollbarSize
9768     */
9769    public int getScrollBarSize() {
9770        return mScrollCache == null ? ViewConfiguration.getScrollBarSize() :
9771                mScrollCache.scrollBarSize;
9772    }
9773
9774    /**
9775     * Define the scrollbar size.
9776     *
9777     * @param scrollBarSize - the scrollbar size
9778     *
9779     * @attr ref android.R.styleable#View_scrollbarSize
9780     */
9781    public void setScrollBarSize(int scrollBarSize) {
9782        getScrollCache().scrollBarSize = scrollBarSize;
9783    }
9784
9785    /**
9786     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9787     * inset. When inset, they add to the padding of the view. And the scrollbars
9788     * can be drawn inside the padding area or on the edge of the view. For example,
9789     * if a view has a background drawable and you want to draw the scrollbars
9790     * inside the padding specified by the drawable, you can use
9791     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9792     * appear at the edge of the view, ignoring the padding, then you can use
9793     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9794     * @param style the style of the scrollbars. Should be one of
9795     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9796     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9797     * @see #SCROLLBARS_INSIDE_OVERLAY
9798     * @see #SCROLLBARS_INSIDE_INSET
9799     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9800     * @see #SCROLLBARS_OUTSIDE_INSET
9801     *
9802     * @attr ref android.R.styleable#View_scrollbarStyle
9803     */
9804    public void setScrollBarStyle(int style) {
9805        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9806            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9807            computeOpaqueFlags();
9808            resolvePadding();
9809        }
9810    }
9811
9812    /**
9813     * <p>Returns the current scrollbar style.</p>
9814     * @return the current scrollbar style
9815     * @see #SCROLLBARS_INSIDE_OVERLAY
9816     * @see #SCROLLBARS_INSIDE_INSET
9817     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9818     * @see #SCROLLBARS_OUTSIDE_INSET
9819     *
9820     * @attr ref android.R.styleable#View_scrollbarStyle
9821     */
9822    @ViewDebug.ExportedProperty(mapping = {
9823            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9824            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9825            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9826            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9827    })
9828    public int getScrollBarStyle() {
9829        return mViewFlags & SCROLLBARS_STYLE_MASK;
9830    }
9831
9832    /**
9833     * <p>Compute the horizontal range that the horizontal scrollbar
9834     * represents.</p>
9835     *
9836     * <p>The range is expressed in arbitrary units that must be the same as the
9837     * units used by {@link #computeHorizontalScrollExtent()} and
9838     * {@link #computeHorizontalScrollOffset()}.</p>
9839     *
9840     * <p>The default range is the drawing width of this view.</p>
9841     *
9842     * @return the total horizontal range represented by the horizontal
9843     *         scrollbar
9844     *
9845     * @see #computeHorizontalScrollExtent()
9846     * @see #computeHorizontalScrollOffset()
9847     * @see android.widget.ScrollBarDrawable
9848     */
9849    protected int computeHorizontalScrollRange() {
9850        return getWidth();
9851    }
9852
9853    /**
9854     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9855     * within the horizontal range. This value is used to compute the position
9856     * of the thumb within the scrollbar's track.</p>
9857     *
9858     * <p>The range is expressed in arbitrary units that must be the same as the
9859     * units used by {@link #computeHorizontalScrollRange()} and
9860     * {@link #computeHorizontalScrollExtent()}.</p>
9861     *
9862     * <p>The default offset is the scroll offset of this view.</p>
9863     *
9864     * @return the horizontal offset of the scrollbar's thumb
9865     *
9866     * @see #computeHorizontalScrollRange()
9867     * @see #computeHorizontalScrollExtent()
9868     * @see android.widget.ScrollBarDrawable
9869     */
9870    protected int computeHorizontalScrollOffset() {
9871        return mScrollX;
9872    }
9873
9874    /**
9875     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9876     * within the horizontal range. This value is used to compute the length
9877     * of the thumb within the scrollbar's track.</p>
9878     *
9879     * <p>The range is expressed in arbitrary units that must be the same as the
9880     * units used by {@link #computeHorizontalScrollRange()} and
9881     * {@link #computeHorizontalScrollOffset()}.</p>
9882     *
9883     * <p>The default extent is the drawing width of this view.</p>
9884     *
9885     * @return the horizontal extent of the scrollbar's thumb
9886     *
9887     * @see #computeHorizontalScrollRange()
9888     * @see #computeHorizontalScrollOffset()
9889     * @see android.widget.ScrollBarDrawable
9890     */
9891    protected int computeHorizontalScrollExtent() {
9892        return getWidth();
9893    }
9894
9895    /**
9896     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9897     *
9898     * <p>The range is expressed in arbitrary units that must be the same as the
9899     * units used by {@link #computeVerticalScrollExtent()} and
9900     * {@link #computeVerticalScrollOffset()}.</p>
9901     *
9902     * @return the total vertical range represented by the vertical scrollbar
9903     *
9904     * <p>The default range is the drawing height of this view.</p>
9905     *
9906     * @see #computeVerticalScrollExtent()
9907     * @see #computeVerticalScrollOffset()
9908     * @see android.widget.ScrollBarDrawable
9909     */
9910    protected int computeVerticalScrollRange() {
9911        return getHeight();
9912    }
9913
9914    /**
9915     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9916     * within the horizontal range. This value is used to compute the position
9917     * of the thumb within the scrollbar's track.</p>
9918     *
9919     * <p>The range is expressed in arbitrary units that must be the same as the
9920     * units used by {@link #computeVerticalScrollRange()} and
9921     * {@link #computeVerticalScrollExtent()}.</p>
9922     *
9923     * <p>The default offset is the scroll offset of this view.</p>
9924     *
9925     * @return the vertical offset of the scrollbar's thumb
9926     *
9927     * @see #computeVerticalScrollRange()
9928     * @see #computeVerticalScrollExtent()
9929     * @see android.widget.ScrollBarDrawable
9930     */
9931    protected int computeVerticalScrollOffset() {
9932        return mScrollY;
9933    }
9934
9935    /**
9936     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9937     * within the vertical range. This value is used to compute the length
9938     * of the thumb within the scrollbar's track.</p>
9939     *
9940     * <p>The range is expressed in arbitrary units that must be the same as the
9941     * units used by {@link #computeVerticalScrollRange()} and
9942     * {@link #computeVerticalScrollOffset()}.</p>
9943     *
9944     * <p>The default extent is the drawing height of this view.</p>
9945     *
9946     * @return the vertical extent of the scrollbar's thumb
9947     *
9948     * @see #computeVerticalScrollRange()
9949     * @see #computeVerticalScrollOffset()
9950     * @see android.widget.ScrollBarDrawable
9951     */
9952    protected int computeVerticalScrollExtent() {
9953        return getHeight();
9954    }
9955
9956    /**
9957     * Check if this view can be scrolled horizontally in a certain direction.
9958     *
9959     * @param direction Negative to check scrolling left, positive to check scrolling right.
9960     * @return true if this view can be scrolled in the specified direction, false otherwise.
9961     */
9962    public boolean canScrollHorizontally(int direction) {
9963        final int offset = computeHorizontalScrollOffset();
9964        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9965        if (range == 0) return false;
9966        if (direction < 0) {
9967            return offset > 0;
9968        } else {
9969            return offset < range - 1;
9970        }
9971    }
9972
9973    /**
9974     * Check if this view can be scrolled vertically in a certain direction.
9975     *
9976     * @param direction Negative to check scrolling up, positive to check scrolling down.
9977     * @return true if this view can be scrolled in the specified direction, false otherwise.
9978     */
9979    public boolean canScrollVertically(int direction) {
9980        final int offset = computeVerticalScrollOffset();
9981        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9982        if (range == 0) return false;
9983        if (direction < 0) {
9984            return offset > 0;
9985        } else {
9986            return offset < range - 1;
9987        }
9988    }
9989
9990    /**
9991     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9992     * scrollbars are painted only if they have been awakened first.</p>
9993     *
9994     * @param canvas the canvas on which to draw the scrollbars
9995     *
9996     * @see #awakenScrollBars(int)
9997     */
9998    protected final void onDrawScrollBars(Canvas canvas) {
9999        // scrollbars are drawn only when the animation is running
10000        final ScrollabilityCache cache = mScrollCache;
10001        if (cache != null) {
10002
10003            int state = cache.state;
10004
10005            if (state == ScrollabilityCache.OFF) {
10006                return;
10007            }
10008
10009            boolean invalidate = false;
10010
10011            if (state == ScrollabilityCache.FADING) {
10012                // We're fading -- get our fade interpolation
10013                if (cache.interpolatorValues == null) {
10014                    cache.interpolatorValues = new float[1];
10015                }
10016
10017                float[] values = cache.interpolatorValues;
10018
10019                // Stops the animation if we're done
10020                if (cache.scrollBarInterpolator.timeToValues(values) ==
10021                        Interpolator.Result.FREEZE_END) {
10022                    cache.state = ScrollabilityCache.OFF;
10023                } else {
10024                    cache.scrollBar.setAlpha(Math.round(values[0]));
10025                }
10026
10027                // This will make the scroll bars inval themselves after
10028                // drawing. We only want this when we're fading so that
10029                // we prevent excessive redraws
10030                invalidate = true;
10031            } else {
10032                // We're just on -- but we may have been fading before so
10033                // reset alpha
10034                cache.scrollBar.setAlpha(255);
10035            }
10036
10037
10038            final int viewFlags = mViewFlags;
10039
10040            final boolean drawHorizontalScrollBar =
10041                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10042            final boolean drawVerticalScrollBar =
10043                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
10044                && !isVerticalScrollBarHidden();
10045
10046            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
10047                final int width = mRight - mLeft;
10048                final int height = mBottom - mTop;
10049
10050                final ScrollBarDrawable scrollBar = cache.scrollBar;
10051
10052                final int scrollX = mScrollX;
10053                final int scrollY = mScrollY;
10054                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
10055
10056                int left, top, right, bottom;
10057
10058                if (drawHorizontalScrollBar) {
10059                    int size = scrollBar.getSize(false);
10060                    if (size <= 0) {
10061                        size = cache.scrollBarSize;
10062                    }
10063
10064                    scrollBar.setParameters(computeHorizontalScrollRange(),
10065                                            computeHorizontalScrollOffset(),
10066                                            computeHorizontalScrollExtent(), false);
10067                    final int verticalScrollBarGap = drawVerticalScrollBar ?
10068                            getVerticalScrollbarWidth() : 0;
10069                    top = scrollY + height - size - (mUserPaddingBottom & inside);
10070                    left = scrollX + (mPaddingLeft & inside);
10071                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
10072                    bottom = top + size;
10073                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
10074                    if (invalidate) {
10075                        invalidate(left, top, right, bottom);
10076                    }
10077                }
10078
10079                if (drawVerticalScrollBar) {
10080                    int size = scrollBar.getSize(true);
10081                    if (size <= 0) {
10082                        size = cache.scrollBarSize;
10083                    }
10084
10085                    scrollBar.setParameters(computeVerticalScrollRange(),
10086                                            computeVerticalScrollOffset(),
10087                                            computeVerticalScrollExtent(), true);
10088                    switch (mVerticalScrollbarPosition) {
10089                        default:
10090                        case SCROLLBAR_POSITION_DEFAULT:
10091                        case SCROLLBAR_POSITION_RIGHT:
10092                            left = scrollX + width - size - (mUserPaddingRight & inside);
10093                            break;
10094                        case SCROLLBAR_POSITION_LEFT:
10095                            left = scrollX + (mUserPaddingLeft & inside);
10096                            break;
10097                    }
10098                    top = scrollY + (mPaddingTop & inside);
10099                    right = left + size;
10100                    bottom = scrollY + height - (mUserPaddingBottom & inside);
10101                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
10102                    if (invalidate) {
10103                        invalidate(left, top, right, bottom);
10104                    }
10105                }
10106            }
10107        }
10108    }
10109
10110    /**
10111     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
10112     * FastScroller is visible.
10113     * @return whether to temporarily hide the vertical scrollbar
10114     * @hide
10115     */
10116    protected boolean isVerticalScrollBarHidden() {
10117        return false;
10118    }
10119
10120    /**
10121     * <p>Draw the horizontal scrollbar if
10122     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
10123     *
10124     * @param canvas the canvas on which to draw the scrollbar
10125     * @param scrollBar the scrollbar's drawable
10126     *
10127     * @see #isHorizontalScrollBarEnabled()
10128     * @see #computeHorizontalScrollRange()
10129     * @see #computeHorizontalScrollExtent()
10130     * @see #computeHorizontalScrollOffset()
10131     * @see android.widget.ScrollBarDrawable
10132     * @hide
10133     */
10134    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
10135            int l, int t, int r, int b) {
10136        scrollBar.setBounds(l, t, r, b);
10137        scrollBar.draw(canvas);
10138    }
10139
10140    /**
10141     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
10142     * returns true.</p>
10143     *
10144     * @param canvas the canvas on which to draw the scrollbar
10145     * @param scrollBar the scrollbar's drawable
10146     *
10147     * @see #isVerticalScrollBarEnabled()
10148     * @see #computeVerticalScrollRange()
10149     * @see #computeVerticalScrollExtent()
10150     * @see #computeVerticalScrollOffset()
10151     * @see android.widget.ScrollBarDrawable
10152     * @hide
10153     */
10154    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
10155            int l, int t, int r, int b) {
10156        scrollBar.setBounds(l, t, r, b);
10157        scrollBar.draw(canvas);
10158    }
10159
10160    /**
10161     * Implement this to do your drawing.
10162     *
10163     * @param canvas the canvas on which the background will be drawn
10164     */
10165    protected void onDraw(Canvas canvas) {
10166    }
10167
10168    /*
10169     * Caller is responsible for calling requestLayout if necessary.
10170     * (This allows addViewInLayout to not request a new layout.)
10171     */
10172    void assignParent(ViewParent parent) {
10173        if (mParent == null) {
10174            mParent = parent;
10175        } else if (parent == null) {
10176            mParent = null;
10177        } else {
10178            throw new RuntimeException("view " + this + " being added, but"
10179                    + " it already has a parent");
10180        }
10181    }
10182
10183    /**
10184     * This is called when the view is attached to a window.  At this point it
10185     * has a Surface and will start drawing.  Note that this function is
10186     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
10187     * however it may be called any time before the first onDraw -- including
10188     * before or after {@link #onMeasure(int, int)}.
10189     *
10190     * @see #onDetachedFromWindow()
10191     */
10192    protected void onAttachedToWindow() {
10193        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
10194            mParent.requestTransparentRegion(this);
10195        }
10196        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
10197            initialAwakenScrollBars();
10198            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
10199        }
10200        jumpDrawablesToCurrentState();
10201        // Order is important here: LayoutDirection MUST be resolved before Padding
10202        // and TextDirection
10203        resolveLayoutDirection();
10204        resolvePadding();
10205        resolveTextDirection();
10206        resolveTextAlignment();
10207        if (isFocused()) {
10208            InputMethodManager imm = InputMethodManager.peekInstance();
10209            imm.focusIn(this);
10210        }
10211    }
10212
10213    /**
10214     * @see #onScreenStateChanged(int)
10215     */
10216    void dispatchScreenStateChanged(int screenState) {
10217        onScreenStateChanged(screenState);
10218    }
10219
10220    /**
10221     * This method is called whenever the state of the screen this view is
10222     * attached to changes. A state change will usually occurs when the screen
10223     * turns on or off (whether it happens automatically or the user does it
10224     * manually.)
10225     *
10226     * @param screenState The new state of the screen. Can be either
10227     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
10228     */
10229    public void onScreenStateChanged(int screenState) {
10230    }
10231
10232    /**
10233     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
10234     */
10235    private boolean hasRtlSupport() {
10236        return mContext.getApplicationInfo().hasRtlSupport();
10237    }
10238
10239    /**
10240     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
10241     * that the parent directionality can and will be resolved before its children.
10242     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
10243     */
10244    public void resolveLayoutDirection() {
10245        // Clear any previous layout direction resolution
10246        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10247
10248        if (hasRtlSupport()) {
10249            // Set resolved depending on layout direction
10250            switch (getLayoutDirection()) {
10251                case LAYOUT_DIRECTION_INHERIT:
10252                    // If this is root view, no need to look at parent's layout dir.
10253                    if (canResolveLayoutDirection()) {
10254                        ViewGroup viewGroup = ((ViewGroup) mParent);
10255
10256                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
10257                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10258                        }
10259                    } else {
10260                        // Nothing to do, LTR by default
10261                    }
10262                    break;
10263                case LAYOUT_DIRECTION_RTL:
10264                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10265                    break;
10266                case LAYOUT_DIRECTION_LOCALE:
10267                    if(isLayoutDirectionRtl(Locale.getDefault())) {
10268                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10269                    }
10270                    break;
10271                default:
10272                    // Nothing to do, LTR by default
10273            }
10274        }
10275
10276        // Set to resolved
10277        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
10278        onResolvedLayoutDirectionChanged();
10279        // Resolve padding
10280        resolvePadding();
10281    }
10282
10283    /**
10284     * Called when layout direction has been resolved.
10285     *
10286     * The default implementation does nothing.
10287     */
10288    public void onResolvedLayoutDirectionChanged() {
10289    }
10290
10291    /**
10292     * Resolve padding depending on layout direction.
10293     */
10294    public void resolvePadding() {
10295        // If the user specified the absolute padding (either with android:padding or
10296        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
10297        // use the default padding or the padding from the background drawable
10298        // (stored at this point in mPadding*)
10299        int resolvedLayoutDirection = getResolvedLayoutDirection();
10300        switch (resolvedLayoutDirection) {
10301            case LAYOUT_DIRECTION_RTL:
10302                // Start user padding override Right user padding. Otherwise, if Right user
10303                // padding is not defined, use the default Right padding. If Right user padding
10304                // is defined, just use it.
10305                if (mUserPaddingStart >= 0) {
10306                    mUserPaddingRight = mUserPaddingStart;
10307                } else if (mUserPaddingRight < 0) {
10308                    mUserPaddingRight = mPaddingRight;
10309                }
10310                if (mUserPaddingEnd >= 0) {
10311                    mUserPaddingLeft = mUserPaddingEnd;
10312                } else if (mUserPaddingLeft < 0) {
10313                    mUserPaddingLeft = mPaddingLeft;
10314                }
10315                break;
10316            case LAYOUT_DIRECTION_LTR:
10317            default:
10318                // Start user padding override Left user padding. Otherwise, if Left user
10319                // padding is not defined, use the default left padding. If Left user padding
10320                // is defined, just use it.
10321                if (mUserPaddingStart >= 0) {
10322                    mUserPaddingLeft = mUserPaddingStart;
10323                } else if (mUserPaddingLeft < 0) {
10324                    mUserPaddingLeft = mPaddingLeft;
10325                }
10326                if (mUserPaddingEnd >= 0) {
10327                    mUserPaddingRight = mUserPaddingEnd;
10328                } else if (mUserPaddingRight < 0) {
10329                    mUserPaddingRight = mPaddingRight;
10330                }
10331        }
10332
10333        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
10334
10335        if(isPaddingRelative()) {
10336            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
10337        } else {
10338            recomputePadding();
10339        }
10340        onPaddingChanged(resolvedLayoutDirection);
10341    }
10342
10343    /**
10344     * Resolve padding depending on the layout direction. Subclasses that care about
10345     * padding resolution should override this method. The default implementation does
10346     * nothing.
10347     *
10348     * @param layoutDirection the direction of the layout
10349     *
10350     * @see {@link #LAYOUT_DIRECTION_LTR}
10351     * @see {@link #LAYOUT_DIRECTION_RTL}
10352     */
10353    public void onPaddingChanged(int layoutDirection) {
10354    }
10355
10356    /**
10357     * Check if layout direction resolution can be done.
10358     *
10359     * @return true if layout direction resolution can be done otherwise return false.
10360     */
10361    public boolean canResolveLayoutDirection() {
10362        switch (getLayoutDirection()) {
10363            case LAYOUT_DIRECTION_INHERIT:
10364                return (mParent != null) && (mParent instanceof ViewGroup);
10365            default:
10366                return true;
10367        }
10368    }
10369
10370    /**
10371     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
10372     * when reset is done.
10373     */
10374    public void resetResolvedLayoutDirection() {
10375        // Reset the current resolved bits
10376        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10377        onResolvedLayoutDirectionReset();
10378        // Reset also the text direction
10379        resetResolvedTextDirection();
10380    }
10381
10382    /**
10383     * Called during reset of resolved layout direction.
10384     *
10385     * Subclasses need to override this method to clear cached information that depends on the
10386     * resolved layout direction, or to inform child views that inherit their layout direction.
10387     *
10388     * The default implementation does nothing.
10389     */
10390    public void onResolvedLayoutDirectionReset() {
10391    }
10392
10393    /**
10394     * Check if a Locale uses an RTL script.
10395     *
10396     * @param locale Locale to check
10397     * @return true if the Locale uses an RTL script.
10398     */
10399    protected static boolean isLayoutDirectionRtl(Locale locale) {
10400        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
10401    }
10402
10403    /**
10404     * This is called when the view is detached from a window.  At this point it
10405     * no longer has a surface for drawing.
10406     *
10407     * @see #onAttachedToWindow()
10408     */
10409    protected void onDetachedFromWindow() {
10410        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
10411
10412        removeUnsetPressCallback();
10413        removeLongPressCallback();
10414        removePerformClickCallback();
10415        removeSendViewScrolledAccessibilityEventCallback();
10416
10417        destroyDrawingCache();
10418
10419        destroyLayer(false);
10420
10421        if (mAttachInfo != null) {
10422            if (mDisplayList != null) {
10423                mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList);
10424            }
10425            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
10426        } else {
10427            if (mDisplayList != null) {
10428                // Should never happen
10429                mDisplayList.invalidate();
10430            }
10431        }
10432
10433        mCurrentAnimation = null;
10434
10435        resetResolvedLayoutDirection();
10436        resetResolvedTextAlignment();
10437    }
10438
10439    /**
10440     * @return The number of times this view has been attached to a window
10441     */
10442    protected int getWindowAttachCount() {
10443        return mWindowAttachCount;
10444    }
10445
10446    /**
10447     * Retrieve a unique token identifying the window this view is attached to.
10448     * @return Return the window's token for use in
10449     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
10450     */
10451    public IBinder getWindowToken() {
10452        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
10453    }
10454
10455    /**
10456     * Retrieve a unique token identifying the top-level "real" window of
10457     * the window that this view is attached to.  That is, this is like
10458     * {@link #getWindowToken}, except if the window this view in is a panel
10459     * window (attached to another containing window), then the token of
10460     * the containing window is returned instead.
10461     *
10462     * @return Returns the associated window token, either
10463     * {@link #getWindowToken()} or the containing window's token.
10464     */
10465    public IBinder getApplicationWindowToken() {
10466        AttachInfo ai = mAttachInfo;
10467        if (ai != null) {
10468            IBinder appWindowToken = ai.mPanelParentWindowToken;
10469            if (appWindowToken == null) {
10470                appWindowToken = ai.mWindowToken;
10471            }
10472            return appWindowToken;
10473        }
10474        return null;
10475    }
10476
10477    /**
10478     * Retrieve private session object this view hierarchy is using to
10479     * communicate with the window manager.
10480     * @return the session object to communicate with the window manager
10481     */
10482    /*package*/ IWindowSession getWindowSession() {
10483        return mAttachInfo != null ? mAttachInfo.mSession : null;
10484    }
10485
10486    /**
10487     * @param info the {@link android.view.View.AttachInfo} to associated with
10488     *        this view
10489     */
10490    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
10491        //System.out.println("Attached! " + this);
10492        mAttachInfo = info;
10493        mWindowAttachCount++;
10494        // We will need to evaluate the drawable state at least once.
10495        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
10496        if (mFloatingTreeObserver != null) {
10497            info.mTreeObserver.merge(mFloatingTreeObserver);
10498            mFloatingTreeObserver = null;
10499        }
10500        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
10501            mAttachInfo.mScrollContainers.add(this);
10502            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
10503        }
10504        performCollectViewAttributes(mAttachInfo, visibility);
10505        onAttachedToWindow();
10506
10507        ListenerInfo li = mListenerInfo;
10508        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10509                li != null ? li.mOnAttachStateChangeListeners : null;
10510        if (listeners != null && listeners.size() > 0) {
10511            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10512            // perform the dispatching. The iterator is a safe guard against listeners that
10513            // could mutate the list by calling the various add/remove methods. This prevents
10514            // the array from being modified while we iterate it.
10515            for (OnAttachStateChangeListener listener : listeners) {
10516                listener.onViewAttachedToWindow(this);
10517            }
10518        }
10519
10520        int vis = info.mWindowVisibility;
10521        if (vis != GONE) {
10522            onWindowVisibilityChanged(vis);
10523        }
10524        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
10525            // If nobody has evaluated the drawable state yet, then do it now.
10526            refreshDrawableState();
10527        }
10528    }
10529
10530    void dispatchDetachedFromWindow() {
10531        AttachInfo info = mAttachInfo;
10532        if (info != null) {
10533            int vis = info.mWindowVisibility;
10534            if (vis != GONE) {
10535                onWindowVisibilityChanged(GONE);
10536            }
10537        }
10538
10539        onDetachedFromWindow();
10540
10541        ListenerInfo li = mListenerInfo;
10542        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10543                li != null ? li.mOnAttachStateChangeListeners : null;
10544        if (listeners != null && listeners.size() > 0) {
10545            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10546            // perform the dispatching. The iterator is a safe guard against listeners that
10547            // could mutate the list by calling the various add/remove methods. This prevents
10548            // the array from being modified while we iterate it.
10549            for (OnAttachStateChangeListener listener : listeners) {
10550                listener.onViewDetachedFromWindow(this);
10551            }
10552        }
10553
10554        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
10555            mAttachInfo.mScrollContainers.remove(this);
10556            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
10557        }
10558
10559        mAttachInfo = null;
10560    }
10561
10562    /**
10563     * Store this view hierarchy's frozen state into the given container.
10564     *
10565     * @param container The SparseArray in which to save the view's state.
10566     *
10567     * @see #restoreHierarchyState(android.util.SparseArray)
10568     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10569     * @see #onSaveInstanceState()
10570     */
10571    public void saveHierarchyState(SparseArray<Parcelable> container) {
10572        dispatchSaveInstanceState(container);
10573    }
10574
10575    /**
10576     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
10577     * this view and its children. May be overridden to modify how freezing happens to a
10578     * view's children; for example, some views may want to not store state for their children.
10579     *
10580     * @param container The SparseArray in which to save the view's state.
10581     *
10582     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10583     * @see #saveHierarchyState(android.util.SparseArray)
10584     * @see #onSaveInstanceState()
10585     */
10586    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
10587        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
10588            mPrivateFlags &= ~SAVE_STATE_CALLED;
10589            Parcelable state = onSaveInstanceState();
10590            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10591                throw new IllegalStateException(
10592                        "Derived class did not call super.onSaveInstanceState()");
10593            }
10594            if (state != null) {
10595                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
10596                // + ": " + state);
10597                container.put(mID, state);
10598            }
10599        }
10600    }
10601
10602    /**
10603     * Hook allowing a view to generate a representation of its internal state
10604     * that can later be used to create a new instance with that same state.
10605     * This state should only contain information that is not persistent or can
10606     * not be reconstructed later. For example, you will never store your
10607     * current position on screen because that will be computed again when a
10608     * new instance of the view is placed in its view hierarchy.
10609     * <p>
10610     * Some examples of things you may store here: the current cursor position
10611     * in a text view (but usually not the text itself since that is stored in a
10612     * content provider or other persistent storage), the currently selected
10613     * item in a list view.
10614     *
10615     * @return Returns a Parcelable object containing the view's current dynamic
10616     *         state, or null if there is nothing interesting to save. The
10617     *         default implementation returns null.
10618     * @see #onRestoreInstanceState(android.os.Parcelable)
10619     * @see #saveHierarchyState(android.util.SparseArray)
10620     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10621     * @see #setSaveEnabled(boolean)
10622     */
10623    protected Parcelable onSaveInstanceState() {
10624        mPrivateFlags |= SAVE_STATE_CALLED;
10625        return BaseSavedState.EMPTY_STATE;
10626    }
10627
10628    /**
10629     * Restore this view hierarchy's frozen state from the given container.
10630     *
10631     * @param container The SparseArray which holds previously frozen states.
10632     *
10633     * @see #saveHierarchyState(android.util.SparseArray)
10634     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10635     * @see #onRestoreInstanceState(android.os.Parcelable)
10636     */
10637    public void restoreHierarchyState(SparseArray<Parcelable> container) {
10638        dispatchRestoreInstanceState(container);
10639    }
10640
10641    /**
10642     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
10643     * state for this view and its children. May be overridden to modify how restoring
10644     * happens to a view's children; for example, some views may want to not store state
10645     * for their children.
10646     *
10647     * @param container The SparseArray which holds previously saved state.
10648     *
10649     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10650     * @see #restoreHierarchyState(android.util.SparseArray)
10651     * @see #onRestoreInstanceState(android.os.Parcelable)
10652     */
10653    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
10654        if (mID != NO_ID) {
10655            Parcelable state = container.get(mID);
10656            if (state != null) {
10657                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
10658                // + ": " + state);
10659                mPrivateFlags &= ~SAVE_STATE_CALLED;
10660                onRestoreInstanceState(state);
10661                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10662                    throw new IllegalStateException(
10663                            "Derived class did not call super.onRestoreInstanceState()");
10664                }
10665            }
10666        }
10667    }
10668
10669    /**
10670     * Hook allowing a view to re-apply a representation of its internal state that had previously
10671     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
10672     * null state.
10673     *
10674     * @param state The frozen state that had previously been returned by
10675     *        {@link #onSaveInstanceState}.
10676     *
10677     * @see #onSaveInstanceState()
10678     * @see #restoreHierarchyState(android.util.SparseArray)
10679     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10680     */
10681    protected void onRestoreInstanceState(Parcelable state) {
10682        mPrivateFlags |= SAVE_STATE_CALLED;
10683        if (state != BaseSavedState.EMPTY_STATE && state != null) {
10684            throw new IllegalArgumentException("Wrong state class, expecting View State but "
10685                    + "received " + state.getClass().toString() + " instead. This usually happens "
10686                    + "when two views of different type have the same id in the same hierarchy. "
10687                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
10688                    + "other views do not use the same id.");
10689        }
10690    }
10691
10692    /**
10693     * <p>Return the time at which the drawing of the view hierarchy started.</p>
10694     *
10695     * @return the drawing start time in milliseconds
10696     */
10697    public long getDrawingTime() {
10698        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
10699    }
10700
10701    /**
10702     * <p>Enables or disables the duplication of the parent's state into this view. When
10703     * duplication is enabled, this view gets its drawable state from its parent rather
10704     * than from its own internal properties.</p>
10705     *
10706     * <p>Note: in the current implementation, setting this property to true after the
10707     * view was added to a ViewGroup might have no effect at all. This property should
10708     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
10709     *
10710     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
10711     * property is enabled, an exception will be thrown.</p>
10712     *
10713     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
10714     * parent, these states should not be affected by this method.</p>
10715     *
10716     * @param enabled True to enable duplication of the parent's drawable state, false
10717     *                to disable it.
10718     *
10719     * @see #getDrawableState()
10720     * @see #isDuplicateParentStateEnabled()
10721     */
10722    public void setDuplicateParentStateEnabled(boolean enabled) {
10723        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
10724    }
10725
10726    /**
10727     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
10728     *
10729     * @return True if this view's drawable state is duplicated from the parent,
10730     *         false otherwise
10731     *
10732     * @see #getDrawableState()
10733     * @see #setDuplicateParentStateEnabled(boolean)
10734     */
10735    public boolean isDuplicateParentStateEnabled() {
10736        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
10737    }
10738
10739    /**
10740     * <p>Specifies the type of layer backing this view. The layer can be
10741     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
10742     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
10743     *
10744     * <p>A layer is associated with an optional {@link android.graphics.Paint}
10745     * instance that controls how the layer is composed on screen. The following
10746     * properties of the paint are taken into account when composing the layer:</p>
10747     * <ul>
10748     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
10749     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
10750     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
10751     * </ul>
10752     *
10753     * <p>If this view has an alpha value set to < 1.0 by calling
10754     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
10755     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
10756     * equivalent to setting a hardware layer on this view and providing a paint with
10757     * the desired alpha value.<p>
10758     *
10759     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
10760     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
10761     * for more information on when and how to use layers.</p>
10762     *
10763     * @param layerType The ype of layer to use with this view, must be one of
10764     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10765     *        {@link #LAYER_TYPE_HARDWARE}
10766     * @param paint The paint used to compose the layer. This argument is optional
10767     *        and can be null. It is ignored when the layer type is
10768     *        {@link #LAYER_TYPE_NONE}
10769     *
10770     * @see #getLayerType()
10771     * @see #LAYER_TYPE_NONE
10772     * @see #LAYER_TYPE_SOFTWARE
10773     * @see #LAYER_TYPE_HARDWARE
10774     * @see #setAlpha(float)
10775     *
10776     * @attr ref android.R.styleable#View_layerType
10777     */
10778    public void setLayerType(int layerType, Paint paint) {
10779        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
10780            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
10781                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
10782        }
10783
10784        if (layerType == mLayerType) {
10785            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
10786                mLayerPaint = paint == null ? new Paint() : paint;
10787                invalidateParentCaches();
10788                invalidate(true);
10789            }
10790            return;
10791        }
10792
10793        // Destroy any previous software drawing cache if needed
10794        switch (mLayerType) {
10795            case LAYER_TYPE_HARDWARE:
10796                destroyLayer(false);
10797                // fall through - non-accelerated views may use software layer mechanism instead
10798            case LAYER_TYPE_SOFTWARE:
10799                destroyDrawingCache();
10800                break;
10801            default:
10802                break;
10803        }
10804
10805        mLayerType = layerType;
10806        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10807        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10808        mLocalDirtyRect = layerDisabled ? null : new Rect();
10809
10810        invalidateParentCaches();
10811        invalidate(true);
10812    }
10813
10814    /**
10815     * Indicates whether this view has a static layer. A view with layer type
10816     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10817     * dynamic.
10818     */
10819    boolean hasStaticLayer() {
10820        return true;
10821    }
10822
10823    /**
10824     * Indicates what type of layer is currently associated with this view. By default
10825     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10826     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10827     * for more information on the different types of layers.
10828     *
10829     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10830     *         {@link #LAYER_TYPE_HARDWARE}
10831     *
10832     * @see #setLayerType(int, android.graphics.Paint)
10833     * @see #buildLayer()
10834     * @see #LAYER_TYPE_NONE
10835     * @see #LAYER_TYPE_SOFTWARE
10836     * @see #LAYER_TYPE_HARDWARE
10837     */
10838    public int getLayerType() {
10839        return mLayerType;
10840    }
10841
10842    /**
10843     * Forces this view's layer to be created and this view to be rendered
10844     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10845     * invoking this method will have no effect.
10846     *
10847     * This method can for instance be used to render a view into its layer before
10848     * starting an animation. If this view is complex, rendering into the layer
10849     * before starting the animation will avoid skipping frames.
10850     *
10851     * @throws IllegalStateException If this view is not attached to a window
10852     *
10853     * @see #setLayerType(int, android.graphics.Paint)
10854     */
10855    public void buildLayer() {
10856        if (mLayerType == LAYER_TYPE_NONE) return;
10857
10858        if (mAttachInfo == null) {
10859            throw new IllegalStateException("This view must be attached to a window first");
10860        }
10861
10862        switch (mLayerType) {
10863            case LAYER_TYPE_HARDWARE:
10864                if (mAttachInfo.mHardwareRenderer != null &&
10865                        mAttachInfo.mHardwareRenderer.isEnabled() &&
10866                        mAttachInfo.mHardwareRenderer.validate()) {
10867                    getHardwareLayer();
10868                }
10869                break;
10870            case LAYER_TYPE_SOFTWARE:
10871                buildDrawingCache(true);
10872                break;
10873        }
10874    }
10875
10876    // Make sure the HardwareRenderer.validate() was invoked before calling this method
10877    void flushLayer() {
10878        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
10879            mHardwareLayer.flush();
10880        }
10881    }
10882
10883    /**
10884     * <p>Returns a hardware layer that can be used to draw this view again
10885     * without executing its draw method.</p>
10886     *
10887     * @return A HardwareLayer ready to render, or null if an error occurred.
10888     */
10889    HardwareLayer getHardwareLayer() {
10890        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10891                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10892            return null;
10893        }
10894
10895        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
10896
10897        final int width = mRight - mLeft;
10898        final int height = mBottom - mTop;
10899
10900        if (width == 0 || height == 0) {
10901            return null;
10902        }
10903
10904        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10905            if (mHardwareLayer == null) {
10906                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10907                        width, height, isOpaque());
10908                mLocalDirtyRect.set(0, 0, width, height);
10909            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10910                mHardwareLayer.resize(width, height);
10911                mLocalDirtyRect.set(0, 0, width, height);
10912            }
10913
10914            // The layer is not valid if the underlying GPU resources cannot be allocated
10915            if (!mHardwareLayer.isValid()) {
10916                return null;
10917            }
10918
10919            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
10920            mLocalDirtyRect.setEmpty();
10921        }
10922
10923        return mHardwareLayer;
10924    }
10925
10926    /**
10927     * Destroys this View's hardware layer if possible.
10928     *
10929     * @return True if the layer was destroyed, false otherwise.
10930     *
10931     * @see #setLayerType(int, android.graphics.Paint)
10932     * @see #LAYER_TYPE_HARDWARE
10933     */
10934    boolean destroyLayer(boolean valid) {
10935        if (mHardwareLayer != null) {
10936            AttachInfo info = mAttachInfo;
10937            if (info != null && info.mHardwareRenderer != null &&
10938                    info.mHardwareRenderer.isEnabled() &&
10939                    (valid || info.mHardwareRenderer.validate())) {
10940                mHardwareLayer.destroy();
10941                mHardwareLayer = null;
10942
10943                invalidate(true);
10944                invalidateParentCaches();
10945            }
10946            return true;
10947        }
10948        return false;
10949    }
10950
10951    /**
10952     * Destroys all hardware rendering resources. This method is invoked
10953     * when the system needs to reclaim resources. Upon execution of this
10954     * method, you should free any OpenGL resources created by the view.
10955     *
10956     * Note: you <strong>must</strong> call
10957     * <code>super.destroyHardwareResources()</code> when overriding
10958     * this method.
10959     *
10960     * @hide
10961     */
10962    protected void destroyHardwareResources() {
10963        destroyLayer(true);
10964    }
10965
10966    /**
10967     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10968     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10969     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10970     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10971     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10972     * null.</p>
10973     *
10974     * <p>Enabling the drawing cache is similar to
10975     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10976     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10977     * drawing cache has no effect on rendering because the system uses a different mechanism
10978     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10979     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10980     * for information on how to enable software and hardware layers.</p>
10981     *
10982     * <p>This API can be used to manually generate
10983     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10984     * {@link #getDrawingCache()}.</p>
10985     *
10986     * @param enabled true to enable the drawing cache, false otherwise
10987     *
10988     * @see #isDrawingCacheEnabled()
10989     * @see #getDrawingCache()
10990     * @see #buildDrawingCache()
10991     * @see #setLayerType(int, android.graphics.Paint)
10992     */
10993    public void setDrawingCacheEnabled(boolean enabled) {
10994        mCachingFailed = false;
10995        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10996    }
10997
10998    /**
10999     * <p>Indicates whether the drawing cache is enabled for this view.</p>
11000     *
11001     * @return true if the drawing cache is enabled
11002     *
11003     * @see #setDrawingCacheEnabled(boolean)
11004     * @see #getDrawingCache()
11005     */
11006    @ViewDebug.ExportedProperty(category = "drawing")
11007    public boolean isDrawingCacheEnabled() {
11008        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
11009    }
11010
11011    /**
11012     * Debugging utility which recursively outputs the dirty state of a view and its
11013     * descendants.
11014     *
11015     * @hide
11016     */
11017    @SuppressWarnings({"UnusedDeclaration"})
11018    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
11019        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
11020                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
11021                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
11022                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
11023        if (clear) {
11024            mPrivateFlags &= clearMask;
11025        }
11026        if (this instanceof ViewGroup) {
11027            ViewGroup parent = (ViewGroup) this;
11028            final int count = parent.getChildCount();
11029            for (int i = 0; i < count; i++) {
11030                final View child = parent.getChildAt(i);
11031                child.outputDirtyFlags(indent + "  ", clear, clearMask);
11032            }
11033        }
11034    }
11035
11036    /**
11037     * This method is used by ViewGroup to cause its children to restore or recreate their
11038     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
11039     * to recreate its own display list, which would happen if it went through the normal
11040     * draw/dispatchDraw mechanisms.
11041     *
11042     * @hide
11043     */
11044    protected void dispatchGetDisplayList() {}
11045
11046    /**
11047     * A view that is not attached or hardware accelerated cannot create a display list.
11048     * This method checks these conditions and returns the appropriate result.
11049     *
11050     * @return true if view has the ability to create a display list, false otherwise.
11051     *
11052     * @hide
11053     */
11054    public boolean canHaveDisplayList() {
11055        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
11056    }
11057
11058    /**
11059     * @return The HardwareRenderer associated with that view or null if hardware rendering
11060     * is not supported or this this has not been attached to a window.
11061     *
11062     * @hide
11063     */
11064    public HardwareRenderer getHardwareRenderer() {
11065        if (mAttachInfo != null) {
11066            return mAttachInfo.mHardwareRenderer;
11067        }
11068        return null;
11069    }
11070
11071    /**
11072     * Returns a DisplayList. If the incoming displayList is null, one will be created.
11073     * Otherwise, the same display list will be returned (after having been rendered into
11074     * along the way, depending on the invalidation state of the view).
11075     *
11076     * @param displayList The previous version of this displayList, could be null.
11077     * @param isLayer Whether the requester of the display list is a layer. If so,
11078     * the view will avoid creating a layer inside the resulting display list.
11079     * @return A new or reused DisplayList object.
11080     */
11081    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
11082        if (!canHaveDisplayList()) {
11083            return null;
11084        }
11085
11086        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
11087                displayList == null || !displayList.isValid() ||
11088                (!isLayer && mRecreateDisplayList))) {
11089            // Don't need to recreate the display list, just need to tell our
11090            // children to restore/recreate theirs
11091            if (displayList != null && displayList.isValid() &&
11092                    !isLayer && !mRecreateDisplayList) {
11093                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11094                mPrivateFlags &= ~DIRTY_MASK;
11095                dispatchGetDisplayList();
11096
11097                return displayList;
11098            }
11099
11100            if (!isLayer) {
11101                // If we got here, we're recreating it. Mark it as such to ensure that
11102                // we copy in child display lists into ours in drawChild()
11103                mRecreateDisplayList = true;
11104            }
11105            if (displayList == null) {
11106                final String name = getClass().getSimpleName();
11107                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
11108                // If we're creating a new display list, make sure our parent gets invalidated
11109                // since they will need to recreate their display list to account for this
11110                // new child display list.
11111                invalidateParentCaches();
11112            }
11113
11114            boolean caching = false;
11115            final HardwareCanvas canvas = displayList.start();
11116            int restoreCount = 0;
11117            int width = mRight - mLeft;
11118            int height = mBottom - mTop;
11119
11120            try {
11121                canvas.setViewport(width, height);
11122                // The dirty rect should always be null for a display list
11123                canvas.onPreDraw(null);
11124                int layerType = (
11125                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
11126                        getLayerType() : LAYER_TYPE_NONE;
11127                if (!isLayer && layerType != LAYER_TYPE_NONE && USE_DISPLAY_LIST_PROPERTIES) {
11128                    if (layerType == LAYER_TYPE_HARDWARE) {
11129                        final HardwareLayer layer = getHardwareLayer();
11130                        if (layer != null && layer.isValid()) {
11131                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
11132                        } else {
11133                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
11134                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
11135                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11136                        }
11137                        caching = true;
11138                    } else {
11139                        buildDrawingCache(true);
11140                        Bitmap cache = getDrawingCache(true);
11141                        if (cache != null) {
11142                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
11143                            caching = true;
11144                        }
11145                    }
11146                } else {
11147
11148                    computeScroll();
11149
11150                    if (!USE_DISPLAY_LIST_PROPERTIES) {
11151                        restoreCount = canvas.save();
11152                    }
11153                    canvas.translate(-mScrollX, -mScrollY);
11154                    if (!isLayer) {
11155                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11156                        mPrivateFlags &= ~DIRTY_MASK;
11157                    }
11158
11159                    // Fast path for layouts with no backgrounds
11160                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11161                        dispatchDraw(canvas);
11162                    } else {
11163                        draw(canvas);
11164                    }
11165                }
11166            } finally {
11167                if (USE_DISPLAY_LIST_PROPERTIES) {
11168                    canvas.restoreToCount(restoreCount);
11169                }
11170                canvas.onPostDraw();
11171
11172                displayList.end();
11173                if (USE_DISPLAY_LIST_PROPERTIES) {
11174                    displayList.setCaching(caching);
11175                }
11176                if (isLayer && USE_DISPLAY_LIST_PROPERTIES) {
11177                    displayList.setLeftTopRightBottom(0, 0, width, height);
11178                } else {
11179                    setDisplayListProperties(displayList);
11180                }
11181            }
11182        } else if (!isLayer) {
11183            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11184            mPrivateFlags &= ~DIRTY_MASK;
11185        }
11186
11187        return displayList;
11188    }
11189
11190    /**
11191     * Get the DisplayList for the HardwareLayer
11192     *
11193     * @param layer The HardwareLayer whose DisplayList we want
11194     * @return A DisplayList fopr the specified HardwareLayer
11195     */
11196    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
11197        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
11198        layer.setDisplayList(displayList);
11199        return displayList;
11200    }
11201
11202
11203    /**
11204     * <p>Returns a display list that can be used to draw this view again
11205     * without executing its draw method.</p>
11206     *
11207     * @return A DisplayList ready to replay, or null if caching is not enabled.
11208     *
11209     * @hide
11210     */
11211    public DisplayList getDisplayList() {
11212        mDisplayList = getDisplayList(mDisplayList, false);
11213        return mDisplayList;
11214    }
11215
11216    /**
11217     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
11218     *
11219     * @return A non-scaled bitmap representing this view or null if cache is disabled.
11220     *
11221     * @see #getDrawingCache(boolean)
11222     */
11223    public Bitmap getDrawingCache() {
11224        return getDrawingCache(false);
11225    }
11226
11227    /**
11228     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
11229     * is null when caching is disabled. If caching is enabled and the cache is not ready,
11230     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
11231     * draw from the cache when the cache is enabled. To benefit from the cache, you must
11232     * request the drawing cache by calling this method and draw it on screen if the
11233     * returned bitmap is not null.</p>
11234     *
11235     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11236     * this method will create a bitmap of the same size as this view. Because this bitmap
11237     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11238     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11239     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11240     * size than the view. This implies that your application must be able to handle this
11241     * size.</p>
11242     *
11243     * @param autoScale Indicates whether the generated bitmap should be scaled based on
11244     *        the current density of the screen when the application is in compatibility
11245     *        mode.
11246     *
11247     * @return A bitmap representing this view or null if cache is disabled.
11248     *
11249     * @see #setDrawingCacheEnabled(boolean)
11250     * @see #isDrawingCacheEnabled()
11251     * @see #buildDrawingCache(boolean)
11252     * @see #destroyDrawingCache()
11253     */
11254    public Bitmap getDrawingCache(boolean autoScale) {
11255        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
11256            return null;
11257        }
11258        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
11259            buildDrawingCache(autoScale);
11260        }
11261        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
11262    }
11263
11264    /**
11265     * <p>Frees the resources used by the drawing cache. If you call
11266     * {@link #buildDrawingCache()} manually without calling
11267     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11268     * should cleanup the cache with this method afterwards.</p>
11269     *
11270     * @see #setDrawingCacheEnabled(boolean)
11271     * @see #buildDrawingCache()
11272     * @see #getDrawingCache()
11273     */
11274    public void destroyDrawingCache() {
11275        if (mDrawingCache != null) {
11276            mDrawingCache.recycle();
11277            mDrawingCache = null;
11278        }
11279        if (mUnscaledDrawingCache != null) {
11280            mUnscaledDrawingCache.recycle();
11281            mUnscaledDrawingCache = null;
11282        }
11283    }
11284
11285    /**
11286     * Setting a solid background color for the drawing cache's bitmaps will improve
11287     * performance and memory usage. Note, though that this should only be used if this
11288     * view will always be drawn on top of a solid color.
11289     *
11290     * @param color The background color to use for the drawing cache's bitmap
11291     *
11292     * @see #setDrawingCacheEnabled(boolean)
11293     * @see #buildDrawingCache()
11294     * @see #getDrawingCache()
11295     */
11296    public void setDrawingCacheBackgroundColor(int color) {
11297        if (color != mDrawingCacheBackgroundColor) {
11298            mDrawingCacheBackgroundColor = color;
11299            mPrivateFlags &= ~DRAWING_CACHE_VALID;
11300        }
11301    }
11302
11303    /**
11304     * @see #setDrawingCacheBackgroundColor(int)
11305     *
11306     * @return The background color to used for the drawing cache's bitmap
11307     */
11308    public int getDrawingCacheBackgroundColor() {
11309        return mDrawingCacheBackgroundColor;
11310    }
11311
11312    /**
11313     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
11314     *
11315     * @see #buildDrawingCache(boolean)
11316     */
11317    public void buildDrawingCache() {
11318        buildDrawingCache(false);
11319    }
11320
11321    /**
11322     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
11323     *
11324     * <p>If you call {@link #buildDrawingCache()} manually without calling
11325     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11326     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
11327     *
11328     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11329     * this method will create a bitmap of the same size as this view. Because this bitmap
11330     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11331     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11332     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11333     * size than the view. This implies that your application must be able to handle this
11334     * size.</p>
11335     *
11336     * <p>You should avoid calling this method when hardware acceleration is enabled. If
11337     * you do not need the drawing cache bitmap, calling this method will increase memory
11338     * usage and cause the view to be rendered in software once, thus negatively impacting
11339     * performance.</p>
11340     *
11341     * @see #getDrawingCache()
11342     * @see #destroyDrawingCache()
11343     */
11344    public void buildDrawingCache(boolean autoScale) {
11345        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
11346                mDrawingCache == null : mUnscaledDrawingCache == null)) {
11347            mCachingFailed = false;
11348
11349            if (ViewDebug.TRACE_HIERARCHY) {
11350                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
11351            }
11352
11353            int width = mRight - mLeft;
11354            int height = mBottom - mTop;
11355
11356            final AttachInfo attachInfo = mAttachInfo;
11357            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
11358
11359            if (autoScale && scalingRequired) {
11360                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
11361                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
11362            }
11363
11364            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
11365            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
11366            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
11367
11368            if (width <= 0 || height <= 0 ||
11369                     // Projected bitmap size in bytes
11370                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
11371                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
11372                destroyDrawingCache();
11373                mCachingFailed = true;
11374                return;
11375            }
11376
11377            boolean clear = true;
11378            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
11379
11380            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
11381                Bitmap.Config quality;
11382                if (!opaque) {
11383                    // Never pick ARGB_4444 because it looks awful
11384                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
11385                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
11386                        case DRAWING_CACHE_QUALITY_AUTO:
11387                            quality = Bitmap.Config.ARGB_8888;
11388                            break;
11389                        case DRAWING_CACHE_QUALITY_LOW:
11390                            quality = Bitmap.Config.ARGB_8888;
11391                            break;
11392                        case DRAWING_CACHE_QUALITY_HIGH:
11393                            quality = Bitmap.Config.ARGB_8888;
11394                            break;
11395                        default:
11396                            quality = Bitmap.Config.ARGB_8888;
11397                            break;
11398                    }
11399                } else {
11400                    // Optimization for translucent windows
11401                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
11402                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
11403                }
11404
11405                // Try to cleanup memory
11406                if (bitmap != null) bitmap.recycle();
11407
11408                try {
11409                    bitmap = Bitmap.createBitmap(width, height, quality);
11410                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
11411                    if (autoScale) {
11412                        mDrawingCache = bitmap;
11413                    } else {
11414                        mUnscaledDrawingCache = bitmap;
11415                    }
11416                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
11417                } catch (OutOfMemoryError e) {
11418                    // If there is not enough memory to create the bitmap cache, just
11419                    // ignore the issue as bitmap caches are not required to draw the
11420                    // view hierarchy
11421                    if (autoScale) {
11422                        mDrawingCache = null;
11423                    } else {
11424                        mUnscaledDrawingCache = null;
11425                    }
11426                    mCachingFailed = true;
11427                    return;
11428                }
11429
11430                clear = drawingCacheBackgroundColor != 0;
11431            }
11432
11433            Canvas canvas;
11434            if (attachInfo != null) {
11435                canvas = attachInfo.mCanvas;
11436                if (canvas == null) {
11437                    canvas = new Canvas();
11438                }
11439                canvas.setBitmap(bitmap);
11440                // Temporarily clobber the cached Canvas in case one of our children
11441                // is also using a drawing cache. Without this, the children would
11442                // steal the canvas by attaching their own bitmap to it and bad, bad
11443                // thing would happen (invisible views, corrupted drawings, etc.)
11444                attachInfo.mCanvas = null;
11445            } else {
11446                // This case should hopefully never or seldom happen
11447                canvas = new Canvas(bitmap);
11448            }
11449
11450            if (clear) {
11451                bitmap.eraseColor(drawingCacheBackgroundColor);
11452            }
11453
11454            computeScroll();
11455            final int restoreCount = canvas.save();
11456
11457            if (autoScale && scalingRequired) {
11458                final float scale = attachInfo.mApplicationScale;
11459                canvas.scale(scale, scale);
11460            }
11461
11462            canvas.translate(-mScrollX, -mScrollY);
11463
11464            mPrivateFlags |= DRAWN;
11465            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
11466                    mLayerType != LAYER_TYPE_NONE) {
11467                mPrivateFlags |= DRAWING_CACHE_VALID;
11468            }
11469
11470            // Fast path for layouts with no backgrounds
11471            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11472                if (ViewDebug.TRACE_HIERARCHY) {
11473                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11474                }
11475                mPrivateFlags &= ~DIRTY_MASK;
11476                dispatchDraw(canvas);
11477            } else {
11478                draw(canvas);
11479            }
11480
11481            canvas.restoreToCount(restoreCount);
11482            canvas.setBitmap(null);
11483
11484            if (attachInfo != null) {
11485                // Restore the cached Canvas for our siblings
11486                attachInfo.mCanvas = canvas;
11487            }
11488        }
11489    }
11490
11491    /**
11492     * Create a snapshot of the view into a bitmap.  We should probably make
11493     * some form of this public, but should think about the API.
11494     */
11495    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
11496        int width = mRight - mLeft;
11497        int height = mBottom - mTop;
11498
11499        final AttachInfo attachInfo = mAttachInfo;
11500        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
11501        width = (int) ((width * scale) + 0.5f);
11502        height = (int) ((height * scale) + 0.5f);
11503
11504        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
11505        if (bitmap == null) {
11506            throw new OutOfMemoryError();
11507        }
11508
11509        Resources resources = getResources();
11510        if (resources != null) {
11511            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
11512        }
11513
11514        Canvas canvas;
11515        if (attachInfo != null) {
11516            canvas = attachInfo.mCanvas;
11517            if (canvas == null) {
11518                canvas = new Canvas();
11519            }
11520            canvas.setBitmap(bitmap);
11521            // Temporarily clobber the cached Canvas in case one of our children
11522            // is also using a drawing cache. Without this, the children would
11523            // steal the canvas by attaching their own bitmap to it and bad, bad
11524            // things would happen (invisible views, corrupted drawings, etc.)
11525            attachInfo.mCanvas = null;
11526        } else {
11527            // This case should hopefully never or seldom happen
11528            canvas = new Canvas(bitmap);
11529        }
11530
11531        if ((backgroundColor & 0xff000000) != 0) {
11532            bitmap.eraseColor(backgroundColor);
11533        }
11534
11535        computeScroll();
11536        final int restoreCount = canvas.save();
11537        canvas.scale(scale, scale);
11538        canvas.translate(-mScrollX, -mScrollY);
11539
11540        // Temporarily remove the dirty mask
11541        int flags = mPrivateFlags;
11542        mPrivateFlags &= ~DIRTY_MASK;
11543
11544        // Fast path for layouts with no backgrounds
11545        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11546            dispatchDraw(canvas);
11547        } else {
11548            draw(canvas);
11549        }
11550
11551        mPrivateFlags = flags;
11552
11553        canvas.restoreToCount(restoreCount);
11554        canvas.setBitmap(null);
11555
11556        if (attachInfo != null) {
11557            // Restore the cached Canvas for our siblings
11558            attachInfo.mCanvas = canvas;
11559        }
11560
11561        return bitmap;
11562    }
11563
11564    /**
11565     * Indicates whether this View is currently in edit mode. A View is usually
11566     * in edit mode when displayed within a developer tool. For instance, if
11567     * this View is being drawn by a visual user interface builder, this method
11568     * should return true.
11569     *
11570     * Subclasses should check the return value of this method to provide
11571     * different behaviors if their normal behavior might interfere with the
11572     * host environment. For instance: the class spawns a thread in its
11573     * constructor, the drawing code relies on device-specific features, etc.
11574     *
11575     * This method is usually checked in the drawing code of custom widgets.
11576     *
11577     * @return True if this View is in edit mode, false otherwise.
11578     */
11579    public boolean isInEditMode() {
11580        return false;
11581    }
11582
11583    /**
11584     * If the View draws content inside its padding and enables fading edges,
11585     * it needs to support padding offsets. Padding offsets are added to the
11586     * fading edges to extend the length of the fade so that it covers pixels
11587     * drawn inside the padding.
11588     *
11589     * Subclasses of this class should override this method if they need
11590     * to draw content inside the padding.
11591     *
11592     * @return True if padding offset must be applied, false otherwise.
11593     *
11594     * @see #getLeftPaddingOffset()
11595     * @see #getRightPaddingOffset()
11596     * @see #getTopPaddingOffset()
11597     * @see #getBottomPaddingOffset()
11598     *
11599     * @since CURRENT
11600     */
11601    protected boolean isPaddingOffsetRequired() {
11602        return false;
11603    }
11604
11605    /**
11606     * Amount by which to extend the left fading region. Called only when
11607     * {@link #isPaddingOffsetRequired()} returns true.
11608     *
11609     * @return The left padding offset in pixels.
11610     *
11611     * @see #isPaddingOffsetRequired()
11612     *
11613     * @since CURRENT
11614     */
11615    protected int getLeftPaddingOffset() {
11616        return 0;
11617    }
11618
11619    /**
11620     * Amount by which to extend the right fading region. Called only when
11621     * {@link #isPaddingOffsetRequired()} returns true.
11622     *
11623     * @return The right padding offset in pixels.
11624     *
11625     * @see #isPaddingOffsetRequired()
11626     *
11627     * @since CURRENT
11628     */
11629    protected int getRightPaddingOffset() {
11630        return 0;
11631    }
11632
11633    /**
11634     * Amount by which to extend the top fading region. Called only when
11635     * {@link #isPaddingOffsetRequired()} returns true.
11636     *
11637     * @return The top padding offset in pixels.
11638     *
11639     * @see #isPaddingOffsetRequired()
11640     *
11641     * @since CURRENT
11642     */
11643    protected int getTopPaddingOffset() {
11644        return 0;
11645    }
11646
11647    /**
11648     * Amount by which to extend the bottom fading region. Called only when
11649     * {@link #isPaddingOffsetRequired()} returns true.
11650     *
11651     * @return The bottom padding offset in pixels.
11652     *
11653     * @see #isPaddingOffsetRequired()
11654     *
11655     * @since CURRENT
11656     */
11657    protected int getBottomPaddingOffset() {
11658        return 0;
11659    }
11660
11661    /**
11662     * @hide
11663     * @param offsetRequired
11664     */
11665    protected int getFadeTop(boolean offsetRequired) {
11666        int top = mPaddingTop;
11667        if (offsetRequired) top += getTopPaddingOffset();
11668        return top;
11669    }
11670
11671    /**
11672     * @hide
11673     * @param offsetRequired
11674     */
11675    protected int getFadeHeight(boolean offsetRequired) {
11676        int padding = mPaddingTop;
11677        if (offsetRequired) padding += getTopPaddingOffset();
11678        return mBottom - mTop - mPaddingBottom - padding;
11679    }
11680
11681    /**
11682     * <p>Indicates whether this view is attached to a hardware accelerated
11683     * window or not.</p>
11684     *
11685     * <p>Even if this method returns true, it does not mean that every call
11686     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
11687     * accelerated {@link android.graphics.Canvas}. For instance, if this view
11688     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
11689     * window is hardware accelerated,
11690     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
11691     * return false, and this method will return true.</p>
11692     *
11693     * @return True if the view is attached to a window and the window is
11694     *         hardware accelerated; false in any other case.
11695     */
11696    public boolean isHardwareAccelerated() {
11697        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
11698    }
11699
11700    /**
11701     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
11702     * case of an active Animation being run on the view.
11703     */
11704    private boolean drawAnimation(ViewGroup parent, long drawingTime,
11705            Animation a, boolean scalingRequired) {
11706        Transformation invalidationTransform;
11707        final int flags = parent.mGroupFlags;
11708        final boolean initialized = a.isInitialized();
11709        if (!initialized) {
11710            a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight());
11711            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
11712            onAnimationStart();
11713        }
11714
11715        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
11716        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
11717            if (parent.mInvalidationTransformation == null) {
11718                parent.mInvalidationTransformation = new Transformation();
11719            }
11720            invalidationTransform = parent.mInvalidationTransformation;
11721            a.getTransformation(drawingTime, invalidationTransform, 1f);
11722        } else {
11723            invalidationTransform = parent.mChildTransformation;
11724        }
11725        if (more) {
11726            if (!a.willChangeBounds()) {
11727                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
11728                        parent.FLAG_OPTIMIZE_INVALIDATE) {
11729                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
11730                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
11731                    // The child need to draw an animation, potentially offscreen, so
11732                    // make sure we do not cancel invalidate requests
11733                    parent.mPrivateFlags |= DRAW_ANIMATION;
11734                    parent.invalidate(mLeft, mTop, mRight, mBottom);
11735                }
11736            } else {
11737                if (parent.mInvalidateRegion == null) {
11738                    parent.mInvalidateRegion = new RectF();
11739                }
11740                final RectF region = parent.mInvalidateRegion;
11741                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
11742                        invalidationTransform);
11743
11744                // The child need to draw an animation, potentially offscreen, so
11745                // make sure we do not cancel invalidate requests
11746                parent.mPrivateFlags |= DRAW_ANIMATION;
11747
11748                final int left = mLeft + (int) region.left;
11749                final int top = mTop + (int) region.top;
11750                parent.invalidate(left, top, left + (int) (region.width() + .5f),
11751                        top + (int) (region.height() + .5f));
11752            }
11753        }
11754        return more;
11755    }
11756
11757    void setDisplayListProperties() {
11758        setDisplayListProperties(mDisplayList);
11759    }
11760
11761    /**
11762     * This method is called by getDisplayList() when a display list is created or re-rendered.
11763     * It sets or resets the current value of all properties on that display list (resetting is
11764     * necessary when a display list is being re-created, because we need to make sure that
11765     * previously-set transform values
11766     */
11767    void setDisplayListProperties(DisplayList displayList) {
11768        if (USE_DISPLAY_LIST_PROPERTIES && displayList != null) {
11769            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
11770            displayList.setHasOverlappingRendering(hasOverlappingRendering());
11771            if (mParent instanceof ViewGroup) {
11772                displayList.setClipChildren(
11773                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
11774            }
11775            float alpha = 1;
11776            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
11777                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
11778                ViewGroup parentVG = (ViewGroup) mParent;
11779                final boolean hasTransform =
11780                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
11781                if (hasTransform) {
11782                    Transformation transform = parentVG.mChildTransformation;
11783                    final int transformType = parentVG.mChildTransformation.getTransformationType();
11784                    if (transformType != Transformation.TYPE_IDENTITY) {
11785                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
11786                            alpha = transform.getAlpha();
11787                        }
11788                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
11789                            displayList.setStaticMatrix(transform.getMatrix());
11790                        }
11791                    }
11792                }
11793            }
11794            if (mTransformationInfo != null) {
11795                alpha *= mTransformationInfo.mAlpha;
11796                if (alpha < 1) {
11797                    final int multipliedAlpha = (int) (255 * alpha);
11798                    if (onSetAlpha(multipliedAlpha)) {
11799                        alpha = 1;
11800                    }
11801                }
11802                displayList.setTransformationInfo(alpha,
11803                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
11804                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
11805                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
11806                        mTransformationInfo.mScaleY);
11807                if (mTransformationInfo.mCamera == null) {
11808                    mTransformationInfo.mCamera = new Camera();
11809                    mTransformationInfo.matrix3D = new Matrix();
11810                }
11811                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
11812                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
11813                    displayList.setPivotX(getPivotX());
11814                    displayList.setPivotY(getPivotY());
11815                }
11816            } else if (alpha < 1) {
11817                displayList.setAlpha(alpha);
11818            }
11819        }
11820    }
11821
11822    /**
11823     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
11824     * This draw() method is an implementation detail and is not intended to be overridden or
11825     * to be called from anywhere else other than ViewGroup.drawChild().
11826     */
11827    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
11828        boolean useDisplayListProperties = USE_DISPLAY_LIST_PROPERTIES && mAttachInfo != null &&
11829                mAttachInfo.mHardwareAccelerated;
11830        boolean more = false;
11831        final boolean childHasIdentityMatrix = hasIdentityMatrix();
11832        final int flags = parent.mGroupFlags;
11833
11834        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
11835            parent.mChildTransformation.clear();
11836            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11837        }
11838
11839        Transformation transformToApply = null;
11840        boolean concatMatrix = false;
11841
11842        boolean scalingRequired = false;
11843        boolean caching;
11844        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
11845
11846        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
11847        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
11848                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
11849            caching = true;
11850            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
11851            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
11852        } else {
11853            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
11854        }
11855
11856        final Animation a = getAnimation();
11857        if (a != null) {
11858            more = drawAnimation(parent, drawingTime, a, scalingRequired);
11859            concatMatrix = a.willChangeTransformationMatrix();
11860            transformToApply = parent.mChildTransformation;
11861        } else if (!useDisplayListProperties &&
11862                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
11863            final boolean hasTransform =
11864                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
11865            if (hasTransform) {
11866                final int transformType = parent.mChildTransformation.getTransformationType();
11867                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
11868                        parent.mChildTransformation : null;
11869                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
11870            }
11871        }
11872
11873        concatMatrix |= !childHasIdentityMatrix;
11874
11875        // Sets the flag as early as possible to allow draw() implementations
11876        // to call invalidate() successfully when doing animations
11877        mPrivateFlags |= DRAWN;
11878
11879        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
11880                (mPrivateFlags & DRAW_ANIMATION) == 0) {
11881            return more;
11882        }
11883
11884        if (hardwareAccelerated) {
11885            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
11886            // retain the flag's value temporarily in the mRecreateDisplayList flag
11887            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
11888            mPrivateFlags &= ~INVALIDATED;
11889        }
11890
11891        computeScroll();
11892
11893        final int sx = mScrollX;
11894        final int sy = mScrollY;
11895
11896        DisplayList displayList = null;
11897        Bitmap cache = null;
11898        boolean hasDisplayList = false;
11899        if (caching) {
11900            if (!hardwareAccelerated) {
11901                if (layerType != LAYER_TYPE_NONE) {
11902                    layerType = LAYER_TYPE_SOFTWARE;
11903                    buildDrawingCache(true);
11904                }
11905                cache = getDrawingCache(true);
11906            } else {
11907                switch (layerType) {
11908                    case LAYER_TYPE_SOFTWARE:
11909                        if (useDisplayListProperties) {
11910                            hasDisplayList = canHaveDisplayList();
11911                        } else {
11912                            buildDrawingCache(true);
11913                            cache = getDrawingCache(true);
11914                        }
11915                        break;
11916                    case LAYER_TYPE_HARDWARE:
11917                        if (useDisplayListProperties) {
11918                            hasDisplayList = canHaveDisplayList();
11919                        }
11920                        break;
11921                    case LAYER_TYPE_NONE:
11922                        // Delay getting the display list until animation-driven alpha values are
11923                        // set up and possibly passed on to the view
11924                        hasDisplayList = canHaveDisplayList();
11925                        break;
11926                }
11927            }
11928        }
11929        useDisplayListProperties &= hasDisplayList;
11930        if (useDisplayListProperties) {
11931            displayList = getDisplayList();
11932            if (!displayList.isValid()) {
11933                // Uncommon, but possible. If a view is removed from the hierarchy during the call
11934                // to getDisplayList(), the display list will be marked invalid and we should not
11935                // try to use it again.
11936                displayList = null;
11937                hasDisplayList = false;
11938                useDisplayListProperties = false;
11939            }
11940        }
11941
11942        final boolean hasNoCache = cache == null || hasDisplayList;
11943        final boolean offsetForScroll = cache == null && !hasDisplayList &&
11944                layerType != LAYER_TYPE_HARDWARE;
11945
11946        int restoreTo = -1;
11947        if (!useDisplayListProperties || transformToApply != null) {
11948            restoreTo = canvas.save();
11949        }
11950        if (offsetForScroll) {
11951            canvas.translate(mLeft - sx, mTop - sy);
11952        } else {
11953            if (!useDisplayListProperties) {
11954                canvas.translate(mLeft, mTop);
11955            }
11956            if (scalingRequired) {
11957                if (useDisplayListProperties) {
11958                    // TODO: Might not need this if we put everything inside the DL
11959                    restoreTo = canvas.save();
11960                }
11961                // mAttachInfo cannot be null, otherwise scalingRequired == false
11962                final float scale = 1.0f / mAttachInfo.mApplicationScale;
11963                canvas.scale(scale, scale);
11964            }
11965        }
11966
11967        float alpha = useDisplayListProperties ? 1 : getAlpha();
11968        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
11969            if (transformToApply != null || !childHasIdentityMatrix) {
11970                int transX = 0;
11971                int transY = 0;
11972
11973                if (offsetForScroll) {
11974                    transX = -sx;
11975                    transY = -sy;
11976                }
11977
11978                if (transformToApply != null) {
11979                    if (concatMatrix) {
11980                        if (useDisplayListProperties) {
11981                            displayList.setAnimationMatrix(transformToApply.getMatrix());
11982                        } else {
11983                            // Undo the scroll translation, apply the transformation matrix,
11984                            // then redo the scroll translate to get the correct result.
11985                            canvas.translate(-transX, -transY);
11986                            canvas.concat(transformToApply.getMatrix());
11987                            canvas.translate(transX, transY);
11988                        }
11989                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11990                    }
11991
11992                    float transformAlpha = transformToApply.getAlpha();
11993                    if (transformAlpha < 1) {
11994                        alpha *= transformToApply.getAlpha();
11995                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11996                    }
11997                }
11998
11999                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12000                    canvas.translate(-transX, -transY);
12001                    canvas.concat(getMatrix());
12002                    canvas.translate(transX, transY);
12003                }
12004            }
12005
12006            if (alpha < 1) {
12007                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12008                if (hasNoCache) {
12009                    final int multipliedAlpha = (int) (255 * alpha);
12010                    if (!onSetAlpha(multipliedAlpha)) {
12011                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12012                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
12013                                layerType != LAYER_TYPE_NONE) {
12014                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
12015                        }
12016                        if (useDisplayListProperties) {
12017                            displayList.setAlpha(alpha * getAlpha());
12018                        } else  if (layerType == LAYER_TYPE_NONE) {
12019                            final int scrollX = hasDisplayList ? 0 : sx;
12020                            final int scrollY = hasDisplayList ? 0 : sy;
12021                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
12022                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
12023                        }
12024                    } else {
12025                        // Alpha is handled by the child directly, clobber the layer's alpha
12026                        mPrivateFlags |= ALPHA_SET;
12027                    }
12028                }
12029            }
12030        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12031            onSetAlpha(255);
12032            mPrivateFlags &= ~ALPHA_SET;
12033        }
12034
12035        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
12036                !useDisplayListProperties) {
12037            if (offsetForScroll) {
12038                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
12039            } else {
12040                if (!scalingRequired || cache == null) {
12041                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
12042                } else {
12043                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
12044                }
12045            }
12046        }
12047
12048        if (!useDisplayListProperties && hasDisplayList) {
12049            displayList = getDisplayList();
12050            if (!displayList.isValid()) {
12051                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12052                // to getDisplayList(), the display list will be marked invalid and we should not
12053                // try to use it again.
12054                displayList = null;
12055                hasDisplayList = false;
12056            }
12057        }
12058
12059        if (hasNoCache) {
12060            boolean layerRendered = false;
12061            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
12062                final HardwareLayer layer = getHardwareLayer();
12063                if (layer != null && layer.isValid()) {
12064                    mLayerPaint.setAlpha((int) (alpha * 255));
12065                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
12066                    layerRendered = true;
12067                } else {
12068                    final int scrollX = hasDisplayList ? 0 : sx;
12069                    final int scrollY = hasDisplayList ? 0 : sy;
12070                    canvas.saveLayer(scrollX, scrollY,
12071                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
12072                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12073                }
12074            }
12075
12076            if (!layerRendered) {
12077                if (!hasDisplayList) {
12078                    // Fast path for layouts with no backgrounds
12079                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12080                        if (ViewDebug.TRACE_HIERARCHY) {
12081                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
12082                        }
12083                        mPrivateFlags &= ~DIRTY_MASK;
12084                        dispatchDraw(canvas);
12085                    } else {
12086                        draw(canvas);
12087                    }
12088                } else {
12089                    mPrivateFlags &= ~DIRTY_MASK;
12090                    ((HardwareCanvas) canvas).drawDisplayList(displayList,
12091                            mRight - mLeft, mBottom - mTop, null, flags);
12092                }
12093            }
12094        } else if (cache != null) {
12095            mPrivateFlags &= ~DIRTY_MASK;
12096            Paint cachePaint;
12097
12098            if (layerType == LAYER_TYPE_NONE) {
12099                cachePaint = parent.mCachePaint;
12100                if (cachePaint == null) {
12101                    cachePaint = new Paint();
12102                    cachePaint.setDither(false);
12103                    parent.mCachePaint = cachePaint;
12104                }
12105                if (alpha < 1) {
12106                    cachePaint.setAlpha((int) (alpha * 255));
12107                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12108                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
12109                    cachePaint.setAlpha(255);
12110                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12111                }
12112            } else {
12113                cachePaint = mLayerPaint;
12114                cachePaint.setAlpha((int) (alpha * 255));
12115            }
12116            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
12117        }
12118
12119        if (restoreTo >= 0) {
12120            canvas.restoreToCount(restoreTo);
12121        }
12122
12123        if (a != null && !more) {
12124            if (!hardwareAccelerated && !a.getFillAfter()) {
12125                onSetAlpha(255);
12126            }
12127            parent.finishAnimatingView(this, a);
12128        }
12129
12130        if (more && hardwareAccelerated) {
12131            // invalidation is the trigger to recreate display lists, so if we're using
12132            // display lists to render, force an invalidate to allow the animation to
12133            // continue drawing another frame
12134            parent.invalidate(true);
12135            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12136                // alpha animations should cause the child to recreate its display list
12137                invalidate(true);
12138            }
12139        }
12140
12141        mRecreateDisplayList = false;
12142
12143        return more;
12144    }
12145
12146    /**
12147     * Manually render this view (and all of its children) to the given Canvas.
12148     * The view must have already done a full layout before this function is
12149     * called.  When implementing a view, implement
12150     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
12151     * If you do need to override this method, call the superclass version.
12152     *
12153     * @param canvas The Canvas to which the View is rendered.
12154     */
12155    public void draw(Canvas canvas) {
12156        if (ViewDebug.TRACE_HIERARCHY) {
12157            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12158        }
12159
12160        final int privateFlags = mPrivateFlags;
12161        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
12162                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
12163        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
12164
12165        /*
12166         * Draw traversal performs several drawing steps which must be executed
12167         * in the appropriate order:
12168         *
12169         *      1. Draw the background
12170         *      2. If necessary, save the canvas' layers to prepare for fading
12171         *      3. Draw view's content
12172         *      4. Draw children
12173         *      5. If necessary, draw the fading edges and restore layers
12174         *      6. Draw decorations (scrollbars for instance)
12175         */
12176
12177        // Step 1, draw the background, if needed
12178        int saveCount;
12179
12180        if (!dirtyOpaque) {
12181            final Drawable background = mBackground;
12182            if (background != null) {
12183                final int scrollX = mScrollX;
12184                final int scrollY = mScrollY;
12185
12186                if (mBackgroundSizeChanged) {
12187                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
12188                    mBackgroundSizeChanged = false;
12189                }
12190
12191                if ((scrollX | scrollY) == 0) {
12192                    background.draw(canvas);
12193                } else {
12194                    canvas.translate(scrollX, scrollY);
12195                    background.draw(canvas);
12196                    canvas.translate(-scrollX, -scrollY);
12197                }
12198            }
12199        }
12200
12201        // skip step 2 & 5 if possible (common case)
12202        final int viewFlags = mViewFlags;
12203        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
12204        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
12205        if (!verticalEdges && !horizontalEdges) {
12206            // Step 3, draw the content
12207            if (!dirtyOpaque) onDraw(canvas);
12208
12209            // Step 4, draw the children
12210            dispatchDraw(canvas);
12211
12212            // Step 6, draw decorations (scrollbars)
12213            onDrawScrollBars(canvas);
12214
12215            // we're done...
12216            return;
12217        }
12218
12219        /*
12220         * Here we do the full fledged routine...
12221         * (this is an uncommon case where speed matters less,
12222         * this is why we repeat some of the tests that have been
12223         * done above)
12224         */
12225
12226        boolean drawTop = false;
12227        boolean drawBottom = false;
12228        boolean drawLeft = false;
12229        boolean drawRight = false;
12230
12231        float topFadeStrength = 0.0f;
12232        float bottomFadeStrength = 0.0f;
12233        float leftFadeStrength = 0.0f;
12234        float rightFadeStrength = 0.0f;
12235
12236        // Step 2, save the canvas' layers
12237        int paddingLeft = mPaddingLeft;
12238
12239        final boolean offsetRequired = isPaddingOffsetRequired();
12240        if (offsetRequired) {
12241            paddingLeft += getLeftPaddingOffset();
12242        }
12243
12244        int left = mScrollX + paddingLeft;
12245        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
12246        int top = mScrollY + getFadeTop(offsetRequired);
12247        int bottom = top + getFadeHeight(offsetRequired);
12248
12249        if (offsetRequired) {
12250            right += getRightPaddingOffset();
12251            bottom += getBottomPaddingOffset();
12252        }
12253
12254        final ScrollabilityCache scrollabilityCache = mScrollCache;
12255        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
12256        int length = (int) fadeHeight;
12257
12258        // clip the fade length if top and bottom fades overlap
12259        // overlapping fades produce odd-looking artifacts
12260        if (verticalEdges && (top + length > bottom - length)) {
12261            length = (bottom - top) / 2;
12262        }
12263
12264        // also clip horizontal fades if necessary
12265        if (horizontalEdges && (left + length > right - length)) {
12266            length = (right - left) / 2;
12267        }
12268
12269        if (verticalEdges) {
12270            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
12271            drawTop = topFadeStrength * fadeHeight > 1.0f;
12272            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
12273            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
12274        }
12275
12276        if (horizontalEdges) {
12277            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
12278            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
12279            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
12280            drawRight = rightFadeStrength * fadeHeight > 1.0f;
12281        }
12282
12283        saveCount = canvas.getSaveCount();
12284
12285        int solidColor = getSolidColor();
12286        if (solidColor == 0) {
12287            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12288
12289            if (drawTop) {
12290                canvas.saveLayer(left, top, right, top + length, null, flags);
12291            }
12292
12293            if (drawBottom) {
12294                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
12295            }
12296
12297            if (drawLeft) {
12298                canvas.saveLayer(left, top, left + length, bottom, null, flags);
12299            }
12300
12301            if (drawRight) {
12302                canvas.saveLayer(right - length, top, right, bottom, null, flags);
12303            }
12304        } else {
12305            scrollabilityCache.setFadeColor(solidColor);
12306        }
12307
12308        // Step 3, draw the content
12309        if (!dirtyOpaque) onDraw(canvas);
12310
12311        // Step 4, draw the children
12312        dispatchDraw(canvas);
12313
12314        // Step 5, draw the fade effect and restore layers
12315        final Paint p = scrollabilityCache.paint;
12316        final Matrix matrix = scrollabilityCache.matrix;
12317        final Shader fade = scrollabilityCache.shader;
12318
12319        if (drawTop) {
12320            matrix.setScale(1, fadeHeight * topFadeStrength);
12321            matrix.postTranslate(left, top);
12322            fade.setLocalMatrix(matrix);
12323            canvas.drawRect(left, top, right, top + length, p);
12324        }
12325
12326        if (drawBottom) {
12327            matrix.setScale(1, fadeHeight * bottomFadeStrength);
12328            matrix.postRotate(180);
12329            matrix.postTranslate(left, bottom);
12330            fade.setLocalMatrix(matrix);
12331            canvas.drawRect(left, bottom - length, right, bottom, p);
12332        }
12333
12334        if (drawLeft) {
12335            matrix.setScale(1, fadeHeight * leftFadeStrength);
12336            matrix.postRotate(-90);
12337            matrix.postTranslate(left, top);
12338            fade.setLocalMatrix(matrix);
12339            canvas.drawRect(left, top, left + length, bottom, p);
12340        }
12341
12342        if (drawRight) {
12343            matrix.setScale(1, fadeHeight * rightFadeStrength);
12344            matrix.postRotate(90);
12345            matrix.postTranslate(right, top);
12346            fade.setLocalMatrix(matrix);
12347            canvas.drawRect(right - length, top, right, bottom, p);
12348        }
12349
12350        canvas.restoreToCount(saveCount);
12351
12352        // Step 6, draw decorations (scrollbars)
12353        onDrawScrollBars(canvas);
12354    }
12355
12356    /**
12357     * Override this if your view is known to always be drawn on top of a solid color background,
12358     * and needs to draw fading edges. Returning a non-zero color enables the view system to
12359     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
12360     * should be set to 0xFF.
12361     *
12362     * @see #setVerticalFadingEdgeEnabled(boolean)
12363     * @see #setHorizontalFadingEdgeEnabled(boolean)
12364     *
12365     * @return The known solid color background for this view, or 0 if the color may vary
12366     */
12367    @ViewDebug.ExportedProperty(category = "drawing")
12368    public int getSolidColor() {
12369        return 0;
12370    }
12371
12372    /**
12373     * Build a human readable string representation of the specified view flags.
12374     *
12375     * @param flags the view flags to convert to a string
12376     * @return a String representing the supplied flags
12377     */
12378    private static String printFlags(int flags) {
12379        String output = "";
12380        int numFlags = 0;
12381        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
12382            output += "TAKES_FOCUS";
12383            numFlags++;
12384        }
12385
12386        switch (flags & VISIBILITY_MASK) {
12387        case INVISIBLE:
12388            if (numFlags > 0) {
12389                output += " ";
12390            }
12391            output += "INVISIBLE";
12392            // USELESS HERE numFlags++;
12393            break;
12394        case GONE:
12395            if (numFlags > 0) {
12396                output += " ";
12397            }
12398            output += "GONE";
12399            // USELESS HERE numFlags++;
12400            break;
12401        default:
12402            break;
12403        }
12404        return output;
12405    }
12406
12407    /**
12408     * Build a human readable string representation of the specified private
12409     * view flags.
12410     *
12411     * @param privateFlags the private view flags to convert to a string
12412     * @return a String representing the supplied flags
12413     */
12414    private static String printPrivateFlags(int privateFlags) {
12415        String output = "";
12416        int numFlags = 0;
12417
12418        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
12419            output += "WANTS_FOCUS";
12420            numFlags++;
12421        }
12422
12423        if ((privateFlags & FOCUSED) == FOCUSED) {
12424            if (numFlags > 0) {
12425                output += " ";
12426            }
12427            output += "FOCUSED";
12428            numFlags++;
12429        }
12430
12431        if ((privateFlags & SELECTED) == SELECTED) {
12432            if (numFlags > 0) {
12433                output += " ";
12434            }
12435            output += "SELECTED";
12436            numFlags++;
12437        }
12438
12439        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
12440            if (numFlags > 0) {
12441                output += " ";
12442            }
12443            output += "IS_ROOT_NAMESPACE";
12444            numFlags++;
12445        }
12446
12447        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
12448            if (numFlags > 0) {
12449                output += " ";
12450            }
12451            output += "HAS_BOUNDS";
12452            numFlags++;
12453        }
12454
12455        if ((privateFlags & DRAWN) == DRAWN) {
12456            if (numFlags > 0) {
12457                output += " ";
12458            }
12459            output += "DRAWN";
12460            // USELESS HERE numFlags++;
12461        }
12462        return output;
12463    }
12464
12465    /**
12466     * <p>Indicates whether or not this view's layout will be requested during
12467     * the next hierarchy layout pass.</p>
12468     *
12469     * @return true if the layout will be forced during next layout pass
12470     */
12471    public boolean isLayoutRequested() {
12472        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
12473    }
12474
12475    /**
12476     * Assign a size and position to a view and all of its
12477     * descendants
12478     *
12479     * <p>This is the second phase of the layout mechanism.
12480     * (The first is measuring). In this phase, each parent calls
12481     * layout on all of its children to position them.
12482     * This is typically done using the child measurements
12483     * that were stored in the measure pass().</p>
12484     *
12485     * <p>Derived classes should not override this method.
12486     * Derived classes with children should override
12487     * onLayout. In that method, they should
12488     * call layout on each of their children.</p>
12489     *
12490     * @param l Left position, relative to parent
12491     * @param t Top position, relative to parent
12492     * @param r Right position, relative to parent
12493     * @param b Bottom position, relative to parent
12494     */
12495    @SuppressWarnings({"unchecked"})
12496    public void layout(int l, int t, int r, int b) {
12497        int oldL = mLeft;
12498        int oldT = mTop;
12499        int oldB = mBottom;
12500        int oldR = mRight;
12501        boolean changed = setFrame(l, t, r, b);
12502        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
12503            if (ViewDebug.TRACE_HIERARCHY) {
12504                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
12505            }
12506
12507            onLayout(changed, l, t, r, b);
12508            mPrivateFlags &= ~LAYOUT_REQUIRED;
12509
12510            ListenerInfo li = mListenerInfo;
12511            if (li != null && li.mOnLayoutChangeListeners != null) {
12512                ArrayList<OnLayoutChangeListener> listenersCopy =
12513                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
12514                int numListeners = listenersCopy.size();
12515                for (int i = 0; i < numListeners; ++i) {
12516                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
12517                }
12518            }
12519        }
12520        mPrivateFlags &= ~FORCE_LAYOUT;
12521    }
12522
12523    /**
12524     * Called from layout when this view should
12525     * assign a size and position to each of its children.
12526     *
12527     * Derived classes with children should override
12528     * this method and call layout on each of
12529     * their children.
12530     * @param changed This is a new size or position for this view
12531     * @param left Left position, relative to parent
12532     * @param top Top position, relative to parent
12533     * @param right Right position, relative to parent
12534     * @param bottom Bottom position, relative to parent
12535     */
12536    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
12537    }
12538
12539    /**
12540     * Assign a size and position to this view.
12541     *
12542     * This is called from layout.
12543     *
12544     * @param left Left position, relative to parent
12545     * @param top Top position, relative to parent
12546     * @param right Right position, relative to parent
12547     * @param bottom Bottom position, relative to parent
12548     * @return true if the new size and position are different than the
12549     *         previous ones
12550     * {@hide}
12551     */
12552    protected boolean setFrame(int left, int top, int right, int bottom) {
12553        boolean changed = false;
12554
12555        if (DBG) {
12556            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
12557                    + right + "," + bottom + ")");
12558        }
12559
12560        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
12561            changed = true;
12562
12563            // Remember our drawn bit
12564            int drawn = mPrivateFlags & DRAWN;
12565
12566            int oldWidth = mRight - mLeft;
12567            int oldHeight = mBottom - mTop;
12568            int newWidth = right - left;
12569            int newHeight = bottom - top;
12570            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
12571
12572            // Invalidate our old position
12573            invalidate(sizeChanged);
12574
12575            mLeft = left;
12576            mTop = top;
12577            mRight = right;
12578            mBottom = bottom;
12579            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
12580                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12581            }
12582
12583            mPrivateFlags |= HAS_BOUNDS;
12584
12585
12586            if (sizeChanged) {
12587                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
12588                    // A change in dimension means an auto-centered pivot point changes, too
12589                    if (mTransformationInfo != null) {
12590                        mTransformationInfo.mMatrixDirty = true;
12591                    }
12592                }
12593                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
12594            }
12595
12596            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
12597                // If we are visible, force the DRAWN bit to on so that
12598                // this invalidate will go through (at least to our parent).
12599                // This is because someone may have invalidated this view
12600                // before this call to setFrame came in, thereby clearing
12601                // the DRAWN bit.
12602                mPrivateFlags |= DRAWN;
12603                invalidate(sizeChanged);
12604                // parent display list may need to be recreated based on a change in the bounds
12605                // of any child
12606                invalidateParentCaches();
12607            }
12608
12609            // Reset drawn bit to original value (invalidate turns it off)
12610            mPrivateFlags |= drawn;
12611
12612            mBackgroundSizeChanged = true;
12613        }
12614        return changed;
12615    }
12616
12617    /**
12618     * Finalize inflating a view from XML.  This is called as the last phase
12619     * of inflation, after all child views have been added.
12620     *
12621     * <p>Even if the subclass overrides onFinishInflate, they should always be
12622     * sure to call the super method, so that we get called.
12623     */
12624    protected void onFinishInflate() {
12625    }
12626
12627    /**
12628     * Returns the resources associated with this view.
12629     *
12630     * @return Resources object.
12631     */
12632    public Resources getResources() {
12633        return mResources;
12634    }
12635
12636    /**
12637     * Invalidates the specified Drawable.
12638     *
12639     * @param drawable the drawable to invalidate
12640     */
12641    public void invalidateDrawable(Drawable drawable) {
12642        if (verifyDrawable(drawable)) {
12643            final Rect dirty = drawable.getBounds();
12644            final int scrollX = mScrollX;
12645            final int scrollY = mScrollY;
12646
12647            invalidate(dirty.left + scrollX, dirty.top + scrollY,
12648                    dirty.right + scrollX, dirty.bottom + scrollY);
12649        }
12650    }
12651
12652    /**
12653     * Schedules an action on a drawable to occur at a specified time.
12654     *
12655     * @param who the recipient of the action
12656     * @param what the action to run on the drawable
12657     * @param when the time at which the action must occur. Uses the
12658     *        {@link SystemClock#uptimeMillis} timebase.
12659     */
12660    public void scheduleDrawable(Drawable who, Runnable what, long when) {
12661        if (verifyDrawable(who) && what != null) {
12662            final long delay = when - SystemClock.uptimeMillis();
12663            if (mAttachInfo != null) {
12664                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12665                        Choreographer.CALLBACK_ANIMATION, what, who,
12666                        Choreographer.subtractFrameDelay(delay));
12667            } else {
12668                ViewRootImpl.getRunQueue().postDelayed(what, delay);
12669            }
12670        }
12671    }
12672
12673    /**
12674     * Cancels a scheduled action on a drawable.
12675     *
12676     * @param who the recipient of the action
12677     * @param what the action to cancel
12678     */
12679    public void unscheduleDrawable(Drawable who, Runnable what) {
12680        if (verifyDrawable(who) && what != null) {
12681            if (mAttachInfo != null) {
12682                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12683                        Choreographer.CALLBACK_ANIMATION, what, who);
12684            } else {
12685                ViewRootImpl.getRunQueue().removeCallbacks(what);
12686            }
12687        }
12688    }
12689
12690    /**
12691     * Unschedule any events associated with the given Drawable.  This can be
12692     * used when selecting a new Drawable into a view, so that the previous
12693     * one is completely unscheduled.
12694     *
12695     * @param who The Drawable to unschedule.
12696     *
12697     * @see #drawableStateChanged
12698     */
12699    public void unscheduleDrawable(Drawable who) {
12700        if (mAttachInfo != null && who != null) {
12701            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12702                    Choreographer.CALLBACK_ANIMATION, null, who);
12703        }
12704    }
12705
12706    /**
12707    * Return the layout direction of a given Drawable.
12708    *
12709    * @param who the Drawable to query
12710    */
12711    public int getResolvedLayoutDirection(Drawable who) {
12712        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
12713    }
12714
12715    /**
12716     * If your view subclass is displaying its own Drawable objects, it should
12717     * override this function and return true for any Drawable it is
12718     * displaying.  This allows animations for those drawables to be
12719     * scheduled.
12720     *
12721     * <p>Be sure to call through to the super class when overriding this
12722     * function.
12723     *
12724     * @param who The Drawable to verify.  Return true if it is one you are
12725     *            displaying, else return the result of calling through to the
12726     *            super class.
12727     *
12728     * @return boolean If true than the Drawable is being displayed in the
12729     *         view; else false and it is not allowed to animate.
12730     *
12731     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
12732     * @see #drawableStateChanged()
12733     */
12734    protected boolean verifyDrawable(Drawable who) {
12735        return who == mBackground;
12736    }
12737
12738    /**
12739     * This function is called whenever the state of the view changes in such
12740     * a way that it impacts the state of drawables being shown.
12741     *
12742     * <p>Be sure to call through to the superclass when overriding this
12743     * function.
12744     *
12745     * @see Drawable#setState(int[])
12746     */
12747    protected void drawableStateChanged() {
12748        Drawable d = mBackground;
12749        if (d != null && d.isStateful()) {
12750            d.setState(getDrawableState());
12751        }
12752    }
12753
12754    /**
12755     * Call this to force a view to update its drawable state. This will cause
12756     * drawableStateChanged to be called on this view. Views that are interested
12757     * in the new state should call getDrawableState.
12758     *
12759     * @see #drawableStateChanged
12760     * @see #getDrawableState
12761     */
12762    public void refreshDrawableState() {
12763        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
12764        drawableStateChanged();
12765
12766        ViewParent parent = mParent;
12767        if (parent != null) {
12768            parent.childDrawableStateChanged(this);
12769        }
12770    }
12771
12772    /**
12773     * Return an array of resource IDs of the drawable states representing the
12774     * current state of the view.
12775     *
12776     * @return The current drawable state
12777     *
12778     * @see Drawable#setState(int[])
12779     * @see #drawableStateChanged()
12780     * @see #onCreateDrawableState(int)
12781     */
12782    public final int[] getDrawableState() {
12783        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
12784            return mDrawableState;
12785        } else {
12786            mDrawableState = onCreateDrawableState(0);
12787            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
12788            return mDrawableState;
12789        }
12790    }
12791
12792    /**
12793     * Generate the new {@link android.graphics.drawable.Drawable} state for
12794     * this view. This is called by the view
12795     * system when the cached Drawable state is determined to be invalid.  To
12796     * retrieve the current state, you should use {@link #getDrawableState}.
12797     *
12798     * @param extraSpace if non-zero, this is the number of extra entries you
12799     * would like in the returned array in which you can place your own
12800     * states.
12801     *
12802     * @return Returns an array holding the current {@link Drawable} state of
12803     * the view.
12804     *
12805     * @see #mergeDrawableStates(int[], int[])
12806     */
12807    protected int[] onCreateDrawableState(int extraSpace) {
12808        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
12809                mParent instanceof View) {
12810            return ((View) mParent).onCreateDrawableState(extraSpace);
12811        }
12812
12813        int[] drawableState;
12814
12815        int privateFlags = mPrivateFlags;
12816
12817        int viewStateIndex = 0;
12818        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
12819        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
12820        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
12821        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
12822        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
12823        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
12824        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
12825                HardwareRenderer.isAvailable()) {
12826            // This is set if HW acceleration is requested, even if the current
12827            // process doesn't allow it.  This is just to allow app preview
12828            // windows to better match their app.
12829            viewStateIndex |= VIEW_STATE_ACCELERATED;
12830        }
12831        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
12832
12833        final int privateFlags2 = mPrivateFlags2;
12834        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
12835        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
12836
12837        drawableState = VIEW_STATE_SETS[viewStateIndex];
12838
12839        //noinspection ConstantIfStatement
12840        if (false) {
12841            Log.i("View", "drawableStateIndex=" + viewStateIndex);
12842            Log.i("View", toString()
12843                    + " pressed=" + ((privateFlags & PRESSED) != 0)
12844                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
12845                    + " fo=" + hasFocus()
12846                    + " sl=" + ((privateFlags & SELECTED) != 0)
12847                    + " wf=" + hasWindowFocus()
12848                    + ": " + Arrays.toString(drawableState));
12849        }
12850
12851        if (extraSpace == 0) {
12852            return drawableState;
12853        }
12854
12855        final int[] fullState;
12856        if (drawableState != null) {
12857            fullState = new int[drawableState.length + extraSpace];
12858            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
12859        } else {
12860            fullState = new int[extraSpace];
12861        }
12862
12863        return fullState;
12864    }
12865
12866    /**
12867     * Merge your own state values in <var>additionalState</var> into the base
12868     * state values <var>baseState</var> that were returned by
12869     * {@link #onCreateDrawableState(int)}.
12870     *
12871     * @param baseState The base state values returned by
12872     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
12873     * own additional state values.
12874     *
12875     * @param additionalState The additional state values you would like
12876     * added to <var>baseState</var>; this array is not modified.
12877     *
12878     * @return As a convenience, the <var>baseState</var> array you originally
12879     * passed into the function is returned.
12880     *
12881     * @see #onCreateDrawableState(int)
12882     */
12883    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
12884        final int N = baseState.length;
12885        int i = N - 1;
12886        while (i >= 0 && baseState[i] == 0) {
12887            i--;
12888        }
12889        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
12890        return baseState;
12891    }
12892
12893    /**
12894     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
12895     * on all Drawable objects associated with this view.
12896     */
12897    public void jumpDrawablesToCurrentState() {
12898        if (mBackground != null) {
12899            mBackground.jumpToCurrentState();
12900        }
12901    }
12902
12903    /**
12904     * Sets the background color for this view.
12905     * @param color the color of the background
12906     */
12907    @RemotableViewMethod
12908    public void setBackgroundColor(int color) {
12909        if (mBackground instanceof ColorDrawable) {
12910            ((ColorDrawable) mBackground).setColor(color);
12911        } else {
12912            setBackground(new ColorDrawable(color));
12913        }
12914    }
12915
12916    /**
12917     * Set the background to a given resource. The resource should refer to
12918     * a Drawable object or 0 to remove the background.
12919     * @param resid The identifier of the resource.
12920     *
12921     * @attr ref android.R.styleable#View_background
12922     */
12923    @RemotableViewMethod
12924    public void setBackgroundResource(int resid) {
12925        if (resid != 0 && resid == mBackgroundResource) {
12926            return;
12927        }
12928
12929        Drawable d= null;
12930        if (resid != 0) {
12931            d = mResources.getDrawable(resid);
12932        }
12933        setBackground(d);
12934
12935        mBackgroundResource = resid;
12936    }
12937
12938    /**
12939     * Set the background to a given Drawable, or remove the background. If the
12940     * background has padding, this View's padding is set to the background's
12941     * padding. However, when a background is removed, this View's padding isn't
12942     * touched. If setting the padding is desired, please use
12943     * {@link #setPadding(int, int, int, int)}.
12944     *
12945     * @param background The Drawable to use as the background, or null to remove the
12946     *        background
12947     */
12948    public void setBackground(Drawable background) {
12949        setBackgroundDrawable(background);
12950    }
12951
12952    /**
12953     * @deprecated use {@link #setBackground(Drawable)} instead
12954     */
12955    @Deprecated
12956    public void setBackgroundDrawable(Drawable background) {
12957        if (background == mBackground) {
12958            return;
12959        }
12960
12961        boolean requestLayout = false;
12962
12963        mBackgroundResource = 0;
12964
12965        /*
12966         * Regardless of whether we're setting a new background or not, we want
12967         * to clear the previous drawable.
12968         */
12969        if (mBackground != null) {
12970            mBackground.setCallback(null);
12971            unscheduleDrawable(mBackground);
12972        }
12973
12974        if (background != null) {
12975            Rect padding = sThreadLocal.get();
12976            if (padding == null) {
12977                padding = new Rect();
12978                sThreadLocal.set(padding);
12979            }
12980            if (background.getPadding(padding)) {
12981                switch (background.getResolvedLayoutDirectionSelf()) {
12982                    case LAYOUT_DIRECTION_RTL:
12983                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
12984                        break;
12985                    case LAYOUT_DIRECTION_LTR:
12986                    default:
12987                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
12988                }
12989            }
12990
12991            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
12992            // if it has a different minimum size, we should layout again
12993            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
12994                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
12995                requestLayout = true;
12996            }
12997
12998            background.setCallback(this);
12999            if (background.isStateful()) {
13000                background.setState(getDrawableState());
13001            }
13002            background.setVisible(getVisibility() == VISIBLE, false);
13003            mBackground = background;
13004
13005            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13006                mPrivateFlags &= ~SKIP_DRAW;
13007                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13008                requestLayout = true;
13009            }
13010        } else {
13011            /* Remove the background */
13012            mBackground = null;
13013
13014            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
13015                /*
13016                 * This view ONLY drew the background before and we're removing
13017                 * the background, so now it won't draw anything
13018                 * (hence we SKIP_DRAW)
13019                 */
13020                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
13021                mPrivateFlags |= SKIP_DRAW;
13022            }
13023
13024            /*
13025             * When the background is set, we try to apply its padding to this
13026             * View. When the background is removed, we don't touch this View's
13027             * padding. This is noted in the Javadocs. Hence, we don't need to
13028             * requestLayout(), the invalidate() below is sufficient.
13029             */
13030
13031            // The old background's minimum size could have affected this
13032            // View's layout, so let's requestLayout
13033            requestLayout = true;
13034        }
13035
13036        computeOpaqueFlags();
13037
13038        if (requestLayout) {
13039            requestLayout();
13040        }
13041
13042        mBackgroundSizeChanged = true;
13043        invalidate(true);
13044    }
13045
13046    /**
13047     * Gets the background drawable
13048     *
13049     * @return The drawable used as the background for this view, if any.
13050     *
13051     * @see #setBackground(Drawable)
13052     *
13053     * @attr ref android.R.styleable#View_background
13054     */
13055    public Drawable getBackground() {
13056        return mBackground;
13057    }
13058
13059    /**
13060     * Sets the padding. The view may add on the space required to display
13061     * the scrollbars, depending on the style and visibility of the scrollbars.
13062     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
13063     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
13064     * from the values set in this call.
13065     *
13066     * @attr ref android.R.styleable#View_padding
13067     * @attr ref android.R.styleable#View_paddingBottom
13068     * @attr ref android.R.styleable#View_paddingLeft
13069     * @attr ref android.R.styleable#View_paddingRight
13070     * @attr ref android.R.styleable#View_paddingTop
13071     * @param left the left padding in pixels
13072     * @param top the top padding in pixels
13073     * @param right the right padding in pixels
13074     * @param bottom the bottom padding in pixels
13075     */
13076    public void setPadding(int left, int top, int right, int bottom) {
13077        mUserPaddingStart = -1;
13078        mUserPaddingEnd = -1;
13079        mUserPaddingRelative = false;
13080
13081        internalSetPadding(left, top, right, bottom);
13082    }
13083
13084    private void internalSetPadding(int left, int top, int right, int bottom) {
13085        mUserPaddingLeft = left;
13086        mUserPaddingRight = right;
13087        mUserPaddingBottom = bottom;
13088
13089        final int viewFlags = mViewFlags;
13090        boolean changed = false;
13091
13092        // Common case is there are no scroll bars.
13093        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
13094            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
13095                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
13096                        ? 0 : getVerticalScrollbarWidth();
13097                switch (mVerticalScrollbarPosition) {
13098                    case SCROLLBAR_POSITION_DEFAULT:
13099                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13100                            left += offset;
13101                        } else {
13102                            right += offset;
13103                        }
13104                        break;
13105                    case SCROLLBAR_POSITION_RIGHT:
13106                        right += offset;
13107                        break;
13108                    case SCROLLBAR_POSITION_LEFT:
13109                        left += offset;
13110                        break;
13111                }
13112            }
13113            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
13114                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
13115                        ? 0 : getHorizontalScrollbarHeight();
13116            }
13117        }
13118
13119        if (mPaddingLeft != left) {
13120            changed = true;
13121            mPaddingLeft = left;
13122        }
13123        if (mPaddingTop != top) {
13124            changed = true;
13125            mPaddingTop = top;
13126        }
13127        if (mPaddingRight != right) {
13128            changed = true;
13129            mPaddingRight = right;
13130        }
13131        if (mPaddingBottom != bottom) {
13132            changed = true;
13133            mPaddingBottom = bottom;
13134        }
13135
13136        if (changed) {
13137            requestLayout();
13138        }
13139    }
13140
13141    /**
13142     * Sets the relative padding. The view may add on the space required to display
13143     * the scrollbars, depending on the style and visibility of the scrollbars.
13144     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
13145     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
13146     * from the values set in this call.
13147     *
13148     * @attr ref android.R.styleable#View_padding
13149     * @attr ref android.R.styleable#View_paddingBottom
13150     * @attr ref android.R.styleable#View_paddingStart
13151     * @attr ref android.R.styleable#View_paddingEnd
13152     * @attr ref android.R.styleable#View_paddingTop
13153     * @param start the start padding in pixels
13154     * @param top the top padding in pixels
13155     * @param end the end padding in pixels
13156     * @param bottom the bottom padding in pixels
13157     */
13158    public void setPaddingRelative(int start, int top, int end, int bottom) {
13159        mUserPaddingStart = start;
13160        mUserPaddingEnd = end;
13161        mUserPaddingRelative = true;
13162
13163        switch(getResolvedLayoutDirection()) {
13164            case LAYOUT_DIRECTION_RTL:
13165                internalSetPadding(end, top, start, bottom);
13166                break;
13167            case LAYOUT_DIRECTION_LTR:
13168            default:
13169                internalSetPadding(start, top, end, bottom);
13170        }
13171    }
13172
13173    /**
13174     * Returns the top padding of this view.
13175     *
13176     * @return the top padding in pixels
13177     */
13178    public int getPaddingTop() {
13179        return mPaddingTop;
13180    }
13181
13182    /**
13183     * Returns the bottom padding of this view. If there are inset and enabled
13184     * scrollbars, this value may include the space required to display the
13185     * scrollbars as well.
13186     *
13187     * @return the bottom padding in pixels
13188     */
13189    public int getPaddingBottom() {
13190        return mPaddingBottom;
13191    }
13192
13193    /**
13194     * Returns the left padding of this view. If there are inset and enabled
13195     * scrollbars, this value may include the space required to display the
13196     * scrollbars as well.
13197     *
13198     * @return the left padding in pixels
13199     */
13200    public int getPaddingLeft() {
13201        return mPaddingLeft;
13202    }
13203
13204    /**
13205     * Returns the start padding of this view depending on its resolved layout direction.
13206     * If there are inset and enabled scrollbars, this value may include the space
13207     * required to display the scrollbars as well.
13208     *
13209     * @return the start padding in pixels
13210     */
13211    public int getPaddingStart() {
13212        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13213                mPaddingRight : mPaddingLeft;
13214    }
13215
13216    /**
13217     * Returns the right padding of this view. If there are inset and enabled
13218     * scrollbars, this value may include the space required to display the
13219     * scrollbars as well.
13220     *
13221     * @return the right padding in pixels
13222     */
13223    public int getPaddingRight() {
13224        return mPaddingRight;
13225    }
13226
13227    /**
13228     * Returns the end padding of this view depending on its resolved layout direction.
13229     * If there are inset and enabled scrollbars, this value may include the space
13230     * required to display the scrollbars as well.
13231     *
13232     * @return the end padding in pixels
13233     */
13234    public int getPaddingEnd() {
13235        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13236                mPaddingLeft : mPaddingRight;
13237    }
13238
13239    /**
13240     * Return if the padding as been set thru relative values
13241     * {@link #setPaddingRelative(int, int, int, int)} or thru
13242     * @attr ref android.R.styleable#View_paddingStart or
13243     * @attr ref android.R.styleable#View_paddingEnd
13244     *
13245     * @return true if the padding is relative or false if it is not.
13246     */
13247    public boolean isPaddingRelative() {
13248        return mUserPaddingRelative;
13249    }
13250
13251    /**
13252     * Changes the selection state of this view. A view can be selected or not.
13253     * Note that selection is not the same as focus. Views are typically
13254     * selected in the context of an AdapterView like ListView or GridView;
13255     * the selected view is the view that is highlighted.
13256     *
13257     * @param selected true if the view must be selected, false otherwise
13258     */
13259    public void setSelected(boolean selected) {
13260        if (((mPrivateFlags & SELECTED) != 0) != selected) {
13261            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
13262            if (!selected) resetPressedState();
13263            invalidate(true);
13264            refreshDrawableState();
13265            dispatchSetSelected(selected);
13266        }
13267    }
13268
13269    /**
13270     * Dispatch setSelected to all of this View's children.
13271     *
13272     * @see #setSelected(boolean)
13273     *
13274     * @param selected The new selected state
13275     */
13276    protected void dispatchSetSelected(boolean selected) {
13277    }
13278
13279    /**
13280     * Indicates the selection state of this view.
13281     *
13282     * @return true if the view is selected, false otherwise
13283     */
13284    @ViewDebug.ExportedProperty
13285    public boolean isSelected() {
13286        return (mPrivateFlags & SELECTED) != 0;
13287    }
13288
13289    /**
13290     * Changes the activated state of this view. A view can be activated or not.
13291     * Note that activation is not the same as selection.  Selection is
13292     * a transient property, representing the view (hierarchy) the user is
13293     * currently interacting with.  Activation is a longer-term state that the
13294     * user can move views in and out of.  For example, in a list view with
13295     * single or multiple selection enabled, the views in the current selection
13296     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
13297     * here.)  The activated state is propagated down to children of the view it
13298     * is set on.
13299     *
13300     * @param activated true if the view must be activated, false otherwise
13301     */
13302    public void setActivated(boolean activated) {
13303        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
13304            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
13305            invalidate(true);
13306            refreshDrawableState();
13307            dispatchSetActivated(activated);
13308        }
13309    }
13310
13311    /**
13312     * Dispatch setActivated to all of this View's children.
13313     *
13314     * @see #setActivated(boolean)
13315     *
13316     * @param activated The new activated state
13317     */
13318    protected void dispatchSetActivated(boolean activated) {
13319    }
13320
13321    /**
13322     * Indicates the activation state of this view.
13323     *
13324     * @return true if the view is activated, false otherwise
13325     */
13326    @ViewDebug.ExportedProperty
13327    public boolean isActivated() {
13328        return (mPrivateFlags & ACTIVATED) != 0;
13329    }
13330
13331    /**
13332     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
13333     * observer can be used to get notifications when global events, like
13334     * layout, happen.
13335     *
13336     * The returned ViewTreeObserver observer is not guaranteed to remain
13337     * valid for the lifetime of this View. If the caller of this method keeps
13338     * a long-lived reference to ViewTreeObserver, it should always check for
13339     * the return value of {@link ViewTreeObserver#isAlive()}.
13340     *
13341     * @return The ViewTreeObserver for this view's hierarchy.
13342     */
13343    public ViewTreeObserver getViewTreeObserver() {
13344        if (mAttachInfo != null) {
13345            return mAttachInfo.mTreeObserver;
13346        }
13347        if (mFloatingTreeObserver == null) {
13348            mFloatingTreeObserver = new ViewTreeObserver();
13349        }
13350        return mFloatingTreeObserver;
13351    }
13352
13353    /**
13354     * <p>Finds the topmost view in the current view hierarchy.</p>
13355     *
13356     * @return the topmost view containing this view
13357     */
13358    public View getRootView() {
13359        if (mAttachInfo != null) {
13360            final View v = mAttachInfo.mRootView;
13361            if (v != null) {
13362                return v;
13363            }
13364        }
13365
13366        View parent = this;
13367
13368        while (parent.mParent != null && parent.mParent instanceof View) {
13369            parent = (View) parent.mParent;
13370        }
13371
13372        return parent;
13373    }
13374
13375    /**
13376     * <p>Computes the coordinates of this view on the screen. The argument
13377     * must be an array of two integers. After the method returns, the array
13378     * contains the x and y location in that order.</p>
13379     *
13380     * @param location an array of two integers in which to hold the coordinates
13381     */
13382    public void getLocationOnScreen(int[] location) {
13383        getLocationInWindow(location);
13384
13385        final AttachInfo info = mAttachInfo;
13386        if (info != null) {
13387            location[0] += info.mWindowLeft;
13388            location[1] += info.mWindowTop;
13389        }
13390    }
13391
13392    /**
13393     * <p>Computes the coordinates of this view in its window. The argument
13394     * must be an array of two integers. After the method returns, the array
13395     * contains the x and y location in that order.</p>
13396     *
13397     * @param location an array of two integers in which to hold the coordinates
13398     */
13399    public void getLocationInWindow(int[] location) {
13400        if (location == null || location.length < 2) {
13401            throw new IllegalArgumentException("location must be an array of two integers");
13402        }
13403
13404        if (mAttachInfo == null) {
13405            // When the view is not attached to a window, this method does not make sense
13406            location[0] = location[1] = 0;
13407            return;
13408        }
13409
13410        float[] position = mAttachInfo.mTmpTransformLocation;
13411        position[0] = position[1] = 0.0f;
13412
13413        if (!hasIdentityMatrix()) {
13414            getMatrix().mapPoints(position);
13415        }
13416
13417        position[0] += mLeft;
13418        position[1] += mTop;
13419
13420        ViewParent viewParent = mParent;
13421        while (viewParent instanceof View) {
13422            final View view = (View) viewParent;
13423
13424            position[0] -= view.mScrollX;
13425            position[1] -= view.mScrollY;
13426
13427            if (!view.hasIdentityMatrix()) {
13428                view.getMatrix().mapPoints(position);
13429            }
13430
13431            position[0] += view.mLeft;
13432            position[1] += view.mTop;
13433
13434            viewParent = view.mParent;
13435        }
13436
13437        if (viewParent instanceof ViewRootImpl) {
13438            // *cough*
13439            final ViewRootImpl vr = (ViewRootImpl) viewParent;
13440            position[1] -= vr.mCurScrollY;
13441        }
13442
13443        location[0] = (int) (position[0] + 0.5f);
13444        location[1] = (int) (position[1] + 0.5f);
13445    }
13446
13447    /**
13448     * {@hide}
13449     * @param id the id of the view to be found
13450     * @return the view of the specified id, null if cannot be found
13451     */
13452    protected View findViewTraversal(int id) {
13453        if (id == mID) {
13454            return this;
13455        }
13456        return null;
13457    }
13458
13459    /**
13460     * {@hide}
13461     * @param tag the tag of the view to be found
13462     * @return the view of specified tag, null if cannot be found
13463     */
13464    protected View findViewWithTagTraversal(Object tag) {
13465        if (tag != null && tag.equals(mTag)) {
13466            return this;
13467        }
13468        return null;
13469    }
13470
13471    /**
13472     * {@hide}
13473     * @param predicate The predicate to evaluate.
13474     * @param childToSkip If not null, ignores this child during the recursive traversal.
13475     * @return The first view that matches the predicate or null.
13476     */
13477    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
13478        if (predicate.apply(this)) {
13479            return this;
13480        }
13481        return null;
13482    }
13483
13484    /**
13485     * Look for a child view with the given id.  If this view has the given
13486     * id, return this view.
13487     *
13488     * @param id The id to search for.
13489     * @return The view that has the given id in the hierarchy or null
13490     */
13491    public final View findViewById(int id) {
13492        if (id < 0) {
13493            return null;
13494        }
13495        return findViewTraversal(id);
13496    }
13497
13498    /**
13499     * Finds a view by its unuque and stable accessibility id.
13500     *
13501     * @param accessibilityId The searched accessibility id.
13502     * @return The found view.
13503     */
13504    final View findViewByAccessibilityId(int accessibilityId) {
13505        if (accessibilityId < 0) {
13506            return null;
13507        }
13508        return findViewByAccessibilityIdTraversal(accessibilityId);
13509    }
13510
13511    /**
13512     * Performs the traversal to find a view by its unuque and stable accessibility id.
13513     *
13514     * <strong>Note:</strong>This method does not stop at the root namespace
13515     * boundary since the user can touch the screen at an arbitrary location
13516     * potentially crossing the root namespace bounday which will send an
13517     * accessibility event to accessibility services and they should be able
13518     * to obtain the event source. Also accessibility ids are guaranteed to be
13519     * unique in the window.
13520     *
13521     * @param accessibilityId The accessibility id.
13522     * @return The found view.
13523     */
13524    View findViewByAccessibilityIdTraversal(int accessibilityId) {
13525        if (getAccessibilityViewId() == accessibilityId) {
13526            return this;
13527        }
13528        return null;
13529    }
13530
13531    /**
13532     * Look for a child view with the given tag.  If this view has the given
13533     * tag, return this view.
13534     *
13535     * @param tag The tag to search for, using "tag.equals(getTag())".
13536     * @return The View that has the given tag in the hierarchy or null
13537     */
13538    public final View findViewWithTag(Object tag) {
13539        if (tag == null) {
13540            return null;
13541        }
13542        return findViewWithTagTraversal(tag);
13543    }
13544
13545    /**
13546     * {@hide}
13547     * Look for a child view that matches the specified predicate.
13548     * If this view matches the predicate, return this view.
13549     *
13550     * @param predicate The predicate to evaluate.
13551     * @return The first view that matches the predicate or null.
13552     */
13553    public final View findViewByPredicate(Predicate<View> predicate) {
13554        return findViewByPredicateTraversal(predicate, null);
13555    }
13556
13557    /**
13558     * {@hide}
13559     * Look for a child view that matches the specified predicate,
13560     * starting with the specified view and its descendents and then
13561     * recusively searching the ancestors and siblings of that view
13562     * until this view is reached.
13563     *
13564     * This method is useful in cases where the predicate does not match
13565     * a single unique view (perhaps multiple views use the same id)
13566     * and we are trying to find the view that is "closest" in scope to the
13567     * starting view.
13568     *
13569     * @param start The view to start from.
13570     * @param predicate The predicate to evaluate.
13571     * @return The first view that matches the predicate or null.
13572     */
13573    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
13574        View childToSkip = null;
13575        for (;;) {
13576            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
13577            if (view != null || start == this) {
13578                return view;
13579            }
13580
13581            ViewParent parent = start.getParent();
13582            if (parent == null || !(parent instanceof View)) {
13583                return null;
13584            }
13585
13586            childToSkip = start;
13587            start = (View) parent;
13588        }
13589    }
13590
13591    /**
13592     * Sets the identifier for this view. The identifier does not have to be
13593     * unique in this view's hierarchy. The identifier should be a positive
13594     * number.
13595     *
13596     * @see #NO_ID
13597     * @see #getId()
13598     * @see #findViewById(int)
13599     *
13600     * @param id a number used to identify the view
13601     *
13602     * @attr ref android.R.styleable#View_id
13603     */
13604    public void setId(int id) {
13605        mID = id;
13606    }
13607
13608    /**
13609     * {@hide}
13610     *
13611     * @param isRoot true if the view belongs to the root namespace, false
13612     *        otherwise
13613     */
13614    public void setIsRootNamespace(boolean isRoot) {
13615        if (isRoot) {
13616            mPrivateFlags |= IS_ROOT_NAMESPACE;
13617        } else {
13618            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
13619        }
13620    }
13621
13622    /**
13623     * {@hide}
13624     *
13625     * @return true if the view belongs to the root namespace, false otherwise
13626     */
13627    public boolean isRootNamespace() {
13628        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
13629    }
13630
13631    /**
13632     * Returns this view's identifier.
13633     *
13634     * @return a positive integer used to identify the view or {@link #NO_ID}
13635     *         if the view has no ID
13636     *
13637     * @see #setId(int)
13638     * @see #findViewById(int)
13639     * @attr ref android.R.styleable#View_id
13640     */
13641    @ViewDebug.CapturedViewProperty
13642    public int getId() {
13643        return mID;
13644    }
13645
13646    /**
13647     * Returns this view's tag.
13648     *
13649     * @return the Object stored in this view as a tag
13650     *
13651     * @see #setTag(Object)
13652     * @see #getTag(int)
13653     */
13654    @ViewDebug.ExportedProperty
13655    public Object getTag() {
13656        return mTag;
13657    }
13658
13659    /**
13660     * Sets the tag associated with this view. A tag can be used to mark
13661     * a view in its hierarchy and does not have to be unique within the
13662     * hierarchy. Tags can also be used to store data within a view without
13663     * resorting to another data structure.
13664     *
13665     * @param tag an Object to tag the view with
13666     *
13667     * @see #getTag()
13668     * @see #setTag(int, Object)
13669     */
13670    public void setTag(final Object tag) {
13671        mTag = tag;
13672    }
13673
13674    /**
13675     * Returns the tag associated with this view and the specified key.
13676     *
13677     * @param key The key identifying the tag
13678     *
13679     * @return the Object stored in this view as a tag
13680     *
13681     * @see #setTag(int, Object)
13682     * @see #getTag()
13683     */
13684    public Object getTag(int key) {
13685        if (mKeyedTags != null) return mKeyedTags.get(key);
13686        return null;
13687    }
13688
13689    /**
13690     * Sets a tag associated with this view and a key. A tag can be used
13691     * to mark a view in its hierarchy and does not have to be unique within
13692     * the hierarchy. Tags can also be used to store data within a view
13693     * without resorting to another data structure.
13694     *
13695     * The specified key should be an id declared in the resources of the
13696     * application to ensure it is unique (see the <a
13697     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
13698     * Keys identified as belonging to
13699     * the Android framework or not associated with any package will cause
13700     * an {@link IllegalArgumentException} to be thrown.
13701     *
13702     * @param key The key identifying the tag
13703     * @param tag An Object to tag the view with
13704     *
13705     * @throws IllegalArgumentException If they specified key is not valid
13706     *
13707     * @see #setTag(Object)
13708     * @see #getTag(int)
13709     */
13710    public void setTag(int key, final Object tag) {
13711        // If the package id is 0x00 or 0x01, it's either an undefined package
13712        // or a framework id
13713        if ((key >>> 24) < 2) {
13714            throw new IllegalArgumentException("The key must be an application-specific "
13715                    + "resource id.");
13716        }
13717
13718        setKeyedTag(key, tag);
13719    }
13720
13721    /**
13722     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
13723     * framework id.
13724     *
13725     * @hide
13726     */
13727    public void setTagInternal(int key, Object tag) {
13728        if ((key >>> 24) != 0x1) {
13729            throw new IllegalArgumentException("The key must be a framework-specific "
13730                    + "resource id.");
13731        }
13732
13733        setKeyedTag(key, tag);
13734    }
13735
13736    private void setKeyedTag(int key, Object tag) {
13737        if (mKeyedTags == null) {
13738            mKeyedTags = new SparseArray<Object>();
13739        }
13740
13741        mKeyedTags.put(key, tag);
13742    }
13743
13744    /**
13745     * @param consistency The type of consistency. See ViewDebug for more information.
13746     *
13747     * @hide
13748     */
13749    protected boolean dispatchConsistencyCheck(int consistency) {
13750        return onConsistencyCheck(consistency);
13751    }
13752
13753    /**
13754     * Method that subclasses should implement to check their consistency. The type of
13755     * consistency check is indicated by the bit field passed as a parameter.
13756     *
13757     * @param consistency The type of consistency. See ViewDebug for more information.
13758     *
13759     * @throws IllegalStateException if the view is in an inconsistent state.
13760     *
13761     * @hide
13762     */
13763    protected boolean onConsistencyCheck(int consistency) {
13764        boolean result = true;
13765
13766        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
13767        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
13768
13769        if (checkLayout) {
13770            if (getParent() == null) {
13771                result = false;
13772                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13773                        "View " + this + " does not have a parent.");
13774            }
13775
13776            if (mAttachInfo == null) {
13777                result = false;
13778                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13779                        "View " + this + " is not attached to a window.");
13780            }
13781        }
13782
13783        if (checkDrawing) {
13784            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
13785            // from their draw() method
13786
13787            if ((mPrivateFlags & DRAWN) != DRAWN &&
13788                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
13789                result = false;
13790                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13791                        "View " + this + " was invalidated but its drawing cache is valid.");
13792            }
13793        }
13794
13795        return result;
13796    }
13797
13798    /**
13799     * Prints information about this view in the log output, with the tag
13800     * {@link #VIEW_LOG_TAG}.
13801     *
13802     * @hide
13803     */
13804    public void debug() {
13805        debug(0);
13806    }
13807
13808    /**
13809     * Prints information about this view in the log output, with the tag
13810     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
13811     * indentation defined by the <code>depth</code>.
13812     *
13813     * @param depth the indentation level
13814     *
13815     * @hide
13816     */
13817    protected void debug(int depth) {
13818        String output = debugIndent(depth - 1);
13819
13820        output += "+ " + this;
13821        int id = getId();
13822        if (id != -1) {
13823            output += " (id=" + id + ")";
13824        }
13825        Object tag = getTag();
13826        if (tag != null) {
13827            output += " (tag=" + tag + ")";
13828        }
13829        Log.d(VIEW_LOG_TAG, output);
13830
13831        if ((mPrivateFlags & FOCUSED) != 0) {
13832            output = debugIndent(depth) + " FOCUSED";
13833            Log.d(VIEW_LOG_TAG, output);
13834        }
13835
13836        output = debugIndent(depth);
13837        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
13838                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
13839                + "} ";
13840        Log.d(VIEW_LOG_TAG, output);
13841
13842        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
13843                || mPaddingBottom != 0) {
13844            output = debugIndent(depth);
13845            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
13846                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
13847            Log.d(VIEW_LOG_TAG, output);
13848        }
13849
13850        output = debugIndent(depth);
13851        output += "mMeasureWidth=" + mMeasuredWidth +
13852                " mMeasureHeight=" + mMeasuredHeight;
13853        Log.d(VIEW_LOG_TAG, output);
13854
13855        output = debugIndent(depth);
13856        if (mLayoutParams == null) {
13857            output += "BAD! no layout params";
13858        } else {
13859            output = mLayoutParams.debug(output);
13860        }
13861        Log.d(VIEW_LOG_TAG, output);
13862
13863        output = debugIndent(depth);
13864        output += "flags={";
13865        output += View.printFlags(mViewFlags);
13866        output += "}";
13867        Log.d(VIEW_LOG_TAG, output);
13868
13869        output = debugIndent(depth);
13870        output += "privateFlags={";
13871        output += View.printPrivateFlags(mPrivateFlags);
13872        output += "}";
13873        Log.d(VIEW_LOG_TAG, output);
13874    }
13875
13876    /**
13877     * Creates a string of whitespaces used for indentation.
13878     *
13879     * @param depth the indentation level
13880     * @return a String containing (depth * 2 + 3) * 2 white spaces
13881     *
13882     * @hide
13883     */
13884    protected static String debugIndent(int depth) {
13885        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
13886        for (int i = 0; i < (depth * 2) + 3; i++) {
13887            spaces.append(' ').append(' ');
13888        }
13889        return spaces.toString();
13890    }
13891
13892    /**
13893     * <p>Return the offset of the widget's text baseline from the widget's top
13894     * boundary. If this widget does not support baseline alignment, this
13895     * method returns -1. </p>
13896     *
13897     * @return the offset of the baseline within the widget's bounds or -1
13898     *         if baseline alignment is not supported
13899     */
13900    @ViewDebug.ExportedProperty(category = "layout")
13901    public int getBaseline() {
13902        return -1;
13903    }
13904
13905    /**
13906     * Call this when something has changed which has invalidated the
13907     * layout of this view. This will schedule a layout pass of the view
13908     * tree.
13909     */
13910    public void requestLayout() {
13911        if (ViewDebug.TRACE_HIERARCHY) {
13912            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
13913        }
13914
13915        mPrivateFlags |= FORCE_LAYOUT;
13916        mPrivateFlags |= INVALIDATED;
13917
13918        if (mLayoutParams != null) {
13919            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
13920        }
13921
13922        if (mParent != null && !mParent.isLayoutRequested()) {
13923            mParent.requestLayout();
13924        }
13925    }
13926
13927    /**
13928     * Forces this view to be laid out during the next layout pass.
13929     * This method does not call requestLayout() or forceLayout()
13930     * on the parent.
13931     */
13932    public void forceLayout() {
13933        mPrivateFlags |= FORCE_LAYOUT;
13934        mPrivateFlags |= INVALIDATED;
13935    }
13936
13937    /**
13938     * <p>
13939     * This is called to find out how big a view should be. The parent
13940     * supplies constraint information in the width and height parameters.
13941     * </p>
13942     *
13943     * <p>
13944     * The actual measurement work of a view is performed in
13945     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
13946     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
13947     * </p>
13948     *
13949     *
13950     * @param widthMeasureSpec Horizontal space requirements as imposed by the
13951     *        parent
13952     * @param heightMeasureSpec Vertical space requirements as imposed by the
13953     *        parent
13954     *
13955     * @see #onMeasure(int, int)
13956     */
13957    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
13958        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
13959                widthMeasureSpec != mOldWidthMeasureSpec ||
13960                heightMeasureSpec != mOldHeightMeasureSpec) {
13961
13962            // first clears the measured dimension flag
13963            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
13964
13965            if (ViewDebug.TRACE_HIERARCHY) {
13966                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
13967            }
13968
13969            // measure ourselves, this should set the measured dimension flag back
13970            onMeasure(widthMeasureSpec, heightMeasureSpec);
13971
13972            // flag not set, setMeasuredDimension() was not invoked, we raise
13973            // an exception to warn the developer
13974            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
13975                throw new IllegalStateException("onMeasure() did not set the"
13976                        + " measured dimension by calling"
13977                        + " setMeasuredDimension()");
13978            }
13979
13980            mPrivateFlags |= LAYOUT_REQUIRED;
13981        }
13982
13983        mOldWidthMeasureSpec = widthMeasureSpec;
13984        mOldHeightMeasureSpec = heightMeasureSpec;
13985    }
13986
13987    /**
13988     * <p>
13989     * Measure the view and its content to determine the measured width and the
13990     * measured height. This method is invoked by {@link #measure(int, int)} and
13991     * should be overriden by subclasses to provide accurate and efficient
13992     * measurement of their contents.
13993     * </p>
13994     *
13995     * <p>
13996     * <strong>CONTRACT:</strong> When overriding this method, you
13997     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
13998     * measured width and height of this view. Failure to do so will trigger an
13999     * <code>IllegalStateException</code>, thrown by
14000     * {@link #measure(int, int)}. Calling the superclass'
14001     * {@link #onMeasure(int, int)} is a valid use.
14002     * </p>
14003     *
14004     * <p>
14005     * The base class implementation of measure defaults to the background size,
14006     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14007     * override {@link #onMeasure(int, int)} to provide better measurements of
14008     * their content.
14009     * </p>
14010     *
14011     * <p>
14012     * If this method is overridden, it is the subclass's responsibility to make
14013     * sure the measured height and width are at least the view's minimum height
14014     * and width ({@link #getSuggestedMinimumHeight()} and
14015     * {@link #getSuggestedMinimumWidth()}).
14016     * </p>
14017     *
14018     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14019     *                         The requirements are encoded with
14020     *                         {@link android.view.View.MeasureSpec}.
14021     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14022     *                         The requirements are encoded with
14023     *                         {@link android.view.View.MeasureSpec}.
14024     *
14025     * @see #getMeasuredWidth()
14026     * @see #getMeasuredHeight()
14027     * @see #setMeasuredDimension(int, int)
14028     * @see #getSuggestedMinimumHeight()
14029     * @see #getSuggestedMinimumWidth()
14030     * @see android.view.View.MeasureSpec#getMode(int)
14031     * @see android.view.View.MeasureSpec#getSize(int)
14032     */
14033    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14034        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14035                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14036    }
14037
14038    /**
14039     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14040     * measured width and measured height. Failing to do so will trigger an
14041     * exception at measurement time.</p>
14042     *
14043     * @param measuredWidth The measured width of this view.  May be a complex
14044     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14045     * {@link #MEASURED_STATE_TOO_SMALL}.
14046     * @param measuredHeight The measured height of this view.  May be a complex
14047     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14048     * {@link #MEASURED_STATE_TOO_SMALL}.
14049     */
14050    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14051        mMeasuredWidth = measuredWidth;
14052        mMeasuredHeight = measuredHeight;
14053
14054        mPrivateFlags |= MEASURED_DIMENSION_SET;
14055    }
14056
14057    /**
14058     * Merge two states as returned by {@link #getMeasuredState()}.
14059     * @param curState The current state as returned from a view or the result
14060     * of combining multiple views.
14061     * @param newState The new view state to combine.
14062     * @return Returns a new integer reflecting the combination of the two
14063     * states.
14064     */
14065    public static int combineMeasuredStates(int curState, int newState) {
14066        return curState | newState;
14067    }
14068
14069    /**
14070     * Version of {@link #resolveSizeAndState(int, int, int)}
14071     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
14072     */
14073    public static int resolveSize(int size, int measureSpec) {
14074        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
14075    }
14076
14077    /**
14078     * Utility to reconcile a desired size and state, with constraints imposed
14079     * by a MeasureSpec.  Will take the desired size, unless a different size
14080     * is imposed by the constraints.  The returned value is a compound integer,
14081     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
14082     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
14083     * size is smaller than the size the view wants to be.
14084     *
14085     * @param size How big the view wants to be
14086     * @param measureSpec Constraints imposed by the parent
14087     * @return Size information bit mask as defined by
14088     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14089     */
14090    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
14091        int result = size;
14092        int specMode = MeasureSpec.getMode(measureSpec);
14093        int specSize =  MeasureSpec.getSize(measureSpec);
14094        switch (specMode) {
14095        case MeasureSpec.UNSPECIFIED:
14096            result = size;
14097            break;
14098        case MeasureSpec.AT_MOST:
14099            if (specSize < size) {
14100                result = specSize | MEASURED_STATE_TOO_SMALL;
14101            } else {
14102                result = size;
14103            }
14104            break;
14105        case MeasureSpec.EXACTLY:
14106            result = specSize;
14107            break;
14108        }
14109        return result | (childMeasuredState&MEASURED_STATE_MASK);
14110    }
14111
14112    /**
14113     * Utility to return a default size. Uses the supplied size if the
14114     * MeasureSpec imposed no constraints. Will get larger if allowed
14115     * by the MeasureSpec.
14116     *
14117     * @param size Default size for this view
14118     * @param measureSpec Constraints imposed by the parent
14119     * @return The size this view should be.
14120     */
14121    public static int getDefaultSize(int size, int measureSpec) {
14122        int result = size;
14123        int specMode = MeasureSpec.getMode(measureSpec);
14124        int specSize = MeasureSpec.getSize(measureSpec);
14125
14126        switch (specMode) {
14127        case MeasureSpec.UNSPECIFIED:
14128            result = size;
14129            break;
14130        case MeasureSpec.AT_MOST:
14131        case MeasureSpec.EXACTLY:
14132            result = specSize;
14133            break;
14134        }
14135        return result;
14136    }
14137
14138    /**
14139     * Returns the suggested minimum height that the view should use. This
14140     * returns the maximum of the view's minimum height
14141     * and the background's minimum height
14142     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
14143     * <p>
14144     * When being used in {@link #onMeasure(int, int)}, the caller should still
14145     * ensure the returned height is within the requirements of the parent.
14146     *
14147     * @return The suggested minimum height of the view.
14148     */
14149    protected int getSuggestedMinimumHeight() {
14150        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
14151
14152    }
14153
14154    /**
14155     * Returns the suggested minimum width that the view should use. This
14156     * returns the maximum of the view's minimum width)
14157     * and the background's minimum width
14158     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
14159     * <p>
14160     * When being used in {@link #onMeasure(int, int)}, the caller should still
14161     * ensure the returned width is within the requirements of the parent.
14162     *
14163     * @return The suggested minimum width of the view.
14164     */
14165    protected int getSuggestedMinimumWidth() {
14166        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
14167    }
14168
14169    /**
14170     * Returns the minimum height of the view.
14171     *
14172     * @return the minimum height the view will try to be.
14173     *
14174     * @see #setMinimumHeight(int)
14175     *
14176     * @attr ref android.R.styleable#View_minHeight
14177     */
14178    public int getMinimumHeight() {
14179        return mMinHeight;
14180    }
14181
14182    /**
14183     * Sets the minimum height of the view. It is not guaranteed the view will
14184     * be able to achieve this minimum height (for example, if its parent layout
14185     * constrains it with less available height).
14186     *
14187     * @param minHeight The minimum height the view will try to be.
14188     *
14189     * @see #getMinimumHeight()
14190     *
14191     * @attr ref android.R.styleable#View_minHeight
14192     */
14193    public void setMinimumHeight(int minHeight) {
14194        mMinHeight = minHeight;
14195        requestLayout();
14196    }
14197
14198    /**
14199     * Returns the minimum width of the view.
14200     *
14201     * @return the minimum width the view will try to be.
14202     *
14203     * @see #setMinimumWidth(int)
14204     *
14205     * @attr ref android.R.styleable#View_minWidth
14206     */
14207    public int getMinimumWidth() {
14208        return mMinWidth;
14209    }
14210
14211    /**
14212     * Sets the minimum width of the view. It is not guaranteed the view will
14213     * be able to achieve this minimum width (for example, if its parent layout
14214     * constrains it with less available width).
14215     *
14216     * @param minWidth The minimum width the view will try to be.
14217     *
14218     * @see #getMinimumWidth()
14219     *
14220     * @attr ref android.R.styleable#View_minWidth
14221     */
14222    public void setMinimumWidth(int minWidth) {
14223        mMinWidth = minWidth;
14224        requestLayout();
14225
14226    }
14227
14228    /**
14229     * Get the animation currently associated with this view.
14230     *
14231     * @return The animation that is currently playing or
14232     *         scheduled to play for this view.
14233     */
14234    public Animation getAnimation() {
14235        return mCurrentAnimation;
14236    }
14237
14238    /**
14239     * Start the specified animation now.
14240     *
14241     * @param animation the animation to start now
14242     */
14243    public void startAnimation(Animation animation) {
14244        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
14245        setAnimation(animation);
14246        invalidateParentCaches();
14247        invalidate(true);
14248    }
14249
14250    /**
14251     * Cancels any animations for this view.
14252     */
14253    public void clearAnimation() {
14254        if (mCurrentAnimation != null) {
14255            mCurrentAnimation.detach();
14256        }
14257        mCurrentAnimation = null;
14258        invalidateParentIfNeeded();
14259    }
14260
14261    /**
14262     * Sets the next animation to play for this view.
14263     * If you want the animation to play immediately, use
14264     * startAnimation. This method provides allows fine-grained
14265     * control over the start time and invalidation, but you
14266     * must make sure that 1) the animation has a start time set, and
14267     * 2) the view will be invalidated when the animation is supposed to
14268     * start.
14269     *
14270     * @param animation The next animation, or null.
14271     */
14272    public void setAnimation(Animation animation) {
14273        mCurrentAnimation = animation;
14274        if (animation != null) {
14275            animation.reset();
14276        }
14277    }
14278
14279    /**
14280     * Invoked by a parent ViewGroup to notify the start of the animation
14281     * currently associated with this view. If you override this method,
14282     * always call super.onAnimationStart();
14283     *
14284     * @see #setAnimation(android.view.animation.Animation)
14285     * @see #getAnimation()
14286     */
14287    protected void onAnimationStart() {
14288        mPrivateFlags |= ANIMATION_STARTED;
14289    }
14290
14291    /**
14292     * Invoked by a parent ViewGroup to notify the end of the animation
14293     * currently associated with this view. If you override this method,
14294     * always call super.onAnimationEnd();
14295     *
14296     * @see #setAnimation(android.view.animation.Animation)
14297     * @see #getAnimation()
14298     */
14299    protected void onAnimationEnd() {
14300        mPrivateFlags &= ~ANIMATION_STARTED;
14301    }
14302
14303    /**
14304     * Invoked if there is a Transform that involves alpha. Subclass that can
14305     * draw themselves with the specified alpha should return true, and then
14306     * respect that alpha when their onDraw() is called. If this returns false
14307     * then the view may be redirected to draw into an offscreen buffer to
14308     * fulfill the request, which will look fine, but may be slower than if the
14309     * subclass handles it internally. The default implementation returns false.
14310     *
14311     * @param alpha The alpha (0..255) to apply to the view's drawing
14312     * @return true if the view can draw with the specified alpha.
14313     */
14314    protected boolean onSetAlpha(int alpha) {
14315        return false;
14316    }
14317
14318    /**
14319     * This is used by the RootView to perform an optimization when
14320     * the view hierarchy contains one or several SurfaceView.
14321     * SurfaceView is always considered transparent, but its children are not,
14322     * therefore all View objects remove themselves from the global transparent
14323     * region (passed as a parameter to this function).
14324     *
14325     * @param region The transparent region for this ViewAncestor (window).
14326     *
14327     * @return Returns true if the effective visibility of the view at this
14328     * point is opaque, regardless of the transparent region; returns false
14329     * if it is possible for underlying windows to be seen behind the view.
14330     *
14331     * {@hide}
14332     */
14333    public boolean gatherTransparentRegion(Region region) {
14334        final AttachInfo attachInfo = mAttachInfo;
14335        if (region != null && attachInfo != null) {
14336            final int pflags = mPrivateFlags;
14337            if ((pflags & SKIP_DRAW) == 0) {
14338                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
14339                // remove it from the transparent region.
14340                final int[] location = attachInfo.mTransparentLocation;
14341                getLocationInWindow(location);
14342                region.op(location[0], location[1], location[0] + mRight - mLeft,
14343                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
14344            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
14345                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
14346                // exists, so we remove the background drawable's non-transparent
14347                // parts from this transparent region.
14348                applyDrawableToTransparentRegion(mBackground, region);
14349            }
14350        }
14351        return true;
14352    }
14353
14354    /**
14355     * Play a sound effect for this view.
14356     *
14357     * <p>The framework will play sound effects for some built in actions, such as
14358     * clicking, but you may wish to play these effects in your widget,
14359     * for instance, for internal navigation.
14360     *
14361     * <p>The sound effect will only be played if sound effects are enabled by the user, and
14362     * {@link #isSoundEffectsEnabled()} is true.
14363     *
14364     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
14365     */
14366    public void playSoundEffect(int soundConstant) {
14367        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
14368            return;
14369        }
14370        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
14371    }
14372
14373    /**
14374     * BZZZTT!!1!
14375     *
14376     * <p>Provide haptic feedback to the user for this view.
14377     *
14378     * <p>The framework will provide haptic feedback for some built in actions,
14379     * such as long presses, but you may wish to provide feedback for your
14380     * own widget.
14381     *
14382     * <p>The feedback will only be performed if
14383     * {@link #isHapticFeedbackEnabled()} is true.
14384     *
14385     * @param feedbackConstant One of the constants defined in
14386     * {@link HapticFeedbackConstants}
14387     */
14388    public boolean performHapticFeedback(int feedbackConstant) {
14389        return performHapticFeedback(feedbackConstant, 0);
14390    }
14391
14392    /**
14393     * BZZZTT!!1!
14394     *
14395     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
14396     *
14397     * @param feedbackConstant One of the constants defined in
14398     * {@link HapticFeedbackConstants}
14399     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
14400     */
14401    public boolean performHapticFeedback(int feedbackConstant, int flags) {
14402        if (mAttachInfo == null) {
14403            return false;
14404        }
14405        //noinspection SimplifiableIfStatement
14406        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
14407                && !isHapticFeedbackEnabled()) {
14408            return false;
14409        }
14410        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
14411                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
14412    }
14413
14414    /**
14415     * Request that the visibility of the status bar or other screen/window
14416     * decorations be changed.
14417     *
14418     * <p>This method is used to put the over device UI into temporary modes
14419     * where the user's attention is focused more on the application content,
14420     * by dimming or hiding surrounding system affordances.  This is typically
14421     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
14422     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
14423     * to be placed behind the action bar (and with these flags other system
14424     * affordances) so that smooth transitions between hiding and showing them
14425     * can be done.
14426     *
14427     * <p>Two representative examples of the use of system UI visibility is
14428     * implementing a content browsing application (like a magazine reader)
14429     * and a video playing application.
14430     *
14431     * <p>The first code shows a typical implementation of a View in a content
14432     * browsing application.  In this implementation, the application goes
14433     * into a content-oriented mode by hiding the status bar and action bar,
14434     * and putting the navigation elements into lights out mode.  The user can
14435     * then interact with content while in this mode.  Such an application should
14436     * provide an easy way for the user to toggle out of the mode (such as to
14437     * check information in the status bar or access notifications).  In the
14438     * implementation here, this is done simply by tapping on the content.
14439     *
14440     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
14441     *      content}
14442     *
14443     * <p>This second code sample shows a typical implementation of a View
14444     * in a video playing application.  In this situation, while the video is
14445     * playing the application would like to go into a complete full-screen mode,
14446     * to use as much of the display as possible for the video.  When in this state
14447     * the user can not interact with the application; the system intercepts
14448     * touching on the screen to pop the UI out of full screen mode.
14449     *
14450     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
14451     *      content}
14452     *
14453     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
14454     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
14455     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
14456     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
14457     */
14458    public void setSystemUiVisibility(int visibility) {
14459        if (visibility != mSystemUiVisibility) {
14460            mSystemUiVisibility = visibility;
14461            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
14462                mParent.recomputeViewAttributes(this);
14463            }
14464        }
14465    }
14466
14467    /**
14468     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
14469     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
14470     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
14471     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
14472     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
14473     */
14474    public int getSystemUiVisibility() {
14475        return mSystemUiVisibility;
14476    }
14477
14478    /**
14479     * Returns the current system UI visibility that is currently set for
14480     * the entire window.  This is the combination of the
14481     * {@link #setSystemUiVisibility(int)} values supplied by all of the
14482     * views in the window.
14483     */
14484    public int getWindowSystemUiVisibility() {
14485        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
14486    }
14487
14488    /**
14489     * Override to find out when the window's requested system UI visibility
14490     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
14491     * This is different from the callbacks recieved through
14492     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
14493     * in that this is only telling you about the local request of the window,
14494     * not the actual values applied by the system.
14495     */
14496    public void onWindowSystemUiVisibilityChanged(int visible) {
14497    }
14498
14499    /**
14500     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
14501     * the view hierarchy.
14502     */
14503    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
14504        onWindowSystemUiVisibilityChanged(visible);
14505    }
14506
14507    /**
14508     * Set a listener to receive callbacks when the visibility of the system bar changes.
14509     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
14510     */
14511    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
14512        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
14513        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
14514            mParent.recomputeViewAttributes(this);
14515        }
14516    }
14517
14518    /**
14519     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
14520     * the view hierarchy.
14521     */
14522    public void dispatchSystemUiVisibilityChanged(int visibility) {
14523        ListenerInfo li = mListenerInfo;
14524        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
14525            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
14526                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
14527        }
14528    }
14529
14530    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
14531        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
14532        if (val != mSystemUiVisibility) {
14533            setSystemUiVisibility(val);
14534        }
14535    }
14536
14537    /**
14538     * Creates an image that the system displays during the drag and drop
14539     * operation. This is called a &quot;drag shadow&quot;. The default implementation
14540     * for a DragShadowBuilder based on a View returns an image that has exactly the same
14541     * appearance as the given View. The default also positions the center of the drag shadow
14542     * directly under the touch point. If no View is provided (the constructor with no parameters
14543     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
14544     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
14545     * default is an invisible drag shadow.
14546     * <p>
14547     * You are not required to use the View you provide to the constructor as the basis of the
14548     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
14549     * anything you want as the drag shadow.
14550     * </p>
14551     * <p>
14552     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
14553     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
14554     *  size and position of the drag shadow. It uses this data to construct a
14555     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
14556     *  so that your application can draw the shadow image in the Canvas.
14557     * </p>
14558     *
14559     * <div class="special reference">
14560     * <h3>Developer Guides</h3>
14561     * <p>For a guide to implementing drag and drop features, read the
14562     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
14563     * </div>
14564     */
14565    public static class DragShadowBuilder {
14566        private final WeakReference<View> mView;
14567
14568        /**
14569         * Constructs a shadow image builder based on a View. By default, the resulting drag
14570         * shadow will have the same appearance and dimensions as the View, with the touch point
14571         * over the center of the View.
14572         * @param view A View. Any View in scope can be used.
14573         */
14574        public DragShadowBuilder(View view) {
14575            mView = new WeakReference<View>(view);
14576        }
14577
14578        /**
14579         * Construct a shadow builder object with no associated View.  This
14580         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
14581         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
14582         * to supply the drag shadow's dimensions and appearance without
14583         * reference to any View object. If they are not overridden, then the result is an
14584         * invisible drag shadow.
14585         */
14586        public DragShadowBuilder() {
14587            mView = new WeakReference<View>(null);
14588        }
14589
14590        /**
14591         * Returns the View object that had been passed to the
14592         * {@link #View.DragShadowBuilder(View)}
14593         * constructor.  If that View parameter was {@code null} or if the
14594         * {@link #View.DragShadowBuilder()}
14595         * constructor was used to instantiate the builder object, this method will return
14596         * null.
14597         *
14598         * @return The View object associate with this builder object.
14599         */
14600        @SuppressWarnings({"JavadocReference"})
14601        final public View getView() {
14602            return mView.get();
14603        }
14604
14605        /**
14606         * Provides the metrics for the shadow image. These include the dimensions of
14607         * the shadow image, and the point within that shadow that should
14608         * be centered under the touch location while dragging.
14609         * <p>
14610         * The default implementation sets the dimensions of the shadow to be the
14611         * same as the dimensions of the View itself and centers the shadow under
14612         * the touch point.
14613         * </p>
14614         *
14615         * @param shadowSize A {@link android.graphics.Point} containing the width and height
14616         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
14617         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
14618         * image.
14619         *
14620         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
14621         * shadow image that should be underneath the touch point during the drag and drop
14622         * operation. Your application must set {@link android.graphics.Point#x} to the
14623         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
14624         */
14625        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
14626            final View view = mView.get();
14627            if (view != null) {
14628                shadowSize.set(view.getWidth(), view.getHeight());
14629                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
14630            } else {
14631                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
14632            }
14633        }
14634
14635        /**
14636         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
14637         * based on the dimensions it received from the
14638         * {@link #onProvideShadowMetrics(Point, Point)} callback.
14639         *
14640         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
14641         */
14642        public void onDrawShadow(Canvas canvas) {
14643            final View view = mView.get();
14644            if (view != null) {
14645                view.draw(canvas);
14646            } else {
14647                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
14648            }
14649        }
14650    }
14651
14652    /**
14653     * Starts a drag and drop operation. When your application calls this method, it passes a
14654     * {@link android.view.View.DragShadowBuilder} object to the system. The
14655     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
14656     * to get metrics for the drag shadow, and then calls the object's
14657     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
14658     * <p>
14659     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
14660     *  drag events to all the View objects in your application that are currently visible. It does
14661     *  this either by calling the View object's drag listener (an implementation of
14662     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
14663     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
14664     *  Both are passed a {@link android.view.DragEvent} object that has a
14665     *  {@link android.view.DragEvent#getAction()} value of
14666     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
14667     * </p>
14668     * <p>
14669     * Your application can invoke startDrag() on any attached View object. The View object does not
14670     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
14671     * be related to the View the user selected for dragging.
14672     * </p>
14673     * @param data A {@link android.content.ClipData} object pointing to the data to be
14674     * transferred by the drag and drop operation.
14675     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
14676     * drag shadow.
14677     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
14678     * drop operation. This Object is put into every DragEvent object sent by the system during the
14679     * current drag.
14680     * <p>
14681     * myLocalState is a lightweight mechanism for the sending information from the dragged View
14682     * to the target Views. For example, it can contain flags that differentiate between a
14683     * a copy operation and a move operation.
14684     * </p>
14685     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
14686     * so the parameter should be set to 0.
14687     * @return {@code true} if the method completes successfully, or
14688     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
14689     * do a drag, and so no drag operation is in progress.
14690     */
14691    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
14692            Object myLocalState, int flags) {
14693        if (ViewDebug.DEBUG_DRAG) {
14694            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
14695        }
14696        boolean okay = false;
14697
14698        Point shadowSize = new Point();
14699        Point shadowTouchPoint = new Point();
14700        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
14701
14702        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
14703                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
14704            throw new IllegalStateException("Drag shadow dimensions must not be negative");
14705        }
14706
14707        if (ViewDebug.DEBUG_DRAG) {
14708            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
14709                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
14710        }
14711        Surface surface = new Surface();
14712        try {
14713            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
14714                    flags, shadowSize.x, shadowSize.y, surface);
14715            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
14716                    + " surface=" + surface);
14717            if (token != null) {
14718                Canvas canvas = surface.lockCanvas(null);
14719                try {
14720                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
14721                    shadowBuilder.onDrawShadow(canvas);
14722                } finally {
14723                    surface.unlockCanvasAndPost(canvas);
14724                }
14725
14726                final ViewRootImpl root = getViewRootImpl();
14727
14728                // Cache the local state object for delivery with DragEvents
14729                root.setLocalDragState(myLocalState);
14730
14731                // repurpose 'shadowSize' for the last touch point
14732                root.getLastTouchPoint(shadowSize);
14733
14734                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
14735                        shadowSize.x, shadowSize.y,
14736                        shadowTouchPoint.x, shadowTouchPoint.y, data);
14737                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
14738
14739                // Off and running!  Release our local surface instance; the drag
14740                // shadow surface is now managed by the system process.
14741                surface.release();
14742            }
14743        } catch (Exception e) {
14744            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
14745            surface.destroy();
14746        }
14747
14748        return okay;
14749    }
14750
14751    /**
14752     * Handles drag events sent by the system following a call to
14753     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
14754     *<p>
14755     * When the system calls this method, it passes a
14756     * {@link android.view.DragEvent} object. A call to
14757     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
14758     * in DragEvent. The method uses these to determine what is happening in the drag and drop
14759     * operation.
14760     * @param event The {@link android.view.DragEvent} sent by the system.
14761     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
14762     * in DragEvent, indicating the type of drag event represented by this object.
14763     * @return {@code true} if the method was successful, otherwise {@code false}.
14764     * <p>
14765     *  The method should return {@code true} in response to an action type of
14766     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
14767     *  operation.
14768     * </p>
14769     * <p>
14770     *  The method should also return {@code true} in response to an action type of
14771     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
14772     *  {@code false} if it didn't.
14773     * </p>
14774     */
14775    public boolean onDragEvent(DragEvent event) {
14776        return false;
14777    }
14778
14779    /**
14780     * Detects if this View is enabled and has a drag event listener.
14781     * If both are true, then it calls the drag event listener with the
14782     * {@link android.view.DragEvent} it received. If the drag event listener returns
14783     * {@code true}, then dispatchDragEvent() returns {@code true}.
14784     * <p>
14785     * For all other cases, the method calls the
14786     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
14787     * method and returns its result.
14788     * </p>
14789     * <p>
14790     * This ensures that a drag event is always consumed, even if the View does not have a drag
14791     * event listener. However, if the View has a listener and the listener returns true, then
14792     * onDragEvent() is not called.
14793     * </p>
14794     */
14795    public boolean dispatchDragEvent(DragEvent event) {
14796        //noinspection SimplifiableIfStatement
14797        ListenerInfo li = mListenerInfo;
14798        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
14799                && li.mOnDragListener.onDrag(this, event)) {
14800            return true;
14801        }
14802        return onDragEvent(event);
14803    }
14804
14805    boolean canAcceptDrag() {
14806        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
14807    }
14808
14809    /**
14810     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
14811     * it is ever exposed at all.
14812     * @hide
14813     */
14814    public void onCloseSystemDialogs(String reason) {
14815    }
14816
14817    /**
14818     * Given a Drawable whose bounds have been set to draw into this view,
14819     * update a Region being computed for
14820     * {@link #gatherTransparentRegion(android.graphics.Region)} so
14821     * that any non-transparent parts of the Drawable are removed from the
14822     * given transparent region.
14823     *
14824     * @param dr The Drawable whose transparency is to be applied to the region.
14825     * @param region A Region holding the current transparency information,
14826     * where any parts of the region that are set are considered to be
14827     * transparent.  On return, this region will be modified to have the
14828     * transparency information reduced by the corresponding parts of the
14829     * Drawable that are not transparent.
14830     * {@hide}
14831     */
14832    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
14833        if (DBG) {
14834            Log.i("View", "Getting transparent region for: " + this);
14835        }
14836        final Region r = dr.getTransparentRegion();
14837        final Rect db = dr.getBounds();
14838        final AttachInfo attachInfo = mAttachInfo;
14839        if (r != null && attachInfo != null) {
14840            final int w = getRight()-getLeft();
14841            final int h = getBottom()-getTop();
14842            if (db.left > 0) {
14843                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
14844                r.op(0, 0, db.left, h, Region.Op.UNION);
14845            }
14846            if (db.right < w) {
14847                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
14848                r.op(db.right, 0, w, h, Region.Op.UNION);
14849            }
14850            if (db.top > 0) {
14851                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
14852                r.op(0, 0, w, db.top, Region.Op.UNION);
14853            }
14854            if (db.bottom < h) {
14855                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
14856                r.op(0, db.bottom, w, h, Region.Op.UNION);
14857            }
14858            final int[] location = attachInfo.mTransparentLocation;
14859            getLocationInWindow(location);
14860            r.translate(location[0], location[1]);
14861            region.op(r, Region.Op.INTERSECT);
14862        } else {
14863            region.op(db, Region.Op.DIFFERENCE);
14864        }
14865    }
14866
14867    private void checkForLongClick(int delayOffset) {
14868        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
14869            mHasPerformedLongPress = false;
14870
14871            if (mPendingCheckForLongPress == null) {
14872                mPendingCheckForLongPress = new CheckForLongPress();
14873            }
14874            mPendingCheckForLongPress.rememberWindowAttachCount();
14875            postDelayed(mPendingCheckForLongPress,
14876                    ViewConfiguration.getLongPressTimeout() - delayOffset);
14877        }
14878    }
14879
14880    /**
14881     * Inflate a view from an XML resource.  This convenience method wraps the {@link
14882     * LayoutInflater} class, which provides a full range of options for view inflation.
14883     *
14884     * @param context The Context object for your activity or application.
14885     * @param resource The resource ID to inflate
14886     * @param root A view group that will be the parent.  Used to properly inflate the
14887     * layout_* parameters.
14888     * @see LayoutInflater
14889     */
14890    public static View inflate(Context context, int resource, ViewGroup root) {
14891        LayoutInflater factory = LayoutInflater.from(context);
14892        return factory.inflate(resource, root);
14893    }
14894
14895    /**
14896     * Scroll the view with standard behavior for scrolling beyond the normal
14897     * content boundaries. Views that call this method should override
14898     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
14899     * results of an over-scroll operation.
14900     *
14901     * Views can use this method to handle any touch or fling-based scrolling.
14902     *
14903     * @param deltaX Change in X in pixels
14904     * @param deltaY Change in Y in pixels
14905     * @param scrollX Current X scroll value in pixels before applying deltaX
14906     * @param scrollY Current Y scroll value in pixels before applying deltaY
14907     * @param scrollRangeX Maximum content scroll range along the X axis
14908     * @param scrollRangeY Maximum content scroll range along the Y axis
14909     * @param maxOverScrollX Number of pixels to overscroll by in either direction
14910     *          along the X axis.
14911     * @param maxOverScrollY Number of pixels to overscroll by in either direction
14912     *          along the Y axis.
14913     * @param isTouchEvent true if this scroll operation is the result of a touch event.
14914     * @return true if scrolling was clamped to an over-scroll boundary along either
14915     *          axis, false otherwise.
14916     */
14917    @SuppressWarnings({"UnusedParameters"})
14918    protected boolean overScrollBy(int deltaX, int deltaY,
14919            int scrollX, int scrollY,
14920            int scrollRangeX, int scrollRangeY,
14921            int maxOverScrollX, int maxOverScrollY,
14922            boolean isTouchEvent) {
14923        final int overScrollMode = mOverScrollMode;
14924        final boolean canScrollHorizontal =
14925                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
14926        final boolean canScrollVertical =
14927                computeVerticalScrollRange() > computeVerticalScrollExtent();
14928        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
14929                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
14930        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
14931                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
14932
14933        int newScrollX = scrollX + deltaX;
14934        if (!overScrollHorizontal) {
14935            maxOverScrollX = 0;
14936        }
14937
14938        int newScrollY = scrollY + deltaY;
14939        if (!overScrollVertical) {
14940            maxOverScrollY = 0;
14941        }
14942
14943        // Clamp values if at the limits and record
14944        final int left = -maxOverScrollX;
14945        final int right = maxOverScrollX + scrollRangeX;
14946        final int top = -maxOverScrollY;
14947        final int bottom = maxOverScrollY + scrollRangeY;
14948
14949        boolean clampedX = false;
14950        if (newScrollX > right) {
14951            newScrollX = right;
14952            clampedX = true;
14953        } else if (newScrollX < left) {
14954            newScrollX = left;
14955            clampedX = true;
14956        }
14957
14958        boolean clampedY = false;
14959        if (newScrollY > bottom) {
14960            newScrollY = bottom;
14961            clampedY = true;
14962        } else if (newScrollY < top) {
14963            newScrollY = top;
14964            clampedY = true;
14965        }
14966
14967        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
14968
14969        return clampedX || clampedY;
14970    }
14971
14972    /**
14973     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
14974     * respond to the results of an over-scroll operation.
14975     *
14976     * @param scrollX New X scroll value in pixels
14977     * @param scrollY New Y scroll value in pixels
14978     * @param clampedX True if scrollX was clamped to an over-scroll boundary
14979     * @param clampedY True if scrollY was clamped to an over-scroll boundary
14980     */
14981    protected void onOverScrolled(int scrollX, int scrollY,
14982            boolean clampedX, boolean clampedY) {
14983        // Intentionally empty.
14984    }
14985
14986    /**
14987     * Returns the over-scroll mode for this view. The result will be
14988     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14989     * (allow over-scrolling only if the view content is larger than the container),
14990     * or {@link #OVER_SCROLL_NEVER}.
14991     *
14992     * @return This view's over-scroll mode.
14993     */
14994    public int getOverScrollMode() {
14995        return mOverScrollMode;
14996    }
14997
14998    /**
14999     * Set the over-scroll mode for this view. Valid over-scroll modes are
15000     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15001     * (allow over-scrolling only if the view content is larger than the container),
15002     * or {@link #OVER_SCROLL_NEVER}.
15003     *
15004     * Setting the over-scroll mode of a view will have an effect only if the
15005     * view is capable of scrolling.
15006     *
15007     * @param overScrollMode The new over-scroll mode for this view.
15008     */
15009    public void setOverScrollMode(int overScrollMode) {
15010        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15011                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15012                overScrollMode != OVER_SCROLL_NEVER) {
15013            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15014        }
15015        mOverScrollMode = overScrollMode;
15016    }
15017
15018    /**
15019     * Gets a scale factor that determines the distance the view should scroll
15020     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15021     * @return The vertical scroll scale factor.
15022     * @hide
15023     */
15024    protected float getVerticalScrollFactor() {
15025        if (mVerticalScrollFactor == 0) {
15026            TypedValue outValue = new TypedValue();
15027            if (!mContext.getTheme().resolveAttribute(
15028                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15029                throw new IllegalStateException(
15030                        "Expected theme to define listPreferredItemHeight.");
15031            }
15032            mVerticalScrollFactor = outValue.getDimension(
15033                    mContext.getResources().getDisplayMetrics());
15034        }
15035        return mVerticalScrollFactor;
15036    }
15037
15038    /**
15039     * Gets a scale factor that determines the distance the view should scroll
15040     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
15041     * @return The horizontal scroll scale factor.
15042     * @hide
15043     */
15044    protected float getHorizontalScrollFactor() {
15045        // TODO: Should use something else.
15046        return getVerticalScrollFactor();
15047    }
15048
15049    /**
15050     * Return the value specifying the text direction or policy that was set with
15051     * {@link #setTextDirection(int)}.
15052     *
15053     * @return the defined text direction. It can be one of:
15054     *
15055     * {@link #TEXT_DIRECTION_INHERIT},
15056     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15057     * {@link #TEXT_DIRECTION_ANY_RTL},
15058     * {@link #TEXT_DIRECTION_LTR},
15059     * {@link #TEXT_DIRECTION_RTL},
15060     * {@link #TEXT_DIRECTION_LOCALE}
15061     */
15062    @ViewDebug.ExportedProperty(category = "text", mapping = {
15063            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
15064            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
15065            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
15066            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
15067            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
15068            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
15069    })
15070    public int getTextDirection() {
15071        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
15072    }
15073
15074    /**
15075     * Set the text direction.
15076     *
15077     * @param textDirection the direction to set. Should be one of:
15078     *
15079     * {@link #TEXT_DIRECTION_INHERIT},
15080     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15081     * {@link #TEXT_DIRECTION_ANY_RTL},
15082     * {@link #TEXT_DIRECTION_LTR},
15083     * {@link #TEXT_DIRECTION_RTL},
15084     * {@link #TEXT_DIRECTION_LOCALE}
15085     */
15086    public void setTextDirection(int textDirection) {
15087        if (getTextDirection() != textDirection) {
15088            // Reset the current text direction and the resolved one
15089            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
15090            resetResolvedTextDirection();
15091            // Set the new text direction
15092            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
15093            // Refresh
15094            requestLayout();
15095            invalidate(true);
15096        }
15097    }
15098
15099    /**
15100     * Return the resolved text direction.
15101     *
15102     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
15103     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
15104     * up the parent chain of the view. if there is no parent, then it will return the default
15105     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
15106     *
15107     * @return the resolved text direction. Returns one of:
15108     *
15109     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15110     * {@link #TEXT_DIRECTION_ANY_RTL},
15111     * {@link #TEXT_DIRECTION_LTR},
15112     * {@link #TEXT_DIRECTION_RTL},
15113     * {@link #TEXT_DIRECTION_LOCALE}
15114     */
15115    public int getResolvedTextDirection() {
15116        // The text direction will be resolved only if needed
15117        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
15118            resolveTextDirection();
15119        }
15120        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
15121    }
15122
15123    /**
15124     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
15125     * resolution is done.
15126     */
15127    public void resolveTextDirection() {
15128        // Reset any previous text direction resolution
15129        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15130
15131        if (hasRtlSupport()) {
15132            // Set resolved text direction flag depending on text direction flag
15133            final int textDirection = getTextDirection();
15134            switch(textDirection) {
15135                case TEXT_DIRECTION_INHERIT:
15136                    if (canResolveTextDirection()) {
15137                        ViewGroup viewGroup = ((ViewGroup) mParent);
15138
15139                        // Set current resolved direction to the same value as the parent's one
15140                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
15141                        switch (parentResolvedDirection) {
15142                            case TEXT_DIRECTION_FIRST_STRONG:
15143                            case TEXT_DIRECTION_ANY_RTL:
15144                            case TEXT_DIRECTION_LTR:
15145                            case TEXT_DIRECTION_RTL:
15146                            case TEXT_DIRECTION_LOCALE:
15147                                mPrivateFlags2 |=
15148                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15149                                break;
15150                            default:
15151                                // Default resolved direction is "first strong" heuristic
15152                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15153                        }
15154                    } else {
15155                        // We cannot do the resolution if there is no parent, so use the default one
15156                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15157                    }
15158                    break;
15159                case TEXT_DIRECTION_FIRST_STRONG:
15160                case TEXT_DIRECTION_ANY_RTL:
15161                case TEXT_DIRECTION_LTR:
15162                case TEXT_DIRECTION_RTL:
15163                case TEXT_DIRECTION_LOCALE:
15164                    // Resolved direction is the same as text direction
15165                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15166                    break;
15167                default:
15168                    // Default resolved direction is "first strong" heuristic
15169                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15170            }
15171        } else {
15172            // Default resolved direction is "first strong" heuristic
15173            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15174        }
15175
15176        // Set to resolved
15177        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
15178        onResolvedTextDirectionChanged();
15179    }
15180
15181    /**
15182     * Called when text direction has been resolved. Subclasses that care about text direction
15183     * resolution should override this method.
15184     *
15185     * The default implementation does nothing.
15186     */
15187    public void onResolvedTextDirectionChanged() {
15188    }
15189
15190    /**
15191     * Check if text direction resolution can be done.
15192     *
15193     * @return true if text direction resolution can be done otherwise return false.
15194     */
15195    public boolean canResolveTextDirection() {
15196        switch (getTextDirection()) {
15197            case TEXT_DIRECTION_INHERIT:
15198                return (mParent != null) && (mParent instanceof ViewGroup);
15199            default:
15200                return true;
15201        }
15202    }
15203
15204    /**
15205     * Reset resolved text direction. Text direction can be resolved with a call to
15206     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
15207     * reset is done.
15208     */
15209    public void resetResolvedTextDirection() {
15210        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15211        onResolvedTextDirectionReset();
15212    }
15213
15214    /**
15215     * Called when text direction is reset. Subclasses that care about text direction reset should
15216     * override this method and do a reset of the text direction of their children. The default
15217     * implementation does nothing.
15218     */
15219    public void onResolvedTextDirectionReset() {
15220    }
15221
15222    /**
15223     * Return the value specifying the text alignment or policy that was set with
15224     * {@link #setTextAlignment(int)}.
15225     *
15226     * @return the defined text alignment. It can be one of:
15227     *
15228     * {@link #TEXT_ALIGNMENT_INHERIT},
15229     * {@link #TEXT_ALIGNMENT_GRAVITY},
15230     * {@link #TEXT_ALIGNMENT_CENTER},
15231     * {@link #TEXT_ALIGNMENT_TEXT_START},
15232     * {@link #TEXT_ALIGNMENT_TEXT_END},
15233     * {@link #TEXT_ALIGNMENT_VIEW_START},
15234     * {@link #TEXT_ALIGNMENT_VIEW_END}
15235     */
15236    @ViewDebug.ExportedProperty(category = "text", mapping = {
15237            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15238            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15239            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15240            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15241            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15242            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15243            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15244    })
15245    public int getTextAlignment() {
15246        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
15247    }
15248
15249    /**
15250     * Set the text alignment.
15251     *
15252     * @param textAlignment The text alignment to set. Should be one of
15253     *
15254     * {@link #TEXT_ALIGNMENT_INHERIT},
15255     * {@link #TEXT_ALIGNMENT_GRAVITY},
15256     * {@link #TEXT_ALIGNMENT_CENTER},
15257     * {@link #TEXT_ALIGNMENT_TEXT_START},
15258     * {@link #TEXT_ALIGNMENT_TEXT_END},
15259     * {@link #TEXT_ALIGNMENT_VIEW_START},
15260     * {@link #TEXT_ALIGNMENT_VIEW_END}
15261     *
15262     * @attr ref android.R.styleable#View_textAlignment
15263     */
15264    public void setTextAlignment(int textAlignment) {
15265        if (textAlignment != getTextAlignment()) {
15266            // Reset the current and resolved text alignment
15267            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
15268            resetResolvedTextAlignment();
15269            // Set the new text alignment
15270            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
15271            // Refresh
15272            requestLayout();
15273            invalidate(true);
15274        }
15275    }
15276
15277    /**
15278     * Return the resolved text alignment.
15279     *
15280     * The resolved text alignment. This needs resolution if the value is
15281     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
15282     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
15283     *
15284     * @return the resolved text alignment. Returns one of:
15285     *
15286     * {@link #TEXT_ALIGNMENT_GRAVITY},
15287     * {@link #TEXT_ALIGNMENT_CENTER},
15288     * {@link #TEXT_ALIGNMENT_TEXT_START},
15289     * {@link #TEXT_ALIGNMENT_TEXT_END},
15290     * {@link #TEXT_ALIGNMENT_VIEW_START},
15291     * {@link #TEXT_ALIGNMENT_VIEW_END}
15292     */
15293    @ViewDebug.ExportedProperty(category = "text", mapping = {
15294            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15295            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15296            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15297            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15298            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15299            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15300            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15301    })
15302    public int getResolvedTextAlignment() {
15303        // If text alignment is not resolved, then resolve it
15304        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
15305            resolveTextAlignment();
15306        }
15307        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
15308    }
15309
15310    /**
15311     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
15312     * resolution is done.
15313     */
15314    public void resolveTextAlignment() {
15315        // Reset any previous text alignment resolution
15316        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
15317
15318        if (hasRtlSupport()) {
15319            // Set resolved text alignment flag depending on text alignment flag
15320            final int textAlignment = getTextAlignment();
15321            switch (textAlignment) {
15322                case TEXT_ALIGNMENT_INHERIT:
15323                    // Check if we can resolve the text alignment
15324                    if (canResolveLayoutDirection() && mParent instanceof View) {
15325                        View view = (View) mParent;
15326
15327                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
15328                        switch (parentResolvedTextAlignment) {
15329                            case TEXT_ALIGNMENT_GRAVITY:
15330                            case TEXT_ALIGNMENT_TEXT_START:
15331                            case TEXT_ALIGNMENT_TEXT_END:
15332                            case TEXT_ALIGNMENT_CENTER:
15333                            case TEXT_ALIGNMENT_VIEW_START:
15334                            case TEXT_ALIGNMENT_VIEW_END:
15335                                // Resolved text alignment is the same as the parent resolved
15336                                // text alignment
15337                                mPrivateFlags2 |=
15338                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
15339                                break;
15340                            default:
15341                                // Use default resolved text alignment
15342                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15343                        }
15344                    }
15345                    else {
15346                        // We cannot do the resolution if there is no parent so use the default
15347                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15348                    }
15349                    break;
15350                case TEXT_ALIGNMENT_GRAVITY:
15351                case TEXT_ALIGNMENT_TEXT_START:
15352                case TEXT_ALIGNMENT_TEXT_END:
15353                case TEXT_ALIGNMENT_CENTER:
15354                case TEXT_ALIGNMENT_VIEW_START:
15355                case TEXT_ALIGNMENT_VIEW_END:
15356                    // Resolved text alignment is the same as text alignment
15357                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
15358                    break;
15359                default:
15360                    // Use default resolved text alignment
15361                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15362            }
15363        } else {
15364            // Use default resolved text alignment
15365            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15366        }
15367
15368        // Set the resolved
15369        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
15370        onResolvedTextAlignmentChanged();
15371    }
15372
15373    /**
15374     * Check if text alignment resolution can be done.
15375     *
15376     * @return true if text alignment resolution can be done otherwise return false.
15377     */
15378    public boolean canResolveTextAlignment() {
15379        switch (getTextAlignment()) {
15380            case TEXT_DIRECTION_INHERIT:
15381                return (mParent != null);
15382            default:
15383                return true;
15384        }
15385    }
15386
15387    /**
15388     * Called when text alignment has been resolved. Subclasses that care about text alignment
15389     * resolution should override this method.
15390     *
15391     * The default implementation does nothing.
15392     */
15393    public void onResolvedTextAlignmentChanged() {
15394    }
15395
15396    /**
15397     * Reset resolved text alignment. Text alignment can be resolved with a call to
15398     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
15399     * reset is done.
15400     */
15401    public void resetResolvedTextAlignment() {
15402        // Reset any previous text alignment resolution
15403        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
15404        onResolvedTextAlignmentReset();
15405    }
15406
15407    /**
15408     * Called when text alignment is reset. Subclasses that care about text alignment reset should
15409     * override this method and do a reset of the text alignment of their children. The default
15410     * implementation does nothing.
15411     */
15412    public void onResolvedTextAlignmentReset() {
15413    }
15414
15415    //
15416    // Properties
15417    //
15418    /**
15419     * A Property wrapper around the <code>alpha</code> functionality handled by the
15420     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
15421     */
15422    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
15423        @Override
15424        public void setValue(View object, float value) {
15425            object.setAlpha(value);
15426        }
15427
15428        @Override
15429        public Float get(View object) {
15430            return object.getAlpha();
15431        }
15432    };
15433
15434    /**
15435     * A Property wrapper around the <code>translationX</code> functionality handled by the
15436     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
15437     */
15438    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
15439        @Override
15440        public void setValue(View object, float value) {
15441            object.setTranslationX(value);
15442        }
15443
15444                @Override
15445        public Float get(View object) {
15446            return object.getTranslationX();
15447        }
15448    };
15449
15450    /**
15451     * A Property wrapper around the <code>translationY</code> functionality handled by the
15452     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
15453     */
15454    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
15455        @Override
15456        public void setValue(View object, float value) {
15457            object.setTranslationY(value);
15458        }
15459
15460        @Override
15461        public Float get(View object) {
15462            return object.getTranslationY();
15463        }
15464    };
15465
15466    /**
15467     * A Property wrapper around the <code>x</code> functionality handled by the
15468     * {@link View#setX(float)} and {@link View#getX()} methods.
15469     */
15470    public static final Property<View, Float> X = new FloatProperty<View>("x") {
15471        @Override
15472        public void setValue(View object, float value) {
15473            object.setX(value);
15474        }
15475
15476        @Override
15477        public Float get(View object) {
15478            return object.getX();
15479        }
15480    };
15481
15482    /**
15483     * A Property wrapper around the <code>y</code> functionality handled by the
15484     * {@link View#setY(float)} and {@link View#getY()} methods.
15485     */
15486    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
15487        @Override
15488        public void setValue(View object, float value) {
15489            object.setY(value);
15490        }
15491
15492        @Override
15493        public Float get(View object) {
15494            return object.getY();
15495        }
15496    };
15497
15498    /**
15499     * A Property wrapper around the <code>rotation</code> functionality handled by the
15500     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
15501     */
15502    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
15503        @Override
15504        public void setValue(View object, float value) {
15505            object.setRotation(value);
15506        }
15507
15508        @Override
15509        public Float get(View object) {
15510            return object.getRotation();
15511        }
15512    };
15513
15514    /**
15515     * A Property wrapper around the <code>rotationX</code> functionality handled by the
15516     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
15517     */
15518    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
15519        @Override
15520        public void setValue(View object, float value) {
15521            object.setRotationX(value);
15522        }
15523
15524        @Override
15525        public Float get(View object) {
15526            return object.getRotationX();
15527        }
15528    };
15529
15530    /**
15531     * A Property wrapper around the <code>rotationY</code> functionality handled by the
15532     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
15533     */
15534    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
15535        @Override
15536        public void setValue(View object, float value) {
15537            object.setRotationY(value);
15538        }
15539
15540        @Override
15541        public Float get(View object) {
15542            return object.getRotationY();
15543        }
15544    };
15545
15546    /**
15547     * A Property wrapper around the <code>scaleX</code> functionality handled by the
15548     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
15549     */
15550    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
15551        @Override
15552        public void setValue(View object, float value) {
15553            object.setScaleX(value);
15554        }
15555
15556        @Override
15557        public Float get(View object) {
15558            return object.getScaleX();
15559        }
15560    };
15561
15562    /**
15563     * A Property wrapper around the <code>scaleY</code> functionality handled by the
15564     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
15565     */
15566    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
15567        @Override
15568        public void setValue(View object, float value) {
15569            object.setScaleY(value);
15570        }
15571
15572        @Override
15573        public Float get(View object) {
15574            return object.getScaleY();
15575        }
15576    };
15577
15578    /**
15579     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
15580     * Each MeasureSpec represents a requirement for either the width or the height.
15581     * A MeasureSpec is comprised of a size and a mode. There are three possible
15582     * modes:
15583     * <dl>
15584     * <dt>UNSPECIFIED</dt>
15585     * <dd>
15586     * The parent has not imposed any constraint on the child. It can be whatever size
15587     * it wants.
15588     * </dd>
15589     *
15590     * <dt>EXACTLY</dt>
15591     * <dd>
15592     * The parent has determined an exact size for the child. The child is going to be
15593     * given those bounds regardless of how big it wants to be.
15594     * </dd>
15595     *
15596     * <dt>AT_MOST</dt>
15597     * <dd>
15598     * The child can be as large as it wants up to the specified size.
15599     * </dd>
15600     * </dl>
15601     *
15602     * MeasureSpecs are implemented as ints to reduce object allocation. This class
15603     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
15604     */
15605    public static class MeasureSpec {
15606        private static final int MODE_SHIFT = 30;
15607        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
15608
15609        /**
15610         * Measure specification mode: The parent has not imposed any constraint
15611         * on the child. It can be whatever size it wants.
15612         */
15613        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
15614
15615        /**
15616         * Measure specification mode: The parent has determined an exact size
15617         * for the child. The child is going to be given those bounds regardless
15618         * of how big it wants to be.
15619         */
15620        public static final int EXACTLY     = 1 << MODE_SHIFT;
15621
15622        /**
15623         * Measure specification mode: The child can be as large as it wants up
15624         * to the specified size.
15625         */
15626        public static final int AT_MOST     = 2 << MODE_SHIFT;
15627
15628        /**
15629         * Creates a measure specification based on the supplied size and mode.
15630         *
15631         * The mode must always be one of the following:
15632         * <ul>
15633         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
15634         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
15635         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
15636         * </ul>
15637         *
15638         * @param size the size of the measure specification
15639         * @param mode the mode of the measure specification
15640         * @return the measure specification based on size and mode
15641         */
15642        public static int makeMeasureSpec(int size, int mode) {
15643            return size + mode;
15644        }
15645
15646        /**
15647         * Extracts the mode from the supplied measure specification.
15648         *
15649         * @param measureSpec the measure specification to extract the mode from
15650         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
15651         *         {@link android.view.View.MeasureSpec#AT_MOST} or
15652         *         {@link android.view.View.MeasureSpec#EXACTLY}
15653         */
15654        public static int getMode(int measureSpec) {
15655            return (measureSpec & MODE_MASK);
15656        }
15657
15658        /**
15659         * Extracts the size from the supplied measure specification.
15660         *
15661         * @param measureSpec the measure specification to extract the size from
15662         * @return the size in pixels defined in the supplied measure specification
15663         */
15664        public static int getSize(int measureSpec) {
15665            return (measureSpec & ~MODE_MASK);
15666        }
15667
15668        /**
15669         * Returns a String representation of the specified measure
15670         * specification.
15671         *
15672         * @param measureSpec the measure specification to convert to a String
15673         * @return a String with the following format: "MeasureSpec: MODE SIZE"
15674         */
15675        public static String toString(int measureSpec) {
15676            int mode = getMode(measureSpec);
15677            int size = getSize(measureSpec);
15678
15679            StringBuilder sb = new StringBuilder("MeasureSpec: ");
15680
15681            if (mode == UNSPECIFIED)
15682                sb.append("UNSPECIFIED ");
15683            else if (mode == EXACTLY)
15684                sb.append("EXACTLY ");
15685            else if (mode == AT_MOST)
15686                sb.append("AT_MOST ");
15687            else
15688                sb.append(mode).append(" ");
15689
15690            sb.append(size);
15691            return sb.toString();
15692        }
15693    }
15694
15695    class CheckForLongPress implements Runnable {
15696
15697        private int mOriginalWindowAttachCount;
15698
15699        public void run() {
15700            if (isPressed() && (mParent != null)
15701                    && mOriginalWindowAttachCount == mWindowAttachCount) {
15702                if (performLongClick()) {
15703                    mHasPerformedLongPress = true;
15704                }
15705            }
15706        }
15707
15708        public void rememberWindowAttachCount() {
15709            mOriginalWindowAttachCount = mWindowAttachCount;
15710        }
15711    }
15712
15713    private final class CheckForTap implements Runnable {
15714        public void run() {
15715            mPrivateFlags &= ~PREPRESSED;
15716            setPressed(true);
15717            checkForLongClick(ViewConfiguration.getTapTimeout());
15718        }
15719    }
15720
15721    private final class PerformClick implements Runnable {
15722        public void run() {
15723            performClick();
15724        }
15725    }
15726
15727    /** @hide */
15728    public void hackTurnOffWindowResizeAnim(boolean off) {
15729        mAttachInfo.mTurnOffWindowResizeAnim = off;
15730    }
15731
15732    /**
15733     * This method returns a ViewPropertyAnimator object, which can be used to animate
15734     * specific properties on this View.
15735     *
15736     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
15737     */
15738    public ViewPropertyAnimator animate() {
15739        if (mAnimator == null) {
15740            mAnimator = new ViewPropertyAnimator(this);
15741        }
15742        return mAnimator;
15743    }
15744
15745    /**
15746     * Interface definition for a callback to be invoked when a key event is
15747     * dispatched to this view. The callback will be invoked before the key
15748     * event is given to the view.
15749     */
15750    public interface OnKeyListener {
15751        /**
15752         * Called when a key is dispatched to a view. This allows listeners to
15753         * get a chance to respond before the target view.
15754         *
15755         * @param v The view the key has been dispatched to.
15756         * @param keyCode The code for the physical key that was pressed
15757         * @param event The KeyEvent object containing full information about
15758         *        the event.
15759         * @return True if the listener has consumed the event, false otherwise.
15760         */
15761        boolean onKey(View v, int keyCode, KeyEvent event);
15762    }
15763
15764    /**
15765     * Interface definition for a callback to be invoked when a touch event is
15766     * dispatched to this view. The callback will be invoked before the touch
15767     * event is given to the view.
15768     */
15769    public interface OnTouchListener {
15770        /**
15771         * Called when a touch event is dispatched to a view. This allows listeners to
15772         * get a chance to respond before the target view.
15773         *
15774         * @param v The view the touch event has been dispatched to.
15775         * @param event The MotionEvent object containing full information about
15776         *        the event.
15777         * @return True if the listener has consumed the event, false otherwise.
15778         */
15779        boolean onTouch(View v, MotionEvent event);
15780    }
15781
15782    /**
15783     * Interface definition for a callback to be invoked when a hover event is
15784     * dispatched to this view. The callback will be invoked before the hover
15785     * event is given to the view.
15786     */
15787    public interface OnHoverListener {
15788        /**
15789         * Called when a hover event is dispatched to a view. This allows listeners to
15790         * get a chance to respond before the target view.
15791         *
15792         * @param v The view the hover event has been dispatched to.
15793         * @param event The MotionEvent object containing full information about
15794         *        the event.
15795         * @return True if the listener has consumed the event, false otherwise.
15796         */
15797        boolean onHover(View v, MotionEvent event);
15798    }
15799
15800    /**
15801     * Interface definition for a callback to be invoked when a generic motion event is
15802     * dispatched to this view. The callback will be invoked before the generic motion
15803     * event is given to the view.
15804     */
15805    public interface OnGenericMotionListener {
15806        /**
15807         * Called when a generic motion event is dispatched to a view. This allows listeners to
15808         * get a chance to respond before the target view.
15809         *
15810         * @param v The view the generic motion event has been dispatched to.
15811         * @param event The MotionEvent object containing full information about
15812         *        the event.
15813         * @return True if the listener has consumed the event, false otherwise.
15814         */
15815        boolean onGenericMotion(View v, MotionEvent event);
15816    }
15817
15818    /**
15819     * Interface definition for a callback to be invoked when a view has been clicked and held.
15820     */
15821    public interface OnLongClickListener {
15822        /**
15823         * Called when a view has been clicked and held.
15824         *
15825         * @param v The view that was clicked and held.
15826         *
15827         * @return true if the callback consumed the long click, false otherwise.
15828         */
15829        boolean onLongClick(View v);
15830    }
15831
15832    /**
15833     * Interface definition for a callback to be invoked when a drag is being dispatched
15834     * to this view.  The callback will be invoked before the hosting view's own
15835     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
15836     * onDrag(event) behavior, it should return 'false' from this callback.
15837     *
15838     * <div class="special reference">
15839     * <h3>Developer Guides</h3>
15840     * <p>For a guide to implementing drag and drop features, read the
15841     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15842     * </div>
15843     */
15844    public interface OnDragListener {
15845        /**
15846         * Called when a drag event is dispatched to a view. This allows listeners
15847         * to get a chance to override base View behavior.
15848         *
15849         * @param v The View that received the drag event.
15850         * @param event The {@link android.view.DragEvent} object for the drag event.
15851         * @return {@code true} if the drag event was handled successfully, or {@code false}
15852         * if the drag event was not handled. Note that {@code false} will trigger the View
15853         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
15854         */
15855        boolean onDrag(View v, DragEvent event);
15856    }
15857
15858    /**
15859     * Interface definition for a callback to be invoked when the focus state of
15860     * a view changed.
15861     */
15862    public interface OnFocusChangeListener {
15863        /**
15864         * Called when the focus state of a view has changed.
15865         *
15866         * @param v The view whose state has changed.
15867         * @param hasFocus The new focus state of v.
15868         */
15869        void onFocusChange(View v, boolean hasFocus);
15870    }
15871
15872    /**
15873     * Interface definition for a callback to be invoked when a view is clicked.
15874     */
15875    public interface OnClickListener {
15876        /**
15877         * Called when a view has been clicked.
15878         *
15879         * @param v The view that was clicked.
15880         */
15881        void onClick(View v);
15882    }
15883
15884    /**
15885     * Interface definition for a callback to be invoked when the context menu
15886     * for this view is being built.
15887     */
15888    public interface OnCreateContextMenuListener {
15889        /**
15890         * Called when the context menu for this view is being built. It is not
15891         * safe to hold onto the menu after this method returns.
15892         *
15893         * @param menu The context menu that is being built
15894         * @param v The view for which the context menu is being built
15895         * @param menuInfo Extra information about the item for which the
15896         *            context menu should be shown. This information will vary
15897         *            depending on the class of v.
15898         */
15899        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
15900    }
15901
15902    /**
15903     * Interface definition for a callback to be invoked when the status bar changes
15904     * visibility.  This reports <strong>global</strong> changes to the system UI
15905     * state, not just what the application is requesting.
15906     *
15907     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
15908     */
15909    public interface OnSystemUiVisibilityChangeListener {
15910        /**
15911         * Called when the status bar changes visibility because of a call to
15912         * {@link View#setSystemUiVisibility(int)}.
15913         *
15914         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
15915         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
15916         * <strong>global</strong> state of the UI visibility flags, not what your
15917         * app is currently applying.
15918         */
15919        public void onSystemUiVisibilityChange(int visibility);
15920    }
15921
15922    /**
15923     * Interface definition for a callback to be invoked when this view is attached
15924     * or detached from its window.
15925     */
15926    public interface OnAttachStateChangeListener {
15927        /**
15928         * Called when the view is attached to a window.
15929         * @param v The view that was attached
15930         */
15931        public void onViewAttachedToWindow(View v);
15932        /**
15933         * Called when the view is detached from a window.
15934         * @param v The view that was detached
15935         */
15936        public void onViewDetachedFromWindow(View v);
15937    }
15938
15939    private final class UnsetPressedState implements Runnable {
15940        public void run() {
15941            setPressed(false);
15942        }
15943    }
15944
15945    /**
15946     * Base class for derived classes that want to save and restore their own
15947     * state in {@link android.view.View#onSaveInstanceState()}.
15948     */
15949    public static class BaseSavedState extends AbsSavedState {
15950        /**
15951         * Constructor used when reading from a parcel. Reads the state of the superclass.
15952         *
15953         * @param source
15954         */
15955        public BaseSavedState(Parcel source) {
15956            super(source);
15957        }
15958
15959        /**
15960         * Constructor called by derived classes when creating their SavedState objects
15961         *
15962         * @param superState The state of the superclass of this view
15963         */
15964        public BaseSavedState(Parcelable superState) {
15965            super(superState);
15966        }
15967
15968        public static final Parcelable.Creator<BaseSavedState> CREATOR =
15969                new Parcelable.Creator<BaseSavedState>() {
15970            public BaseSavedState createFromParcel(Parcel in) {
15971                return new BaseSavedState(in);
15972            }
15973
15974            public BaseSavedState[] newArray(int size) {
15975                return new BaseSavedState[size];
15976            }
15977        };
15978    }
15979
15980    /**
15981     * A set of information given to a view when it is attached to its parent
15982     * window.
15983     */
15984    static class AttachInfo {
15985        interface Callbacks {
15986            void playSoundEffect(int effectId);
15987            boolean performHapticFeedback(int effectId, boolean always);
15988        }
15989
15990        /**
15991         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
15992         * to a Handler. This class contains the target (View) to invalidate and
15993         * the coordinates of the dirty rectangle.
15994         *
15995         * For performance purposes, this class also implements a pool of up to
15996         * POOL_LIMIT objects that get reused. This reduces memory allocations
15997         * whenever possible.
15998         */
15999        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16000            private static final int POOL_LIMIT = 10;
16001            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16002                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16003                        public InvalidateInfo newInstance() {
16004                            return new InvalidateInfo();
16005                        }
16006
16007                        public void onAcquired(InvalidateInfo element) {
16008                        }
16009
16010                        public void onReleased(InvalidateInfo element) {
16011                            element.target = null;
16012                        }
16013                    }, POOL_LIMIT)
16014            );
16015
16016            private InvalidateInfo mNext;
16017            private boolean mIsPooled;
16018
16019            View target;
16020
16021            int left;
16022            int top;
16023            int right;
16024            int bottom;
16025
16026            public void setNextPoolable(InvalidateInfo element) {
16027                mNext = element;
16028            }
16029
16030            public InvalidateInfo getNextPoolable() {
16031                return mNext;
16032            }
16033
16034            static InvalidateInfo acquire() {
16035                return sPool.acquire();
16036            }
16037
16038            void release() {
16039                sPool.release(this);
16040            }
16041
16042            public boolean isPooled() {
16043                return mIsPooled;
16044            }
16045
16046            public void setPooled(boolean isPooled) {
16047                mIsPooled = isPooled;
16048            }
16049        }
16050
16051        final IWindowSession mSession;
16052
16053        final IWindow mWindow;
16054
16055        final IBinder mWindowToken;
16056
16057        final Callbacks mRootCallbacks;
16058
16059        HardwareCanvas mHardwareCanvas;
16060
16061        /**
16062         * The top view of the hierarchy.
16063         */
16064        View mRootView;
16065
16066        IBinder mPanelParentWindowToken;
16067        Surface mSurface;
16068
16069        boolean mHardwareAccelerated;
16070        boolean mHardwareAccelerationRequested;
16071        HardwareRenderer mHardwareRenderer;
16072
16073        boolean mScreenOn;
16074
16075        /**
16076         * Scale factor used by the compatibility mode
16077         */
16078        float mApplicationScale;
16079
16080        /**
16081         * Indicates whether the application is in compatibility mode
16082         */
16083        boolean mScalingRequired;
16084
16085        /**
16086         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
16087         */
16088        boolean mTurnOffWindowResizeAnim;
16089
16090        /**
16091         * Left position of this view's window
16092         */
16093        int mWindowLeft;
16094
16095        /**
16096         * Top position of this view's window
16097         */
16098        int mWindowTop;
16099
16100        /**
16101         * Indicates whether views need to use 32-bit drawing caches
16102         */
16103        boolean mUse32BitDrawingCache;
16104
16105        /**
16106         * For windows that are full-screen but using insets to layout inside
16107         * of the screen decorations, these are the current insets for the
16108         * content of the window.
16109         */
16110        final Rect mContentInsets = new Rect();
16111
16112        /**
16113         * For windows that are full-screen but using insets to layout inside
16114         * of the screen decorations, these are the current insets for the
16115         * actual visible parts of the window.
16116         */
16117        final Rect mVisibleInsets = new Rect();
16118
16119        /**
16120         * The internal insets given by this window.  This value is
16121         * supplied by the client (through
16122         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
16123         * be given to the window manager when changed to be used in laying
16124         * out windows behind it.
16125         */
16126        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
16127                = new ViewTreeObserver.InternalInsetsInfo();
16128
16129        /**
16130         * All views in the window's hierarchy that serve as scroll containers,
16131         * used to determine if the window can be resized or must be panned
16132         * to adjust for a soft input area.
16133         */
16134        final ArrayList<View> mScrollContainers = new ArrayList<View>();
16135
16136        final KeyEvent.DispatcherState mKeyDispatchState
16137                = new KeyEvent.DispatcherState();
16138
16139        /**
16140         * Indicates whether the view's window currently has the focus.
16141         */
16142        boolean mHasWindowFocus;
16143
16144        /**
16145         * The current visibility of the window.
16146         */
16147        int mWindowVisibility;
16148
16149        /**
16150         * Indicates the time at which drawing started to occur.
16151         */
16152        long mDrawingTime;
16153
16154        /**
16155         * Indicates whether or not ignoring the DIRTY_MASK flags.
16156         */
16157        boolean mIgnoreDirtyState;
16158
16159        /**
16160         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
16161         * to avoid clearing that flag prematurely.
16162         */
16163        boolean mSetIgnoreDirtyState = false;
16164
16165        /**
16166         * Indicates whether the view's window is currently in touch mode.
16167         */
16168        boolean mInTouchMode;
16169
16170        /**
16171         * Indicates that ViewAncestor should trigger a global layout change
16172         * the next time it performs a traversal
16173         */
16174        boolean mRecomputeGlobalAttributes;
16175
16176        /**
16177         * Always report new attributes at next traversal.
16178         */
16179        boolean mForceReportNewAttributes;
16180
16181        /**
16182         * Set during a traveral if any views want to keep the screen on.
16183         */
16184        boolean mKeepScreenOn;
16185
16186        /**
16187         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
16188         */
16189        int mSystemUiVisibility;
16190
16191        /**
16192         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
16193         * attached.
16194         */
16195        boolean mHasSystemUiListeners;
16196
16197        /**
16198         * Set if the visibility of any views has changed.
16199         */
16200        boolean mViewVisibilityChanged;
16201
16202        /**
16203         * Set to true if a view has been scrolled.
16204         */
16205        boolean mViewScrollChanged;
16206
16207        /**
16208         * Global to the view hierarchy used as a temporary for dealing with
16209         * x/y points in the transparent region computations.
16210         */
16211        final int[] mTransparentLocation = new int[2];
16212
16213        /**
16214         * Global to the view hierarchy used as a temporary for dealing with
16215         * x/y points in the ViewGroup.invalidateChild implementation.
16216         */
16217        final int[] mInvalidateChildLocation = new int[2];
16218
16219
16220        /**
16221         * Global to the view hierarchy used as a temporary for dealing with
16222         * x/y location when view is transformed.
16223         */
16224        final float[] mTmpTransformLocation = new float[2];
16225
16226        /**
16227         * The view tree observer used to dispatch global events like
16228         * layout, pre-draw, touch mode change, etc.
16229         */
16230        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
16231
16232        /**
16233         * A Canvas used by the view hierarchy to perform bitmap caching.
16234         */
16235        Canvas mCanvas;
16236
16237        /**
16238         * The view root impl.
16239         */
16240        final ViewRootImpl mViewRootImpl;
16241
16242        /**
16243         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
16244         * handler can be used to pump events in the UI events queue.
16245         */
16246        final Handler mHandler;
16247
16248        /**
16249         * Temporary for use in computing invalidate rectangles while
16250         * calling up the hierarchy.
16251         */
16252        final Rect mTmpInvalRect = new Rect();
16253
16254        /**
16255         * Temporary for use in computing hit areas with transformed views
16256         */
16257        final RectF mTmpTransformRect = new RectF();
16258
16259        /**
16260         * Temporary list for use in collecting focusable descendents of a view.
16261         */
16262        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
16263
16264        /**
16265         * The id of the window for accessibility purposes.
16266         */
16267        int mAccessibilityWindowId = View.NO_ID;
16268
16269        /**
16270         * Creates a new set of attachment information with the specified
16271         * events handler and thread.
16272         *
16273         * @param handler the events handler the view must use
16274         */
16275        AttachInfo(IWindowSession session, IWindow window,
16276                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
16277            mSession = session;
16278            mWindow = window;
16279            mWindowToken = window.asBinder();
16280            mViewRootImpl = viewRootImpl;
16281            mHandler = handler;
16282            mRootCallbacks = effectPlayer;
16283        }
16284    }
16285
16286    /**
16287     * <p>ScrollabilityCache holds various fields used by a View when scrolling
16288     * is supported. This avoids keeping too many unused fields in most
16289     * instances of View.</p>
16290     */
16291    private static class ScrollabilityCache implements Runnable {
16292
16293        /**
16294         * Scrollbars are not visible
16295         */
16296        public static final int OFF = 0;
16297
16298        /**
16299         * Scrollbars are visible
16300         */
16301        public static final int ON = 1;
16302
16303        /**
16304         * Scrollbars are fading away
16305         */
16306        public static final int FADING = 2;
16307
16308        public boolean fadeScrollBars;
16309
16310        public int fadingEdgeLength;
16311        public int scrollBarDefaultDelayBeforeFade;
16312        public int scrollBarFadeDuration;
16313
16314        public int scrollBarSize;
16315        public ScrollBarDrawable scrollBar;
16316        public float[] interpolatorValues;
16317        public View host;
16318
16319        public final Paint paint;
16320        public final Matrix matrix;
16321        public Shader shader;
16322
16323        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
16324
16325        private static final float[] OPAQUE = { 255 };
16326        private static final float[] TRANSPARENT = { 0.0f };
16327
16328        /**
16329         * When fading should start. This time moves into the future every time
16330         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
16331         */
16332        public long fadeStartTime;
16333
16334
16335        /**
16336         * The current state of the scrollbars: ON, OFF, or FADING
16337         */
16338        public int state = OFF;
16339
16340        private int mLastColor;
16341
16342        public ScrollabilityCache(ViewConfiguration configuration, View host) {
16343            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
16344            scrollBarSize = configuration.getScaledScrollBarSize();
16345            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
16346            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
16347
16348            paint = new Paint();
16349            matrix = new Matrix();
16350            // use use a height of 1, and then wack the matrix each time we
16351            // actually use it.
16352            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
16353
16354            paint.setShader(shader);
16355            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
16356            this.host = host;
16357        }
16358
16359        public void setFadeColor(int color) {
16360            if (color != 0 && color != mLastColor) {
16361                mLastColor = color;
16362                color |= 0xFF000000;
16363
16364                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
16365                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
16366
16367                paint.setShader(shader);
16368                // Restore the default transfer mode (src_over)
16369                paint.setXfermode(null);
16370            }
16371        }
16372
16373        public void run() {
16374            long now = AnimationUtils.currentAnimationTimeMillis();
16375            if (now >= fadeStartTime) {
16376
16377                // the animation fades the scrollbars out by changing
16378                // the opacity (alpha) from fully opaque to fully
16379                // transparent
16380                int nextFrame = (int) now;
16381                int framesCount = 0;
16382
16383                Interpolator interpolator = scrollBarInterpolator;
16384
16385                // Start opaque
16386                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
16387
16388                // End transparent
16389                nextFrame += scrollBarFadeDuration;
16390                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
16391
16392                state = FADING;
16393
16394                // Kick off the fade animation
16395                host.invalidate(true);
16396            }
16397        }
16398    }
16399
16400    /**
16401     * Resuable callback for sending
16402     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
16403     */
16404    private class SendViewScrolledAccessibilityEvent implements Runnable {
16405        public volatile boolean mIsPending;
16406
16407        public void run() {
16408            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
16409            mIsPending = false;
16410        }
16411    }
16412
16413    /**
16414     * <p>
16415     * This class represents a delegate that can be registered in a {@link View}
16416     * to enhance accessibility support via composition rather via inheritance.
16417     * It is specifically targeted to widget developers that extend basic View
16418     * classes i.e. classes in package android.view, that would like their
16419     * applications to be backwards compatible.
16420     * </p>
16421     * <div class="special reference">
16422     * <h3>Developer Guides</h3>
16423     * <p>For more information about making applications accessible, read the
16424     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
16425     * developer guide.</p>
16426     * </div>
16427     * <p>
16428     * A scenario in which a developer would like to use an accessibility delegate
16429     * is overriding a method introduced in a later API version then the minimal API
16430     * version supported by the application. For example, the method
16431     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
16432     * in API version 4 when the accessibility APIs were first introduced. If a
16433     * developer would like his application to run on API version 4 devices (assuming
16434     * all other APIs used by the application are version 4 or lower) and take advantage
16435     * of this method, instead of overriding the method which would break the application's
16436     * backwards compatibility, he can override the corresponding method in this
16437     * delegate and register the delegate in the target View if the API version of
16438     * the system is high enough i.e. the API version is same or higher to the API
16439     * version that introduced
16440     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
16441     * </p>
16442     * <p>
16443     * Here is an example implementation:
16444     * </p>
16445     * <code><pre><p>
16446     * if (Build.VERSION.SDK_INT >= 14) {
16447     *     // If the API version is equal of higher than the version in
16448     *     // which onInitializeAccessibilityNodeInfo was introduced we
16449     *     // register a delegate with a customized implementation.
16450     *     View view = findViewById(R.id.view_id);
16451     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
16452     *         public void onInitializeAccessibilityNodeInfo(View host,
16453     *                 AccessibilityNodeInfo info) {
16454     *             // Let the default implementation populate the info.
16455     *             super.onInitializeAccessibilityNodeInfo(host, info);
16456     *             // Set some other information.
16457     *             info.setEnabled(host.isEnabled());
16458     *         }
16459     *     });
16460     * }
16461     * </code></pre></p>
16462     * <p>
16463     * This delegate contains methods that correspond to the accessibility methods
16464     * in View. If a delegate has been specified the implementation in View hands
16465     * off handling to the corresponding method in this delegate. The default
16466     * implementation the delegate methods behaves exactly as the corresponding
16467     * method in View for the case of no accessibility delegate been set. Hence,
16468     * to customize the behavior of a View method, clients can override only the
16469     * corresponding delegate method without altering the behavior of the rest
16470     * accessibility related methods of the host view.
16471     * </p>
16472     */
16473    public static class AccessibilityDelegate {
16474
16475        /**
16476         * Sends an accessibility event of the given type. If accessibility is not
16477         * enabled this method has no effect.
16478         * <p>
16479         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
16480         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
16481         * been set.
16482         * </p>
16483         *
16484         * @param host The View hosting the delegate.
16485         * @param eventType The type of the event to send.
16486         *
16487         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
16488         */
16489        public void sendAccessibilityEvent(View host, int eventType) {
16490            host.sendAccessibilityEventInternal(eventType);
16491        }
16492
16493        /**
16494         * Sends an accessibility event. This method behaves exactly as
16495         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
16496         * empty {@link AccessibilityEvent} and does not perform a check whether
16497         * accessibility is enabled.
16498         * <p>
16499         * The default implementation behaves as
16500         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
16501         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
16502         * the case of no accessibility delegate been set.
16503         * </p>
16504         *
16505         * @param host The View hosting the delegate.
16506         * @param event The event to send.
16507         *
16508         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
16509         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
16510         */
16511        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
16512            host.sendAccessibilityEventUncheckedInternal(event);
16513        }
16514
16515        /**
16516         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
16517         * to its children for adding their text content to the event.
16518         * <p>
16519         * The default implementation behaves as
16520         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
16521         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
16522         * the case of no accessibility delegate been set.
16523         * </p>
16524         *
16525         * @param host The View hosting the delegate.
16526         * @param event The event.
16527         * @return True if the event population was completed.
16528         *
16529         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
16530         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
16531         */
16532        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
16533            return host.dispatchPopulateAccessibilityEventInternal(event);
16534        }
16535
16536        /**
16537         * Gives a chance to the host View to populate the accessibility event with its
16538         * text content.
16539         * <p>
16540         * The default implementation behaves as
16541         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
16542         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
16543         * the case of no accessibility delegate been set.
16544         * </p>
16545         *
16546         * @param host The View hosting the delegate.
16547         * @param event The accessibility event which to populate.
16548         *
16549         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
16550         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
16551         */
16552        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
16553            host.onPopulateAccessibilityEventInternal(event);
16554        }
16555
16556        /**
16557         * Initializes an {@link AccessibilityEvent} with information about the
16558         * the host View which is the event source.
16559         * <p>
16560         * The default implementation behaves as
16561         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
16562         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
16563         * the case of no accessibility delegate been set.
16564         * </p>
16565         *
16566         * @param host The View hosting the delegate.
16567         * @param event The event to initialize.
16568         *
16569         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
16570         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
16571         */
16572        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
16573            host.onInitializeAccessibilityEventInternal(event);
16574        }
16575
16576        /**
16577         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
16578         * <p>
16579         * The default implementation behaves as
16580         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
16581         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
16582         * the case of no accessibility delegate been set.
16583         * </p>
16584         *
16585         * @param host The View hosting the delegate.
16586         * @param info The instance to initialize.
16587         *
16588         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
16589         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
16590         */
16591        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
16592            host.onInitializeAccessibilityNodeInfoInternal(info);
16593        }
16594
16595        /**
16596         * Called when a child of the host View has requested sending an
16597         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
16598         * to augment the event.
16599         * <p>
16600         * The default implementation behaves as
16601         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
16602         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
16603         * the case of no accessibility delegate been set.
16604         * </p>
16605         *
16606         * @param host The View hosting the delegate.
16607         * @param child The child which requests sending the event.
16608         * @param event The event to be sent.
16609         * @return True if the event should be sent
16610         *
16611         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
16612         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
16613         */
16614        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
16615                AccessibilityEvent event) {
16616            return host.onRequestSendAccessibilityEventInternal(child, event);
16617        }
16618
16619        /**
16620         * Gets the provider for managing a virtual view hierarchy rooted at this View
16621         * and reported to {@link android.accessibilityservice.AccessibilityService}s
16622         * that explore the window content.
16623         * <p>
16624         * The default implementation behaves as
16625         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
16626         * the case of no accessibility delegate been set.
16627         * </p>
16628         *
16629         * @return The provider.
16630         *
16631         * @see AccessibilityNodeProvider
16632         */
16633        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
16634            return null;
16635        }
16636    }
16637}
16638