View.java revision b934db7e3e6d4c3963d2a4a5c00cfb0c3ffbfce4
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Interpolator;
28import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
32import android.graphics.Point;
33import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.Region;
38import android.graphics.Shader;
39import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Parcel;
44import android.os.Parcelable;
45import android.os.RemoteException;
46import android.os.SystemClock;
47import android.text.TextUtils;
48import android.util.AttributeSet;
49import android.util.FloatProperty;
50import android.util.LocaleUtil;
51import android.util.Log;
52import android.util.Pool;
53import android.util.Poolable;
54import android.util.PoolableManager;
55import android.util.Pools;
56import android.util.Property;
57import android.util.SparseArray;
58import android.util.TypedValue;
59import android.view.ContextMenu.ContextMenuInfo;
60import android.view.accessibility.AccessibilityEvent;
61import android.view.accessibility.AccessibilityEventSource;
62import android.view.accessibility.AccessibilityManager;
63import android.view.accessibility.AccessibilityNodeInfo;
64import android.view.accessibility.AccessibilityNodeProvider;
65import android.view.animation.Animation;
66import android.view.animation.AnimationUtils;
67import android.view.animation.Transformation;
68import android.view.inputmethod.EditorInfo;
69import android.view.inputmethod.InputConnection;
70import android.view.inputmethod.InputMethodManager;
71import android.widget.ScrollBarDrawable;
72
73import static android.os.Build.VERSION_CODES.*;
74
75import com.android.internal.R;
76import com.android.internal.util.Predicate;
77import com.android.internal.view.menu.MenuBuilder;
78
79import java.lang.ref.WeakReference;
80import java.lang.reflect.InvocationTargetException;
81import java.lang.reflect.Method;
82import java.util.ArrayList;
83import java.util.Arrays;
84import java.util.Locale;
85import java.util.concurrent.CopyOnWriteArrayList;
86
87/**
88 * <p>
89 * This class represents the basic building block for user interface components. A View
90 * occupies a rectangular area on the screen and is responsible for drawing and
91 * event handling. View is the base class for <em>widgets</em>, which are
92 * used to create interactive UI components (buttons, text fields, etc.). The
93 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
94 * are invisible containers that hold other Views (or other ViewGroups) and define
95 * their layout properties.
96 * </p>
97 *
98 * <div class="special reference">
99 * <h3>Developer Guides</h3>
100 * <p>For information about using this class to develop your application's user interface,
101 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
102 * </div>
103 *
104 * <a name="Using"></a>
105 * <h3>Using Views</h3>
106 * <p>
107 * All of the views in a window are arranged in a single tree. You can add views
108 * either from code or by specifying a tree of views in one or more XML layout
109 * files. There are many specialized subclasses of views that act as controls or
110 * are capable of displaying text, images, or other content.
111 * </p>
112 * <p>
113 * Once you have created a tree of views, there are typically a few types of
114 * common operations you may wish to perform:
115 * <ul>
116 * <li><strong>Set properties:</strong> for example setting the text of a
117 * {@link android.widget.TextView}. The available properties and the methods
118 * that set them will vary among the different subclasses of views. Note that
119 * properties that are known at build time can be set in the XML layout
120 * files.</li>
121 * <li><strong>Set focus:</strong> The framework will handled moving focus in
122 * response to user input. To force focus to a specific view, call
123 * {@link #requestFocus}.</li>
124 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
125 * that will be notified when something interesting happens to the view. For
126 * example, all views will let you set a listener to be notified when the view
127 * gains or loses focus. You can register such a listener using
128 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
129 * Other view subclasses offer more specialized listeners. For example, a Button
130 * exposes a listener to notify clients when the button is clicked.</li>
131 * <li><strong>Set visibility:</strong> You can hide or show views using
132 * {@link #setVisibility(int)}.</li>
133 * </ul>
134 * </p>
135 * <p><em>
136 * Note: The Android framework is responsible for measuring, laying out and
137 * drawing views. You should not call methods that perform these actions on
138 * views yourself unless you are actually implementing a
139 * {@link android.view.ViewGroup}.
140 * </em></p>
141 *
142 * <a name="Lifecycle"></a>
143 * <h3>Implementing a Custom View</h3>
144 *
145 * <p>
146 * To implement a custom view, you will usually begin by providing overrides for
147 * some of the standard methods that the framework calls on all views. You do
148 * not need to override all of these methods. In fact, you can start by just
149 * overriding {@link #onDraw(android.graphics.Canvas)}.
150 * <table border="2" width="85%" align="center" cellpadding="5">
151 *     <thead>
152 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
153 *     </thead>
154 *
155 *     <tbody>
156 *     <tr>
157 *         <td rowspan="2">Creation</td>
158 *         <td>Constructors</td>
159 *         <td>There is a form of the constructor that are called when the view
160 *         is created from code and a form that is called when the view is
161 *         inflated from a layout file. The second form should parse and apply
162 *         any attributes defined in the layout file.
163 *         </td>
164 *     </tr>
165 *     <tr>
166 *         <td><code>{@link #onFinishInflate()}</code></td>
167 *         <td>Called after a view and all of its children has been inflated
168 *         from XML.</td>
169 *     </tr>
170 *
171 *     <tr>
172 *         <td rowspan="3">Layout</td>
173 *         <td><code>{@link #onMeasure(int, int)}</code></td>
174 *         <td>Called to determine the size requirements for this view and all
175 *         of its children.
176 *         </td>
177 *     </tr>
178 *     <tr>
179 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
180 *         <td>Called when this view should assign a size and position to all
181 *         of its children.
182 *         </td>
183 *     </tr>
184 *     <tr>
185 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
186 *         <td>Called when the size of this view has changed.
187 *         </td>
188 *     </tr>
189 *
190 *     <tr>
191 *         <td>Drawing</td>
192 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
193 *         <td>Called when the view should render its content.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td rowspan="4">Event processing</td>
199 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
200 *         <td>Called when a new key event occurs.
201 *         </td>
202 *     </tr>
203 *     <tr>
204 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
205 *         <td>Called when a key up event occurs.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
210 *         <td>Called when a trackball motion event occurs.
211 *         </td>
212 *     </tr>
213 *     <tr>
214 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
215 *         <td>Called when a touch screen motion event occurs.
216 *         </td>
217 *     </tr>
218 *
219 *     <tr>
220 *         <td rowspan="2">Focus</td>
221 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
222 *         <td>Called when the view gains or loses focus.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
228 *         <td>Called when the window containing the view gains or loses focus.
229 *         </td>
230 *     </tr>
231 *
232 *     <tr>
233 *         <td rowspan="3">Attaching</td>
234 *         <td><code>{@link #onAttachedToWindow()}</code></td>
235 *         <td>Called when the view is attached to a window.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td><code>{@link #onDetachedFromWindow}</code></td>
241 *         <td>Called when the view is detached from its window.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
247 *         <td>Called when the visibility of the window containing the view
248 *         has changed.
249 *         </td>
250 *     </tr>
251 *     </tbody>
252 *
253 * </table>
254 * </p>
255 *
256 * <a name="IDs"></a>
257 * <h3>IDs</h3>
258 * Views may have an integer id associated with them. These ids are typically
259 * assigned in the layout XML files, and are used to find specific views within
260 * the view tree. A common pattern is to:
261 * <ul>
262 * <li>Define a Button in the layout file and assign it a unique ID.
263 * <pre>
264 * &lt;Button
265 *     android:id="@+id/my_button"
266 *     android:layout_width="wrap_content"
267 *     android:layout_height="wrap_content"
268 *     android:text="@string/my_button_text"/&gt;
269 * </pre></li>
270 * <li>From the onCreate method of an Activity, find the Button
271 * <pre class="prettyprint">
272 *      Button myButton = (Button) findViewById(R.id.my_button);
273 * </pre></li>
274 * </ul>
275 * <p>
276 * View IDs need not be unique throughout the tree, but it is good practice to
277 * ensure that they are at least unique within the part of the tree you are
278 * searching.
279 * </p>
280 *
281 * <a name="Position"></a>
282 * <h3>Position</h3>
283 * <p>
284 * The geometry of a view is that of a rectangle. A view has a location,
285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
286 * two dimensions, expressed as a width and a height. The unit for location
287 * and dimensions is the pixel.
288 * </p>
289 *
290 * <p>
291 * It is possible to retrieve the location of a view by invoking the methods
292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
293 * coordinate of the rectangle representing the view. The latter returns the
294 * top, or Y, coordinate of the rectangle representing the view. These methods
295 * both return the location of the view relative to its parent. For instance,
296 * when getLeft() returns 20, that means the view is located 20 pixels to the
297 * right of the left edge of its direct parent.
298 * </p>
299 *
300 * <p>
301 * In addition, several convenience methods are offered to avoid unnecessary
302 * computations, namely {@link #getRight()} and {@link #getBottom()}.
303 * These methods return the coordinates of the right and bottom edges of the
304 * rectangle representing the view. For instance, calling {@link #getRight()}
305 * is similar to the following computation: <code>getLeft() + getWidth()</code>
306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
307 * </p>
308 *
309 * <a name="SizePaddingMargins"></a>
310 * <h3>Size, padding and margins</h3>
311 * <p>
312 * The size of a view is expressed with a width and a height. A view actually
313 * possess two pairs of width and height values.
314 * </p>
315 *
316 * <p>
317 * The first pair is known as <em>measured width</em> and
318 * <em>measured height</em>. These dimensions define how big a view wants to be
319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
321 * and {@link #getMeasuredHeight()}.
322 * </p>
323 *
324 * <p>
325 * The second pair is simply known as <em>width</em> and <em>height</em>, or
326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
327 * dimensions define the actual size of the view on screen, at drawing time and
328 * after layout. These values may, but do not have to, be different from the
329 * measured width and height. The width and height can be obtained by calling
330 * {@link #getWidth()} and {@link #getHeight()}.
331 * </p>
332 *
333 * <p>
334 * To measure its dimensions, a view takes into account its padding. The padding
335 * is expressed in pixels for the left, top, right and bottom parts of the view.
336 * Padding can be used to offset the content of the view by a specific amount of
337 * pixels. For instance, a left padding of 2 will push the view's content by
338 * 2 pixels to the right of the left edge. Padding can be set using the
339 * {@link #setPadding(int, int, int, int)} method and queried by calling
340 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
341 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
342 * </p>
343 *
344 * <p>
345 * Even though a view can define a padding, it does not provide any support for
346 * margins. However, view groups provide such a support. Refer to
347 * {@link android.view.ViewGroup} and
348 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
349 * </p>
350 *
351 * <a name="Layout"></a>
352 * <h3>Layout</h3>
353 * <p>
354 * Layout is a two pass process: a measure pass and a layout pass. The measuring
355 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
356 * of the view tree. Each view pushes dimension specifications down the tree
357 * during the recursion. At the end of the measure pass, every view has stored
358 * its measurements. The second pass happens in
359 * {@link #layout(int,int,int,int)} and is also top-down. During
360 * this pass each parent is responsible for positioning all of its children
361 * using the sizes computed in the measure pass.
362 * </p>
363 *
364 * <p>
365 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
366 * {@link #getMeasuredHeight()} values must be set, along with those for all of
367 * that view's descendants. A view's measured width and measured height values
368 * must respect the constraints imposed by the view's parents. This guarantees
369 * that at the end of the measure pass, all parents accept all of their
370 * children's measurements. A parent view may call measure() more than once on
371 * its children. For example, the parent may measure each child once with
372 * unspecified dimensions to find out how big they want to be, then call
373 * measure() on them again with actual numbers if the sum of all the children's
374 * unconstrained sizes is too big or too small.
375 * </p>
376 *
377 * <p>
378 * The measure pass uses two classes to communicate dimensions. The
379 * {@link MeasureSpec} class is used by views to tell their parents how they
380 * want to be measured and positioned. The base LayoutParams class just
381 * describes how big the view wants to be for both width and height. For each
382 * dimension, it can specify one of:
383 * <ul>
384 * <li> an exact number
385 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
386 * (minus padding)
387 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
388 * enclose its content (plus padding).
389 * </ul>
390 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
391 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
392 * an X and Y value.
393 * </p>
394 *
395 * <p>
396 * MeasureSpecs are used to push requirements down the tree from parent to
397 * child. A MeasureSpec can be in one of three modes:
398 * <ul>
399 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
400 * of a child view. For example, a LinearLayout may call measure() on its child
401 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
402 * tall the child view wants to be given a width of 240 pixels.
403 * <li>EXACTLY: This is used by the parent to impose an exact size on the
404 * child. The child must use this size, and guarantee that all of its
405 * descendants will fit within this size.
406 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
407 * child. The child must gurantee that it and all of its descendants will fit
408 * within this size.
409 * </ul>
410 * </p>
411 *
412 * <p>
413 * To intiate a layout, call {@link #requestLayout}. This method is typically
414 * called by a view on itself when it believes that is can no longer fit within
415 * its current bounds.
416 * </p>
417 *
418 * <a name="Drawing"></a>
419 * <h3>Drawing</h3>
420 * <p>
421 * Drawing is handled by walking the tree and rendering each view that
422 * intersects the invalid region. Because the tree is traversed in-order,
423 * this means that parents will draw before (i.e., behind) their children, with
424 * siblings drawn in the order they appear in the tree.
425 * If you set a background drawable for a View, then the View will draw it for you
426 * before calling back to its <code>onDraw()</code> method.
427 * </p>
428 *
429 * <p>
430 * Note that the framework will not draw views that are not in the invalid region.
431 * </p>
432 *
433 * <p>
434 * To force a view to draw, call {@link #invalidate()}.
435 * </p>
436 *
437 * <a name="EventHandlingThreading"></a>
438 * <h3>Event Handling and Threading</h3>
439 * <p>
440 * The basic cycle of a view is as follows:
441 * <ol>
442 * <li>An event comes in and is dispatched to the appropriate view. The view
443 * handles the event and notifies any listeners.</li>
444 * <li>If in the course of processing the event, the view's bounds may need
445 * to be changed, the view will call {@link #requestLayout()}.</li>
446 * <li>Similarly, if in the course of processing the event the view's appearance
447 * may need to be changed, the view will call {@link #invalidate()}.</li>
448 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
449 * the framework will take care of measuring, laying out, and drawing the tree
450 * as appropriate.</li>
451 * </ol>
452 * </p>
453 *
454 * <p><em>Note: The entire view tree is single threaded. You must always be on
455 * the UI thread when calling any method on any view.</em>
456 * If you are doing work on other threads and want to update the state of a view
457 * from that thread, you should use a {@link Handler}.
458 * </p>
459 *
460 * <a name="FocusHandling"></a>
461 * <h3>Focus Handling</h3>
462 * <p>
463 * The framework will handle routine focus movement in response to user input.
464 * This includes changing the focus as views are removed or hidden, or as new
465 * views become available. Views indicate their willingness to take focus
466 * through the {@link #isFocusable} method. To change whether a view can take
467 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
468 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
469 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
470 * </p>
471 * <p>
472 * Focus movement is based on an algorithm which finds the nearest neighbor in a
473 * given direction. In rare cases, the default algorithm may not match the
474 * intended behavior of the developer. In these situations, you can provide
475 * explicit overrides by using these XML attributes in the layout file:
476 * <pre>
477 * nextFocusDown
478 * nextFocusLeft
479 * nextFocusRight
480 * nextFocusUp
481 * </pre>
482 * </p>
483 *
484 *
485 * <p>
486 * To get a particular view to take focus, call {@link #requestFocus()}.
487 * </p>
488 *
489 * <a name="TouchMode"></a>
490 * <h3>Touch Mode</h3>
491 * <p>
492 * When a user is navigating a user interface via directional keys such as a D-pad, it is
493 * necessary to give focus to actionable items such as buttons so the user can see
494 * what will take input.  If the device has touch capabilities, however, and the user
495 * begins interacting with the interface by touching it, it is no longer necessary to
496 * always highlight, or give focus to, a particular view.  This motivates a mode
497 * for interaction named 'touch mode'.
498 * </p>
499 * <p>
500 * For a touch capable device, once the user touches the screen, the device
501 * will enter touch mode.  From this point onward, only views for which
502 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
503 * Other views that are touchable, like buttons, will not take focus when touched; they will
504 * only fire the on click listeners.
505 * </p>
506 * <p>
507 * Any time a user hits a directional key, such as a D-pad direction, the view device will
508 * exit touch mode, and find a view to take focus, so that the user may resume interacting
509 * with the user interface without touching the screen again.
510 * </p>
511 * <p>
512 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
513 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
514 * </p>
515 *
516 * <a name="Scrolling"></a>
517 * <h3>Scrolling</h3>
518 * <p>
519 * The framework provides basic support for views that wish to internally
520 * scroll their content. This includes keeping track of the X and Y scroll
521 * offset as well as mechanisms for drawing scrollbars. See
522 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
523 * {@link #awakenScrollBars()} for more details.
524 * </p>
525 *
526 * <a name="Tags"></a>
527 * <h3>Tags</h3>
528 * <p>
529 * Unlike IDs, tags are not used to identify views. Tags are essentially an
530 * extra piece of information that can be associated with a view. They are most
531 * often used as a convenience to store data related to views in the views
532 * themselves rather than by putting them in a separate structure.
533 * </p>
534 *
535 * <a name="Animation"></a>
536 * <h3>Animation</h3>
537 * <p>
538 * You can attach an {@link Animation} object to a view using
539 * {@link #setAnimation(Animation)} or
540 * {@link #startAnimation(Animation)}. The animation can alter the scale,
541 * rotation, translation and alpha of a view over time. If the animation is
542 * attached to a view that has children, the animation will affect the entire
543 * subtree rooted by that node. When an animation is started, the framework will
544 * take care of redrawing the appropriate views until the animation completes.
545 * </p>
546 * <p>
547 * Starting with Android 3.0, the preferred way of animating views is to use the
548 * {@link android.animation} package APIs.
549 * </p>
550 *
551 * <a name="Security"></a>
552 * <h3>Security</h3>
553 * <p>
554 * Sometimes it is essential that an application be able to verify that an action
555 * is being performed with the full knowledge and consent of the user, such as
556 * granting a permission request, making a purchase or clicking on an advertisement.
557 * Unfortunately, a malicious application could try to spoof the user into
558 * performing these actions, unaware, by concealing the intended purpose of the view.
559 * As a remedy, the framework offers a touch filtering mechanism that can be used to
560 * improve the security of views that provide access to sensitive functionality.
561 * </p><p>
562 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
563 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
564 * will discard touches that are received whenever the view's window is obscured by
565 * another visible window.  As a result, the view will not receive touches whenever a
566 * toast, dialog or other window appears above the view's window.
567 * </p><p>
568 * For more fine-grained control over security, consider overriding the
569 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
570 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
571 * </p>
572 *
573 * @attr ref android.R.styleable#View_alpha
574 * @attr ref android.R.styleable#View_background
575 * @attr ref android.R.styleable#View_clickable
576 * @attr ref android.R.styleable#View_contentDescription
577 * @attr ref android.R.styleable#View_drawingCacheQuality
578 * @attr ref android.R.styleable#View_duplicateParentState
579 * @attr ref android.R.styleable#View_id
580 * @attr ref android.R.styleable#View_requiresFadingEdge
581 * @attr ref android.R.styleable#View_fadingEdgeLength
582 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
583 * @attr ref android.R.styleable#View_fitsSystemWindows
584 * @attr ref android.R.styleable#View_isScrollContainer
585 * @attr ref android.R.styleable#View_focusable
586 * @attr ref android.R.styleable#View_focusableInTouchMode
587 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
588 * @attr ref android.R.styleable#View_keepScreenOn
589 * @attr ref android.R.styleable#View_layerType
590 * @attr ref android.R.styleable#View_longClickable
591 * @attr ref android.R.styleable#View_minHeight
592 * @attr ref android.R.styleable#View_minWidth
593 * @attr ref android.R.styleable#View_nextFocusDown
594 * @attr ref android.R.styleable#View_nextFocusLeft
595 * @attr ref android.R.styleable#View_nextFocusRight
596 * @attr ref android.R.styleable#View_nextFocusUp
597 * @attr ref android.R.styleable#View_onClick
598 * @attr ref android.R.styleable#View_padding
599 * @attr ref android.R.styleable#View_paddingBottom
600 * @attr ref android.R.styleable#View_paddingLeft
601 * @attr ref android.R.styleable#View_paddingRight
602 * @attr ref android.R.styleable#View_paddingTop
603 * @attr ref android.R.styleable#View_paddingStart
604 * @attr ref android.R.styleable#View_paddingEnd
605 * @attr ref android.R.styleable#View_saveEnabled
606 * @attr ref android.R.styleable#View_rotation
607 * @attr ref android.R.styleable#View_rotationX
608 * @attr ref android.R.styleable#View_rotationY
609 * @attr ref android.R.styleable#View_scaleX
610 * @attr ref android.R.styleable#View_scaleY
611 * @attr ref android.R.styleable#View_scrollX
612 * @attr ref android.R.styleable#View_scrollY
613 * @attr ref android.R.styleable#View_scrollbarSize
614 * @attr ref android.R.styleable#View_scrollbarStyle
615 * @attr ref android.R.styleable#View_scrollbars
616 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
617 * @attr ref android.R.styleable#View_scrollbarFadeDuration
618 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
619 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
620 * @attr ref android.R.styleable#View_scrollbarThumbVertical
621 * @attr ref android.R.styleable#View_scrollbarTrackVertical
622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
624 * @attr ref android.R.styleable#View_soundEffectsEnabled
625 * @attr ref android.R.styleable#View_tag
626 * @attr ref android.R.styleable#View_transformPivotX
627 * @attr ref android.R.styleable#View_transformPivotY
628 * @attr ref android.R.styleable#View_translationX
629 * @attr ref android.R.styleable#View_translationY
630 * @attr ref android.R.styleable#View_visibility
631 *
632 * @see android.view.ViewGroup
633 */
634public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
635        AccessibilityEventSource {
636    private static final boolean DBG = false;
637
638    /**
639     * The logging tag used by this class with android.util.Log.
640     */
641    protected static final String VIEW_LOG_TAG = "View";
642
643    /**
644     * Used to mark a View that has no ID.
645     */
646    public static final int NO_ID = -1;
647
648    /**
649     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
650     * calling setFlags.
651     */
652    private static final int NOT_FOCUSABLE = 0x00000000;
653
654    /**
655     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
656     * setFlags.
657     */
658    private static final int FOCUSABLE = 0x00000001;
659
660    /**
661     * Mask for use with setFlags indicating bits used for focus.
662     */
663    private static final int FOCUSABLE_MASK = 0x00000001;
664
665    /**
666     * This view will adjust its padding to fit sytem windows (e.g. status bar)
667     */
668    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
669
670    /**
671     * This view is visible.
672     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
673     * android:visibility}.
674     */
675    public static final int VISIBLE = 0x00000000;
676
677    /**
678     * This view is invisible, but it still takes up space for layout purposes.
679     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
680     * android:visibility}.
681     */
682    public static final int INVISIBLE = 0x00000004;
683
684    /**
685     * This view is invisible, and it doesn't take any space for layout
686     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
687     * android:visibility}.
688     */
689    public static final int GONE = 0x00000008;
690
691    /**
692     * Mask for use with setFlags indicating bits used for visibility.
693     * {@hide}
694     */
695    static final int VISIBILITY_MASK = 0x0000000C;
696
697    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
698
699    /**
700     * This view is enabled. Interpretation varies by subclass.
701     * Use with ENABLED_MASK when calling setFlags.
702     * {@hide}
703     */
704    static final int ENABLED = 0x00000000;
705
706    /**
707     * This view is disabled. Interpretation varies by subclass.
708     * Use with ENABLED_MASK when calling setFlags.
709     * {@hide}
710     */
711    static final int DISABLED = 0x00000020;
712
713   /**
714    * Mask for use with setFlags indicating bits used for indicating whether
715    * this view is enabled
716    * {@hide}
717    */
718    static final int ENABLED_MASK = 0x00000020;
719
720    /**
721     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
722     * called and further optimizations will be performed. It is okay to have
723     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
724     * {@hide}
725     */
726    static final int WILL_NOT_DRAW = 0x00000080;
727
728    /**
729     * Mask for use with setFlags indicating bits used for indicating whether
730     * this view is will draw
731     * {@hide}
732     */
733    static final int DRAW_MASK = 0x00000080;
734
735    /**
736     * <p>This view doesn't show scrollbars.</p>
737     * {@hide}
738     */
739    static final int SCROLLBARS_NONE = 0x00000000;
740
741    /**
742     * <p>This view shows horizontal scrollbars.</p>
743     * {@hide}
744     */
745    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
746
747    /**
748     * <p>This view shows vertical scrollbars.</p>
749     * {@hide}
750     */
751    static final int SCROLLBARS_VERTICAL = 0x00000200;
752
753    /**
754     * <p>Mask for use with setFlags indicating bits used for indicating which
755     * scrollbars are enabled.</p>
756     * {@hide}
757     */
758    static final int SCROLLBARS_MASK = 0x00000300;
759
760    /**
761     * Indicates that the view should filter touches when its window is obscured.
762     * Refer to the class comments for more information about this security feature.
763     * {@hide}
764     */
765    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
766
767    // note flag value 0x00000800 is now available for next flags...
768
769    /**
770     * <p>This view doesn't show fading edges.</p>
771     * {@hide}
772     */
773    static final int FADING_EDGE_NONE = 0x00000000;
774
775    /**
776     * <p>This view shows horizontal fading edges.</p>
777     * {@hide}
778     */
779    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
780
781    /**
782     * <p>This view shows vertical fading edges.</p>
783     * {@hide}
784     */
785    static final int FADING_EDGE_VERTICAL = 0x00002000;
786
787    /**
788     * <p>Mask for use with setFlags indicating bits used for indicating which
789     * fading edges are enabled.</p>
790     * {@hide}
791     */
792    static final int FADING_EDGE_MASK = 0x00003000;
793
794    /**
795     * <p>Indicates this view can be clicked. When clickable, a View reacts
796     * to clicks by notifying the OnClickListener.<p>
797     * {@hide}
798     */
799    static final int CLICKABLE = 0x00004000;
800
801    /**
802     * <p>Indicates this view is caching its drawing into a bitmap.</p>
803     * {@hide}
804     */
805    static final int DRAWING_CACHE_ENABLED = 0x00008000;
806
807    /**
808     * <p>Indicates that no icicle should be saved for this view.<p>
809     * {@hide}
810     */
811    static final int SAVE_DISABLED = 0x000010000;
812
813    /**
814     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
815     * property.</p>
816     * {@hide}
817     */
818    static final int SAVE_DISABLED_MASK = 0x000010000;
819
820    /**
821     * <p>Indicates that no drawing cache should ever be created for this view.<p>
822     * {@hide}
823     */
824    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
825
826    /**
827     * <p>Indicates this view can take / keep focus when int touch mode.</p>
828     * {@hide}
829     */
830    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
831
832    /**
833     * <p>Enables low quality mode for the drawing cache.</p>
834     */
835    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
836
837    /**
838     * <p>Enables high quality mode for the drawing cache.</p>
839     */
840    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
841
842    /**
843     * <p>Enables automatic quality mode for the drawing cache.</p>
844     */
845    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
846
847    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
848            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
849    };
850
851    /**
852     * <p>Mask for use with setFlags indicating bits used for the cache
853     * quality property.</p>
854     * {@hide}
855     */
856    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
857
858    /**
859     * <p>
860     * Indicates this view can be long clicked. When long clickable, a View
861     * reacts to long clicks by notifying the OnLongClickListener or showing a
862     * context menu.
863     * </p>
864     * {@hide}
865     */
866    static final int LONG_CLICKABLE = 0x00200000;
867
868    /**
869     * <p>Indicates that this view gets its drawable states from its direct parent
870     * and ignores its original internal states.</p>
871     *
872     * @hide
873     */
874    static final int DUPLICATE_PARENT_STATE = 0x00400000;
875
876    /**
877     * The scrollbar style to display the scrollbars inside the content area,
878     * without increasing the padding. The scrollbars will be overlaid with
879     * translucency on the view's content.
880     */
881    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
882
883    /**
884     * The scrollbar style to display the scrollbars inside the padded area,
885     * increasing the padding of the view. The scrollbars will not overlap the
886     * content area of the view.
887     */
888    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
889
890    /**
891     * The scrollbar style to display the scrollbars at the edge of the view,
892     * without increasing the padding. The scrollbars will be overlaid with
893     * translucency.
894     */
895    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
896
897    /**
898     * The scrollbar style to display the scrollbars at the edge of the view,
899     * increasing the padding of the view. The scrollbars will only overlap the
900     * background, if any.
901     */
902    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
903
904    /**
905     * Mask to check if the scrollbar style is overlay or inset.
906     * {@hide}
907     */
908    static final int SCROLLBARS_INSET_MASK = 0x01000000;
909
910    /**
911     * Mask to check if the scrollbar style is inside or outside.
912     * {@hide}
913     */
914    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
915
916    /**
917     * Mask for scrollbar style.
918     * {@hide}
919     */
920    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
921
922    /**
923     * View flag indicating that the screen should remain on while the
924     * window containing this view is visible to the user.  This effectively
925     * takes care of automatically setting the WindowManager's
926     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
927     */
928    public static final int KEEP_SCREEN_ON = 0x04000000;
929
930    /**
931     * View flag indicating whether this view should have sound effects enabled
932     * for events such as clicking and touching.
933     */
934    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
935
936    /**
937     * View flag indicating whether this view should have haptic feedback
938     * enabled for events such as long presses.
939     */
940    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
941
942    /**
943     * <p>Indicates that the view hierarchy should stop saving state when
944     * it reaches this view.  If state saving is initiated immediately at
945     * the view, it will be allowed.
946     * {@hide}
947     */
948    static final int PARENT_SAVE_DISABLED = 0x20000000;
949
950    /**
951     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
952     * {@hide}
953     */
954    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
955
956    /**
957     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
958     * should add all focusable Views regardless if they are focusable in touch mode.
959     */
960    public static final int FOCUSABLES_ALL = 0x00000000;
961
962    /**
963     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
964     * should add only Views focusable in touch mode.
965     */
966    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
967
968    /**
969     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
970     * item.
971     */
972    public static final int FOCUS_BACKWARD = 0x00000001;
973
974    /**
975     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
976     * item.
977     */
978    public static final int FOCUS_FORWARD = 0x00000002;
979
980    /**
981     * Use with {@link #focusSearch(int)}. Move focus to the left.
982     */
983    public static final int FOCUS_LEFT = 0x00000011;
984
985    /**
986     * Use with {@link #focusSearch(int)}. Move focus up.
987     */
988    public static final int FOCUS_UP = 0x00000021;
989
990    /**
991     * Use with {@link #focusSearch(int)}. Move focus to the right.
992     */
993    public static final int FOCUS_RIGHT = 0x00000042;
994
995    /**
996     * Use with {@link #focusSearch(int)}. Move focus down.
997     */
998    public static final int FOCUS_DOWN = 0x00000082;
999
1000    /**
1001     * Bits of {@link #getMeasuredWidthAndState()} and
1002     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1003     */
1004    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1005
1006    /**
1007     * Bits of {@link #getMeasuredWidthAndState()} and
1008     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1009     */
1010    public static final int MEASURED_STATE_MASK = 0xff000000;
1011
1012    /**
1013     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1014     * for functions that combine both width and height into a single int,
1015     * such as {@link #getMeasuredState()} and the childState argument of
1016     * {@link #resolveSizeAndState(int, int, int)}.
1017     */
1018    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1019
1020    /**
1021     * Bit of {@link #getMeasuredWidthAndState()} and
1022     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1023     * is smaller that the space the view would like to have.
1024     */
1025    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1026
1027    /**
1028     * Base View state sets
1029     */
1030    // Singles
1031    /**
1032     * Indicates the view has no states set. States are used with
1033     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1034     * view depending on its state.
1035     *
1036     * @see android.graphics.drawable.Drawable
1037     * @see #getDrawableState()
1038     */
1039    protected static final int[] EMPTY_STATE_SET;
1040    /**
1041     * Indicates the view is enabled. 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[] ENABLED_STATE_SET;
1049    /**
1050     * Indicates the view is focused. 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[] FOCUSED_STATE_SET;
1058    /**
1059     * Indicates the view is selected. 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[] SELECTED_STATE_SET;
1067    /**
1068     * Indicates the view is pressed. 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     * @hide
1075     */
1076    protected static final int[] PRESSED_STATE_SET;
1077    /**
1078     * Indicates the view's window has focus. States are used with
1079     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1080     * view depending on its state.
1081     *
1082     * @see android.graphics.drawable.Drawable
1083     * @see #getDrawableState()
1084     */
1085    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1086    // Doubles
1087    /**
1088     * Indicates the view is enabled and has the focus.
1089     *
1090     * @see #ENABLED_STATE_SET
1091     * @see #FOCUSED_STATE_SET
1092     */
1093    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1094    /**
1095     * Indicates the view is enabled and selected.
1096     *
1097     * @see #ENABLED_STATE_SET
1098     * @see #SELECTED_STATE_SET
1099     */
1100    protected static final int[] ENABLED_SELECTED_STATE_SET;
1101    /**
1102     * Indicates the view is enabled and that its window has focus.
1103     *
1104     * @see #ENABLED_STATE_SET
1105     * @see #WINDOW_FOCUSED_STATE_SET
1106     */
1107    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1108    /**
1109     * Indicates the view is focused and selected.
1110     *
1111     * @see #FOCUSED_STATE_SET
1112     * @see #SELECTED_STATE_SET
1113     */
1114    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1115    /**
1116     * Indicates the view has the focus and that its window has the focus.
1117     *
1118     * @see #FOCUSED_STATE_SET
1119     * @see #WINDOW_FOCUSED_STATE_SET
1120     */
1121    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1122    /**
1123     * Indicates the view is selected and that its window has the focus.
1124     *
1125     * @see #SELECTED_STATE_SET
1126     * @see #WINDOW_FOCUSED_STATE_SET
1127     */
1128    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1129    // Triples
1130    /**
1131     * Indicates the view is enabled, focused and selected.
1132     *
1133     * @see #ENABLED_STATE_SET
1134     * @see #FOCUSED_STATE_SET
1135     * @see #SELECTED_STATE_SET
1136     */
1137    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1138    /**
1139     * Indicates the view is enabled, focused and its window has the focus.
1140     *
1141     * @see #ENABLED_STATE_SET
1142     * @see #FOCUSED_STATE_SET
1143     * @see #WINDOW_FOCUSED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled, selected and its window has the focus.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #SELECTED_STATE_SET
1151     * @see #WINDOW_FOCUSED_STATE_SET
1152     */
1153    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1154    /**
1155     * Indicates the view is focused, selected and its window has the focus.
1156     *
1157     * @see #FOCUSED_STATE_SET
1158     * @see #SELECTED_STATE_SET
1159     * @see #WINDOW_FOCUSED_STATE_SET
1160     */
1161    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1162    /**
1163     * Indicates the view is enabled, focused, selected and its window
1164     * has the focus.
1165     *
1166     * @see #ENABLED_STATE_SET
1167     * @see #FOCUSED_STATE_SET
1168     * @see #SELECTED_STATE_SET
1169     * @see #WINDOW_FOCUSED_STATE_SET
1170     */
1171    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1172    /**
1173     * Indicates the view is pressed and its window has the focus.
1174     *
1175     * @see #PRESSED_STATE_SET
1176     * @see #WINDOW_FOCUSED_STATE_SET
1177     */
1178    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1179    /**
1180     * Indicates the view is pressed and selected.
1181     *
1182     * @see #PRESSED_STATE_SET
1183     * @see #SELECTED_STATE_SET
1184     */
1185    protected static final int[] PRESSED_SELECTED_STATE_SET;
1186    /**
1187     * Indicates the view is pressed, selected and its window has the focus.
1188     *
1189     * @see #PRESSED_STATE_SET
1190     * @see #SELECTED_STATE_SET
1191     * @see #WINDOW_FOCUSED_STATE_SET
1192     */
1193    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1194    /**
1195     * Indicates the view is pressed and focused.
1196     *
1197     * @see #PRESSED_STATE_SET
1198     * @see #FOCUSED_STATE_SET
1199     */
1200    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1201    /**
1202     * Indicates the view is pressed, focused and its window has the focus.
1203     *
1204     * @see #PRESSED_STATE_SET
1205     * @see #FOCUSED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1209    /**
1210     * Indicates the view is pressed, focused and selected.
1211     *
1212     * @see #PRESSED_STATE_SET
1213     * @see #SELECTED_STATE_SET
1214     * @see #FOCUSED_STATE_SET
1215     */
1216    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1217    /**
1218     * Indicates the view is pressed, focused, selected and its window has the focus.
1219     *
1220     * @see #PRESSED_STATE_SET
1221     * @see #FOCUSED_STATE_SET
1222     * @see #SELECTED_STATE_SET
1223     * @see #WINDOW_FOCUSED_STATE_SET
1224     */
1225    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1226    /**
1227     * Indicates the view is pressed and enabled.
1228     *
1229     * @see #PRESSED_STATE_SET
1230     * @see #ENABLED_STATE_SET
1231     */
1232    protected static final int[] PRESSED_ENABLED_STATE_SET;
1233    /**
1234     * Indicates the view is pressed, enabled and its window has the focus.
1235     *
1236     * @see #PRESSED_STATE_SET
1237     * @see #ENABLED_STATE_SET
1238     * @see #WINDOW_FOCUSED_STATE_SET
1239     */
1240    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1241    /**
1242     * Indicates the view is pressed, enabled and selected.
1243     *
1244     * @see #PRESSED_STATE_SET
1245     * @see #ENABLED_STATE_SET
1246     * @see #SELECTED_STATE_SET
1247     */
1248    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1249    /**
1250     * Indicates the view is pressed, enabled, selected and its window has the
1251     * focus.
1252     *
1253     * @see #PRESSED_STATE_SET
1254     * @see #ENABLED_STATE_SET
1255     * @see #SELECTED_STATE_SET
1256     * @see #WINDOW_FOCUSED_STATE_SET
1257     */
1258    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1259    /**
1260     * Indicates the view is pressed, enabled and focused.
1261     *
1262     * @see #PRESSED_STATE_SET
1263     * @see #ENABLED_STATE_SET
1264     * @see #FOCUSED_STATE_SET
1265     */
1266    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1267    /**
1268     * Indicates the view is pressed, enabled, focused and its window has the
1269     * focus.
1270     *
1271     * @see #PRESSED_STATE_SET
1272     * @see #ENABLED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed, enabled, focused and selected.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #ENABLED_STATE_SET
1282     * @see #SELECTED_STATE_SET
1283     * @see #FOCUSED_STATE_SET
1284     */
1285    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1286    /**
1287     * Indicates the view is pressed, enabled, focused, selected and its window
1288     * has the focus.
1289     *
1290     * @see #PRESSED_STATE_SET
1291     * @see #ENABLED_STATE_SET
1292     * @see #SELECTED_STATE_SET
1293     * @see #FOCUSED_STATE_SET
1294     * @see #WINDOW_FOCUSED_STATE_SET
1295     */
1296    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1297
1298    /**
1299     * The order here is very important to {@link #getDrawableState()}
1300     */
1301    private static final int[][] VIEW_STATE_SETS;
1302
1303    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1304    static final int VIEW_STATE_SELECTED = 1 << 1;
1305    static final int VIEW_STATE_FOCUSED = 1 << 2;
1306    static final int VIEW_STATE_ENABLED = 1 << 3;
1307    static final int VIEW_STATE_PRESSED = 1 << 4;
1308    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1309    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1310    static final int VIEW_STATE_HOVERED = 1 << 7;
1311    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1312    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1313
1314    static final int[] VIEW_STATE_IDS = new int[] {
1315        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1316        R.attr.state_selected,          VIEW_STATE_SELECTED,
1317        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1318        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1319        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1320        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1321        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1322        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1323        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1324        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1325    };
1326
1327    static {
1328        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1329            throw new IllegalStateException(
1330                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1331        }
1332        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1333        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1334            int viewState = R.styleable.ViewDrawableStates[i];
1335            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1336                if (VIEW_STATE_IDS[j] == viewState) {
1337                    orderedIds[i * 2] = viewState;
1338                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1339                }
1340            }
1341        }
1342        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1343        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1344        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1345            int numBits = Integer.bitCount(i);
1346            int[] set = new int[numBits];
1347            int pos = 0;
1348            for (int j = 0; j < orderedIds.length; j += 2) {
1349                if ((i & orderedIds[j+1]) != 0) {
1350                    set[pos++] = orderedIds[j];
1351                }
1352            }
1353            VIEW_STATE_SETS[i] = set;
1354        }
1355
1356        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1357        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1358        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1359        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1360                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1361        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1362        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1363                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1364        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1365                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1366        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1367                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1368                | VIEW_STATE_FOCUSED];
1369        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1370        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1371                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1372        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1373                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1374        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1375                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1376                | VIEW_STATE_ENABLED];
1377        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1378                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1379        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1380                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1381                | VIEW_STATE_ENABLED];
1382        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1383                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1384                | VIEW_STATE_ENABLED];
1385        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1386                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1387                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1388
1389        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1390        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1391                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1392        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1393                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1394        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1395                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1396                | VIEW_STATE_PRESSED];
1397        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1398                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1399        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1400                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1401                | VIEW_STATE_PRESSED];
1402        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1403                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1404                | VIEW_STATE_PRESSED];
1405        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1406                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1407                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1408        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1409                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1410        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1412                | VIEW_STATE_PRESSED];
1413        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1415                | VIEW_STATE_PRESSED];
1416        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1418                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1419        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1421                | VIEW_STATE_PRESSED];
1422        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1424                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1425        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1427                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1428        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1430                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1431                | VIEW_STATE_PRESSED];
1432    }
1433
1434    /**
1435     * Accessibility event types that are dispatched for text population.
1436     */
1437    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1438            AccessibilityEvent.TYPE_VIEW_CLICKED
1439            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1440            | AccessibilityEvent.TYPE_VIEW_SELECTED
1441            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1442            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1443            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1444            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1445            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1446            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
1447
1448    /**
1449     * Temporary Rect currently for use in setBackground().  This will probably
1450     * be extended in the future to hold our own class with more than just
1451     * a Rect. :)
1452     */
1453    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1454
1455    /**
1456     * Map used to store views' tags.
1457     */
1458    private SparseArray<Object> mKeyedTags;
1459
1460    /**
1461     * The next available accessiiblity id.
1462     */
1463    private static int sNextAccessibilityViewId;
1464
1465    /**
1466     * The animation currently associated with this view.
1467     * @hide
1468     */
1469    protected Animation mCurrentAnimation = null;
1470
1471    /**
1472     * Width as measured during measure pass.
1473     * {@hide}
1474     */
1475    @ViewDebug.ExportedProperty(category = "measurement")
1476    int mMeasuredWidth;
1477
1478    /**
1479     * Height as measured during measure pass.
1480     * {@hide}
1481     */
1482    @ViewDebug.ExportedProperty(category = "measurement")
1483    int mMeasuredHeight;
1484
1485    /**
1486     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1487     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1488     * its display list. This flag, used only when hw accelerated, allows us to clear the
1489     * flag while retaining this information until it's needed (at getDisplayList() time and
1490     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1491     *
1492     * {@hide}
1493     */
1494    boolean mRecreateDisplayList = false;
1495
1496    /**
1497     * The view's identifier.
1498     * {@hide}
1499     *
1500     * @see #setId(int)
1501     * @see #getId()
1502     */
1503    @ViewDebug.ExportedProperty(resolveId = true)
1504    int mID = NO_ID;
1505
1506    /**
1507     * The stable ID of this view for accessibility purposes.
1508     */
1509    int mAccessibilityViewId = NO_ID;
1510
1511    /**
1512     * The view's tag.
1513     * {@hide}
1514     *
1515     * @see #setTag(Object)
1516     * @see #getTag()
1517     */
1518    protected Object mTag;
1519
1520    // for mPrivateFlags:
1521    /** {@hide} */
1522    static final int WANTS_FOCUS                    = 0x00000001;
1523    /** {@hide} */
1524    static final int FOCUSED                        = 0x00000002;
1525    /** {@hide} */
1526    static final int SELECTED                       = 0x00000004;
1527    /** {@hide} */
1528    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1529    /** {@hide} */
1530    static final int HAS_BOUNDS                     = 0x00000010;
1531    /** {@hide} */
1532    static final int DRAWN                          = 0x00000020;
1533    /**
1534     * When this flag is set, this view is running an animation on behalf of its
1535     * children and should therefore not cancel invalidate requests, even if they
1536     * lie outside of this view's bounds.
1537     *
1538     * {@hide}
1539     */
1540    static final int DRAW_ANIMATION                 = 0x00000040;
1541    /** {@hide} */
1542    static final int SKIP_DRAW                      = 0x00000080;
1543    /** {@hide} */
1544    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1545    /** {@hide} */
1546    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1547    /** {@hide} */
1548    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1549    /** {@hide} */
1550    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1551    /** {@hide} */
1552    static final int FORCE_LAYOUT                   = 0x00001000;
1553    /** {@hide} */
1554    static final int LAYOUT_REQUIRED                = 0x00002000;
1555
1556    private static final int PRESSED                = 0x00004000;
1557
1558    /** {@hide} */
1559    static final int DRAWING_CACHE_VALID            = 0x00008000;
1560    /**
1561     * Flag used to indicate that this view should be drawn once more (and only once
1562     * more) after its animation has completed.
1563     * {@hide}
1564     */
1565    static final int ANIMATION_STARTED              = 0x00010000;
1566
1567    private static final int SAVE_STATE_CALLED      = 0x00020000;
1568
1569    /**
1570     * Indicates that the View returned true when onSetAlpha() was called and that
1571     * the alpha must be restored.
1572     * {@hide}
1573     */
1574    static final int ALPHA_SET                      = 0x00040000;
1575
1576    /**
1577     * Set by {@link #setScrollContainer(boolean)}.
1578     */
1579    static final int SCROLL_CONTAINER               = 0x00080000;
1580
1581    /**
1582     * Set by {@link #setScrollContainer(boolean)}.
1583     */
1584    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1585
1586    /**
1587     * View flag indicating whether this view was invalidated (fully or partially.)
1588     *
1589     * @hide
1590     */
1591    static final int DIRTY                          = 0x00200000;
1592
1593    /**
1594     * View flag indicating whether this view was invalidated by an opaque
1595     * invalidate request.
1596     *
1597     * @hide
1598     */
1599    static final int DIRTY_OPAQUE                   = 0x00400000;
1600
1601    /**
1602     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1603     *
1604     * @hide
1605     */
1606    static final int DIRTY_MASK                     = 0x00600000;
1607
1608    /**
1609     * Indicates whether the background is opaque.
1610     *
1611     * @hide
1612     */
1613    static final int OPAQUE_BACKGROUND              = 0x00800000;
1614
1615    /**
1616     * Indicates whether the scrollbars are opaque.
1617     *
1618     * @hide
1619     */
1620    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1621
1622    /**
1623     * Indicates whether the view is opaque.
1624     *
1625     * @hide
1626     */
1627    static final int OPAQUE_MASK                    = 0x01800000;
1628
1629    /**
1630     * Indicates a prepressed state;
1631     * the short time between ACTION_DOWN and recognizing
1632     * a 'real' press. Prepressed is used to recognize quick taps
1633     * even when they are shorter than ViewConfiguration.getTapTimeout().
1634     *
1635     * @hide
1636     */
1637    private static final int PREPRESSED             = 0x02000000;
1638
1639    /**
1640     * Indicates whether the view is temporarily detached.
1641     *
1642     * @hide
1643     */
1644    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1645
1646    /**
1647     * Indicates that we should awaken scroll bars once attached
1648     *
1649     * @hide
1650     */
1651    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1652
1653    /**
1654     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1655     * @hide
1656     */
1657    private static final int HOVERED              = 0x10000000;
1658
1659    /**
1660     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1661     * for transform operations
1662     *
1663     * @hide
1664     */
1665    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1666
1667    /** {@hide} */
1668    static final int ACTIVATED                    = 0x40000000;
1669
1670    /**
1671     * Indicates that this view was specifically invalidated, not just dirtied because some
1672     * child view was invalidated. The flag is used to determine when we need to recreate
1673     * a view's display list (as opposed to just returning a reference to its existing
1674     * display list).
1675     *
1676     * @hide
1677     */
1678    static final int INVALIDATED                  = 0x80000000;
1679
1680    /* Masks for mPrivateFlags2 */
1681
1682    /**
1683     * Indicates that this view has reported that it can accept the current drag's content.
1684     * Cleared when the drag operation concludes.
1685     * @hide
1686     */
1687    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1688
1689    /**
1690     * Indicates that this view is currently directly under the drag location in a
1691     * drag-and-drop operation involving content that it can accept.  Cleared when
1692     * the drag exits the view, or when the drag operation concludes.
1693     * @hide
1694     */
1695    static final int DRAG_HOVERED                 = 0x00000002;
1696
1697    /**
1698     * Horizontal layout direction of this view is from Left to Right.
1699     * Use with {@link #setLayoutDirection}.
1700     */
1701    public static final int LAYOUT_DIRECTION_LTR = 0;
1702
1703    /**
1704     * Horizontal layout direction of this view is from Right to Left.
1705     * Use with {@link #setLayoutDirection}.
1706     */
1707    public static final int LAYOUT_DIRECTION_RTL = 1;
1708
1709    /**
1710     * Horizontal layout direction of this view is inherited from its parent.
1711     * Use with {@link #setLayoutDirection}.
1712     */
1713    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1714
1715    /**
1716     * Horizontal layout direction of this view is from deduced from the default language
1717     * script for the locale. Use with {@link #setLayoutDirection}.
1718     */
1719    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1720
1721    /**
1722     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1723     * @hide
1724     */
1725    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1726
1727    /**
1728     * Mask for use with private flags indicating bits used for horizontal layout direction.
1729     * @hide
1730     */
1731    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1732
1733    /**
1734     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1735     * right-to-left direction.
1736     * @hide
1737     */
1738    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1739
1740    /**
1741     * Indicates whether the view horizontal layout direction has been resolved.
1742     * @hide
1743     */
1744    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1745
1746    /**
1747     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1748     * @hide
1749     */
1750    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1751
1752    /*
1753     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1754     * flag value.
1755     * @hide
1756     */
1757    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1758            LAYOUT_DIRECTION_LTR,
1759            LAYOUT_DIRECTION_RTL,
1760            LAYOUT_DIRECTION_INHERIT,
1761            LAYOUT_DIRECTION_LOCALE
1762    };
1763
1764    /**
1765     * Default horizontal layout direction.
1766     * @hide
1767     */
1768    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1769
1770
1771    /**
1772     * Indicates that the view is tracking some sort of transient state
1773     * that the app should not need to be aware of, but that the framework
1774     * should take special care to preserve.
1775     *
1776     * @hide
1777     */
1778    static final int HAS_TRANSIENT_STATE = 0x00000100;
1779
1780
1781    /**
1782     * Text direction is inherited thru {@link ViewGroup}
1783     */
1784    public static final int TEXT_DIRECTION_INHERIT = 0;
1785
1786    /**
1787     * Text direction is using "first strong algorithm". The first strong directional character
1788     * determines the paragraph direction. If there is no strong directional character, the
1789     * paragraph direction is the view's resolved layout direction.
1790     */
1791    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1792
1793    /**
1794     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1795     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1796     * If there are neither, the paragraph direction is the view's resolved layout direction.
1797     */
1798    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1799
1800    /**
1801     * Text direction is forced to LTR.
1802     */
1803    public static final int TEXT_DIRECTION_LTR = 3;
1804
1805    /**
1806     * Text direction is forced to RTL.
1807     */
1808    public static final int TEXT_DIRECTION_RTL = 4;
1809
1810    /**
1811     * Text direction is coming from the system Locale.
1812     */
1813    public static final int TEXT_DIRECTION_LOCALE = 5;
1814
1815    /**
1816     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1817     * @hide
1818     */
1819    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1820
1821    /**
1822     * Default text direction is inherited
1823     */
1824    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1825
1826    /**
1827     * Mask for use with private flags indicating bits used for text direction.
1828     * @hide
1829     */
1830    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1831
1832    /**
1833     * Array of text direction flags for mapping attribute "textDirection" to correct
1834     * flag value.
1835     * @hide
1836     */
1837    private static final int[] TEXT_DIRECTION_FLAGS = {
1838            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1839            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1840            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1841            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1842            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1843            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1844    };
1845
1846    /**
1847     * Indicates whether the view text direction has been resolved.
1848     * @hide
1849     */
1850    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1851
1852    /**
1853     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1854     * @hide
1855     */
1856    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1857
1858    /**
1859     * Mask for use with private flags indicating bits used for resolved text direction.
1860     * @hide
1861     */
1862    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1863
1864    /**
1865     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1866     * @hide
1867     */
1868    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1869            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1870
1871
1872    /* End of masks for mPrivateFlags2 */
1873
1874    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1875
1876    /**
1877     * Always allow a user to over-scroll this view, provided it is a
1878     * view that can scroll.
1879     *
1880     * @see #getOverScrollMode()
1881     * @see #setOverScrollMode(int)
1882     */
1883    public static final int OVER_SCROLL_ALWAYS = 0;
1884
1885    /**
1886     * Allow a user to over-scroll this view only if the content is large
1887     * enough to meaningfully scroll, provided it is a view that can scroll.
1888     *
1889     * @see #getOverScrollMode()
1890     * @see #setOverScrollMode(int)
1891     */
1892    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1893
1894    /**
1895     * Never allow a user to over-scroll this view.
1896     *
1897     * @see #getOverScrollMode()
1898     * @see #setOverScrollMode(int)
1899     */
1900    public static final int OVER_SCROLL_NEVER = 2;
1901
1902    /**
1903     * View has requested the system UI (status bar) to be visible (the default).
1904     *
1905     * @see #setSystemUiVisibility(int)
1906     */
1907    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1908
1909    /**
1910     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1911     *
1912     * This is for use in games, book readers, video players, or any other "immersive" application
1913     * where the usual system chrome is deemed too distracting.
1914     *
1915     * In low profile mode, the status bar and/or navigation icons may dim.
1916     *
1917     * @see #setSystemUiVisibility(int)
1918     */
1919    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1920
1921    /**
1922     * View has requested that the system navigation be temporarily hidden.
1923     *
1924     * This is an even less obtrusive state than that called for by
1925     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1926     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1927     * those to disappear. This is useful (in conjunction with the
1928     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1929     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1930     * window flags) for displaying content using every last pixel on the display.
1931     *
1932     * There is a limitation: because navigation controls are so important, the least user
1933     * interaction will cause them to reappear immediately.
1934     *
1935     * @see #setSystemUiVisibility(int)
1936     */
1937    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1938
1939    /**
1940     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1941     */
1942    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1943
1944    /**
1945     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1946     */
1947    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1948
1949    /**
1950     * @hide
1951     *
1952     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1953     * out of the public fields to keep the undefined bits out of the developer's way.
1954     *
1955     * Flag to make the status bar not expandable.  Unless you also
1956     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1957     */
1958    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1959
1960    /**
1961     * @hide
1962     *
1963     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1964     * out of the public fields to keep the undefined bits out of the developer's way.
1965     *
1966     * Flag to hide notification icons and scrolling ticker text.
1967     */
1968    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1969
1970    /**
1971     * @hide
1972     *
1973     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1974     * out of the public fields to keep the undefined bits out of the developer's way.
1975     *
1976     * Flag to disable incoming notification alerts.  This will not block
1977     * icons, but it will block sound, vibrating and other visual or aural notifications.
1978     */
1979    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1980
1981    /**
1982     * @hide
1983     *
1984     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1985     * out of the public fields to keep the undefined bits out of the developer's way.
1986     *
1987     * Flag to hide only the scrolling ticker.  Note that
1988     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1989     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1990     */
1991    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1992
1993    /**
1994     * @hide
1995     *
1996     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1997     * out of the public fields to keep the undefined bits out of the developer's way.
1998     *
1999     * Flag to hide the center system info area.
2000     */
2001    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2002
2003    /**
2004     * @hide
2005     *
2006     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2007     * out of the public fields to keep the undefined bits out of the developer's way.
2008     *
2009     * Flag to hide only the home button.  Don't use this
2010     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2011     */
2012    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2013
2014    /**
2015     * @hide
2016     *
2017     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2018     * out of the public fields to keep the undefined bits out of the developer's way.
2019     *
2020     * Flag to hide only the back button. Don't use this
2021     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2022     */
2023    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2024
2025    /**
2026     * @hide
2027     *
2028     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2029     * out of the public fields to keep the undefined bits out of the developer's way.
2030     *
2031     * Flag to hide only the clock.  You might use this if your activity has
2032     * its own clock making the status bar's clock redundant.
2033     */
2034    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2035
2036    /**
2037     * @hide
2038     *
2039     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2040     * out of the public fields to keep the undefined bits out of the developer's way.
2041     *
2042     * Flag to hide only the recent apps button. Don't use this
2043     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2044     */
2045    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2046
2047    /**
2048     * @hide
2049     *
2050     * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc.
2051     *
2052     * This hides HOME and RECENT and is provided for compatibility with interim implementations.
2053     */
2054    @Deprecated
2055    public static final int STATUS_BAR_DISABLE_NAVIGATION =
2056            STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT;
2057
2058    /**
2059     * @hide
2060     */
2061    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2062
2063    /**
2064     * These are the system UI flags that can be cleared by events outside
2065     * of an application.  Currently this is just the ability to tap on the
2066     * screen while hiding the navigation bar to have it return.
2067     * @hide
2068     */
2069    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2070            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
2071
2072    /**
2073     * Find views that render the specified text.
2074     *
2075     * @see #findViewsWithText(ArrayList, CharSequence, int)
2076     */
2077    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2078
2079    /**
2080     * Find find views that contain the specified content description.
2081     *
2082     * @see #findViewsWithText(ArrayList, CharSequence, int)
2083     */
2084    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2085
2086    /**
2087     * Find views that contain {@link AccessibilityNodeProvider}. Such
2088     * a View is a root of virtual view hierarchy and may contain the searched
2089     * text. If this flag is set Views with providers are automatically
2090     * added and it is a responsibility of the client to call the APIs of
2091     * the provider to determine whether the virtual tree rooted at this View
2092     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2093     * represeting the virtual views with this text.
2094     *
2095     * @see #findViewsWithText(ArrayList, CharSequence, int)
2096     *
2097     * @hide
2098     */
2099    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2100
2101    /**
2102     * Indicates that the screen has changed state and is now off.
2103     *
2104     * @see #onScreenStateChanged(int)
2105     */
2106    public static final int SCREEN_STATE_OFF = 0x0;
2107
2108    /**
2109     * Indicates that the screen has changed state and is now on.
2110     *
2111     * @see #onScreenStateChanged(int)
2112     */
2113    public static final int SCREEN_STATE_ON = 0x1;
2114
2115    /**
2116     * Controls the over-scroll mode for this view.
2117     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2118     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2119     * and {@link #OVER_SCROLL_NEVER}.
2120     */
2121    private int mOverScrollMode;
2122
2123    /**
2124     * The parent this view is attached to.
2125     * {@hide}
2126     *
2127     * @see #getParent()
2128     */
2129    protected ViewParent mParent;
2130
2131    /**
2132     * {@hide}
2133     */
2134    AttachInfo mAttachInfo;
2135
2136    /**
2137     * {@hide}
2138     */
2139    @ViewDebug.ExportedProperty(flagMapping = {
2140        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2141                name = "FORCE_LAYOUT"),
2142        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2143                name = "LAYOUT_REQUIRED"),
2144        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2145            name = "DRAWING_CACHE_INVALID", outputIf = false),
2146        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2147        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2148        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2149        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2150    })
2151    int mPrivateFlags;
2152    int mPrivateFlags2;
2153
2154    /**
2155     * This view's request for the visibility of the status bar.
2156     * @hide
2157     */
2158    @ViewDebug.ExportedProperty(flagMapping = {
2159        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2160                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2161                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2162        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2163                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2164                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2165        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2166                                equals = SYSTEM_UI_FLAG_VISIBLE,
2167                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2168    })
2169    int mSystemUiVisibility;
2170
2171    /**
2172     * Count of how many windows this view has been attached to.
2173     */
2174    int mWindowAttachCount;
2175
2176    /**
2177     * The layout parameters associated with this view and used by the parent
2178     * {@link android.view.ViewGroup} to determine how this view should be
2179     * laid out.
2180     * {@hide}
2181     */
2182    protected ViewGroup.LayoutParams mLayoutParams;
2183
2184    /**
2185     * The view flags hold various views states.
2186     * {@hide}
2187     */
2188    @ViewDebug.ExportedProperty
2189    int mViewFlags;
2190
2191    static class TransformationInfo {
2192        /**
2193         * The transform matrix for the View. This transform is calculated internally
2194         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2195         * is used by default. Do *not* use this variable directly; instead call
2196         * getMatrix(), which will automatically recalculate the matrix if necessary
2197         * to get the correct matrix based on the latest rotation and scale properties.
2198         */
2199        private final Matrix mMatrix = new Matrix();
2200
2201        /**
2202         * The transform matrix for the View. This transform is calculated internally
2203         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2204         * is used by default. Do *not* use this variable directly; instead call
2205         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2206         * to get the correct matrix based on the latest rotation and scale properties.
2207         */
2208        private Matrix mInverseMatrix;
2209
2210        /**
2211         * An internal variable that tracks whether we need to recalculate the
2212         * transform matrix, based on whether the rotation or scaleX/Y properties
2213         * have changed since the matrix was last calculated.
2214         */
2215        boolean mMatrixDirty = false;
2216
2217        /**
2218         * An internal variable that tracks whether we need to recalculate the
2219         * transform matrix, based on whether the rotation or scaleX/Y properties
2220         * have changed since the matrix was last calculated.
2221         */
2222        private boolean mInverseMatrixDirty = true;
2223
2224        /**
2225         * A variable that tracks whether we need to recalculate the
2226         * transform matrix, based on whether the rotation or scaleX/Y properties
2227         * have changed since the matrix was last calculated. This variable
2228         * is only valid after a call to updateMatrix() or to a function that
2229         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2230         */
2231        private boolean mMatrixIsIdentity = true;
2232
2233        /**
2234         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2235         */
2236        private Camera mCamera = null;
2237
2238        /**
2239         * This matrix is used when computing the matrix for 3D rotations.
2240         */
2241        private Matrix matrix3D = null;
2242
2243        /**
2244         * These prev values are used to recalculate a centered pivot point when necessary. The
2245         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2246         * set), so thes values are only used then as well.
2247         */
2248        private int mPrevWidth = -1;
2249        private int mPrevHeight = -1;
2250
2251        /**
2252         * The degrees rotation around the vertical axis through the pivot point.
2253         */
2254        @ViewDebug.ExportedProperty
2255        float mRotationY = 0f;
2256
2257        /**
2258         * The degrees rotation around the horizontal axis through the pivot point.
2259         */
2260        @ViewDebug.ExportedProperty
2261        float mRotationX = 0f;
2262
2263        /**
2264         * The degrees rotation around the pivot point.
2265         */
2266        @ViewDebug.ExportedProperty
2267        float mRotation = 0f;
2268
2269        /**
2270         * The amount of translation of the object away from its left property (post-layout).
2271         */
2272        @ViewDebug.ExportedProperty
2273        float mTranslationX = 0f;
2274
2275        /**
2276         * The amount of translation of the object away from its top property (post-layout).
2277         */
2278        @ViewDebug.ExportedProperty
2279        float mTranslationY = 0f;
2280
2281        /**
2282         * The amount of scale in the x direction around the pivot point. A
2283         * value of 1 means no scaling is applied.
2284         */
2285        @ViewDebug.ExportedProperty
2286        float mScaleX = 1f;
2287
2288        /**
2289         * The amount of scale in the y direction around the pivot point. A
2290         * value of 1 means no scaling is applied.
2291         */
2292        @ViewDebug.ExportedProperty
2293        float mScaleY = 1f;
2294
2295        /**
2296         * The x location of the point around which the view is rotated and scaled.
2297         */
2298        @ViewDebug.ExportedProperty
2299        float mPivotX = 0f;
2300
2301        /**
2302         * The y location of the point around which the view is rotated and scaled.
2303         */
2304        @ViewDebug.ExportedProperty
2305        float mPivotY = 0f;
2306
2307        /**
2308         * The opacity of the View. This is a value from 0 to 1, where 0 means
2309         * completely transparent and 1 means completely opaque.
2310         */
2311        @ViewDebug.ExportedProperty
2312        float mAlpha = 1f;
2313    }
2314
2315    TransformationInfo mTransformationInfo;
2316
2317    private boolean mLastIsOpaque;
2318
2319    /**
2320     * Convenience value to check for float values that are close enough to zero to be considered
2321     * zero.
2322     */
2323    private static final float NONZERO_EPSILON = .001f;
2324
2325    /**
2326     * The distance in pixels from the left edge of this view's parent
2327     * to the left edge of this view.
2328     * {@hide}
2329     */
2330    @ViewDebug.ExportedProperty(category = "layout")
2331    protected int mLeft;
2332    /**
2333     * The distance in pixels from the left edge of this view's parent
2334     * to the right edge of this view.
2335     * {@hide}
2336     */
2337    @ViewDebug.ExportedProperty(category = "layout")
2338    protected int mRight;
2339    /**
2340     * The distance in pixels from the top edge of this view's parent
2341     * to the top edge of this view.
2342     * {@hide}
2343     */
2344    @ViewDebug.ExportedProperty(category = "layout")
2345    protected int mTop;
2346    /**
2347     * The distance in pixels from the top edge of this view's parent
2348     * to the bottom edge of this view.
2349     * {@hide}
2350     */
2351    @ViewDebug.ExportedProperty(category = "layout")
2352    protected int mBottom;
2353
2354    /**
2355     * The offset, in pixels, by which the content of this view is scrolled
2356     * horizontally.
2357     * {@hide}
2358     */
2359    @ViewDebug.ExportedProperty(category = "scrolling")
2360    protected int mScrollX;
2361    /**
2362     * The offset, in pixels, by which the content of this view is scrolled
2363     * vertically.
2364     * {@hide}
2365     */
2366    @ViewDebug.ExportedProperty(category = "scrolling")
2367    protected int mScrollY;
2368
2369    /**
2370     * The left padding in pixels, that is the distance in pixels between the
2371     * left edge of this view and the left edge of its content.
2372     * {@hide}
2373     */
2374    @ViewDebug.ExportedProperty(category = "padding")
2375    protected int mPaddingLeft;
2376    /**
2377     * The right padding in pixels, that is the distance in pixels between the
2378     * right edge of this view and the right edge of its content.
2379     * {@hide}
2380     */
2381    @ViewDebug.ExportedProperty(category = "padding")
2382    protected int mPaddingRight;
2383    /**
2384     * The top padding in pixels, that is the distance in pixels between the
2385     * top edge of this view and the top edge of its content.
2386     * {@hide}
2387     */
2388    @ViewDebug.ExportedProperty(category = "padding")
2389    protected int mPaddingTop;
2390    /**
2391     * The bottom padding in pixels, that is the distance in pixels between the
2392     * bottom edge of this view and the bottom edge of its content.
2393     * {@hide}
2394     */
2395    @ViewDebug.ExportedProperty(category = "padding")
2396    protected int mPaddingBottom;
2397
2398    /**
2399     * Briefly describes the view and is primarily used for accessibility support.
2400     */
2401    private CharSequence mContentDescription;
2402
2403    /**
2404     * Cache the paddingRight set by the user to append to the scrollbar's size.
2405     *
2406     * @hide
2407     */
2408    @ViewDebug.ExportedProperty(category = "padding")
2409    protected int mUserPaddingRight;
2410
2411    /**
2412     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2413     *
2414     * @hide
2415     */
2416    @ViewDebug.ExportedProperty(category = "padding")
2417    protected int mUserPaddingBottom;
2418
2419    /**
2420     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2421     *
2422     * @hide
2423     */
2424    @ViewDebug.ExportedProperty(category = "padding")
2425    protected int mUserPaddingLeft;
2426
2427    /**
2428     * Cache if the user padding is relative.
2429     *
2430     */
2431    @ViewDebug.ExportedProperty(category = "padding")
2432    boolean mUserPaddingRelative;
2433
2434    /**
2435     * Cache the paddingStart set by the user to append to the scrollbar's size.
2436     *
2437     */
2438    @ViewDebug.ExportedProperty(category = "padding")
2439    int mUserPaddingStart;
2440
2441    /**
2442     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2443     *
2444     */
2445    @ViewDebug.ExportedProperty(category = "padding")
2446    int mUserPaddingEnd;
2447
2448    /**
2449     * @hide
2450     */
2451    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2452    /**
2453     * @hide
2454     */
2455    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2456
2457    private Drawable mBGDrawable;
2458
2459    private int mBackgroundResource;
2460    private boolean mBackgroundSizeChanged;
2461
2462    static class ListenerInfo {
2463        /**
2464         * Listener used to dispatch focus change events.
2465         * This field should be made private, so it is hidden from the SDK.
2466         * {@hide}
2467         */
2468        protected OnFocusChangeListener mOnFocusChangeListener;
2469
2470        /**
2471         * Listeners for layout change events.
2472         */
2473        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2474
2475        /**
2476         * Listeners for attach events.
2477         */
2478        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2479
2480        /**
2481         * Listener used to dispatch click events.
2482         * This field should be made private, so it is hidden from the SDK.
2483         * {@hide}
2484         */
2485        public OnClickListener mOnClickListener;
2486
2487        /**
2488         * Listener used to dispatch long click events.
2489         * This field should be made private, so it is hidden from the SDK.
2490         * {@hide}
2491         */
2492        protected OnLongClickListener mOnLongClickListener;
2493
2494        /**
2495         * Listener used to build the context menu.
2496         * This field should be made private, so it is hidden from the SDK.
2497         * {@hide}
2498         */
2499        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2500
2501        private OnKeyListener mOnKeyListener;
2502
2503        private OnTouchListener mOnTouchListener;
2504
2505        private OnHoverListener mOnHoverListener;
2506
2507        private OnGenericMotionListener mOnGenericMotionListener;
2508
2509        private OnDragListener mOnDragListener;
2510
2511        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2512    }
2513
2514    ListenerInfo mListenerInfo;
2515
2516    /**
2517     * The application environment this view lives in.
2518     * This field should be made private, so it is hidden from the SDK.
2519     * {@hide}
2520     */
2521    protected Context mContext;
2522
2523    private final Resources mResources;
2524
2525    private ScrollabilityCache mScrollCache;
2526
2527    private int[] mDrawableState = null;
2528
2529    /**
2530     * Set to true when drawing cache is enabled and cannot be created.
2531     *
2532     * @hide
2533     */
2534    public boolean mCachingFailed;
2535
2536    private Bitmap mDrawingCache;
2537    private Bitmap mUnscaledDrawingCache;
2538    private HardwareLayer mHardwareLayer;
2539    DisplayList mDisplayList;
2540
2541    /**
2542     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2543     * the user may specify which view to go to next.
2544     */
2545    private int mNextFocusLeftId = View.NO_ID;
2546
2547    /**
2548     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2549     * the user may specify which view to go to next.
2550     */
2551    private int mNextFocusRightId = View.NO_ID;
2552
2553    /**
2554     * When this view has focus and the next focus is {@link #FOCUS_UP},
2555     * the user may specify which view to go to next.
2556     */
2557    private int mNextFocusUpId = View.NO_ID;
2558
2559    /**
2560     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2561     * the user may specify which view to go to next.
2562     */
2563    private int mNextFocusDownId = View.NO_ID;
2564
2565    /**
2566     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2567     * the user may specify which view to go to next.
2568     */
2569    int mNextFocusForwardId = View.NO_ID;
2570
2571    private CheckForLongPress mPendingCheckForLongPress;
2572    private CheckForTap mPendingCheckForTap = null;
2573    private PerformClick mPerformClick;
2574    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2575
2576    private UnsetPressedState mUnsetPressedState;
2577
2578    /**
2579     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2580     * up event while a long press is invoked as soon as the long press duration is reached, so
2581     * a long press could be performed before the tap is checked, in which case the tap's action
2582     * should not be invoked.
2583     */
2584    private boolean mHasPerformedLongPress;
2585
2586    /**
2587     * The minimum height of the view. We'll try our best to have the height
2588     * of this view to at least this amount.
2589     */
2590    @ViewDebug.ExportedProperty(category = "measurement")
2591    private int mMinHeight;
2592
2593    /**
2594     * The minimum width of the view. We'll try our best to have the width
2595     * of this view to at least this amount.
2596     */
2597    @ViewDebug.ExportedProperty(category = "measurement")
2598    private int mMinWidth;
2599
2600    /**
2601     * The delegate to handle touch events that are physically in this view
2602     * but should be handled by another view.
2603     */
2604    private TouchDelegate mTouchDelegate = null;
2605
2606    /**
2607     * Solid color to use as a background when creating the drawing cache. Enables
2608     * the cache to use 16 bit bitmaps instead of 32 bit.
2609     */
2610    private int mDrawingCacheBackgroundColor = 0;
2611
2612    /**
2613     * Special tree observer used when mAttachInfo is null.
2614     */
2615    private ViewTreeObserver mFloatingTreeObserver;
2616
2617    /**
2618     * Cache the touch slop from the context that created the view.
2619     */
2620    private int mTouchSlop;
2621
2622    /**
2623     * Object that handles automatic animation of view properties.
2624     */
2625    private ViewPropertyAnimator mAnimator = null;
2626
2627    /**
2628     * Flag indicating that a drag can cross window boundaries.  When
2629     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2630     * with this flag set, all visible applications will be able to participate
2631     * in the drag operation and receive the dragged content.
2632     *
2633     * @hide
2634     */
2635    public static final int DRAG_FLAG_GLOBAL = 1;
2636
2637    /**
2638     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2639     */
2640    private float mVerticalScrollFactor;
2641
2642    /**
2643     * Position of the vertical scroll bar.
2644     */
2645    private int mVerticalScrollbarPosition;
2646
2647    /**
2648     * Position the scroll bar at the default position as determined by the system.
2649     */
2650    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2651
2652    /**
2653     * Position the scroll bar along the left edge.
2654     */
2655    public static final int SCROLLBAR_POSITION_LEFT = 1;
2656
2657    /**
2658     * Position the scroll bar along the right edge.
2659     */
2660    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2661
2662    /**
2663     * Indicates that the view does not have a layer.
2664     *
2665     * @see #getLayerType()
2666     * @see #setLayerType(int, android.graphics.Paint)
2667     * @see #LAYER_TYPE_SOFTWARE
2668     * @see #LAYER_TYPE_HARDWARE
2669     */
2670    public static final int LAYER_TYPE_NONE = 0;
2671
2672    /**
2673     * <p>Indicates that the view has a software layer. A software layer is backed
2674     * by a bitmap and causes the view to be rendered using Android's software
2675     * rendering pipeline, even if hardware acceleration is enabled.</p>
2676     *
2677     * <p>Software layers have various usages:</p>
2678     * <p>When the application is not using hardware acceleration, a software layer
2679     * is useful to apply a specific color filter and/or blending mode and/or
2680     * translucency to a view and all its children.</p>
2681     * <p>When the application is using hardware acceleration, a software layer
2682     * is useful to render drawing primitives not supported by the hardware
2683     * accelerated pipeline. It can also be used to cache a complex view tree
2684     * into a texture and reduce the complexity of drawing operations. For instance,
2685     * when animating a complex view tree with a translation, a software layer can
2686     * be used to render the view tree only once.</p>
2687     * <p>Software layers should be avoided when the affected view tree updates
2688     * often. Every update will require to re-render the software layer, which can
2689     * potentially be slow (particularly when hardware acceleration is turned on
2690     * since the layer will have to be uploaded into a hardware texture after every
2691     * update.)</p>
2692     *
2693     * @see #getLayerType()
2694     * @see #setLayerType(int, android.graphics.Paint)
2695     * @see #LAYER_TYPE_NONE
2696     * @see #LAYER_TYPE_HARDWARE
2697     */
2698    public static final int LAYER_TYPE_SOFTWARE = 1;
2699
2700    /**
2701     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2702     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2703     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2704     * rendering pipeline, but only if hardware acceleration is turned on for the
2705     * view hierarchy. When hardware acceleration is turned off, hardware layers
2706     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2707     *
2708     * <p>A hardware layer is useful to apply a specific color filter and/or
2709     * blending mode and/or translucency to a view and all its children.</p>
2710     * <p>A hardware layer can be used to cache a complex view tree into a
2711     * texture and reduce the complexity of drawing operations. For instance,
2712     * when animating a complex view tree with a translation, a hardware layer can
2713     * be used to render the view tree only once.</p>
2714     * <p>A hardware layer can also be used to increase the rendering quality when
2715     * rotation transformations are applied on a view. It can also be used to
2716     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2717     *
2718     * @see #getLayerType()
2719     * @see #setLayerType(int, android.graphics.Paint)
2720     * @see #LAYER_TYPE_NONE
2721     * @see #LAYER_TYPE_SOFTWARE
2722     */
2723    public static final int LAYER_TYPE_HARDWARE = 2;
2724
2725    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2726            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2727            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2728            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2729    })
2730    int mLayerType = LAYER_TYPE_NONE;
2731    Paint mLayerPaint;
2732    Rect mLocalDirtyRect;
2733
2734    /**
2735     * Set to true when the view is sending hover accessibility events because it
2736     * is the innermost hovered view.
2737     */
2738    private boolean mSendingHoverAccessibilityEvents;
2739
2740    /**
2741     * Delegate for injecting accessiblity functionality.
2742     */
2743    AccessibilityDelegate mAccessibilityDelegate;
2744
2745    /**
2746     * Consistency verifier for debugging purposes.
2747     * @hide
2748     */
2749    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2750            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2751                    new InputEventConsistencyVerifier(this, 0) : null;
2752
2753    /**
2754     * Simple constructor to use when creating a view from code.
2755     *
2756     * @param context The Context the view is running in, through which it can
2757     *        access the current theme, resources, etc.
2758     */
2759    public View(Context context) {
2760        mContext = context;
2761        mResources = context != null ? context.getResources() : null;
2762        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
2763        // Set layout and text direction defaults
2764        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
2765                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT);
2766        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2767        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2768        mUserPaddingStart = -1;
2769        mUserPaddingEnd = -1;
2770        mUserPaddingRelative = false;
2771    }
2772
2773    /**
2774     * Constructor that is called when inflating a view from XML. This is called
2775     * when a view is being constructed from an XML file, supplying attributes
2776     * that were specified in the XML file. This version uses a default style of
2777     * 0, so the only attribute values applied are those in the Context's Theme
2778     * and the given AttributeSet.
2779     *
2780     * <p>
2781     * The method onFinishInflate() will be called after all children have been
2782     * added.
2783     *
2784     * @param context The Context the view is running in, through which it can
2785     *        access the current theme, resources, etc.
2786     * @param attrs The attributes of the XML tag that is inflating the view.
2787     * @see #View(Context, AttributeSet, int)
2788     */
2789    public View(Context context, AttributeSet attrs) {
2790        this(context, attrs, 0);
2791    }
2792
2793    /**
2794     * Perform inflation from XML and apply a class-specific base style. This
2795     * constructor of View allows subclasses to use their own base style when
2796     * they are inflating. For example, a Button class's constructor would call
2797     * this version of the super class constructor and supply
2798     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2799     * the theme's button style to modify all of the base view attributes (in
2800     * particular its background) as well as the Button class's attributes.
2801     *
2802     * @param context The Context the view is running in, through which it can
2803     *        access the current theme, resources, etc.
2804     * @param attrs The attributes of the XML tag that is inflating the view.
2805     * @param defStyle The default style to apply to this view. If 0, no style
2806     *        will be applied (beyond what is included in the theme). This may
2807     *        either be an attribute resource, whose value will be retrieved
2808     *        from the current theme, or an explicit style resource.
2809     * @see #View(Context, AttributeSet)
2810     */
2811    public View(Context context, AttributeSet attrs, int defStyle) {
2812        this(context);
2813
2814        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2815                defStyle, 0);
2816
2817        Drawable background = null;
2818
2819        int leftPadding = -1;
2820        int topPadding = -1;
2821        int rightPadding = -1;
2822        int bottomPadding = -1;
2823        int startPadding = -1;
2824        int endPadding = -1;
2825
2826        int padding = -1;
2827
2828        int viewFlagValues = 0;
2829        int viewFlagMasks = 0;
2830
2831        boolean setScrollContainer = false;
2832
2833        int x = 0;
2834        int y = 0;
2835
2836        float tx = 0;
2837        float ty = 0;
2838        float rotation = 0;
2839        float rotationX = 0;
2840        float rotationY = 0;
2841        float sx = 1f;
2842        float sy = 1f;
2843        boolean transformSet = false;
2844
2845        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2846
2847        int overScrollMode = mOverScrollMode;
2848        final int N = a.getIndexCount();
2849        for (int i = 0; i < N; i++) {
2850            int attr = a.getIndex(i);
2851            switch (attr) {
2852                case com.android.internal.R.styleable.View_background:
2853                    background = a.getDrawable(attr);
2854                    break;
2855                case com.android.internal.R.styleable.View_padding:
2856                    padding = a.getDimensionPixelSize(attr, -1);
2857                    break;
2858                 case com.android.internal.R.styleable.View_paddingLeft:
2859                    leftPadding = a.getDimensionPixelSize(attr, -1);
2860                    break;
2861                case com.android.internal.R.styleable.View_paddingTop:
2862                    topPadding = a.getDimensionPixelSize(attr, -1);
2863                    break;
2864                case com.android.internal.R.styleable.View_paddingRight:
2865                    rightPadding = a.getDimensionPixelSize(attr, -1);
2866                    break;
2867                case com.android.internal.R.styleable.View_paddingBottom:
2868                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2869                    break;
2870                case com.android.internal.R.styleable.View_paddingStart:
2871                    startPadding = a.getDimensionPixelSize(attr, -1);
2872                    break;
2873                case com.android.internal.R.styleable.View_paddingEnd:
2874                    endPadding = a.getDimensionPixelSize(attr, -1);
2875                    break;
2876                case com.android.internal.R.styleable.View_scrollX:
2877                    x = a.getDimensionPixelOffset(attr, 0);
2878                    break;
2879                case com.android.internal.R.styleable.View_scrollY:
2880                    y = a.getDimensionPixelOffset(attr, 0);
2881                    break;
2882                case com.android.internal.R.styleable.View_alpha:
2883                    setAlpha(a.getFloat(attr, 1f));
2884                    break;
2885                case com.android.internal.R.styleable.View_transformPivotX:
2886                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2887                    break;
2888                case com.android.internal.R.styleable.View_transformPivotY:
2889                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2890                    break;
2891                case com.android.internal.R.styleable.View_translationX:
2892                    tx = a.getDimensionPixelOffset(attr, 0);
2893                    transformSet = true;
2894                    break;
2895                case com.android.internal.R.styleable.View_translationY:
2896                    ty = a.getDimensionPixelOffset(attr, 0);
2897                    transformSet = true;
2898                    break;
2899                case com.android.internal.R.styleable.View_rotation:
2900                    rotation = a.getFloat(attr, 0);
2901                    transformSet = true;
2902                    break;
2903                case com.android.internal.R.styleable.View_rotationX:
2904                    rotationX = a.getFloat(attr, 0);
2905                    transformSet = true;
2906                    break;
2907                case com.android.internal.R.styleable.View_rotationY:
2908                    rotationY = a.getFloat(attr, 0);
2909                    transformSet = true;
2910                    break;
2911                case com.android.internal.R.styleable.View_scaleX:
2912                    sx = a.getFloat(attr, 1f);
2913                    transformSet = true;
2914                    break;
2915                case com.android.internal.R.styleable.View_scaleY:
2916                    sy = a.getFloat(attr, 1f);
2917                    transformSet = true;
2918                    break;
2919                case com.android.internal.R.styleable.View_id:
2920                    mID = a.getResourceId(attr, NO_ID);
2921                    break;
2922                case com.android.internal.R.styleable.View_tag:
2923                    mTag = a.getText(attr);
2924                    break;
2925                case com.android.internal.R.styleable.View_fitsSystemWindows:
2926                    if (a.getBoolean(attr, false)) {
2927                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2928                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2929                    }
2930                    break;
2931                case com.android.internal.R.styleable.View_focusable:
2932                    if (a.getBoolean(attr, false)) {
2933                        viewFlagValues |= FOCUSABLE;
2934                        viewFlagMasks |= FOCUSABLE_MASK;
2935                    }
2936                    break;
2937                case com.android.internal.R.styleable.View_focusableInTouchMode:
2938                    if (a.getBoolean(attr, false)) {
2939                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2940                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2941                    }
2942                    break;
2943                case com.android.internal.R.styleable.View_clickable:
2944                    if (a.getBoolean(attr, false)) {
2945                        viewFlagValues |= CLICKABLE;
2946                        viewFlagMasks |= CLICKABLE;
2947                    }
2948                    break;
2949                case com.android.internal.R.styleable.View_longClickable:
2950                    if (a.getBoolean(attr, false)) {
2951                        viewFlagValues |= LONG_CLICKABLE;
2952                        viewFlagMasks |= LONG_CLICKABLE;
2953                    }
2954                    break;
2955                case com.android.internal.R.styleable.View_saveEnabled:
2956                    if (!a.getBoolean(attr, true)) {
2957                        viewFlagValues |= SAVE_DISABLED;
2958                        viewFlagMasks |= SAVE_DISABLED_MASK;
2959                    }
2960                    break;
2961                case com.android.internal.R.styleable.View_duplicateParentState:
2962                    if (a.getBoolean(attr, false)) {
2963                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2964                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2965                    }
2966                    break;
2967                case com.android.internal.R.styleable.View_visibility:
2968                    final int visibility = a.getInt(attr, 0);
2969                    if (visibility != 0) {
2970                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2971                        viewFlagMasks |= VISIBILITY_MASK;
2972                    }
2973                    break;
2974                case com.android.internal.R.styleable.View_layoutDirection:
2975                    // Clear any layout direction flags (included resolved bits) already set
2976                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
2977                    // Set the layout direction flags depending on the value of the attribute
2978                    final int layoutDirection = a.getInt(attr, -1);
2979                    final int value = (layoutDirection != -1) ?
2980                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
2981                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
2982                    break;
2983                case com.android.internal.R.styleable.View_drawingCacheQuality:
2984                    final int cacheQuality = a.getInt(attr, 0);
2985                    if (cacheQuality != 0) {
2986                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2987                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2988                    }
2989                    break;
2990                case com.android.internal.R.styleable.View_contentDescription:
2991                    mContentDescription = a.getString(attr);
2992                    break;
2993                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2994                    if (!a.getBoolean(attr, true)) {
2995                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2996                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2997                    }
2998                    break;
2999                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3000                    if (!a.getBoolean(attr, true)) {
3001                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3002                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3003                    }
3004                    break;
3005                case R.styleable.View_scrollbars:
3006                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3007                    if (scrollbars != SCROLLBARS_NONE) {
3008                        viewFlagValues |= scrollbars;
3009                        viewFlagMasks |= SCROLLBARS_MASK;
3010                        initializeScrollbars(a);
3011                    }
3012                    break;
3013                //noinspection deprecation
3014                case R.styleable.View_fadingEdge:
3015                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3016                        // Ignore the attribute starting with ICS
3017                        break;
3018                    }
3019                    // With builds < ICS, fall through and apply fading edges
3020                case R.styleable.View_requiresFadingEdge:
3021                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3022                    if (fadingEdge != FADING_EDGE_NONE) {
3023                        viewFlagValues |= fadingEdge;
3024                        viewFlagMasks |= FADING_EDGE_MASK;
3025                        initializeFadingEdge(a);
3026                    }
3027                    break;
3028                case R.styleable.View_scrollbarStyle:
3029                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3030                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3031                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3032                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3033                    }
3034                    break;
3035                case R.styleable.View_isScrollContainer:
3036                    setScrollContainer = true;
3037                    if (a.getBoolean(attr, false)) {
3038                        setScrollContainer(true);
3039                    }
3040                    break;
3041                case com.android.internal.R.styleable.View_keepScreenOn:
3042                    if (a.getBoolean(attr, false)) {
3043                        viewFlagValues |= KEEP_SCREEN_ON;
3044                        viewFlagMasks |= KEEP_SCREEN_ON;
3045                    }
3046                    break;
3047                case R.styleable.View_filterTouchesWhenObscured:
3048                    if (a.getBoolean(attr, false)) {
3049                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3050                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3051                    }
3052                    break;
3053                case R.styleable.View_nextFocusLeft:
3054                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3055                    break;
3056                case R.styleable.View_nextFocusRight:
3057                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3058                    break;
3059                case R.styleable.View_nextFocusUp:
3060                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3061                    break;
3062                case R.styleable.View_nextFocusDown:
3063                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3064                    break;
3065                case R.styleable.View_nextFocusForward:
3066                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3067                    break;
3068                case R.styleable.View_minWidth:
3069                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3070                    break;
3071                case R.styleable.View_minHeight:
3072                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3073                    break;
3074                case R.styleable.View_onClick:
3075                    if (context.isRestricted()) {
3076                        throw new IllegalStateException("The android:onClick attribute cannot "
3077                                + "be used within a restricted context");
3078                    }
3079
3080                    final String handlerName = a.getString(attr);
3081                    if (handlerName != null) {
3082                        setOnClickListener(new OnClickListener() {
3083                            private Method mHandler;
3084
3085                            public void onClick(View v) {
3086                                if (mHandler == null) {
3087                                    try {
3088                                        mHandler = getContext().getClass().getMethod(handlerName,
3089                                                View.class);
3090                                    } catch (NoSuchMethodException e) {
3091                                        int id = getId();
3092                                        String idText = id == NO_ID ? "" : " with id '"
3093                                                + getContext().getResources().getResourceEntryName(
3094                                                    id) + "'";
3095                                        throw new IllegalStateException("Could not find a method " +
3096                                                handlerName + "(View) in the activity "
3097                                                + getContext().getClass() + " for onClick handler"
3098                                                + " on view " + View.this.getClass() + idText, e);
3099                                    }
3100                                }
3101
3102                                try {
3103                                    mHandler.invoke(getContext(), View.this);
3104                                } catch (IllegalAccessException e) {
3105                                    throw new IllegalStateException("Could not execute non "
3106                                            + "public method of the activity", e);
3107                                } catch (InvocationTargetException e) {
3108                                    throw new IllegalStateException("Could not execute "
3109                                            + "method of the activity", e);
3110                                }
3111                            }
3112                        });
3113                    }
3114                    break;
3115                case R.styleable.View_overScrollMode:
3116                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3117                    break;
3118                case R.styleable.View_verticalScrollbarPosition:
3119                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3120                    break;
3121                case R.styleable.View_layerType:
3122                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3123                    break;
3124                case R.styleable.View_textDirection:
3125                    // Clear any text direction flag already set
3126                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3127                    // Set the text direction flags depending on the value of the attribute
3128                    final int textDirection = a.getInt(attr, -1);
3129                    if (textDirection != -1) {
3130                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3131                    }
3132                    break;
3133            }
3134        }
3135
3136        a.recycle();
3137
3138        setOverScrollMode(overScrollMode);
3139
3140        if (background != null) {
3141            setBackgroundDrawable(background);
3142        }
3143
3144        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3145        // layout direction). Those cached values will be used later during padding resolution.
3146        mUserPaddingStart = startPadding;
3147        mUserPaddingEnd = endPadding;
3148
3149        updateUserPaddingRelative();
3150
3151        if (padding >= 0) {
3152            leftPadding = padding;
3153            topPadding = padding;
3154            rightPadding = padding;
3155            bottomPadding = padding;
3156        }
3157
3158        // If the user specified the padding (either with android:padding or
3159        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3160        // use the default padding or the padding from the background drawable
3161        // (stored at this point in mPadding*)
3162        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3163                topPadding >= 0 ? topPadding : mPaddingTop,
3164                rightPadding >= 0 ? rightPadding : mPaddingRight,
3165                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3166
3167        if (viewFlagMasks != 0) {
3168            setFlags(viewFlagValues, viewFlagMasks);
3169        }
3170
3171        // Needs to be called after mViewFlags is set
3172        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3173            recomputePadding();
3174        }
3175
3176        if (x != 0 || y != 0) {
3177            scrollTo(x, y);
3178        }
3179
3180        if (transformSet) {
3181            setTranslationX(tx);
3182            setTranslationY(ty);
3183            setRotation(rotation);
3184            setRotationX(rotationX);
3185            setRotationY(rotationY);
3186            setScaleX(sx);
3187            setScaleY(sy);
3188        }
3189
3190        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3191            setScrollContainer(true);
3192        }
3193
3194        computeOpaqueFlags();
3195    }
3196
3197    private void updateUserPaddingRelative() {
3198        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3199    }
3200
3201    /**
3202     * Non-public constructor for use in testing
3203     */
3204    View() {
3205        mResources = null;
3206    }
3207
3208    /**
3209     * <p>
3210     * Initializes the fading edges from a given set of styled attributes. This
3211     * method should be called by subclasses that need fading edges and when an
3212     * instance of these subclasses is created programmatically rather than
3213     * being inflated from XML. This method is automatically called when the XML
3214     * is inflated.
3215     * </p>
3216     *
3217     * @param a the styled attributes set to initialize the fading edges from
3218     */
3219    protected void initializeFadingEdge(TypedArray a) {
3220        initScrollCache();
3221
3222        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3223                R.styleable.View_fadingEdgeLength,
3224                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3225    }
3226
3227    /**
3228     * Returns the size of the vertical faded edges used to indicate that more
3229     * content in this view is visible.
3230     *
3231     * @return The size in pixels of the vertical faded edge or 0 if vertical
3232     *         faded edges are not enabled for this view.
3233     * @attr ref android.R.styleable#View_fadingEdgeLength
3234     */
3235    public int getVerticalFadingEdgeLength() {
3236        if (isVerticalFadingEdgeEnabled()) {
3237            ScrollabilityCache cache = mScrollCache;
3238            if (cache != null) {
3239                return cache.fadingEdgeLength;
3240            }
3241        }
3242        return 0;
3243    }
3244
3245    /**
3246     * Set the size of the faded edge used to indicate that more content in this
3247     * view is available.  Will not change whether the fading edge is enabled; use
3248     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3249     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3250     * for the vertical or horizontal fading edges.
3251     *
3252     * @param length The size in pixels of the faded edge used to indicate that more
3253     *        content in this view is visible.
3254     */
3255    public void setFadingEdgeLength(int length) {
3256        initScrollCache();
3257        mScrollCache.fadingEdgeLength = length;
3258    }
3259
3260    /**
3261     * Returns the size of the horizontal faded edges used to indicate that more
3262     * content in this view is visible.
3263     *
3264     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3265     *         faded edges are not enabled for this view.
3266     * @attr ref android.R.styleable#View_fadingEdgeLength
3267     */
3268    public int getHorizontalFadingEdgeLength() {
3269        if (isHorizontalFadingEdgeEnabled()) {
3270            ScrollabilityCache cache = mScrollCache;
3271            if (cache != null) {
3272                return cache.fadingEdgeLength;
3273            }
3274        }
3275        return 0;
3276    }
3277
3278    /**
3279     * Returns the width of the vertical scrollbar.
3280     *
3281     * @return The width in pixels of the vertical scrollbar or 0 if there
3282     *         is no vertical scrollbar.
3283     */
3284    public int getVerticalScrollbarWidth() {
3285        ScrollabilityCache cache = mScrollCache;
3286        if (cache != null) {
3287            ScrollBarDrawable scrollBar = cache.scrollBar;
3288            if (scrollBar != null) {
3289                int size = scrollBar.getSize(true);
3290                if (size <= 0) {
3291                    size = cache.scrollBarSize;
3292                }
3293                return size;
3294            }
3295            return 0;
3296        }
3297        return 0;
3298    }
3299
3300    /**
3301     * Returns the height of the horizontal scrollbar.
3302     *
3303     * @return The height in pixels of the horizontal scrollbar or 0 if
3304     *         there is no horizontal scrollbar.
3305     */
3306    protected int getHorizontalScrollbarHeight() {
3307        ScrollabilityCache cache = mScrollCache;
3308        if (cache != null) {
3309            ScrollBarDrawable scrollBar = cache.scrollBar;
3310            if (scrollBar != null) {
3311                int size = scrollBar.getSize(false);
3312                if (size <= 0) {
3313                    size = cache.scrollBarSize;
3314                }
3315                return size;
3316            }
3317            return 0;
3318        }
3319        return 0;
3320    }
3321
3322    /**
3323     * <p>
3324     * Initializes the scrollbars from a given set of styled attributes. This
3325     * method should be called by subclasses that need scrollbars and when an
3326     * instance of these subclasses is created programmatically rather than
3327     * being inflated from XML. This method is automatically called when the XML
3328     * is inflated.
3329     * </p>
3330     *
3331     * @param a the styled attributes set to initialize the scrollbars from
3332     */
3333    protected void initializeScrollbars(TypedArray a) {
3334        initScrollCache();
3335
3336        final ScrollabilityCache scrollabilityCache = mScrollCache;
3337
3338        if (scrollabilityCache.scrollBar == null) {
3339            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3340        }
3341
3342        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3343
3344        if (!fadeScrollbars) {
3345            scrollabilityCache.state = ScrollabilityCache.ON;
3346        }
3347        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3348
3349
3350        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3351                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3352                        .getScrollBarFadeDuration());
3353        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3354                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3355                ViewConfiguration.getScrollDefaultDelay());
3356
3357
3358        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3359                com.android.internal.R.styleable.View_scrollbarSize,
3360                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3361
3362        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3363        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3364
3365        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3366        if (thumb != null) {
3367            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3368        }
3369
3370        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3371                false);
3372        if (alwaysDraw) {
3373            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3374        }
3375
3376        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3377        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3378
3379        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3380        if (thumb != null) {
3381            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3382        }
3383
3384        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3385                false);
3386        if (alwaysDraw) {
3387            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3388        }
3389
3390        // Re-apply user/background padding so that scrollbar(s) get added
3391        resolvePadding();
3392    }
3393
3394    /**
3395     * <p>
3396     * Initalizes the scrollability cache if necessary.
3397     * </p>
3398     */
3399    private void initScrollCache() {
3400        if (mScrollCache == null) {
3401            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3402        }
3403    }
3404
3405    /**
3406     * Set the position of the vertical scroll bar. Should be one of
3407     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3408     * {@link #SCROLLBAR_POSITION_RIGHT}.
3409     *
3410     * @param position Where the vertical scroll bar should be positioned.
3411     */
3412    public void setVerticalScrollbarPosition(int position) {
3413        if (mVerticalScrollbarPosition != position) {
3414            mVerticalScrollbarPosition = position;
3415            computeOpaqueFlags();
3416            resolvePadding();
3417        }
3418    }
3419
3420    /**
3421     * @return The position where the vertical scroll bar will show, if applicable.
3422     * @see #setVerticalScrollbarPosition(int)
3423     */
3424    public int getVerticalScrollbarPosition() {
3425        return mVerticalScrollbarPosition;
3426    }
3427
3428    ListenerInfo getListenerInfo() {
3429        if (mListenerInfo != null) {
3430            return mListenerInfo;
3431        }
3432        mListenerInfo = new ListenerInfo();
3433        return mListenerInfo;
3434    }
3435
3436    /**
3437     * Register a callback to be invoked when focus of this view changed.
3438     *
3439     * @param l The callback that will run.
3440     */
3441    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3442        getListenerInfo().mOnFocusChangeListener = l;
3443    }
3444
3445    /**
3446     * Add a listener that will be called when the bounds of the view change due to
3447     * layout processing.
3448     *
3449     * @param listener The listener that will be called when layout bounds change.
3450     */
3451    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3452        ListenerInfo li = getListenerInfo();
3453        if (li.mOnLayoutChangeListeners == null) {
3454            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3455        }
3456        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3457            li.mOnLayoutChangeListeners.add(listener);
3458        }
3459    }
3460
3461    /**
3462     * Remove a listener for layout changes.
3463     *
3464     * @param listener The listener for layout bounds change.
3465     */
3466    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3467        ListenerInfo li = mListenerInfo;
3468        if (li == null || li.mOnLayoutChangeListeners == null) {
3469            return;
3470        }
3471        li.mOnLayoutChangeListeners.remove(listener);
3472    }
3473
3474    /**
3475     * Add a listener for attach state changes.
3476     *
3477     * This listener will be called whenever this view is attached or detached
3478     * from a window. Remove the listener using
3479     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3480     *
3481     * @param listener Listener to attach
3482     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3483     */
3484    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3485        ListenerInfo li = getListenerInfo();
3486        if (li.mOnAttachStateChangeListeners == null) {
3487            li.mOnAttachStateChangeListeners
3488                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3489        }
3490        li.mOnAttachStateChangeListeners.add(listener);
3491    }
3492
3493    /**
3494     * Remove a listener for attach state changes. The listener will receive no further
3495     * notification of window attach/detach events.
3496     *
3497     * @param listener Listener to remove
3498     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3499     */
3500    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3501        ListenerInfo li = mListenerInfo;
3502        if (li == null || li.mOnAttachStateChangeListeners == null) {
3503            return;
3504        }
3505        li.mOnAttachStateChangeListeners.remove(listener);
3506    }
3507
3508    /**
3509     * Returns the focus-change callback registered for this view.
3510     *
3511     * @return The callback, or null if one is not registered.
3512     */
3513    public OnFocusChangeListener getOnFocusChangeListener() {
3514        ListenerInfo li = mListenerInfo;
3515        return li != null ? li.mOnFocusChangeListener : null;
3516    }
3517
3518    /**
3519     * Register a callback to be invoked when this view is clicked. If this view is not
3520     * clickable, it becomes clickable.
3521     *
3522     * @param l The callback that will run
3523     *
3524     * @see #setClickable(boolean)
3525     */
3526    public void setOnClickListener(OnClickListener l) {
3527        if (!isClickable()) {
3528            setClickable(true);
3529        }
3530        getListenerInfo().mOnClickListener = l;
3531    }
3532
3533    /**
3534     * Return whether this view has an attached OnClickListener.  Returns
3535     * true if there is a listener, false if there is none.
3536     */
3537    public boolean hasOnClickListeners() {
3538        ListenerInfo li = mListenerInfo;
3539        return (li != null && li.mOnClickListener != null);
3540    }
3541
3542    /**
3543     * Register a callback to be invoked when this view is clicked and held. If this view is not
3544     * long clickable, it becomes long clickable.
3545     *
3546     * @param l The callback that will run
3547     *
3548     * @see #setLongClickable(boolean)
3549     */
3550    public void setOnLongClickListener(OnLongClickListener l) {
3551        if (!isLongClickable()) {
3552            setLongClickable(true);
3553        }
3554        getListenerInfo().mOnLongClickListener = l;
3555    }
3556
3557    /**
3558     * Register a callback to be invoked when the context menu for this view is
3559     * being built. If this view is not long clickable, it becomes long clickable.
3560     *
3561     * @param l The callback that will run
3562     *
3563     */
3564    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3565        if (!isLongClickable()) {
3566            setLongClickable(true);
3567        }
3568        getListenerInfo().mOnCreateContextMenuListener = l;
3569    }
3570
3571    /**
3572     * Call this view's OnClickListener, if it is defined.  Performs all normal
3573     * actions associated with clicking: reporting accessibility event, playing
3574     * a sound, etc.
3575     *
3576     * @return True there was an assigned OnClickListener that was called, false
3577     *         otherwise is returned.
3578     */
3579    public boolean performClick() {
3580        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3581
3582        ListenerInfo li = mListenerInfo;
3583        if (li != null && li.mOnClickListener != null) {
3584            playSoundEffect(SoundEffectConstants.CLICK);
3585            li.mOnClickListener.onClick(this);
3586            return true;
3587        }
3588
3589        return false;
3590    }
3591
3592    /**
3593     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3594     * this only calls the listener, and does not do any associated clicking
3595     * actions like reporting an accessibility event.
3596     *
3597     * @return True there was an assigned OnClickListener that was called, false
3598     *         otherwise is returned.
3599     */
3600    public boolean callOnClick() {
3601        ListenerInfo li = mListenerInfo;
3602        if (li != null && li.mOnClickListener != null) {
3603            li.mOnClickListener.onClick(this);
3604            return true;
3605        }
3606        return false;
3607    }
3608
3609    /**
3610     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3611     * OnLongClickListener did not consume the event.
3612     *
3613     * @return True if one of the above receivers consumed the event, false otherwise.
3614     */
3615    public boolean performLongClick() {
3616        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3617
3618        boolean handled = false;
3619        ListenerInfo li = mListenerInfo;
3620        if (li != null && li.mOnLongClickListener != null) {
3621            handled = li.mOnLongClickListener.onLongClick(View.this);
3622        }
3623        if (!handled) {
3624            handled = showContextMenu();
3625        }
3626        if (handled) {
3627            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3628        }
3629        return handled;
3630    }
3631
3632    /**
3633     * Performs button-related actions during a touch down event.
3634     *
3635     * @param event The event.
3636     * @return True if the down was consumed.
3637     *
3638     * @hide
3639     */
3640    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3641        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3642            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3643                return true;
3644            }
3645        }
3646        return false;
3647    }
3648
3649    /**
3650     * Bring up the context menu for this view.
3651     *
3652     * @return Whether a context menu was displayed.
3653     */
3654    public boolean showContextMenu() {
3655        return getParent().showContextMenuForChild(this);
3656    }
3657
3658    /**
3659     * Bring up the context menu for this view, referring to the item under the specified point.
3660     *
3661     * @param x The referenced x coordinate.
3662     * @param y The referenced y coordinate.
3663     * @param metaState The keyboard modifiers that were pressed.
3664     * @return Whether a context menu was displayed.
3665     *
3666     * @hide
3667     */
3668    public boolean showContextMenu(float x, float y, int metaState) {
3669        return showContextMenu();
3670    }
3671
3672    /**
3673     * Start an action mode.
3674     *
3675     * @param callback Callback that will control the lifecycle of the action mode
3676     * @return The new action mode if it is started, null otherwise
3677     *
3678     * @see ActionMode
3679     */
3680    public ActionMode startActionMode(ActionMode.Callback callback) {
3681        ViewParent parent = getParent();
3682        if (parent == null) return null;
3683        return parent.startActionModeForChild(this, callback);
3684    }
3685
3686    /**
3687     * Register a callback to be invoked when a key is pressed in this view.
3688     * @param l the key listener to attach to this view
3689     */
3690    public void setOnKeyListener(OnKeyListener l) {
3691        getListenerInfo().mOnKeyListener = l;
3692    }
3693
3694    /**
3695     * Register a callback to be invoked when a touch event is sent to this view.
3696     * @param l the touch listener to attach to this view
3697     */
3698    public void setOnTouchListener(OnTouchListener l) {
3699        getListenerInfo().mOnTouchListener = l;
3700    }
3701
3702    /**
3703     * Register a callback to be invoked when a generic motion event is sent to this view.
3704     * @param l the generic motion listener to attach to this view
3705     */
3706    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3707        getListenerInfo().mOnGenericMotionListener = l;
3708    }
3709
3710    /**
3711     * Register a callback to be invoked when a hover event is sent to this view.
3712     * @param l the hover listener to attach to this view
3713     */
3714    public void setOnHoverListener(OnHoverListener l) {
3715        getListenerInfo().mOnHoverListener = l;
3716    }
3717
3718    /**
3719     * Register a drag event listener callback object for this View. The parameter is
3720     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3721     * View, the system calls the
3722     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3723     * @param l An implementation of {@link android.view.View.OnDragListener}.
3724     */
3725    public void setOnDragListener(OnDragListener l) {
3726        getListenerInfo().mOnDragListener = l;
3727    }
3728
3729    /**
3730     * Give this view focus. This will cause
3731     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3732     *
3733     * Note: this does not check whether this {@link View} should get focus, it just
3734     * gives it focus no matter what.  It should only be called internally by framework
3735     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3736     *
3737     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3738     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3739     *        focus moved when requestFocus() is called. It may not always
3740     *        apply, in which case use the default View.FOCUS_DOWN.
3741     * @param previouslyFocusedRect The rectangle of the view that had focus
3742     *        prior in this View's coordinate system.
3743     */
3744    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3745        if (DBG) {
3746            System.out.println(this + " requestFocus()");
3747        }
3748
3749        if ((mPrivateFlags & FOCUSED) == 0) {
3750            mPrivateFlags |= FOCUSED;
3751
3752            if (mParent != null) {
3753                mParent.requestChildFocus(this, this);
3754            }
3755
3756            onFocusChanged(true, direction, previouslyFocusedRect);
3757            refreshDrawableState();
3758        }
3759    }
3760
3761    /**
3762     * Request that a rectangle of this view be visible on the screen,
3763     * scrolling if necessary just enough.
3764     *
3765     * <p>A View should call this if it maintains some notion of which part
3766     * of its content is interesting.  For example, a text editing view
3767     * should call this when its cursor moves.
3768     *
3769     * @param rectangle The rectangle.
3770     * @return Whether any parent scrolled.
3771     */
3772    public boolean requestRectangleOnScreen(Rect rectangle) {
3773        return requestRectangleOnScreen(rectangle, false);
3774    }
3775
3776    /**
3777     * Request that a rectangle of this view be visible on the screen,
3778     * scrolling if necessary just enough.
3779     *
3780     * <p>A View should call this if it maintains some notion of which part
3781     * of its content is interesting.  For example, a text editing view
3782     * should call this when its cursor moves.
3783     *
3784     * <p>When <code>immediate</code> is set to true, scrolling will not be
3785     * animated.
3786     *
3787     * @param rectangle The rectangle.
3788     * @param immediate True to forbid animated scrolling, false otherwise
3789     * @return Whether any parent scrolled.
3790     */
3791    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3792        View child = this;
3793        ViewParent parent = mParent;
3794        boolean scrolled = false;
3795        while (parent != null) {
3796            scrolled |= parent.requestChildRectangleOnScreen(child,
3797                    rectangle, immediate);
3798
3799            // offset rect so next call has the rectangle in the
3800            // coordinate system of its direct child.
3801            rectangle.offset(child.getLeft(), child.getTop());
3802            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3803
3804            if (!(parent instanceof View)) {
3805                break;
3806            }
3807
3808            child = (View) parent;
3809            parent = child.getParent();
3810        }
3811        return scrolled;
3812    }
3813
3814    /**
3815     * Called when this view wants to give up focus. If focus is cleared
3816     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
3817     * <p>
3818     * <strong>Note:</strong> When a View clears focus the framework is trying
3819     * to give focus to the first focusable View from the top. Hence, if this
3820     * View is the first from the top that can take focus, then its focus will
3821     * not be cleared nor will the focus change callback be invoked.
3822     * </p>
3823     */
3824    public void clearFocus() {
3825        if (DBG) {
3826            System.out.println(this + " clearFocus()");
3827        }
3828
3829        if ((mPrivateFlags & FOCUSED) != 0) {
3830            mPrivateFlags &= ~FOCUSED;
3831
3832            if (mParent != null) {
3833                mParent.clearChildFocus(this);
3834            }
3835
3836            onFocusChanged(false, 0, null);
3837            refreshDrawableState();
3838        }
3839    }
3840
3841    /**
3842     * Called to clear the focus of a view that is about to be removed.
3843     * Doesn't call clearChildFocus, which prevents this view from taking
3844     * focus again before it has been removed from the parent
3845     */
3846    void clearFocusForRemoval() {
3847        if ((mPrivateFlags & FOCUSED) != 0) {
3848            mPrivateFlags &= ~FOCUSED;
3849
3850            onFocusChanged(false, 0, null);
3851            refreshDrawableState();
3852
3853            // The view cleared focus and invoked the callbacks, so  now is the
3854            // time to give focus to the the first focusable from the top to
3855            // ensure that the gain focus is announced after clear focus.
3856            getRootView().requestFocus(FOCUS_FORWARD);
3857        }
3858    }
3859
3860    /**
3861     * Called internally by the view system when a new view is getting focus.
3862     * This is what clears the old focus.
3863     */
3864    void unFocus() {
3865        if (DBG) {
3866            System.out.println(this + " unFocus()");
3867        }
3868
3869        if ((mPrivateFlags & FOCUSED) != 0) {
3870            mPrivateFlags &= ~FOCUSED;
3871
3872            onFocusChanged(false, 0, null);
3873            refreshDrawableState();
3874        }
3875    }
3876
3877    /**
3878     * Returns true if this view has focus iteself, or is the ancestor of the
3879     * view that has focus.
3880     *
3881     * @return True if this view has or contains focus, false otherwise.
3882     */
3883    @ViewDebug.ExportedProperty(category = "focus")
3884    public boolean hasFocus() {
3885        return (mPrivateFlags & FOCUSED) != 0;
3886    }
3887
3888    /**
3889     * Returns true if this view is focusable or if it contains a reachable View
3890     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3891     * is a View whose parents do not block descendants focus.
3892     *
3893     * Only {@link #VISIBLE} views are considered focusable.
3894     *
3895     * @return True if the view is focusable or if the view contains a focusable
3896     *         View, false otherwise.
3897     *
3898     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3899     */
3900    public boolean hasFocusable() {
3901        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3902    }
3903
3904    /**
3905     * Called by the view system when the focus state of this view changes.
3906     * When the focus change event is caused by directional navigation, direction
3907     * and previouslyFocusedRect provide insight into where the focus is coming from.
3908     * When overriding, be sure to call up through to the super class so that
3909     * the standard focus handling will occur.
3910     *
3911     * @param gainFocus True if the View has focus; false otherwise.
3912     * @param direction The direction focus has moved when requestFocus()
3913     *                  is called to give this view focus. Values are
3914     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3915     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3916     *                  It may not always apply, in which case use the default.
3917     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3918     *        system, of the previously focused view.  If applicable, this will be
3919     *        passed in as finer grained information about where the focus is coming
3920     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3921     */
3922    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3923        if (gainFocus) {
3924            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3925        }
3926
3927        InputMethodManager imm = InputMethodManager.peekInstance();
3928        if (!gainFocus) {
3929            if (isPressed()) {
3930                setPressed(false);
3931            }
3932            if (imm != null && mAttachInfo != null
3933                    && mAttachInfo.mHasWindowFocus) {
3934                imm.focusOut(this);
3935            }
3936            onFocusLost();
3937        } else if (imm != null && mAttachInfo != null
3938                && mAttachInfo.mHasWindowFocus) {
3939            imm.focusIn(this);
3940        }
3941
3942        invalidate(true);
3943        ListenerInfo li = mListenerInfo;
3944        if (li != null && li.mOnFocusChangeListener != null) {
3945            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
3946        }
3947
3948        if (mAttachInfo != null) {
3949            mAttachInfo.mKeyDispatchState.reset(this);
3950        }
3951    }
3952
3953    /**
3954     * Sends an accessibility event of the given type. If accessiiblity is
3955     * not enabled this method has no effect. The default implementation calls
3956     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3957     * to populate information about the event source (this View), then calls
3958     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3959     * populate the text content of the event source including its descendants,
3960     * and last calls
3961     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3962     * on its parent to resuest sending of the event to interested parties.
3963     * <p>
3964     * If an {@link AccessibilityDelegate} has been specified via calling
3965     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3966     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3967     * responsible for handling this call.
3968     * </p>
3969     *
3970     * @param eventType The type of the event to send, as defined by several types from
3971     * {@link android.view.accessibility.AccessibilityEvent}, such as
3972     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
3973     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
3974     *
3975     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3976     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3977     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3978     * @see AccessibilityDelegate
3979     */
3980    public void sendAccessibilityEvent(int eventType) {
3981        if (mAccessibilityDelegate != null) {
3982            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3983        } else {
3984            sendAccessibilityEventInternal(eventType);
3985        }
3986    }
3987
3988    /**
3989     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
3990     * {@link AccessibilityEvent} to make an announcement which is related to some
3991     * sort of a context change for which none of the events representing UI transitions
3992     * is a good fit. For example, announcing a new page in a book. If accessibility
3993     * is not enabled this method does nothing.
3994     *
3995     * @param text The announcement text.
3996     */
3997    public void announceForAccessibility(CharSequence text) {
3998        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3999            AccessibilityEvent event = AccessibilityEvent.obtain(
4000                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4001            event.getText().add(text);
4002            sendAccessibilityEventUnchecked(event);
4003        }
4004    }
4005
4006    /**
4007     * @see #sendAccessibilityEvent(int)
4008     *
4009     * Note: Called from the default {@link AccessibilityDelegate}.
4010     */
4011    void sendAccessibilityEventInternal(int eventType) {
4012        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4013            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4014        }
4015    }
4016
4017    /**
4018     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4019     * takes as an argument an empty {@link AccessibilityEvent} and does not
4020     * perform a check whether accessibility is enabled.
4021     * <p>
4022     * If an {@link AccessibilityDelegate} has been specified via calling
4023     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4024     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4025     * is responsible for handling this call.
4026     * </p>
4027     *
4028     * @param event The event to send.
4029     *
4030     * @see #sendAccessibilityEvent(int)
4031     */
4032    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4033        if (mAccessibilityDelegate != null) {
4034           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4035        } else {
4036            sendAccessibilityEventUncheckedInternal(event);
4037        }
4038    }
4039
4040    /**
4041     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4042     *
4043     * Note: Called from the default {@link AccessibilityDelegate}.
4044     */
4045    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4046        if (!isShown()) {
4047            return;
4048        }
4049        onInitializeAccessibilityEvent(event);
4050        // Only a subset of accessibility events populates text content.
4051        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4052            dispatchPopulateAccessibilityEvent(event);
4053        }
4054        // In the beginning we called #isShown(), so we know that getParent() is not null.
4055        getParent().requestSendAccessibilityEvent(this, event);
4056    }
4057
4058    /**
4059     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4060     * to its children for adding their text content to the event. Note that the
4061     * event text is populated in a separate dispatch path since we add to the
4062     * event not only the text of the source but also the text of all its descendants.
4063     * A typical implementation will call
4064     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4065     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4066     * on each child. Override this method if custom population of the event text
4067     * content is required.
4068     * <p>
4069     * If an {@link AccessibilityDelegate} has been specified via calling
4070     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4071     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4072     * is responsible for handling this call.
4073     * </p>
4074     * <p>
4075     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4076     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4077     * </p>
4078     *
4079     * @param event The event.
4080     *
4081     * @return True if the event population was completed.
4082     */
4083    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4084        if (mAccessibilityDelegate != null) {
4085            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4086        } else {
4087            return dispatchPopulateAccessibilityEventInternal(event);
4088        }
4089    }
4090
4091    /**
4092     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4093     *
4094     * Note: Called from the default {@link AccessibilityDelegate}.
4095     */
4096    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4097        onPopulateAccessibilityEvent(event);
4098        return false;
4099    }
4100
4101    /**
4102     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4103     * giving a chance to this View to populate the accessibility event with its
4104     * text content. While this method is free to modify event
4105     * attributes other than text content, doing so should normally be performed in
4106     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4107     * <p>
4108     * Example: Adding formatted date string to an accessibility event in addition
4109     *          to the text added by the super implementation:
4110     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4111     *     super.onPopulateAccessibilityEvent(event);
4112     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4113     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4114     *         mCurrentDate.getTimeInMillis(), flags);
4115     *     event.getText().add(selectedDateUtterance);
4116     * }</pre>
4117     * <p>
4118     * If an {@link AccessibilityDelegate} has been specified via calling
4119     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4120     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4121     * is responsible for handling this call.
4122     * </p>
4123     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4124     * information to the event, in case the default implementation has basic information to add.
4125     * </p>
4126     *
4127     * @param event The accessibility event which to populate.
4128     *
4129     * @see #sendAccessibilityEvent(int)
4130     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4131     */
4132    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4133        if (mAccessibilityDelegate != null) {
4134            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4135        } else {
4136            onPopulateAccessibilityEventInternal(event);
4137        }
4138    }
4139
4140    /**
4141     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4142     *
4143     * Note: Called from the default {@link AccessibilityDelegate}.
4144     */
4145    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4146
4147    }
4148
4149    /**
4150     * Initializes an {@link AccessibilityEvent} with information about
4151     * this View which is the event source. In other words, the source of
4152     * an accessibility event is the view whose state change triggered firing
4153     * the event.
4154     * <p>
4155     * Example: Setting the password property of an event in addition
4156     *          to properties set by the super implementation:
4157     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4158     *     super.onInitializeAccessibilityEvent(event);
4159     *     event.setPassword(true);
4160     * }</pre>
4161     * <p>
4162     * If an {@link AccessibilityDelegate} has been specified via calling
4163     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4164     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4165     * is responsible for handling this call.
4166     * </p>
4167     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4168     * information to the event, in case the default implementation has basic information to add.
4169     * </p>
4170     * @param event The event to initialize.
4171     *
4172     * @see #sendAccessibilityEvent(int)
4173     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4174     */
4175    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4176        if (mAccessibilityDelegate != null) {
4177            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4178        } else {
4179            onInitializeAccessibilityEventInternal(event);
4180        }
4181    }
4182
4183    /**
4184     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4185     *
4186     * Note: Called from the default {@link AccessibilityDelegate}.
4187     */
4188    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4189        event.setSource(this);
4190        event.setClassName(View.class.getName());
4191        event.setPackageName(getContext().getPackageName());
4192        event.setEnabled(isEnabled());
4193        event.setContentDescription(mContentDescription);
4194
4195        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4196            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4197            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4198                    FOCUSABLES_ALL);
4199            event.setItemCount(focusablesTempList.size());
4200            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4201            focusablesTempList.clear();
4202        }
4203    }
4204
4205    /**
4206     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4207     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4208     * This method is responsible for obtaining an accessibility node info from a
4209     * pool of reusable instances and calling
4210     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4211     * initialize the former.
4212     * <p>
4213     * Note: The client is responsible for recycling the obtained instance by calling
4214     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4215     * </p>
4216     *
4217     * @return A populated {@link AccessibilityNodeInfo}.
4218     *
4219     * @see AccessibilityNodeInfo
4220     */
4221    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4222        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4223        if (provider != null) {
4224            return provider.createAccessibilityNodeInfo(View.NO_ID);
4225        } else {
4226            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4227            onInitializeAccessibilityNodeInfo(info);
4228            return info;
4229        }
4230    }
4231
4232    /**
4233     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4234     * The base implementation sets:
4235     * <ul>
4236     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4237     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4238     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4239     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4240     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4241     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4242     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4243     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4244     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4245     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4246     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4247     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4248     * </ul>
4249     * <p>
4250     * Subclasses should override this method, call the super implementation,
4251     * and set additional attributes.
4252     * </p>
4253     * <p>
4254     * If an {@link AccessibilityDelegate} has been specified via calling
4255     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4256     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4257     * is responsible for handling this call.
4258     * </p>
4259     *
4260     * @param info The instance to initialize.
4261     */
4262    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4263        if (mAccessibilityDelegate != null) {
4264            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4265        } else {
4266            onInitializeAccessibilityNodeInfoInternal(info);
4267        }
4268    }
4269
4270    /**
4271     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4272     *
4273     * Note: Called from the default {@link AccessibilityDelegate}.
4274     */
4275    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4276        Rect bounds = mAttachInfo.mTmpInvalRect;
4277        getDrawingRect(bounds);
4278        info.setBoundsInParent(bounds);
4279
4280        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4281        getLocationOnScreen(locationOnScreen);
4282        bounds.offsetTo(0, 0);
4283        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4284        info.setBoundsInScreen(bounds);
4285
4286        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4287            ViewParent parent = getParent();
4288            if (parent instanceof View) {
4289                View parentView = (View) parent;
4290                info.setParent(parentView);
4291            }
4292        }
4293
4294        info.setPackageName(mContext.getPackageName());
4295        info.setClassName(View.class.getName());
4296        info.setContentDescription(getContentDescription());
4297
4298        info.setEnabled(isEnabled());
4299        info.setClickable(isClickable());
4300        info.setFocusable(isFocusable());
4301        info.setFocused(isFocused());
4302        info.setSelected(isSelected());
4303        info.setLongClickable(isLongClickable());
4304
4305        // TODO: These make sense only if we are in an AdapterView but all
4306        // views can be selected. Maybe from accessiiblity perspective
4307        // we should report as selectable view in an AdapterView.
4308        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4309        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4310
4311        if (isFocusable()) {
4312            if (isFocused()) {
4313                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4314            } else {
4315                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4316            }
4317        }
4318    }
4319
4320    /**
4321     * Sets a delegate for implementing accessibility support via compositon as
4322     * opposed to inheritance. The delegate's primary use is for implementing
4323     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4324     *
4325     * @param delegate The delegate instance.
4326     *
4327     * @see AccessibilityDelegate
4328     */
4329    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4330        mAccessibilityDelegate = delegate;
4331    }
4332
4333    /**
4334     * Gets the provider for managing a virtual view hierarchy rooted at this View
4335     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4336     * that explore the window content.
4337     * <p>
4338     * If this method returns an instance, this instance is responsible for managing
4339     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4340     * View including the one representing the View itself. Similarly the returned
4341     * instance is responsible for performing accessibility actions on any virtual
4342     * view or the root view itself.
4343     * </p>
4344     * <p>
4345     * If an {@link AccessibilityDelegate} has been specified via calling
4346     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4347     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4348     * is responsible for handling this call.
4349     * </p>
4350     *
4351     * @return The provider.
4352     *
4353     * @see AccessibilityNodeProvider
4354     */
4355    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4356        if (mAccessibilityDelegate != null) {
4357            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4358        } else {
4359            return null;
4360        }
4361    }
4362
4363    /**
4364     * Gets the unique identifier of this view on the screen for accessibility purposes.
4365     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4366     *
4367     * @return The view accessibility id.
4368     *
4369     * @hide
4370     */
4371    public int getAccessibilityViewId() {
4372        if (mAccessibilityViewId == NO_ID) {
4373            mAccessibilityViewId = sNextAccessibilityViewId++;
4374        }
4375        return mAccessibilityViewId;
4376    }
4377
4378    /**
4379     * Gets the unique identifier of the window in which this View reseides.
4380     *
4381     * @return The window accessibility id.
4382     *
4383     * @hide
4384     */
4385    public int getAccessibilityWindowId() {
4386        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4387    }
4388
4389    /**
4390     * Gets the {@link View} description. It briefly describes the view and is
4391     * primarily used for accessibility support. Set this property to enable
4392     * better accessibility support for your application. This is especially
4393     * true for views that do not have textual representation (For example,
4394     * ImageButton).
4395     *
4396     * @return The content descriptiopn.
4397     *
4398     * @attr ref android.R.styleable#View_contentDescription
4399     */
4400    public CharSequence getContentDescription() {
4401        return mContentDescription;
4402    }
4403
4404    /**
4405     * Sets the {@link View} description. It briefly describes the view and is
4406     * primarily used for accessibility support. Set this property to enable
4407     * better accessibility support for your application. This is especially
4408     * true for views that do not have textual representation (For example,
4409     * ImageButton).
4410     *
4411     * @param contentDescription The content description.
4412     *
4413     * @attr ref android.R.styleable#View_contentDescription
4414     */
4415    @RemotableViewMethod
4416    public void setContentDescription(CharSequence contentDescription) {
4417        mContentDescription = contentDescription;
4418    }
4419
4420    /**
4421     * Invoked whenever this view loses focus, either by losing window focus or by losing
4422     * focus within its window. This method can be used to clear any state tied to the
4423     * focus. For instance, if a button is held pressed with the trackball and the window
4424     * loses focus, this method can be used to cancel the press.
4425     *
4426     * Subclasses of View overriding this method should always call super.onFocusLost().
4427     *
4428     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4429     * @see #onWindowFocusChanged(boolean)
4430     *
4431     * @hide pending API council approval
4432     */
4433    protected void onFocusLost() {
4434        resetPressedState();
4435    }
4436
4437    private void resetPressedState() {
4438        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4439            return;
4440        }
4441
4442        if (isPressed()) {
4443            setPressed(false);
4444
4445            if (!mHasPerformedLongPress) {
4446                removeLongPressCallback();
4447            }
4448        }
4449    }
4450
4451    /**
4452     * Returns true if this view has focus
4453     *
4454     * @return True if this view has focus, false otherwise.
4455     */
4456    @ViewDebug.ExportedProperty(category = "focus")
4457    public boolean isFocused() {
4458        return (mPrivateFlags & FOCUSED) != 0;
4459    }
4460
4461    /**
4462     * Find the view in the hierarchy rooted at this view that currently has
4463     * focus.
4464     *
4465     * @return The view that currently has focus, or null if no focused view can
4466     *         be found.
4467     */
4468    public View findFocus() {
4469        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4470    }
4471
4472    /**
4473     * Change whether this view is one of the set of scrollable containers in
4474     * its window.  This will be used to determine whether the window can
4475     * resize or must pan when a soft input area is open -- scrollable
4476     * containers allow the window to use resize mode since the container
4477     * will appropriately shrink.
4478     */
4479    public void setScrollContainer(boolean isScrollContainer) {
4480        if (isScrollContainer) {
4481            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4482                mAttachInfo.mScrollContainers.add(this);
4483                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4484            }
4485            mPrivateFlags |= SCROLL_CONTAINER;
4486        } else {
4487            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4488                mAttachInfo.mScrollContainers.remove(this);
4489            }
4490            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4491        }
4492    }
4493
4494    /**
4495     * Returns the quality of the drawing cache.
4496     *
4497     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4498     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4499     *
4500     * @see #setDrawingCacheQuality(int)
4501     * @see #setDrawingCacheEnabled(boolean)
4502     * @see #isDrawingCacheEnabled()
4503     *
4504     * @attr ref android.R.styleable#View_drawingCacheQuality
4505     */
4506    public int getDrawingCacheQuality() {
4507        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4508    }
4509
4510    /**
4511     * Set the drawing cache quality of this view. This value is used only when the
4512     * drawing cache is enabled
4513     *
4514     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4515     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4516     *
4517     * @see #getDrawingCacheQuality()
4518     * @see #setDrawingCacheEnabled(boolean)
4519     * @see #isDrawingCacheEnabled()
4520     *
4521     * @attr ref android.R.styleable#View_drawingCacheQuality
4522     */
4523    public void setDrawingCacheQuality(int quality) {
4524        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4525    }
4526
4527    /**
4528     * Returns whether the screen should remain on, corresponding to the current
4529     * value of {@link #KEEP_SCREEN_ON}.
4530     *
4531     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4532     *
4533     * @see #setKeepScreenOn(boolean)
4534     *
4535     * @attr ref android.R.styleable#View_keepScreenOn
4536     */
4537    public boolean getKeepScreenOn() {
4538        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4539    }
4540
4541    /**
4542     * Controls whether the screen should remain on, modifying the
4543     * value of {@link #KEEP_SCREEN_ON}.
4544     *
4545     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4546     *
4547     * @see #getKeepScreenOn()
4548     *
4549     * @attr ref android.R.styleable#View_keepScreenOn
4550     */
4551    public void setKeepScreenOn(boolean keepScreenOn) {
4552        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4553    }
4554
4555    /**
4556     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4557     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4558     *
4559     * @attr ref android.R.styleable#View_nextFocusLeft
4560     */
4561    public int getNextFocusLeftId() {
4562        return mNextFocusLeftId;
4563    }
4564
4565    /**
4566     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4567     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4568     * decide automatically.
4569     *
4570     * @attr ref android.R.styleable#View_nextFocusLeft
4571     */
4572    public void setNextFocusLeftId(int nextFocusLeftId) {
4573        mNextFocusLeftId = nextFocusLeftId;
4574    }
4575
4576    /**
4577     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4578     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4579     *
4580     * @attr ref android.R.styleable#View_nextFocusRight
4581     */
4582    public int getNextFocusRightId() {
4583        return mNextFocusRightId;
4584    }
4585
4586    /**
4587     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4588     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4589     * decide automatically.
4590     *
4591     * @attr ref android.R.styleable#View_nextFocusRight
4592     */
4593    public void setNextFocusRightId(int nextFocusRightId) {
4594        mNextFocusRightId = nextFocusRightId;
4595    }
4596
4597    /**
4598     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4599     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4600     *
4601     * @attr ref android.R.styleable#View_nextFocusUp
4602     */
4603    public int getNextFocusUpId() {
4604        return mNextFocusUpId;
4605    }
4606
4607    /**
4608     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4609     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4610     * decide automatically.
4611     *
4612     * @attr ref android.R.styleable#View_nextFocusUp
4613     */
4614    public void setNextFocusUpId(int nextFocusUpId) {
4615        mNextFocusUpId = nextFocusUpId;
4616    }
4617
4618    /**
4619     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4620     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4621     *
4622     * @attr ref android.R.styleable#View_nextFocusDown
4623     */
4624    public int getNextFocusDownId() {
4625        return mNextFocusDownId;
4626    }
4627
4628    /**
4629     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4630     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4631     * decide automatically.
4632     *
4633     * @attr ref android.R.styleable#View_nextFocusDown
4634     */
4635    public void setNextFocusDownId(int nextFocusDownId) {
4636        mNextFocusDownId = nextFocusDownId;
4637    }
4638
4639    /**
4640     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4641     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4642     *
4643     * @attr ref android.R.styleable#View_nextFocusForward
4644     */
4645    public int getNextFocusForwardId() {
4646        return mNextFocusForwardId;
4647    }
4648
4649    /**
4650     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4651     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4652     * decide automatically.
4653     *
4654     * @attr ref android.R.styleable#View_nextFocusForward
4655     */
4656    public void setNextFocusForwardId(int nextFocusForwardId) {
4657        mNextFocusForwardId = nextFocusForwardId;
4658    }
4659
4660    /**
4661     * Returns the visibility of this view and all of its ancestors
4662     *
4663     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4664     */
4665    public boolean isShown() {
4666        View current = this;
4667        //noinspection ConstantConditions
4668        do {
4669            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4670                return false;
4671            }
4672            ViewParent parent = current.mParent;
4673            if (parent == null) {
4674                return false; // We are not attached to the view root
4675            }
4676            if (!(parent instanceof View)) {
4677                return true;
4678            }
4679            current = (View) parent;
4680        } while (current != null);
4681
4682        return false;
4683    }
4684
4685    /**
4686     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4687     * is set
4688     *
4689     * @param insets Insets for system windows
4690     *
4691     * @return True if this view applied the insets, false otherwise
4692     */
4693    protected boolean fitSystemWindows(Rect insets) {
4694        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4695            mPaddingLeft = insets.left;
4696            mPaddingTop = insets.top;
4697            mPaddingRight = insets.right;
4698            mPaddingBottom = insets.bottom;
4699            requestLayout();
4700            return true;
4701        }
4702        return false;
4703    }
4704
4705    /**
4706     * Set whether or not this view should account for system screen decorations
4707     * such as the status bar and inset its content. This allows this view to be
4708     * positioned in absolute screen coordinates and remain visible to the user.
4709     *
4710     * <p>This should only be used by top-level window decor views.
4711     *
4712     * @param fitSystemWindows true to inset content for system screen decorations, false for
4713     *                         default behavior.
4714     *
4715     * @attr ref android.R.styleable#View_fitsSystemWindows
4716     */
4717    public void setFitsSystemWindows(boolean fitSystemWindows) {
4718        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4719    }
4720
4721    /**
4722     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4723     * will account for system screen decorations such as the status bar and inset its
4724     * content. This allows the view to be positioned in absolute screen coordinates
4725     * and remain visible to the user.
4726     *
4727     * @return true if this view will adjust its content bounds for system screen decorations.
4728     *
4729     * @attr ref android.R.styleable#View_fitsSystemWindows
4730     */
4731    public boolean fitsSystemWindows() {
4732        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4733    }
4734
4735    /**
4736     * Returns the visibility status for this view.
4737     *
4738     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4739     * @attr ref android.R.styleable#View_visibility
4740     */
4741    @ViewDebug.ExportedProperty(mapping = {
4742        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4743        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4744        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4745    })
4746    public int getVisibility() {
4747        return mViewFlags & VISIBILITY_MASK;
4748    }
4749
4750    /**
4751     * Set the enabled state of this view.
4752     *
4753     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4754     * @attr ref android.R.styleable#View_visibility
4755     */
4756    @RemotableViewMethod
4757    public void setVisibility(int visibility) {
4758        setFlags(visibility, VISIBILITY_MASK);
4759        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4760    }
4761
4762    /**
4763     * Returns the enabled status for this view. The interpretation of the
4764     * enabled state varies by subclass.
4765     *
4766     * @return True if this view is enabled, false otherwise.
4767     */
4768    @ViewDebug.ExportedProperty
4769    public boolean isEnabled() {
4770        return (mViewFlags & ENABLED_MASK) == ENABLED;
4771    }
4772
4773    /**
4774     * Set the enabled state of this view. The interpretation of the enabled
4775     * state varies by subclass.
4776     *
4777     * @param enabled True if this view is enabled, false otherwise.
4778     */
4779    @RemotableViewMethod
4780    public void setEnabled(boolean enabled) {
4781        if (enabled == isEnabled()) return;
4782
4783        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4784
4785        /*
4786         * The View most likely has to change its appearance, so refresh
4787         * the drawable state.
4788         */
4789        refreshDrawableState();
4790
4791        // Invalidate too, since the default behavior for views is to be
4792        // be drawn at 50% alpha rather than to change the drawable.
4793        invalidate(true);
4794    }
4795
4796    /**
4797     * Set whether this view can receive the focus.
4798     *
4799     * Setting this to false will also ensure that this view is not focusable
4800     * in touch mode.
4801     *
4802     * @param focusable If true, this view can receive the focus.
4803     *
4804     * @see #setFocusableInTouchMode(boolean)
4805     * @attr ref android.R.styleable#View_focusable
4806     */
4807    public void setFocusable(boolean focusable) {
4808        if (!focusable) {
4809            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4810        }
4811        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4812    }
4813
4814    /**
4815     * Set whether this view can receive focus while in touch mode.
4816     *
4817     * Setting this to true will also ensure that this view is focusable.
4818     *
4819     * @param focusableInTouchMode If true, this view can receive the focus while
4820     *   in touch mode.
4821     *
4822     * @see #setFocusable(boolean)
4823     * @attr ref android.R.styleable#View_focusableInTouchMode
4824     */
4825    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4826        // Focusable in touch mode should always be set before the focusable flag
4827        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4828        // which, in touch mode, will not successfully request focus on this view
4829        // because the focusable in touch mode flag is not set
4830        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4831        if (focusableInTouchMode) {
4832            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4833        }
4834    }
4835
4836    /**
4837     * Set whether this view should have sound effects enabled for events such as
4838     * clicking and touching.
4839     *
4840     * <p>You may wish to disable sound effects for a view if you already play sounds,
4841     * for instance, a dial key that plays dtmf tones.
4842     *
4843     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4844     * @see #isSoundEffectsEnabled()
4845     * @see #playSoundEffect(int)
4846     * @attr ref android.R.styleable#View_soundEffectsEnabled
4847     */
4848    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4849        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4850    }
4851
4852    /**
4853     * @return whether this view should have sound effects enabled for events such as
4854     *     clicking and touching.
4855     *
4856     * @see #setSoundEffectsEnabled(boolean)
4857     * @see #playSoundEffect(int)
4858     * @attr ref android.R.styleable#View_soundEffectsEnabled
4859     */
4860    @ViewDebug.ExportedProperty
4861    public boolean isSoundEffectsEnabled() {
4862        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4863    }
4864
4865    /**
4866     * Set whether this view should have haptic feedback for events such as
4867     * long presses.
4868     *
4869     * <p>You may wish to disable haptic feedback if your view already controls
4870     * its own haptic feedback.
4871     *
4872     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4873     * @see #isHapticFeedbackEnabled()
4874     * @see #performHapticFeedback(int)
4875     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4876     */
4877    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4878        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4879    }
4880
4881    /**
4882     * @return whether this view should have haptic feedback enabled for events
4883     * long presses.
4884     *
4885     * @see #setHapticFeedbackEnabled(boolean)
4886     * @see #performHapticFeedback(int)
4887     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4888     */
4889    @ViewDebug.ExportedProperty
4890    public boolean isHapticFeedbackEnabled() {
4891        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4892    }
4893
4894    /**
4895     * Returns the layout direction for this view.
4896     *
4897     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4898     *   {@link #LAYOUT_DIRECTION_RTL},
4899     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4900     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4901     * @attr ref android.R.styleable#View_layoutDirection
4902     */
4903    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4904        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4905        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4906        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4907        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4908    })
4909    public int getLayoutDirection() {
4910        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
4911    }
4912
4913    /**
4914     * Set the layout direction for this view. This will propagate a reset of layout direction
4915     * resolution to the view's children and resolve layout direction for this view.
4916     *
4917     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4918     *   {@link #LAYOUT_DIRECTION_RTL},
4919     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4920     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4921     *
4922     * @attr ref android.R.styleable#View_layoutDirection
4923     */
4924    @RemotableViewMethod
4925    public void setLayoutDirection(int layoutDirection) {
4926        if (getLayoutDirection() != layoutDirection) {
4927            // Reset the current layout direction
4928            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
4929            // Reset the current resolved layout direction
4930            resetResolvedLayoutDirection();
4931            // Set the new layout direction (filtered) and ask for a layout pass
4932            mPrivateFlags2 |=
4933                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
4934            requestLayout();
4935        }
4936    }
4937
4938    /**
4939     * Returns the resolved layout direction for this view.
4940     *
4941     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4942     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
4943     */
4944    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4945        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
4946        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
4947    })
4948    public int getResolvedLayoutDirection() {
4949        resolveLayoutDirectionIfNeeded();
4950        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4951                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4952    }
4953
4954    /**
4955     * Indicates whether or not this view's layout is right-to-left. This is resolved from
4956     * layout attribute and/or the inherited value from the parent
4957     *
4958     * @return true if the layout is right-to-left.
4959     */
4960    @ViewDebug.ExportedProperty(category = "layout")
4961    public boolean isLayoutRtl() {
4962        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4963    }
4964
4965    /**
4966     * Indicates whether the view is currently tracking transient state that the
4967     * app should not need to concern itself with saving and restoring, but that
4968     * the framework should take special note to preserve when possible.
4969     *
4970     * @return true if the view has transient state
4971     */
4972    @ViewDebug.ExportedProperty(category = "layout")
4973    public boolean hasTransientState() {
4974        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
4975    }
4976
4977    /**
4978     * Set whether this view is currently tracking transient state that the
4979     * framework should attempt to preserve when possible.
4980     *
4981     * @param hasTransientState true if this view has transient state
4982     */
4983    public void setHasTransientState(boolean hasTransientState) {
4984        if (hasTransientState() == hasTransientState) return;
4985
4986        mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
4987                (hasTransientState ? HAS_TRANSIENT_STATE : 0);
4988        if (mParent != null) {
4989            try {
4990                mParent.childHasTransientStateChanged(this, hasTransientState);
4991            } catch (AbstractMethodError e) {
4992                Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
4993                        " does not fully implement ViewParent", e);
4994            }
4995        }
4996    }
4997
4998    /**
4999     * If this view doesn't do any drawing on its own, set this flag to
5000     * allow further optimizations. By default, this flag is not set on
5001     * View, but could be set on some View subclasses such as ViewGroup.
5002     *
5003     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5004     * you should clear this flag.
5005     *
5006     * @param willNotDraw whether or not this View draw on its own
5007     */
5008    public void setWillNotDraw(boolean willNotDraw) {
5009        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5010    }
5011
5012    /**
5013     * Returns whether or not this View draws on its own.
5014     *
5015     * @return true if this view has nothing to draw, false otherwise
5016     */
5017    @ViewDebug.ExportedProperty(category = "drawing")
5018    public boolean willNotDraw() {
5019        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5020    }
5021
5022    /**
5023     * When a View's drawing cache is enabled, drawing is redirected to an
5024     * offscreen bitmap. Some views, like an ImageView, must be able to
5025     * bypass this mechanism if they already draw a single bitmap, to avoid
5026     * unnecessary usage of the memory.
5027     *
5028     * @param willNotCacheDrawing true if this view does not cache its
5029     *        drawing, false otherwise
5030     */
5031    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5032        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5033    }
5034
5035    /**
5036     * Returns whether or not this View can cache its drawing or not.
5037     *
5038     * @return true if this view does not cache its drawing, false otherwise
5039     */
5040    @ViewDebug.ExportedProperty(category = "drawing")
5041    public boolean willNotCacheDrawing() {
5042        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5043    }
5044
5045    /**
5046     * Indicates whether this view reacts to click events or not.
5047     *
5048     * @return true if the view is clickable, false otherwise
5049     *
5050     * @see #setClickable(boolean)
5051     * @attr ref android.R.styleable#View_clickable
5052     */
5053    @ViewDebug.ExportedProperty
5054    public boolean isClickable() {
5055        return (mViewFlags & CLICKABLE) == CLICKABLE;
5056    }
5057
5058    /**
5059     * Enables or disables click events for this view. When a view
5060     * is clickable it will change its state to "pressed" on every click.
5061     * Subclasses should set the view clickable to visually react to
5062     * user's clicks.
5063     *
5064     * @param clickable true to make the view clickable, false otherwise
5065     *
5066     * @see #isClickable()
5067     * @attr ref android.R.styleable#View_clickable
5068     */
5069    public void setClickable(boolean clickable) {
5070        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5071    }
5072
5073    /**
5074     * Indicates whether this view reacts to long click events or not.
5075     *
5076     * @return true if the view is long clickable, false otherwise
5077     *
5078     * @see #setLongClickable(boolean)
5079     * @attr ref android.R.styleable#View_longClickable
5080     */
5081    public boolean isLongClickable() {
5082        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5083    }
5084
5085    /**
5086     * Enables or disables long click events for this view. When a view is long
5087     * clickable it reacts to the user holding down the button for a longer
5088     * duration than a tap. This event can either launch the listener or a
5089     * context menu.
5090     *
5091     * @param longClickable true to make the view long clickable, false otherwise
5092     * @see #isLongClickable()
5093     * @attr ref android.R.styleable#View_longClickable
5094     */
5095    public void setLongClickable(boolean longClickable) {
5096        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5097    }
5098
5099    /**
5100     * Sets the pressed state for this view.
5101     *
5102     * @see #isClickable()
5103     * @see #setClickable(boolean)
5104     *
5105     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5106     *        the View's internal state from a previously set "pressed" state.
5107     */
5108    public void setPressed(boolean pressed) {
5109        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5110
5111        if (pressed) {
5112            mPrivateFlags |= PRESSED;
5113        } else {
5114            mPrivateFlags &= ~PRESSED;
5115        }
5116
5117        if (needsRefresh) {
5118            refreshDrawableState();
5119        }
5120        dispatchSetPressed(pressed);
5121    }
5122
5123    /**
5124     * Dispatch setPressed to all of this View's children.
5125     *
5126     * @see #setPressed(boolean)
5127     *
5128     * @param pressed The new pressed state
5129     */
5130    protected void dispatchSetPressed(boolean pressed) {
5131    }
5132
5133    /**
5134     * Indicates whether the view is currently in pressed state. Unless
5135     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5136     * the pressed state.
5137     *
5138     * @see #setPressed(boolean)
5139     * @see #isClickable()
5140     * @see #setClickable(boolean)
5141     *
5142     * @return true if the view is currently pressed, false otherwise
5143     */
5144    public boolean isPressed() {
5145        return (mPrivateFlags & PRESSED) == PRESSED;
5146    }
5147
5148    /**
5149     * Indicates whether this view will save its state (that is,
5150     * whether its {@link #onSaveInstanceState} method will be called).
5151     *
5152     * @return Returns true if the view state saving is enabled, else false.
5153     *
5154     * @see #setSaveEnabled(boolean)
5155     * @attr ref android.R.styleable#View_saveEnabled
5156     */
5157    public boolean isSaveEnabled() {
5158        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5159    }
5160
5161    /**
5162     * Controls whether the saving of this view's state is
5163     * enabled (that is, whether its {@link #onSaveInstanceState} method
5164     * will be called).  Note that even if freezing is enabled, the
5165     * view still must have an id assigned to it (via {@link #setId(int)})
5166     * for its state to be saved.  This flag can only disable the
5167     * saving of this view; any child views may still have their state saved.
5168     *
5169     * @param enabled Set to false to <em>disable</em> state saving, or true
5170     * (the default) to allow it.
5171     *
5172     * @see #isSaveEnabled()
5173     * @see #setId(int)
5174     * @see #onSaveInstanceState()
5175     * @attr ref android.R.styleable#View_saveEnabled
5176     */
5177    public void setSaveEnabled(boolean enabled) {
5178        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5179    }
5180
5181    /**
5182     * Gets whether the framework should discard touches when the view's
5183     * window is obscured by another visible window.
5184     * Refer to the {@link View} security documentation for more details.
5185     *
5186     * @return True if touch filtering is enabled.
5187     *
5188     * @see #setFilterTouchesWhenObscured(boolean)
5189     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5190     */
5191    @ViewDebug.ExportedProperty
5192    public boolean getFilterTouchesWhenObscured() {
5193        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5194    }
5195
5196    /**
5197     * Sets whether the framework should discard touches when the view's
5198     * window is obscured by another visible window.
5199     * Refer to the {@link View} security documentation for more details.
5200     *
5201     * @param enabled True if touch filtering should be enabled.
5202     *
5203     * @see #getFilterTouchesWhenObscured
5204     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5205     */
5206    public void setFilterTouchesWhenObscured(boolean enabled) {
5207        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5208                FILTER_TOUCHES_WHEN_OBSCURED);
5209    }
5210
5211    /**
5212     * Indicates whether the entire hierarchy under this view will save its
5213     * state when a state saving traversal occurs from its parent.  The default
5214     * is true; if false, these views will not be saved unless
5215     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5216     *
5217     * @return Returns true if the view state saving from parent is enabled, else false.
5218     *
5219     * @see #setSaveFromParentEnabled(boolean)
5220     */
5221    public boolean isSaveFromParentEnabled() {
5222        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5223    }
5224
5225    /**
5226     * Controls whether the entire hierarchy under this view will save its
5227     * state when a state saving traversal occurs from its parent.  The default
5228     * is true; if false, these views will not be saved unless
5229     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5230     *
5231     * @param enabled Set to false to <em>disable</em> state saving, or true
5232     * (the default) to allow it.
5233     *
5234     * @see #isSaveFromParentEnabled()
5235     * @see #setId(int)
5236     * @see #onSaveInstanceState()
5237     */
5238    public void setSaveFromParentEnabled(boolean enabled) {
5239        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5240    }
5241
5242
5243    /**
5244     * Returns whether this View is able to take focus.
5245     *
5246     * @return True if this view can take focus, or false otherwise.
5247     * @attr ref android.R.styleable#View_focusable
5248     */
5249    @ViewDebug.ExportedProperty(category = "focus")
5250    public final boolean isFocusable() {
5251        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5252    }
5253
5254    /**
5255     * When a view is focusable, it may not want to take focus when in touch mode.
5256     * For example, a button would like focus when the user is navigating via a D-pad
5257     * so that the user can click on it, but once the user starts touching the screen,
5258     * the button shouldn't take focus
5259     * @return Whether the view is focusable in touch mode.
5260     * @attr ref android.R.styleable#View_focusableInTouchMode
5261     */
5262    @ViewDebug.ExportedProperty
5263    public final boolean isFocusableInTouchMode() {
5264        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5265    }
5266
5267    /**
5268     * Find the nearest view in the specified direction that can take focus.
5269     * This does not actually give focus to that view.
5270     *
5271     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5272     *
5273     * @return The nearest focusable in the specified direction, or null if none
5274     *         can be found.
5275     */
5276    public View focusSearch(int direction) {
5277        if (mParent != null) {
5278            return mParent.focusSearch(this, direction);
5279        } else {
5280            return null;
5281        }
5282    }
5283
5284    /**
5285     * This method is the last chance for the focused view and its ancestors to
5286     * respond to an arrow key. This is called when the focused view did not
5287     * consume the key internally, nor could the view system find a new view in
5288     * the requested direction to give focus to.
5289     *
5290     * @param focused The currently focused view.
5291     * @param direction The direction focus wants to move. One of FOCUS_UP,
5292     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5293     * @return True if the this view consumed this unhandled move.
5294     */
5295    public boolean dispatchUnhandledMove(View focused, int direction) {
5296        return false;
5297    }
5298
5299    /**
5300     * If a user manually specified the next view id for a particular direction,
5301     * use the root to look up the view.
5302     * @param root The root view of the hierarchy containing this view.
5303     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5304     * or FOCUS_BACKWARD.
5305     * @return The user specified next view, or null if there is none.
5306     */
5307    View findUserSetNextFocus(View root, int direction) {
5308        switch (direction) {
5309            case FOCUS_LEFT:
5310                if (mNextFocusLeftId == View.NO_ID) return null;
5311                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5312            case FOCUS_RIGHT:
5313                if (mNextFocusRightId == View.NO_ID) return null;
5314                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5315            case FOCUS_UP:
5316                if (mNextFocusUpId == View.NO_ID) return null;
5317                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5318            case FOCUS_DOWN:
5319                if (mNextFocusDownId == View.NO_ID) return null;
5320                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5321            case FOCUS_FORWARD:
5322                if (mNextFocusForwardId == View.NO_ID) return null;
5323                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5324            case FOCUS_BACKWARD: {
5325                if (mID == View.NO_ID) return null;
5326                final int id = mID;
5327                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5328                    @Override
5329                    public boolean apply(View t) {
5330                        return t.mNextFocusForwardId == id;
5331                    }
5332                });
5333            }
5334        }
5335        return null;
5336    }
5337
5338    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5339        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5340            @Override
5341            public boolean apply(View t) {
5342                return t.mID == childViewId;
5343            }
5344        });
5345
5346        if (result == null) {
5347            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5348                    + "by user for id " + childViewId);
5349        }
5350        return result;
5351    }
5352
5353    /**
5354     * Find and return all focusable views that are descendants of this view,
5355     * possibly including this view if it is focusable itself.
5356     *
5357     * @param direction The direction of the focus
5358     * @return A list of focusable views
5359     */
5360    public ArrayList<View> getFocusables(int direction) {
5361        ArrayList<View> result = new ArrayList<View>(24);
5362        addFocusables(result, direction);
5363        return result;
5364    }
5365
5366    /**
5367     * Add any focusable views that are descendants of this view (possibly
5368     * including this view if it is focusable itself) to views.  If we are in touch mode,
5369     * only add views that are also focusable in touch mode.
5370     *
5371     * @param views Focusable views found so far
5372     * @param direction The direction of the focus
5373     */
5374    public void addFocusables(ArrayList<View> views, int direction) {
5375        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5376    }
5377
5378    /**
5379     * Adds any focusable views that are descendants of this view (possibly
5380     * including this view if it is focusable itself) to views. This method
5381     * adds all focusable views regardless if we are in touch mode or
5382     * only views focusable in touch mode if we are in touch mode depending on
5383     * the focusable mode paramater.
5384     *
5385     * @param views Focusable views found so far or null if all we are interested is
5386     *        the number of focusables.
5387     * @param direction The direction of the focus.
5388     * @param focusableMode The type of focusables to be added.
5389     *
5390     * @see #FOCUSABLES_ALL
5391     * @see #FOCUSABLES_TOUCH_MODE
5392     */
5393    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5394        if (!isFocusable()) {
5395            return;
5396        }
5397
5398        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5399                isInTouchMode() && !isFocusableInTouchMode()) {
5400            return;
5401        }
5402
5403        if (views != null) {
5404            views.add(this);
5405        }
5406    }
5407
5408    /**
5409     * Finds the Views that contain given text. The containment is case insensitive.
5410     * The search is performed by either the text that the View renders or the content
5411     * description that describes the view for accessibility purposes and the view does
5412     * not render or both. Clients can specify how the search is to be performed via
5413     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5414     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5415     *
5416     * @param outViews The output list of matching Views.
5417     * @param searched The text to match against.
5418     *
5419     * @see #FIND_VIEWS_WITH_TEXT
5420     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5421     * @see #setContentDescription(CharSequence)
5422     */
5423    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5424        if (getAccessibilityNodeProvider() != null) {
5425            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5426                outViews.add(this);
5427            }
5428        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5429                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5430            String searchedLowerCase = searched.toString().toLowerCase();
5431            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5432            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5433                outViews.add(this);
5434            }
5435        }
5436    }
5437
5438    /**
5439     * Find and return all touchable views that are descendants of this view,
5440     * possibly including this view if it is touchable itself.
5441     *
5442     * @return A list of touchable views
5443     */
5444    public ArrayList<View> getTouchables() {
5445        ArrayList<View> result = new ArrayList<View>();
5446        addTouchables(result);
5447        return result;
5448    }
5449
5450    /**
5451     * Add any touchable views that are descendants of this view (possibly
5452     * including this view if it is touchable itself) to views.
5453     *
5454     * @param views Touchable views found so far
5455     */
5456    public void addTouchables(ArrayList<View> views) {
5457        final int viewFlags = mViewFlags;
5458
5459        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5460                && (viewFlags & ENABLED_MASK) == ENABLED) {
5461            views.add(this);
5462        }
5463    }
5464
5465    /**
5466     * Call this to try to give focus to a specific view or to one of its
5467     * descendants.
5468     *
5469     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5470     * false), or if it is focusable and it is not focusable in touch mode
5471     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5472     *
5473     * See also {@link #focusSearch(int)}, which is what you call to say that you
5474     * have focus, and you want your parent to look for the next one.
5475     *
5476     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5477     * {@link #FOCUS_DOWN} and <code>null</code>.
5478     *
5479     * @return Whether this view or one of its descendants actually took focus.
5480     */
5481    public final boolean requestFocus() {
5482        return requestFocus(View.FOCUS_DOWN);
5483    }
5484
5485
5486    /**
5487     * Call this to try to give focus to a specific view or to one of its
5488     * descendants and give it a hint about what direction focus is heading.
5489     *
5490     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5491     * false), or if it is focusable and it is not focusable in touch mode
5492     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5493     *
5494     * See also {@link #focusSearch(int)}, which is what you call to say that you
5495     * have focus, and you want your parent to look for the next one.
5496     *
5497     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5498     * <code>null</code> set for the previously focused rectangle.
5499     *
5500     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5501     * @return Whether this view or one of its descendants actually took focus.
5502     */
5503    public final boolean requestFocus(int direction) {
5504        return requestFocus(direction, null);
5505    }
5506
5507    /**
5508     * Call this to try to give focus to a specific view or to one of its descendants
5509     * and give it hints about the direction and a specific rectangle that the focus
5510     * is coming from.  The rectangle can help give larger views a finer grained hint
5511     * about where focus is coming from, and therefore, where to show selection, or
5512     * forward focus change internally.
5513     *
5514     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5515     * false), or if it is focusable and it is not focusable in touch mode
5516     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5517     *
5518     * A View will not take focus if it is not visible.
5519     *
5520     * A View will not take focus if one of its parents has
5521     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5522     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5523     *
5524     * See also {@link #focusSearch(int)}, which is what you call to say that you
5525     * have focus, and you want your parent to look for the next one.
5526     *
5527     * You may wish to override this method if your custom {@link View} has an internal
5528     * {@link View} that it wishes to forward the request to.
5529     *
5530     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5531     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5532     *        to give a finer grained hint about where focus is coming from.  May be null
5533     *        if there is no hint.
5534     * @return Whether this view or one of its descendants actually took focus.
5535     */
5536    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5537        // need to be focusable
5538        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5539                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5540            return false;
5541        }
5542
5543        // need to be focusable in touch mode if in touch mode
5544        if (isInTouchMode() &&
5545            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5546               return false;
5547        }
5548
5549        // need to not have any parents blocking us
5550        if (hasAncestorThatBlocksDescendantFocus()) {
5551            return false;
5552        }
5553
5554        handleFocusGainInternal(direction, previouslyFocusedRect);
5555        return true;
5556    }
5557
5558    /**
5559     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5560     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5561     * touch mode to request focus when they are touched.
5562     *
5563     * @return Whether this view or one of its descendants actually took focus.
5564     *
5565     * @see #isInTouchMode()
5566     *
5567     */
5568    public final boolean requestFocusFromTouch() {
5569        // Leave touch mode if we need to
5570        if (isInTouchMode()) {
5571            ViewRootImpl viewRoot = getViewRootImpl();
5572            if (viewRoot != null) {
5573                viewRoot.ensureTouchMode(false);
5574            }
5575        }
5576        return requestFocus(View.FOCUS_DOWN);
5577    }
5578
5579    /**
5580     * @return Whether any ancestor of this view blocks descendant focus.
5581     */
5582    private boolean hasAncestorThatBlocksDescendantFocus() {
5583        ViewParent ancestor = mParent;
5584        while (ancestor instanceof ViewGroup) {
5585            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5586            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5587                return true;
5588            } else {
5589                ancestor = vgAncestor.getParent();
5590            }
5591        }
5592        return false;
5593    }
5594
5595    /**
5596     * @hide
5597     */
5598    public void dispatchStartTemporaryDetach() {
5599        onStartTemporaryDetach();
5600    }
5601
5602    /**
5603     * This is called when a container is going to temporarily detach a child, with
5604     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5605     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5606     * {@link #onDetachedFromWindow()} when the container is done.
5607     */
5608    public void onStartTemporaryDetach() {
5609        removeUnsetPressCallback();
5610        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5611    }
5612
5613    /**
5614     * @hide
5615     */
5616    public void dispatchFinishTemporaryDetach() {
5617        onFinishTemporaryDetach();
5618    }
5619
5620    /**
5621     * Called after {@link #onStartTemporaryDetach} when the container is done
5622     * changing the view.
5623     */
5624    public void onFinishTemporaryDetach() {
5625    }
5626
5627    /**
5628     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5629     * for this view's window.  Returns null if the view is not currently attached
5630     * to the window.  Normally you will not need to use this directly, but
5631     * just use the standard high-level event callbacks like
5632     * {@link #onKeyDown(int, KeyEvent)}.
5633     */
5634    public KeyEvent.DispatcherState getKeyDispatcherState() {
5635        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5636    }
5637
5638    /**
5639     * Dispatch a key event before it is processed by any input method
5640     * associated with the view hierarchy.  This can be used to intercept
5641     * key events in special situations before the IME consumes them; a
5642     * typical example would be handling the BACK key to update the application's
5643     * UI instead of allowing the IME to see it and close itself.
5644     *
5645     * @param event The key event to be dispatched.
5646     * @return True if the event was handled, false otherwise.
5647     */
5648    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5649        return onKeyPreIme(event.getKeyCode(), event);
5650    }
5651
5652    /**
5653     * Dispatch a key event to the next view on the focus path. This path runs
5654     * from the top of the view tree down to the currently focused view. If this
5655     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5656     * the next node down the focus path. This method also fires any key
5657     * listeners.
5658     *
5659     * @param event The key event to be dispatched.
5660     * @return True if the event was handled, false otherwise.
5661     */
5662    public boolean dispatchKeyEvent(KeyEvent event) {
5663        if (mInputEventConsistencyVerifier != null) {
5664            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5665        }
5666
5667        // Give any attached key listener a first crack at the event.
5668        //noinspection SimplifiableIfStatement
5669        ListenerInfo li = mListenerInfo;
5670        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5671                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5672            return true;
5673        }
5674
5675        if (event.dispatch(this, mAttachInfo != null
5676                ? mAttachInfo.mKeyDispatchState : null, this)) {
5677            return true;
5678        }
5679
5680        if (mInputEventConsistencyVerifier != null) {
5681            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5682        }
5683        return false;
5684    }
5685
5686    /**
5687     * Dispatches a key shortcut event.
5688     *
5689     * @param event The key event to be dispatched.
5690     * @return True if the event was handled by the view, false otherwise.
5691     */
5692    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5693        return onKeyShortcut(event.getKeyCode(), event);
5694    }
5695
5696    /**
5697     * Pass the touch screen motion event down to the target view, or this
5698     * view if it is the target.
5699     *
5700     * @param event The motion event to be dispatched.
5701     * @return True if the event was handled by the view, false otherwise.
5702     */
5703    public boolean dispatchTouchEvent(MotionEvent event) {
5704        if (mInputEventConsistencyVerifier != null) {
5705            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5706        }
5707
5708        if (onFilterTouchEventForSecurity(event)) {
5709            //noinspection SimplifiableIfStatement
5710            ListenerInfo li = mListenerInfo;
5711            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5712                    && li.mOnTouchListener.onTouch(this, event)) {
5713                return true;
5714            }
5715
5716            if (onTouchEvent(event)) {
5717                return true;
5718            }
5719        }
5720
5721        if (mInputEventConsistencyVerifier != null) {
5722            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5723        }
5724        return false;
5725    }
5726
5727    /**
5728     * Filter the touch event to apply security policies.
5729     *
5730     * @param event The motion event to be filtered.
5731     * @return True if the event should be dispatched, false if the event should be dropped.
5732     *
5733     * @see #getFilterTouchesWhenObscured
5734     */
5735    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5736        //noinspection RedundantIfStatement
5737        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5738                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5739            // Window is obscured, drop this touch.
5740            return false;
5741        }
5742        return true;
5743    }
5744
5745    /**
5746     * Pass a trackball motion event down to the focused view.
5747     *
5748     * @param event The motion event to be dispatched.
5749     * @return True if the event was handled by the view, false otherwise.
5750     */
5751    public boolean dispatchTrackballEvent(MotionEvent event) {
5752        if (mInputEventConsistencyVerifier != null) {
5753            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5754        }
5755
5756        return onTrackballEvent(event);
5757    }
5758
5759    /**
5760     * Dispatch a generic motion event.
5761     * <p>
5762     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5763     * are delivered to the view under the pointer.  All other generic motion events are
5764     * delivered to the focused view.  Hover events are handled specially and are delivered
5765     * to {@link #onHoverEvent(MotionEvent)}.
5766     * </p>
5767     *
5768     * @param event The motion event to be dispatched.
5769     * @return True if the event was handled by the view, false otherwise.
5770     */
5771    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5772        if (mInputEventConsistencyVerifier != null) {
5773            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5774        }
5775
5776        final int source = event.getSource();
5777        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5778            final int action = event.getAction();
5779            if (action == MotionEvent.ACTION_HOVER_ENTER
5780                    || action == MotionEvent.ACTION_HOVER_MOVE
5781                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5782                if (dispatchHoverEvent(event)) {
5783                    return true;
5784                }
5785            } else if (dispatchGenericPointerEvent(event)) {
5786                return true;
5787            }
5788        } else if (dispatchGenericFocusedEvent(event)) {
5789            return true;
5790        }
5791
5792        if (dispatchGenericMotionEventInternal(event)) {
5793            return true;
5794        }
5795
5796        if (mInputEventConsistencyVerifier != null) {
5797            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5798        }
5799        return false;
5800    }
5801
5802    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5803        //noinspection SimplifiableIfStatement
5804        ListenerInfo li = mListenerInfo;
5805        if (li != null && li.mOnGenericMotionListener != null
5806                && (mViewFlags & ENABLED_MASK) == ENABLED
5807                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
5808            return true;
5809        }
5810
5811        if (onGenericMotionEvent(event)) {
5812            return true;
5813        }
5814
5815        if (mInputEventConsistencyVerifier != null) {
5816            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5817        }
5818        return false;
5819    }
5820
5821    /**
5822     * Dispatch a hover event.
5823     * <p>
5824     * Do not call this method directly.
5825     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5826     * </p>
5827     *
5828     * @param event The motion event to be dispatched.
5829     * @return True if the event was handled by the view, false otherwise.
5830     */
5831    protected boolean dispatchHoverEvent(MotionEvent event) {
5832        //noinspection SimplifiableIfStatement
5833        ListenerInfo li = mListenerInfo;
5834        if (li != null && li.mOnHoverListener != null
5835                && (mViewFlags & ENABLED_MASK) == ENABLED
5836                && li.mOnHoverListener.onHover(this, event)) {
5837            return true;
5838        }
5839
5840        return onHoverEvent(event);
5841    }
5842
5843    /**
5844     * Returns true if the view has a child to which it has recently sent
5845     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5846     * it does not have a hovered child, then it must be the innermost hovered view.
5847     * @hide
5848     */
5849    protected boolean hasHoveredChild() {
5850        return false;
5851    }
5852
5853    /**
5854     * Dispatch a generic motion event to the view under the first pointer.
5855     * <p>
5856     * Do not call this method directly.
5857     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5858     * </p>
5859     *
5860     * @param event The motion event to be dispatched.
5861     * @return True if the event was handled by the view, false otherwise.
5862     */
5863    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5864        return false;
5865    }
5866
5867    /**
5868     * Dispatch a generic motion event to the currently focused view.
5869     * <p>
5870     * Do not call this method directly.
5871     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5872     * </p>
5873     *
5874     * @param event The motion event to be dispatched.
5875     * @return True if the event was handled by the view, false otherwise.
5876     */
5877    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5878        return false;
5879    }
5880
5881    /**
5882     * Dispatch a pointer event.
5883     * <p>
5884     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5885     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5886     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5887     * and should not be expected to handle other pointing device features.
5888     * </p>
5889     *
5890     * @param event The motion event to be dispatched.
5891     * @return True if the event was handled by the view, false otherwise.
5892     * @hide
5893     */
5894    public final boolean dispatchPointerEvent(MotionEvent event) {
5895        if (event.isTouchEvent()) {
5896            return dispatchTouchEvent(event);
5897        } else {
5898            return dispatchGenericMotionEvent(event);
5899        }
5900    }
5901
5902    /**
5903     * Called when the window containing this view gains or loses window focus.
5904     * ViewGroups should override to route to their children.
5905     *
5906     * @param hasFocus True if the window containing this view now has focus,
5907     *        false otherwise.
5908     */
5909    public void dispatchWindowFocusChanged(boolean hasFocus) {
5910        onWindowFocusChanged(hasFocus);
5911    }
5912
5913    /**
5914     * Called when the window containing this view gains or loses focus.  Note
5915     * that this is separate from view focus: to receive key events, both
5916     * your view and its window must have focus.  If a window is displayed
5917     * on top of yours that takes input focus, then your own window will lose
5918     * focus but the view focus will remain unchanged.
5919     *
5920     * @param hasWindowFocus True if the window containing this view now has
5921     *        focus, false otherwise.
5922     */
5923    public void onWindowFocusChanged(boolean hasWindowFocus) {
5924        InputMethodManager imm = InputMethodManager.peekInstance();
5925        if (!hasWindowFocus) {
5926            if (isPressed()) {
5927                setPressed(false);
5928            }
5929            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5930                imm.focusOut(this);
5931            }
5932            removeLongPressCallback();
5933            removeTapCallback();
5934            onFocusLost();
5935        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5936            imm.focusIn(this);
5937        }
5938        refreshDrawableState();
5939    }
5940
5941    /**
5942     * Returns true if this view is in a window that currently has window focus.
5943     * Note that this is not the same as the view itself having focus.
5944     *
5945     * @return True if this view is in a window that currently has window focus.
5946     */
5947    public boolean hasWindowFocus() {
5948        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5949    }
5950
5951    /**
5952     * Dispatch a view visibility change down the view hierarchy.
5953     * ViewGroups should override to route to their children.
5954     * @param changedView The view whose visibility changed. Could be 'this' or
5955     * an ancestor view.
5956     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5957     * {@link #INVISIBLE} or {@link #GONE}.
5958     */
5959    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5960        onVisibilityChanged(changedView, visibility);
5961    }
5962
5963    /**
5964     * Called when the visibility of the view or an ancestor of the view is changed.
5965     * @param changedView The view whose visibility changed. Could be 'this' or
5966     * an ancestor view.
5967     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5968     * {@link #INVISIBLE} or {@link #GONE}.
5969     */
5970    protected void onVisibilityChanged(View changedView, int visibility) {
5971        if (visibility == VISIBLE) {
5972            if (mAttachInfo != null) {
5973                initialAwakenScrollBars();
5974            } else {
5975                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5976            }
5977        }
5978    }
5979
5980    /**
5981     * Dispatch a hint about whether this view is displayed. For instance, when
5982     * a View moves out of the screen, it might receives a display hint indicating
5983     * the view is not displayed. Applications should not <em>rely</em> on this hint
5984     * as there is no guarantee that they will receive one.
5985     *
5986     * @param hint A hint about whether or not this view is displayed:
5987     * {@link #VISIBLE} or {@link #INVISIBLE}.
5988     */
5989    public void dispatchDisplayHint(int hint) {
5990        onDisplayHint(hint);
5991    }
5992
5993    /**
5994     * Gives this view a hint about whether is displayed or not. For instance, when
5995     * a View moves out of the screen, it might receives a display hint indicating
5996     * the view is not displayed. Applications should not <em>rely</em> on this hint
5997     * as there is no guarantee that they will receive one.
5998     *
5999     * @param hint A hint about whether or not this view is displayed:
6000     * {@link #VISIBLE} or {@link #INVISIBLE}.
6001     */
6002    protected void onDisplayHint(int hint) {
6003    }
6004
6005    /**
6006     * Dispatch a window visibility change down the view hierarchy.
6007     * ViewGroups should override to route to their children.
6008     *
6009     * @param visibility The new visibility of the window.
6010     *
6011     * @see #onWindowVisibilityChanged(int)
6012     */
6013    public void dispatchWindowVisibilityChanged(int visibility) {
6014        onWindowVisibilityChanged(visibility);
6015    }
6016
6017    /**
6018     * Called when the window containing has change its visibility
6019     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
6020     * that this tells you whether or not your window is being made visible
6021     * to the window manager; this does <em>not</em> tell you whether or not
6022     * your window is obscured by other windows on the screen, even if it
6023     * is itself visible.
6024     *
6025     * @param visibility The new visibility of the window.
6026     */
6027    protected void onWindowVisibilityChanged(int visibility) {
6028        if (visibility == VISIBLE) {
6029            initialAwakenScrollBars();
6030        }
6031    }
6032
6033    /**
6034     * Returns the current visibility of the window this view is attached to
6035     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6036     *
6037     * @return Returns the current visibility of the view's window.
6038     */
6039    public int getWindowVisibility() {
6040        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6041    }
6042
6043    /**
6044     * Retrieve the overall visible display size in which the window this view is
6045     * attached to has been positioned in.  This takes into account screen
6046     * decorations above the window, for both cases where the window itself
6047     * is being position inside of them or the window is being placed under
6048     * then and covered insets are used for the window to position its content
6049     * inside.  In effect, this tells you the available area where content can
6050     * be placed and remain visible to users.
6051     *
6052     * <p>This function requires an IPC back to the window manager to retrieve
6053     * the requested information, so should not be used in performance critical
6054     * code like drawing.
6055     *
6056     * @param outRect Filled in with the visible display frame.  If the view
6057     * is not attached to a window, this is simply the raw display size.
6058     */
6059    public void getWindowVisibleDisplayFrame(Rect outRect) {
6060        if (mAttachInfo != null) {
6061            try {
6062                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6063            } catch (RemoteException e) {
6064                return;
6065            }
6066            // XXX This is really broken, and probably all needs to be done
6067            // in the window manager, and we need to know more about whether
6068            // we want the area behind or in front of the IME.
6069            final Rect insets = mAttachInfo.mVisibleInsets;
6070            outRect.left += insets.left;
6071            outRect.top += insets.top;
6072            outRect.right -= insets.right;
6073            outRect.bottom -= insets.bottom;
6074            return;
6075        }
6076        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6077        d.getRectSize(outRect);
6078    }
6079
6080    /**
6081     * Dispatch a notification about a resource configuration change down
6082     * the view hierarchy.
6083     * ViewGroups should override to route to their children.
6084     *
6085     * @param newConfig The new resource configuration.
6086     *
6087     * @see #onConfigurationChanged(android.content.res.Configuration)
6088     */
6089    public void dispatchConfigurationChanged(Configuration newConfig) {
6090        onConfigurationChanged(newConfig);
6091    }
6092
6093    /**
6094     * Called when the current configuration of the resources being used
6095     * by the application have changed.  You can use this to decide when
6096     * to reload resources that can changed based on orientation and other
6097     * configuration characterstics.  You only need to use this if you are
6098     * not relying on the normal {@link android.app.Activity} mechanism of
6099     * recreating the activity instance upon a configuration change.
6100     *
6101     * @param newConfig The new resource configuration.
6102     */
6103    protected void onConfigurationChanged(Configuration newConfig) {
6104    }
6105
6106    /**
6107     * Private function to aggregate all per-view attributes in to the view
6108     * root.
6109     */
6110    void dispatchCollectViewAttributes(int visibility) {
6111        performCollectViewAttributes(visibility);
6112    }
6113
6114    void performCollectViewAttributes(int visibility) {
6115        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
6116            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6117                mAttachInfo.mKeepScreenOn = true;
6118            }
6119            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6120            ListenerInfo li = mListenerInfo;
6121            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6122                mAttachInfo.mHasSystemUiListeners = true;
6123            }
6124        }
6125    }
6126
6127    void needGlobalAttributesUpdate(boolean force) {
6128        final AttachInfo ai = mAttachInfo;
6129        if (ai != null) {
6130            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6131                    || ai.mHasSystemUiListeners) {
6132                ai.mRecomputeGlobalAttributes = true;
6133            }
6134        }
6135    }
6136
6137    /**
6138     * Returns whether the device is currently in touch mode.  Touch mode is entered
6139     * once the user begins interacting with the device by touch, and affects various
6140     * things like whether focus is always visible to the user.
6141     *
6142     * @return Whether the device is in touch mode.
6143     */
6144    @ViewDebug.ExportedProperty
6145    public boolean isInTouchMode() {
6146        if (mAttachInfo != null) {
6147            return mAttachInfo.mInTouchMode;
6148        } else {
6149            return ViewRootImpl.isInTouchMode();
6150        }
6151    }
6152
6153    /**
6154     * Returns the context the view is running in, through which it can
6155     * access the current theme, resources, etc.
6156     *
6157     * @return The view's Context.
6158     */
6159    @ViewDebug.CapturedViewProperty
6160    public final Context getContext() {
6161        return mContext;
6162    }
6163
6164    /**
6165     * Handle a key event before it is processed by any input method
6166     * associated with the view hierarchy.  This can be used to intercept
6167     * key events in special situations before the IME consumes them; a
6168     * typical example would be handling the BACK key to update the application's
6169     * UI instead of allowing the IME to see it and close itself.
6170     *
6171     * @param keyCode The value in event.getKeyCode().
6172     * @param event Description of the key event.
6173     * @return If you handled the event, return true. If you want to allow the
6174     *         event to be handled by the next receiver, return false.
6175     */
6176    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6177        return false;
6178    }
6179
6180    /**
6181     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6182     * KeyEvent.Callback.onKeyDown()}: perform press of the view
6183     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
6184     * is released, if the view is enabled and clickable.
6185     *
6186     * @param keyCode A key code that represents the button pressed, from
6187     *                {@link android.view.KeyEvent}.
6188     * @param event   The KeyEvent object that defines the button action.
6189     */
6190    public boolean onKeyDown(int keyCode, KeyEvent event) {
6191        boolean result = false;
6192
6193        switch (keyCode) {
6194            case KeyEvent.KEYCODE_DPAD_CENTER:
6195            case KeyEvent.KEYCODE_ENTER: {
6196                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6197                    return true;
6198                }
6199                // Long clickable items don't necessarily have to be clickable
6200                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
6201                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
6202                        (event.getRepeatCount() == 0)) {
6203                    setPressed(true);
6204                    checkForLongClick(0);
6205                    return true;
6206                }
6207                break;
6208            }
6209        }
6210        return result;
6211    }
6212
6213    /**
6214     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
6215     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
6216     * the event).
6217     */
6218    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
6219        return false;
6220    }
6221
6222    /**
6223     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
6224     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
6225     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
6226     * {@link KeyEvent#KEYCODE_ENTER} is released.
6227     *
6228     * @param keyCode A key code that represents the button pressed, from
6229     *                {@link android.view.KeyEvent}.
6230     * @param event   The KeyEvent object that defines the button action.
6231     */
6232    public boolean onKeyUp(int keyCode, KeyEvent event) {
6233        boolean result = false;
6234
6235        switch (keyCode) {
6236            case KeyEvent.KEYCODE_DPAD_CENTER:
6237            case KeyEvent.KEYCODE_ENTER: {
6238                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6239                    return true;
6240                }
6241                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
6242                    setPressed(false);
6243
6244                    if (!mHasPerformedLongPress) {
6245                        // This is a tap, so remove the longpress check
6246                        removeLongPressCallback();
6247
6248                        result = performClick();
6249                    }
6250                }
6251                break;
6252            }
6253        }
6254        return result;
6255    }
6256
6257    /**
6258     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6259     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6260     * the event).
6261     *
6262     * @param keyCode     A key code that represents the button pressed, from
6263     *                    {@link android.view.KeyEvent}.
6264     * @param repeatCount The number of times the action was made.
6265     * @param event       The KeyEvent object that defines the button action.
6266     */
6267    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6268        return false;
6269    }
6270
6271    /**
6272     * Called on the focused view when a key shortcut event is not handled.
6273     * Override this method to implement local key shortcuts for the View.
6274     * Key shortcuts can also be implemented by setting the
6275     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6276     *
6277     * @param keyCode The value in event.getKeyCode().
6278     * @param event Description of the key event.
6279     * @return If you handled the event, return true. If you want to allow the
6280     *         event to be handled by the next receiver, return false.
6281     */
6282    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6283        return false;
6284    }
6285
6286    /**
6287     * Check whether the called view is a text editor, in which case it
6288     * would make sense to automatically display a soft input window for
6289     * it.  Subclasses should override this if they implement
6290     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6291     * a call on that method would return a non-null InputConnection, and
6292     * they are really a first-class editor that the user would normally
6293     * start typing on when the go into a window containing your view.
6294     *
6295     * <p>The default implementation always returns false.  This does
6296     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6297     * will not be called or the user can not otherwise perform edits on your
6298     * view; it is just a hint to the system that this is not the primary
6299     * purpose of this view.
6300     *
6301     * @return Returns true if this view is a text editor, else false.
6302     */
6303    public boolean onCheckIsTextEditor() {
6304        return false;
6305    }
6306
6307    /**
6308     * Create a new InputConnection for an InputMethod to interact
6309     * with the view.  The default implementation returns null, since it doesn't
6310     * support input methods.  You can override this to implement such support.
6311     * This is only needed for views that take focus and text input.
6312     *
6313     * <p>When implementing this, you probably also want to implement
6314     * {@link #onCheckIsTextEditor()} to indicate you will return a
6315     * non-null InputConnection.
6316     *
6317     * @param outAttrs Fill in with attribute information about the connection.
6318     */
6319    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6320        return null;
6321    }
6322
6323    /**
6324     * Called by the {@link android.view.inputmethod.InputMethodManager}
6325     * when a view who is not the current
6326     * input connection target is trying to make a call on the manager.  The
6327     * default implementation returns false; you can override this to return
6328     * true for certain views if you are performing InputConnection proxying
6329     * to them.
6330     * @param view The View that is making the InputMethodManager call.
6331     * @return Return true to allow the call, false to reject.
6332     */
6333    public boolean checkInputConnectionProxy(View view) {
6334        return false;
6335    }
6336
6337    /**
6338     * Show the context menu for this view. It is not safe to hold on to the
6339     * menu after returning from this method.
6340     *
6341     * You should normally not overload this method. Overload
6342     * {@link #onCreateContextMenu(ContextMenu)} or define an
6343     * {@link OnCreateContextMenuListener} to add items to the context menu.
6344     *
6345     * @param menu The context menu to populate
6346     */
6347    public void createContextMenu(ContextMenu menu) {
6348        ContextMenuInfo menuInfo = getContextMenuInfo();
6349
6350        // Sets the current menu info so all items added to menu will have
6351        // my extra info set.
6352        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6353
6354        onCreateContextMenu(menu);
6355        ListenerInfo li = mListenerInfo;
6356        if (li != null && li.mOnCreateContextMenuListener != null) {
6357            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6358        }
6359
6360        // Clear the extra information so subsequent items that aren't mine don't
6361        // have my extra info.
6362        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6363
6364        if (mParent != null) {
6365            mParent.createContextMenu(menu);
6366        }
6367    }
6368
6369    /**
6370     * Views should implement this if they have extra information to associate
6371     * with the context menu. The return result is supplied as a parameter to
6372     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6373     * callback.
6374     *
6375     * @return Extra information about the item for which the context menu
6376     *         should be shown. This information will vary across different
6377     *         subclasses of View.
6378     */
6379    protected ContextMenuInfo getContextMenuInfo() {
6380        return null;
6381    }
6382
6383    /**
6384     * Views should implement this if the view itself is going to add items to
6385     * the context menu.
6386     *
6387     * @param menu the context menu to populate
6388     */
6389    protected void onCreateContextMenu(ContextMenu menu) {
6390    }
6391
6392    /**
6393     * Implement this method to handle trackball motion events.  The
6394     * <em>relative</em> movement of the trackball since the last event
6395     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6396     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6397     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6398     * they will often be fractional values, representing the more fine-grained
6399     * movement information available from a trackball).
6400     *
6401     * @param event The motion event.
6402     * @return True if the event was handled, false otherwise.
6403     */
6404    public boolean onTrackballEvent(MotionEvent event) {
6405        return false;
6406    }
6407
6408    /**
6409     * Implement this method to handle generic motion events.
6410     * <p>
6411     * Generic motion events describe joystick movements, mouse hovers, track pad
6412     * touches, scroll wheel movements and other input events.  The
6413     * {@link MotionEvent#getSource() source} of the motion event specifies
6414     * the class of input that was received.  Implementations of this method
6415     * must examine the bits in the source before processing the event.
6416     * The following code example shows how this is done.
6417     * </p><p>
6418     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6419     * are delivered to the view under the pointer.  All other generic motion events are
6420     * delivered to the focused view.
6421     * </p>
6422     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
6423     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6424     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6425     *             // process the joystick movement...
6426     *             return true;
6427     *         }
6428     *     }
6429     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6430     *         switch (event.getAction()) {
6431     *             case MotionEvent.ACTION_HOVER_MOVE:
6432     *                 // process the mouse hover movement...
6433     *                 return true;
6434     *             case MotionEvent.ACTION_SCROLL:
6435     *                 // process the scroll wheel movement...
6436     *                 return true;
6437     *         }
6438     *     }
6439     *     return super.onGenericMotionEvent(event);
6440     * }</pre>
6441     *
6442     * @param event The generic motion event being processed.
6443     * @return True if the event was handled, false otherwise.
6444     */
6445    public boolean onGenericMotionEvent(MotionEvent event) {
6446        return false;
6447    }
6448
6449    /**
6450     * Implement this method to handle hover events.
6451     * <p>
6452     * This method is called whenever a pointer is hovering into, over, or out of the
6453     * bounds of a view and the view is not currently being touched.
6454     * Hover events are represented as pointer events with action
6455     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6456     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6457     * </p>
6458     * <ul>
6459     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6460     * when the pointer enters the bounds of the view.</li>
6461     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6462     * when the pointer has already entered the bounds of the view and has moved.</li>
6463     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6464     * when the pointer has exited the bounds of the view or when the pointer is
6465     * about to go down due to a button click, tap, or similar user action that
6466     * causes the view to be touched.</li>
6467     * </ul>
6468     * <p>
6469     * The view should implement this method to return true to indicate that it is
6470     * handling the hover event, such as by changing its drawable state.
6471     * </p><p>
6472     * The default implementation calls {@link #setHovered} to update the hovered state
6473     * of the view when a hover enter or hover exit event is received, if the view
6474     * is enabled and is clickable.  The default implementation also sends hover
6475     * accessibility events.
6476     * </p>
6477     *
6478     * @param event The motion event that describes the hover.
6479     * @return True if the view handled the hover event.
6480     *
6481     * @see #isHovered
6482     * @see #setHovered
6483     * @see #onHoverChanged
6484     */
6485    public boolean onHoverEvent(MotionEvent event) {
6486        // The root view may receive hover (or touch) events that are outside the bounds of
6487        // the window.  This code ensures that we only send accessibility events for
6488        // hovers that are actually within the bounds of the root view.
6489        final int action = event.getAction();
6490        if (!mSendingHoverAccessibilityEvents) {
6491            if ((action == MotionEvent.ACTION_HOVER_ENTER
6492                    || action == MotionEvent.ACTION_HOVER_MOVE)
6493                    && !hasHoveredChild()
6494                    && pointInView(event.getX(), event.getY())) {
6495                mSendingHoverAccessibilityEvents = true;
6496                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6497            }
6498        } else {
6499            if (action == MotionEvent.ACTION_HOVER_EXIT
6500                    || (action == MotionEvent.ACTION_HOVER_MOVE
6501                            && !pointInView(event.getX(), event.getY()))) {
6502                mSendingHoverAccessibilityEvents = false;
6503                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6504            }
6505        }
6506
6507        if (isHoverable()) {
6508            switch (action) {
6509                case MotionEvent.ACTION_HOVER_ENTER:
6510                    setHovered(true);
6511                    break;
6512                case MotionEvent.ACTION_HOVER_EXIT:
6513                    setHovered(false);
6514                    break;
6515            }
6516
6517            // Dispatch the event to onGenericMotionEvent before returning true.
6518            // This is to provide compatibility with existing applications that
6519            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6520            // break because of the new default handling for hoverable views
6521            // in onHoverEvent.
6522            // Note that onGenericMotionEvent will be called by default when
6523            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6524            dispatchGenericMotionEventInternal(event);
6525            return true;
6526        }
6527        return false;
6528    }
6529
6530    /**
6531     * Returns true if the view should handle {@link #onHoverEvent}
6532     * by calling {@link #setHovered} to change its hovered state.
6533     *
6534     * @return True if the view is hoverable.
6535     */
6536    private boolean isHoverable() {
6537        final int viewFlags = mViewFlags;
6538        //noinspection SimplifiableIfStatement
6539        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6540            return false;
6541        }
6542
6543        return (viewFlags & CLICKABLE) == CLICKABLE
6544                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6545    }
6546
6547    /**
6548     * Returns true if the view is currently hovered.
6549     *
6550     * @return True if the view is currently hovered.
6551     *
6552     * @see #setHovered
6553     * @see #onHoverChanged
6554     */
6555    @ViewDebug.ExportedProperty
6556    public boolean isHovered() {
6557        return (mPrivateFlags & HOVERED) != 0;
6558    }
6559
6560    /**
6561     * Sets whether the view is currently hovered.
6562     * <p>
6563     * Calling this method also changes the drawable state of the view.  This
6564     * enables the view to react to hover by using different drawable resources
6565     * to change its appearance.
6566     * </p><p>
6567     * The {@link #onHoverChanged} method is called when the hovered state changes.
6568     * </p>
6569     *
6570     * @param hovered True if the view is hovered.
6571     *
6572     * @see #isHovered
6573     * @see #onHoverChanged
6574     */
6575    public void setHovered(boolean hovered) {
6576        if (hovered) {
6577            if ((mPrivateFlags & HOVERED) == 0) {
6578                mPrivateFlags |= HOVERED;
6579                refreshDrawableState();
6580                onHoverChanged(true);
6581            }
6582        } else {
6583            if ((mPrivateFlags & HOVERED) != 0) {
6584                mPrivateFlags &= ~HOVERED;
6585                refreshDrawableState();
6586                onHoverChanged(false);
6587            }
6588        }
6589    }
6590
6591    /**
6592     * Implement this method to handle hover state changes.
6593     * <p>
6594     * This method is called whenever the hover state changes as a result of a
6595     * call to {@link #setHovered}.
6596     * </p>
6597     *
6598     * @param hovered The current hover state, as returned by {@link #isHovered}.
6599     *
6600     * @see #isHovered
6601     * @see #setHovered
6602     */
6603    public void onHoverChanged(boolean hovered) {
6604    }
6605
6606    /**
6607     * Implement this method to handle touch screen motion events.
6608     *
6609     * @param event The motion event.
6610     * @return True if the event was handled, false otherwise.
6611     */
6612    public boolean onTouchEvent(MotionEvent event) {
6613        final int viewFlags = mViewFlags;
6614
6615        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6616            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6617                setPressed(false);
6618            }
6619            // A disabled view that is clickable still consumes the touch
6620            // events, it just doesn't respond to them.
6621            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6622                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6623        }
6624
6625        if (mTouchDelegate != null) {
6626            if (mTouchDelegate.onTouchEvent(event)) {
6627                return true;
6628            }
6629        }
6630
6631        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6632                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6633            switch (event.getAction()) {
6634                case MotionEvent.ACTION_UP:
6635                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6636                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6637                        // take focus if we don't have it already and we should in
6638                        // touch mode.
6639                        boolean focusTaken = false;
6640                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6641                            focusTaken = requestFocus();
6642                        }
6643
6644                        if (prepressed) {
6645                            // The button is being released before we actually
6646                            // showed it as pressed.  Make it show the pressed
6647                            // state now (before scheduling the click) to ensure
6648                            // the user sees it.
6649                            setPressed(true);
6650                       }
6651
6652                        if (!mHasPerformedLongPress) {
6653                            // This is a tap, so remove the longpress check
6654                            removeLongPressCallback();
6655
6656                            // Only perform take click actions if we were in the pressed state
6657                            if (!focusTaken) {
6658                                // Use a Runnable and post this rather than calling
6659                                // performClick directly. This lets other visual state
6660                                // of the view update before click actions start.
6661                                if (mPerformClick == null) {
6662                                    mPerformClick = new PerformClick();
6663                                }
6664                                if (!post(mPerformClick)) {
6665                                    performClick();
6666                                }
6667                            }
6668                        }
6669
6670                        if (mUnsetPressedState == null) {
6671                            mUnsetPressedState = new UnsetPressedState();
6672                        }
6673
6674                        if (prepressed) {
6675                            postDelayed(mUnsetPressedState,
6676                                    ViewConfiguration.getPressedStateDuration());
6677                        } else if (!post(mUnsetPressedState)) {
6678                            // If the post failed, unpress right now
6679                            mUnsetPressedState.run();
6680                        }
6681                        removeTapCallback();
6682                    }
6683                    break;
6684
6685                case MotionEvent.ACTION_DOWN:
6686                    mHasPerformedLongPress = false;
6687
6688                    if (performButtonActionOnTouchDown(event)) {
6689                        break;
6690                    }
6691
6692                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6693                    boolean isInScrollingContainer = isInScrollingContainer();
6694
6695                    // For views inside a scrolling container, delay the pressed feedback for
6696                    // a short period in case this is a scroll.
6697                    if (isInScrollingContainer) {
6698                        mPrivateFlags |= PREPRESSED;
6699                        if (mPendingCheckForTap == null) {
6700                            mPendingCheckForTap = new CheckForTap();
6701                        }
6702                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6703                    } else {
6704                        // Not inside a scrolling container, so show the feedback right away
6705                        setPressed(true);
6706                        checkForLongClick(0);
6707                    }
6708                    break;
6709
6710                case MotionEvent.ACTION_CANCEL:
6711                    setPressed(false);
6712                    removeTapCallback();
6713                    break;
6714
6715                case MotionEvent.ACTION_MOVE:
6716                    final int x = (int) event.getX();
6717                    final int y = (int) event.getY();
6718
6719                    // Be lenient about moving outside of buttons
6720                    if (!pointInView(x, y, mTouchSlop)) {
6721                        // Outside button
6722                        removeTapCallback();
6723                        if ((mPrivateFlags & PRESSED) != 0) {
6724                            // Remove any future long press/tap checks
6725                            removeLongPressCallback();
6726
6727                            setPressed(false);
6728                        }
6729                    }
6730                    break;
6731            }
6732            return true;
6733        }
6734
6735        return false;
6736    }
6737
6738    /**
6739     * @hide
6740     */
6741    public boolean isInScrollingContainer() {
6742        ViewParent p = getParent();
6743        while (p != null && p instanceof ViewGroup) {
6744            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6745                return true;
6746            }
6747            p = p.getParent();
6748        }
6749        return false;
6750    }
6751
6752    /**
6753     * Remove the longpress detection timer.
6754     */
6755    private void removeLongPressCallback() {
6756        if (mPendingCheckForLongPress != null) {
6757          removeCallbacks(mPendingCheckForLongPress);
6758        }
6759    }
6760
6761    /**
6762     * Remove the pending click action
6763     */
6764    private void removePerformClickCallback() {
6765        if (mPerformClick != null) {
6766            removeCallbacks(mPerformClick);
6767        }
6768    }
6769
6770    /**
6771     * Remove the prepress detection timer.
6772     */
6773    private void removeUnsetPressCallback() {
6774        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6775            setPressed(false);
6776            removeCallbacks(mUnsetPressedState);
6777        }
6778    }
6779
6780    /**
6781     * Remove the tap detection timer.
6782     */
6783    private void removeTapCallback() {
6784        if (mPendingCheckForTap != null) {
6785            mPrivateFlags &= ~PREPRESSED;
6786            removeCallbacks(mPendingCheckForTap);
6787        }
6788    }
6789
6790    /**
6791     * Cancels a pending long press.  Your subclass can use this if you
6792     * want the context menu to come up if the user presses and holds
6793     * at the same place, but you don't want it to come up if they press
6794     * and then move around enough to cause scrolling.
6795     */
6796    public void cancelLongPress() {
6797        removeLongPressCallback();
6798
6799        /*
6800         * The prepressed state handled by the tap callback is a display
6801         * construct, but the tap callback will post a long press callback
6802         * less its own timeout. Remove it here.
6803         */
6804        removeTapCallback();
6805    }
6806
6807    /**
6808     * Remove the pending callback for sending a
6809     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6810     */
6811    private void removeSendViewScrolledAccessibilityEventCallback() {
6812        if (mSendViewScrolledAccessibilityEvent != null) {
6813            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6814        }
6815    }
6816
6817    /**
6818     * Sets the TouchDelegate for this View.
6819     */
6820    public void setTouchDelegate(TouchDelegate delegate) {
6821        mTouchDelegate = delegate;
6822    }
6823
6824    /**
6825     * Gets the TouchDelegate for this View.
6826     */
6827    public TouchDelegate getTouchDelegate() {
6828        return mTouchDelegate;
6829    }
6830
6831    /**
6832     * Set flags controlling behavior of this view.
6833     *
6834     * @param flags Constant indicating the value which should be set
6835     * @param mask Constant indicating the bit range that should be changed
6836     */
6837    void setFlags(int flags, int mask) {
6838        int old = mViewFlags;
6839        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6840
6841        int changed = mViewFlags ^ old;
6842        if (changed == 0) {
6843            return;
6844        }
6845        int privateFlags = mPrivateFlags;
6846
6847        /* Check if the FOCUSABLE bit has changed */
6848        if (((changed & FOCUSABLE_MASK) != 0) &&
6849                ((privateFlags & HAS_BOUNDS) !=0)) {
6850            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6851                    && ((privateFlags & FOCUSED) != 0)) {
6852                /* Give up focus if we are no longer focusable */
6853                clearFocus();
6854            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6855                    && ((privateFlags & FOCUSED) == 0)) {
6856                /*
6857                 * Tell the view system that we are now available to take focus
6858                 * if no one else already has it.
6859                 */
6860                if (mParent != null) mParent.focusableViewAvailable(this);
6861            }
6862        }
6863
6864        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6865            if ((changed & VISIBILITY_MASK) != 0) {
6866                /*
6867                 * If this view is becoming visible, invalidate it in case it changed while
6868                 * it was not visible. Marking it drawn ensures that the invalidation will
6869                 * go through.
6870                 */
6871                mPrivateFlags |= DRAWN;
6872                invalidate(true);
6873
6874                needGlobalAttributesUpdate(true);
6875
6876                // a view becoming visible is worth notifying the parent
6877                // about in case nothing has focus.  even if this specific view
6878                // isn't focusable, it may contain something that is, so let
6879                // the root view try to give this focus if nothing else does.
6880                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6881                    mParent.focusableViewAvailable(this);
6882                }
6883            }
6884        }
6885
6886        /* Check if the GONE bit has changed */
6887        if ((changed & GONE) != 0) {
6888            needGlobalAttributesUpdate(false);
6889            requestLayout();
6890
6891            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6892                if (hasFocus()) clearFocus();
6893                destroyDrawingCache();
6894                if (mParent instanceof View) {
6895                    // GONE views noop invalidation, so invalidate the parent
6896                    ((View) mParent).invalidate(true);
6897                }
6898                // Mark the view drawn to ensure that it gets invalidated properly the next
6899                // time it is visible and gets invalidated
6900                mPrivateFlags |= DRAWN;
6901            }
6902            if (mAttachInfo != null) {
6903                mAttachInfo.mViewVisibilityChanged = true;
6904            }
6905        }
6906
6907        /* Check if the VISIBLE bit has changed */
6908        if ((changed & INVISIBLE) != 0) {
6909            needGlobalAttributesUpdate(false);
6910            /*
6911             * If this view is becoming invisible, set the DRAWN flag so that
6912             * the next invalidate() will not be skipped.
6913             */
6914            mPrivateFlags |= DRAWN;
6915
6916            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6917                // root view becoming invisible shouldn't clear focus
6918                if (getRootView() != this) {
6919                    clearFocus();
6920                }
6921            }
6922            if (mAttachInfo != null) {
6923                mAttachInfo.mViewVisibilityChanged = true;
6924            }
6925        }
6926
6927        if ((changed & VISIBILITY_MASK) != 0) {
6928            if (mParent instanceof ViewGroup) {
6929                ((ViewGroup) mParent).onChildVisibilityChanged(this,
6930                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
6931                ((View) mParent).invalidate(true);
6932            } else if (mParent != null) {
6933                mParent.invalidateChild(this, null);
6934            }
6935            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6936        }
6937
6938        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6939            destroyDrawingCache();
6940        }
6941
6942        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6943            destroyDrawingCache();
6944            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6945            invalidateParentCaches();
6946        }
6947
6948        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6949            destroyDrawingCache();
6950            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6951        }
6952
6953        if ((changed & DRAW_MASK) != 0) {
6954            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6955                if (mBGDrawable != null) {
6956                    mPrivateFlags &= ~SKIP_DRAW;
6957                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6958                } else {
6959                    mPrivateFlags |= SKIP_DRAW;
6960                }
6961            } else {
6962                mPrivateFlags &= ~SKIP_DRAW;
6963            }
6964            requestLayout();
6965            invalidate(true);
6966        }
6967
6968        if ((changed & KEEP_SCREEN_ON) != 0) {
6969            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6970                mParent.recomputeViewAttributes(this);
6971            }
6972        }
6973    }
6974
6975    /**
6976     * Change the view's z order in the tree, so it's on top of other sibling
6977     * views
6978     */
6979    public void bringToFront() {
6980        if (mParent != null) {
6981            mParent.bringChildToFront(this);
6982        }
6983    }
6984
6985    /**
6986     * This is called in response to an internal scroll in this view (i.e., the
6987     * view scrolled its own contents). This is typically as a result of
6988     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6989     * called.
6990     *
6991     * @param l Current horizontal scroll origin.
6992     * @param t Current vertical scroll origin.
6993     * @param oldl Previous horizontal scroll origin.
6994     * @param oldt Previous vertical scroll origin.
6995     */
6996    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6997        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6998            postSendViewScrolledAccessibilityEventCallback();
6999        }
7000
7001        mBackgroundSizeChanged = true;
7002
7003        final AttachInfo ai = mAttachInfo;
7004        if (ai != null) {
7005            ai.mViewScrollChanged = true;
7006        }
7007    }
7008
7009    /**
7010     * Interface definition for a callback to be invoked when the layout bounds of a view
7011     * changes due to layout processing.
7012     */
7013    public interface OnLayoutChangeListener {
7014        /**
7015         * Called when the focus state of a view has changed.
7016         *
7017         * @param v The view whose state has changed.
7018         * @param left The new value of the view's left property.
7019         * @param top The new value of the view's top property.
7020         * @param right The new value of the view's right property.
7021         * @param bottom The new value of the view's bottom property.
7022         * @param oldLeft The previous value of the view's left property.
7023         * @param oldTop The previous value of the view's top property.
7024         * @param oldRight The previous value of the view's right property.
7025         * @param oldBottom The previous value of the view's bottom property.
7026         */
7027        void onLayoutChange(View v, int left, int top, int right, int bottom,
7028            int oldLeft, int oldTop, int oldRight, int oldBottom);
7029    }
7030
7031    /**
7032     * This is called during layout when the size of this view has changed. If
7033     * you were just added to the view hierarchy, you're called with the old
7034     * values of 0.
7035     *
7036     * @param w Current width of this view.
7037     * @param h Current height of this view.
7038     * @param oldw Old width of this view.
7039     * @param oldh Old height of this view.
7040     */
7041    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7042    }
7043
7044    /**
7045     * Called by draw to draw the child views. This may be overridden
7046     * by derived classes to gain control just before its children are drawn
7047     * (but after its own view has been drawn).
7048     * @param canvas the canvas on which to draw the view
7049     */
7050    protected void dispatchDraw(Canvas canvas) {
7051    }
7052
7053    /**
7054     * Gets the parent of this view. Note that the parent is a
7055     * ViewParent and not necessarily a View.
7056     *
7057     * @return Parent of this view.
7058     */
7059    public final ViewParent getParent() {
7060        return mParent;
7061    }
7062
7063    /**
7064     * Set the horizontal scrolled position of your view. This will cause a call to
7065     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7066     * invalidated.
7067     * @param value the x position to scroll to
7068     */
7069    public void setScrollX(int value) {
7070        scrollTo(value, mScrollY);
7071    }
7072
7073    /**
7074     * Set the vertical scrolled position of your view. This will cause a call to
7075     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7076     * invalidated.
7077     * @param value the y position to scroll to
7078     */
7079    public void setScrollY(int value) {
7080        scrollTo(mScrollX, value);
7081    }
7082
7083    /**
7084     * Return the scrolled left position of this view. This is the left edge of
7085     * the displayed part of your view. You do not need to draw any pixels
7086     * farther left, since those are outside of the frame of your view on
7087     * screen.
7088     *
7089     * @return The left edge of the displayed part of your view, in pixels.
7090     */
7091    public final int getScrollX() {
7092        return mScrollX;
7093    }
7094
7095    /**
7096     * Return the scrolled top position of this view. This is the top edge of
7097     * the displayed part of your view. You do not need to draw any pixels above
7098     * it, since those are outside of the frame of your view on screen.
7099     *
7100     * @return The top edge of the displayed part of your view, in pixels.
7101     */
7102    public final int getScrollY() {
7103        return mScrollY;
7104    }
7105
7106    /**
7107     * Return the width of the your view.
7108     *
7109     * @return The width of your view, in pixels.
7110     */
7111    @ViewDebug.ExportedProperty(category = "layout")
7112    public final int getWidth() {
7113        return mRight - mLeft;
7114    }
7115
7116    /**
7117     * Return the height of your view.
7118     *
7119     * @return The height of your view, in pixels.
7120     */
7121    @ViewDebug.ExportedProperty(category = "layout")
7122    public final int getHeight() {
7123        return mBottom - mTop;
7124    }
7125
7126    /**
7127     * Return the visible drawing bounds of your view. Fills in the output
7128     * rectangle with the values from getScrollX(), getScrollY(),
7129     * getWidth(), and getHeight().
7130     *
7131     * @param outRect The (scrolled) drawing bounds of the view.
7132     */
7133    public void getDrawingRect(Rect outRect) {
7134        outRect.left = mScrollX;
7135        outRect.top = mScrollY;
7136        outRect.right = mScrollX + (mRight - mLeft);
7137        outRect.bottom = mScrollY + (mBottom - mTop);
7138    }
7139
7140    /**
7141     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7142     * raw width component (that is the result is masked by
7143     * {@link #MEASURED_SIZE_MASK}).
7144     *
7145     * @return The raw measured width of this view.
7146     */
7147    public final int getMeasuredWidth() {
7148        return mMeasuredWidth & MEASURED_SIZE_MASK;
7149    }
7150
7151    /**
7152     * Return the full width measurement information for this view as computed
7153     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7154     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7155     * This should be used during measurement and layout calculations only. Use
7156     * {@link #getWidth()} to see how wide a view is after layout.
7157     *
7158     * @return The measured width of this view as a bit mask.
7159     */
7160    public final int getMeasuredWidthAndState() {
7161        return mMeasuredWidth;
7162    }
7163
7164    /**
7165     * Like {@link #getMeasuredHeightAndState()}, but only returns the
7166     * raw width component (that is the result is masked by
7167     * {@link #MEASURED_SIZE_MASK}).
7168     *
7169     * @return The raw measured height of this view.
7170     */
7171    public final int getMeasuredHeight() {
7172        return mMeasuredHeight & MEASURED_SIZE_MASK;
7173    }
7174
7175    /**
7176     * Return the full height measurement information for this view as computed
7177     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7178     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7179     * This should be used during measurement and layout calculations only. Use
7180     * {@link #getHeight()} to see how wide a view is after layout.
7181     *
7182     * @return The measured width of this view as a bit mask.
7183     */
7184    public final int getMeasuredHeightAndState() {
7185        return mMeasuredHeight;
7186    }
7187
7188    /**
7189     * Return only the state bits of {@link #getMeasuredWidthAndState()}
7190     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
7191     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
7192     * and the height component is at the shifted bits
7193     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
7194     */
7195    public final int getMeasuredState() {
7196        return (mMeasuredWidth&MEASURED_STATE_MASK)
7197                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
7198                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
7199    }
7200
7201    /**
7202     * The transform matrix of this view, which is calculated based on the current
7203     * roation, scale, and pivot properties.
7204     *
7205     * @see #getRotation()
7206     * @see #getScaleX()
7207     * @see #getScaleY()
7208     * @see #getPivotX()
7209     * @see #getPivotY()
7210     * @return The current transform matrix for the view
7211     */
7212    public Matrix getMatrix() {
7213        if (mTransformationInfo != null) {
7214            updateMatrix();
7215            return mTransformationInfo.mMatrix;
7216        }
7217        return Matrix.IDENTITY_MATRIX;
7218    }
7219
7220    /**
7221     * Utility function to determine if the value is far enough away from zero to be
7222     * considered non-zero.
7223     * @param value A floating point value to check for zero-ness
7224     * @return whether the passed-in value is far enough away from zero to be considered non-zero
7225     */
7226    private static boolean nonzero(float value) {
7227        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
7228    }
7229
7230    /**
7231     * Returns true if the transform matrix is the identity matrix.
7232     * Recomputes the matrix if necessary.
7233     *
7234     * @return True if the transform matrix is the identity matrix, false otherwise.
7235     */
7236    final boolean hasIdentityMatrix() {
7237        if (mTransformationInfo != null) {
7238            updateMatrix();
7239            return mTransformationInfo.mMatrixIsIdentity;
7240        }
7241        return true;
7242    }
7243
7244    void ensureTransformationInfo() {
7245        if (mTransformationInfo == null) {
7246            mTransformationInfo = new TransformationInfo();
7247        }
7248    }
7249
7250    /**
7251     * Recomputes the transform matrix if necessary.
7252     */
7253    private void updateMatrix() {
7254        final TransformationInfo info = mTransformationInfo;
7255        if (info == null) {
7256            return;
7257        }
7258        if (info.mMatrixDirty) {
7259            // transform-related properties have changed since the last time someone
7260            // asked for the matrix; recalculate it with the current values
7261
7262            // Figure out if we need to update the pivot point
7263            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7264                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7265                    info.mPrevWidth = mRight - mLeft;
7266                    info.mPrevHeight = mBottom - mTop;
7267                    info.mPivotX = info.mPrevWidth / 2f;
7268                    info.mPivotY = info.mPrevHeight / 2f;
7269                }
7270            }
7271            info.mMatrix.reset();
7272            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7273                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7274                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7275                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7276            } else {
7277                if (info.mCamera == null) {
7278                    info.mCamera = new Camera();
7279                    info.matrix3D = new Matrix();
7280                }
7281                info.mCamera.save();
7282                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7283                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7284                info.mCamera.getMatrix(info.matrix3D);
7285                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7286                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7287                        info.mPivotY + info.mTranslationY);
7288                info.mMatrix.postConcat(info.matrix3D);
7289                info.mCamera.restore();
7290            }
7291            info.mMatrixDirty = false;
7292            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7293            info.mInverseMatrixDirty = true;
7294        }
7295    }
7296
7297    /**
7298     * Utility method to retrieve the inverse of the current mMatrix property.
7299     * We cache the matrix to avoid recalculating it when transform properties
7300     * have not changed.
7301     *
7302     * @return The inverse of the current matrix of this view.
7303     */
7304    final Matrix getInverseMatrix() {
7305        final TransformationInfo info = mTransformationInfo;
7306        if (info != null) {
7307            updateMatrix();
7308            if (info.mInverseMatrixDirty) {
7309                if (info.mInverseMatrix == null) {
7310                    info.mInverseMatrix = new Matrix();
7311                }
7312                info.mMatrix.invert(info.mInverseMatrix);
7313                info.mInverseMatrixDirty = false;
7314            }
7315            return info.mInverseMatrix;
7316        }
7317        return Matrix.IDENTITY_MATRIX;
7318    }
7319
7320    /**
7321     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7322     * views are drawn) from the camera to this view. The camera's distance
7323     * affects 3D transformations, for instance rotations around the X and Y
7324     * axis. If the rotationX or rotationY properties are changed and this view is
7325     * large (more than half the size of the screen), it is recommended to always
7326     * use a camera distance that's greater than the height (X axis rotation) or
7327     * the width (Y axis rotation) of this view.</p>
7328     *
7329     * <p>The distance of the camera from the view plane can have an affect on the
7330     * perspective distortion of the view when it is rotated around the x or y axis.
7331     * For example, a large distance will result in a large viewing angle, and there
7332     * will not be much perspective distortion of the view as it rotates. A short
7333     * distance may cause much more perspective distortion upon rotation, and can
7334     * also result in some drawing artifacts if the rotated view ends up partially
7335     * behind the camera (which is why the recommendation is to use a distance at
7336     * least as far as the size of the view, if the view is to be rotated.)</p>
7337     *
7338     * <p>The distance is expressed in "depth pixels." The default distance depends
7339     * on the screen density. For instance, on a medium density display, the
7340     * default distance is 1280. On a high density display, the default distance
7341     * is 1920.</p>
7342     *
7343     * <p>If you want to specify a distance that leads to visually consistent
7344     * results across various densities, use the following formula:</p>
7345     * <pre>
7346     * float scale = context.getResources().getDisplayMetrics().density;
7347     * view.setCameraDistance(distance * scale);
7348     * </pre>
7349     *
7350     * <p>The density scale factor of a high density display is 1.5,
7351     * and 1920 = 1280 * 1.5.</p>
7352     *
7353     * @param distance The distance in "depth pixels", if negative the opposite
7354     *        value is used
7355     *
7356     * @see #setRotationX(float)
7357     * @see #setRotationY(float)
7358     */
7359    public void setCameraDistance(float distance) {
7360        invalidateParentCaches();
7361        invalidate(false);
7362
7363        ensureTransformationInfo();
7364        final float dpi = mResources.getDisplayMetrics().densityDpi;
7365        final TransformationInfo info = mTransformationInfo;
7366        if (info.mCamera == null) {
7367            info.mCamera = new Camera();
7368            info.matrix3D = new Matrix();
7369        }
7370
7371        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7372        info.mMatrixDirty = true;
7373
7374        invalidate(false);
7375    }
7376
7377    /**
7378     * The degrees that the view is rotated around the pivot point.
7379     *
7380     * @see #setRotation(float)
7381     * @see #getPivotX()
7382     * @see #getPivotY()
7383     *
7384     * @return The degrees of rotation.
7385     */
7386    @ViewDebug.ExportedProperty(category = "drawing")
7387    public float getRotation() {
7388        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7389    }
7390
7391    /**
7392     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7393     * result in clockwise rotation.
7394     *
7395     * @param rotation The degrees of rotation.
7396     *
7397     * @see #getRotation()
7398     * @see #getPivotX()
7399     * @see #getPivotY()
7400     * @see #setRotationX(float)
7401     * @see #setRotationY(float)
7402     *
7403     * @attr ref android.R.styleable#View_rotation
7404     */
7405    public void setRotation(float rotation) {
7406        ensureTransformationInfo();
7407        final TransformationInfo info = mTransformationInfo;
7408        if (info.mRotation != rotation) {
7409            invalidateParentCaches();
7410            // Double-invalidation is necessary to capture view's old and new areas
7411            invalidate(false);
7412            info.mRotation = rotation;
7413            info.mMatrixDirty = true;
7414            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7415            invalidate(false);
7416        }
7417    }
7418
7419    /**
7420     * The degrees that the view is rotated around the vertical axis through the pivot point.
7421     *
7422     * @see #getPivotX()
7423     * @see #getPivotY()
7424     * @see #setRotationY(float)
7425     *
7426     * @return The degrees of Y rotation.
7427     */
7428    @ViewDebug.ExportedProperty(category = "drawing")
7429    public float getRotationY() {
7430        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7431    }
7432
7433    /**
7434     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7435     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7436     * down the y axis.
7437     *
7438     * When rotating large views, it is recommended to adjust the camera distance
7439     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7440     *
7441     * @param rotationY The degrees of Y rotation.
7442     *
7443     * @see #getRotationY()
7444     * @see #getPivotX()
7445     * @see #getPivotY()
7446     * @see #setRotation(float)
7447     * @see #setRotationX(float)
7448     * @see #setCameraDistance(float)
7449     *
7450     * @attr ref android.R.styleable#View_rotationY
7451     */
7452    public void setRotationY(float rotationY) {
7453        ensureTransformationInfo();
7454        final TransformationInfo info = mTransformationInfo;
7455        if (info.mRotationY != rotationY) {
7456            invalidateParentCaches();
7457            // Double-invalidation is necessary to capture view's old and new areas
7458            invalidate(false);
7459            info.mRotationY = rotationY;
7460            info.mMatrixDirty = true;
7461            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7462            invalidate(false);
7463        }
7464    }
7465
7466    /**
7467     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7468     *
7469     * @see #getPivotX()
7470     * @see #getPivotY()
7471     * @see #setRotationX(float)
7472     *
7473     * @return The degrees of X rotation.
7474     */
7475    @ViewDebug.ExportedProperty(category = "drawing")
7476    public float getRotationX() {
7477        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7478    }
7479
7480    /**
7481     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7482     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7483     * x axis.
7484     *
7485     * When rotating large views, it is recommended to adjust the camera distance
7486     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7487     *
7488     * @param rotationX The degrees of X rotation.
7489     *
7490     * @see #getRotationX()
7491     * @see #getPivotX()
7492     * @see #getPivotY()
7493     * @see #setRotation(float)
7494     * @see #setRotationY(float)
7495     * @see #setCameraDistance(float)
7496     *
7497     * @attr ref android.R.styleable#View_rotationX
7498     */
7499    public void setRotationX(float rotationX) {
7500        ensureTransformationInfo();
7501        final TransformationInfo info = mTransformationInfo;
7502        if (info.mRotationX != rotationX) {
7503            invalidateParentCaches();
7504            // Double-invalidation is necessary to capture view's old and new areas
7505            invalidate(false);
7506            info.mRotationX = rotationX;
7507            info.mMatrixDirty = true;
7508            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7509            invalidate(false);
7510        }
7511    }
7512
7513    /**
7514     * The amount that the view is scaled in x around the pivot point, as a proportion of
7515     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7516     *
7517     * <p>By default, this is 1.0f.
7518     *
7519     * @see #getPivotX()
7520     * @see #getPivotY()
7521     * @return The scaling factor.
7522     */
7523    @ViewDebug.ExportedProperty(category = "drawing")
7524    public float getScaleX() {
7525        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7526    }
7527
7528    /**
7529     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7530     * the view's unscaled width. A value of 1 means that no scaling is applied.
7531     *
7532     * @param scaleX The scaling factor.
7533     * @see #getPivotX()
7534     * @see #getPivotY()
7535     *
7536     * @attr ref android.R.styleable#View_scaleX
7537     */
7538    public void setScaleX(float scaleX) {
7539        ensureTransformationInfo();
7540        final TransformationInfo info = mTransformationInfo;
7541        if (info.mScaleX != scaleX) {
7542            invalidateParentCaches();
7543            // Double-invalidation is necessary to capture view's old and new areas
7544            invalidate(false);
7545            info.mScaleX = scaleX;
7546            info.mMatrixDirty = true;
7547            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7548            invalidate(false);
7549        }
7550    }
7551
7552    /**
7553     * The amount that the view is scaled in y around the pivot point, as a proportion of
7554     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7555     *
7556     * <p>By default, this is 1.0f.
7557     *
7558     * @see #getPivotX()
7559     * @see #getPivotY()
7560     * @return The scaling factor.
7561     */
7562    @ViewDebug.ExportedProperty(category = "drawing")
7563    public float getScaleY() {
7564        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7565    }
7566
7567    /**
7568     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7569     * the view's unscaled width. A value of 1 means that no scaling is applied.
7570     *
7571     * @param scaleY The scaling factor.
7572     * @see #getPivotX()
7573     * @see #getPivotY()
7574     *
7575     * @attr ref android.R.styleable#View_scaleY
7576     */
7577    public void setScaleY(float scaleY) {
7578        ensureTransformationInfo();
7579        final TransformationInfo info = mTransformationInfo;
7580        if (info.mScaleY != scaleY) {
7581            invalidateParentCaches();
7582            // Double-invalidation is necessary to capture view's old and new areas
7583            invalidate(false);
7584            info.mScaleY = scaleY;
7585            info.mMatrixDirty = true;
7586            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7587            invalidate(false);
7588        }
7589    }
7590
7591    /**
7592     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7593     * and {@link #setScaleX(float) scaled}.
7594     *
7595     * @see #getRotation()
7596     * @see #getScaleX()
7597     * @see #getScaleY()
7598     * @see #getPivotY()
7599     * @return The x location of the pivot point.
7600     */
7601    @ViewDebug.ExportedProperty(category = "drawing")
7602    public float getPivotX() {
7603        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7604    }
7605
7606    /**
7607     * Sets the x location of the point around which the view is
7608     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7609     * By default, the pivot point is centered on the object.
7610     * Setting this property disables this behavior and causes the view to use only the
7611     * explicitly set pivotX and pivotY values.
7612     *
7613     * @param pivotX The x location of the pivot point.
7614     * @see #getRotation()
7615     * @see #getScaleX()
7616     * @see #getScaleY()
7617     * @see #getPivotY()
7618     *
7619     * @attr ref android.R.styleable#View_transformPivotX
7620     */
7621    public void setPivotX(float pivotX) {
7622        ensureTransformationInfo();
7623        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7624        final TransformationInfo info = mTransformationInfo;
7625        if (info.mPivotX != pivotX) {
7626            invalidateParentCaches();
7627            // Double-invalidation is necessary to capture view's old and new areas
7628            invalidate(false);
7629            info.mPivotX = pivotX;
7630            info.mMatrixDirty = true;
7631            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7632            invalidate(false);
7633        }
7634    }
7635
7636    /**
7637     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7638     * and {@link #setScaleY(float) scaled}.
7639     *
7640     * @see #getRotation()
7641     * @see #getScaleX()
7642     * @see #getScaleY()
7643     * @see #getPivotY()
7644     * @return The y location of the pivot point.
7645     */
7646    @ViewDebug.ExportedProperty(category = "drawing")
7647    public float getPivotY() {
7648        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7649    }
7650
7651    /**
7652     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7653     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7654     * Setting this property disables this behavior and causes the view to use only the
7655     * explicitly set pivotX and pivotY values.
7656     *
7657     * @param pivotY The y location of the pivot point.
7658     * @see #getRotation()
7659     * @see #getScaleX()
7660     * @see #getScaleY()
7661     * @see #getPivotY()
7662     *
7663     * @attr ref android.R.styleable#View_transformPivotY
7664     */
7665    public void setPivotY(float pivotY) {
7666        ensureTransformationInfo();
7667        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7668        final TransformationInfo info = mTransformationInfo;
7669        if (info.mPivotY != pivotY) {
7670            invalidateParentCaches();
7671            // Double-invalidation is necessary to capture view's old and new areas
7672            invalidate(false);
7673            info.mPivotY = pivotY;
7674            info.mMatrixDirty = true;
7675            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7676            invalidate(false);
7677        }
7678    }
7679
7680    /**
7681     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7682     * completely transparent and 1 means the view is completely opaque.
7683     *
7684     * <p>By default this is 1.0f.
7685     * @return The opacity of the view.
7686     */
7687    @ViewDebug.ExportedProperty(category = "drawing")
7688    public float getAlpha() {
7689        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7690    }
7691
7692    /**
7693     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7694     * completely transparent and 1 means the view is completely opaque.</p>
7695     *
7696     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7697     * responsible for applying the opacity itself. Otherwise, calling this method is
7698     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7699     * setting a hardware layer.</p>
7700     *
7701     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
7702     * performance implications. It is generally best to use the alpha property sparingly and
7703     * transiently, as in the case of fading animations.</p>
7704     *
7705     * @param alpha The opacity of the view.
7706     *
7707     * @see #setLayerType(int, android.graphics.Paint)
7708     *
7709     * @attr ref android.R.styleable#View_alpha
7710     */
7711    public void setAlpha(float alpha) {
7712        ensureTransformationInfo();
7713        if (mTransformationInfo.mAlpha != alpha) {
7714            mTransformationInfo.mAlpha = alpha;
7715            invalidateParentCaches();
7716            if (onSetAlpha((int) (alpha * 255))) {
7717                mPrivateFlags |= ALPHA_SET;
7718                // subclass is handling alpha - don't optimize rendering cache invalidation
7719                invalidate(true);
7720            } else {
7721                mPrivateFlags &= ~ALPHA_SET;
7722                invalidate(false);
7723            }
7724        }
7725    }
7726
7727    /**
7728     * Faster version of setAlpha() which performs the same steps except there are
7729     * no calls to invalidate(). The caller of this function should perform proper invalidation
7730     * on the parent and this object. The return value indicates whether the subclass handles
7731     * alpha (the return value for onSetAlpha()).
7732     *
7733     * @param alpha The new value for the alpha property
7734     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
7735     *         the new value for the alpha property is different from the old value
7736     */
7737    boolean setAlphaNoInvalidation(float alpha) {
7738        ensureTransformationInfo();
7739        if (mTransformationInfo.mAlpha != alpha) {
7740            mTransformationInfo.mAlpha = alpha;
7741            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7742            if (subclassHandlesAlpha) {
7743                mPrivateFlags |= ALPHA_SET;
7744                return true;
7745            } else {
7746                mPrivateFlags &= ~ALPHA_SET;
7747            }
7748        }
7749        return false;
7750    }
7751
7752    /**
7753     * Top position of this view relative to its parent.
7754     *
7755     * @return The top of this view, in pixels.
7756     */
7757    @ViewDebug.CapturedViewProperty
7758    public final int getTop() {
7759        return mTop;
7760    }
7761
7762    /**
7763     * Sets the top position of this view relative to its parent. This method is meant to be called
7764     * by the layout system and should not generally be called otherwise, because the property
7765     * may be changed at any time by the layout.
7766     *
7767     * @param top The top of this view, in pixels.
7768     */
7769    public final void setTop(int top) {
7770        if (top != mTop) {
7771            updateMatrix();
7772            final boolean matrixIsIdentity = mTransformationInfo == null
7773                    || mTransformationInfo.mMatrixIsIdentity;
7774            if (matrixIsIdentity) {
7775                if (mAttachInfo != null) {
7776                    int minTop;
7777                    int yLoc;
7778                    if (top < mTop) {
7779                        minTop = top;
7780                        yLoc = top - mTop;
7781                    } else {
7782                        minTop = mTop;
7783                        yLoc = 0;
7784                    }
7785                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7786                }
7787            } else {
7788                // Double-invalidation is necessary to capture view's old and new areas
7789                invalidate(true);
7790            }
7791
7792            int width = mRight - mLeft;
7793            int oldHeight = mBottom - mTop;
7794
7795            mTop = top;
7796
7797            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7798
7799            if (!matrixIsIdentity) {
7800                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7801                    // A change in dimension means an auto-centered pivot point changes, too
7802                    mTransformationInfo.mMatrixDirty = true;
7803                }
7804                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7805                invalidate(true);
7806            }
7807            mBackgroundSizeChanged = true;
7808            invalidateParentIfNeeded();
7809        }
7810    }
7811
7812    /**
7813     * Bottom position of this view relative to its parent.
7814     *
7815     * @return The bottom of this view, in pixels.
7816     */
7817    @ViewDebug.CapturedViewProperty
7818    public final int getBottom() {
7819        return mBottom;
7820    }
7821
7822    /**
7823     * True if this view has changed since the last time being drawn.
7824     *
7825     * @return The dirty state of this view.
7826     */
7827    public boolean isDirty() {
7828        return (mPrivateFlags & DIRTY_MASK) != 0;
7829    }
7830
7831    /**
7832     * Sets the bottom position of this view relative to its parent. This method is meant to be
7833     * called by the layout system and should not generally be called otherwise, because the
7834     * property may be changed at any time by the layout.
7835     *
7836     * @param bottom The bottom of this view, in pixels.
7837     */
7838    public final void setBottom(int bottom) {
7839        if (bottom != mBottom) {
7840            updateMatrix();
7841            final boolean matrixIsIdentity = mTransformationInfo == null
7842                    || mTransformationInfo.mMatrixIsIdentity;
7843            if (matrixIsIdentity) {
7844                if (mAttachInfo != null) {
7845                    int maxBottom;
7846                    if (bottom < mBottom) {
7847                        maxBottom = mBottom;
7848                    } else {
7849                        maxBottom = bottom;
7850                    }
7851                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7852                }
7853            } else {
7854                // Double-invalidation is necessary to capture view's old and new areas
7855                invalidate(true);
7856            }
7857
7858            int width = mRight - mLeft;
7859            int oldHeight = mBottom - mTop;
7860
7861            mBottom = bottom;
7862
7863            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7864
7865            if (!matrixIsIdentity) {
7866                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7867                    // A change in dimension means an auto-centered pivot point changes, too
7868                    mTransformationInfo.mMatrixDirty = true;
7869                }
7870                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7871                invalidate(true);
7872            }
7873            mBackgroundSizeChanged = true;
7874            invalidateParentIfNeeded();
7875        }
7876    }
7877
7878    /**
7879     * Left position of this view relative to its parent.
7880     *
7881     * @return The left edge of this view, in pixels.
7882     */
7883    @ViewDebug.CapturedViewProperty
7884    public final int getLeft() {
7885        return mLeft;
7886    }
7887
7888    /**
7889     * Sets the left position of this view relative to its parent. This method is meant to be called
7890     * by the layout system and should not generally be called otherwise, because the property
7891     * may be changed at any time by the layout.
7892     *
7893     * @param left The bottom of this view, in pixels.
7894     */
7895    public final void setLeft(int left) {
7896        if (left != mLeft) {
7897            updateMatrix();
7898            final boolean matrixIsIdentity = mTransformationInfo == null
7899                    || mTransformationInfo.mMatrixIsIdentity;
7900            if (matrixIsIdentity) {
7901                if (mAttachInfo != null) {
7902                    int minLeft;
7903                    int xLoc;
7904                    if (left < mLeft) {
7905                        minLeft = left;
7906                        xLoc = left - mLeft;
7907                    } else {
7908                        minLeft = mLeft;
7909                        xLoc = 0;
7910                    }
7911                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7912                }
7913            } else {
7914                // Double-invalidation is necessary to capture view's old and new areas
7915                invalidate(true);
7916            }
7917
7918            int oldWidth = mRight - mLeft;
7919            int height = mBottom - mTop;
7920
7921            mLeft = left;
7922
7923            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7924
7925            if (!matrixIsIdentity) {
7926                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7927                    // A change in dimension means an auto-centered pivot point changes, too
7928                    mTransformationInfo.mMatrixDirty = true;
7929                }
7930                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7931                invalidate(true);
7932            }
7933            mBackgroundSizeChanged = true;
7934            invalidateParentIfNeeded();
7935        }
7936    }
7937
7938    /**
7939     * Right position of this view relative to its parent.
7940     *
7941     * @return The right edge of this view, in pixels.
7942     */
7943    @ViewDebug.CapturedViewProperty
7944    public final int getRight() {
7945        return mRight;
7946    }
7947
7948    /**
7949     * Sets the right position of this view relative to its parent. This method is meant to be called
7950     * by the layout system and should not generally be called otherwise, because the property
7951     * may be changed at any time by the layout.
7952     *
7953     * @param right The bottom of this view, in pixels.
7954     */
7955    public final void setRight(int right) {
7956        if (right != mRight) {
7957            updateMatrix();
7958            final boolean matrixIsIdentity = mTransformationInfo == null
7959                    || mTransformationInfo.mMatrixIsIdentity;
7960            if (matrixIsIdentity) {
7961                if (mAttachInfo != null) {
7962                    int maxRight;
7963                    if (right < mRight) {
7964                        maxRight = mRight;
7965                    } else {
7966                        maxRight = right;
7967                    }
7968                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7969                }
7970            } else {
7971                // Double-invalidation is necessary to capture view's old and new areas
7972                invalidate(true);
7973            }
7974
7975            int oldWidth = mRight - mLeft;
7976            int height = mBottom - mTop;
7977
7978            mRight = right;
7979
7980            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7981
7982            if (!matrixIsIdentity) {
7983                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7984                    // A change in dimension means an auto-centered pivot point changes, too
7985                    mTransformationInfo.mMatrixDirty = true;
7986                }
7987                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7988                invalidate(true);
7989            }
7990            mBackgroundSizeChanged = true;
7991            invalidateParentIfNeeded();
7992        }
7993    }
7994
7995    /**
7996     * The visual x position of this view, in pixels. This is equivalent to the
7997     * {@link #setTranslationX(float) translationX} property plus the current
7998     * {@link #getLeft() left} property.
7999     *
8000     * @return The visual x position of this view, in pixels.
8001     */
8002    @ViewDebug.ExportedProperty(category = "drawing")
8003    public float getX() {
8004        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8005    }
8006
8007    /**
8008     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8009     * {@link #setTranslationX(float) translationX} property to be the difference between
8010     * the x value passed in and the current {@link #getLeft() left} property.
8011     *
8012     * @param x The visual x position of this view, in pixels.
8013     */
8014    public void setX(float x) {
8015        setTranslationX(x - mLeft);
8016    }
8017
8018    /**
8019     * The visual y position of this view, in pixels. This is equivalent to the
8020     * {@link #setTranslationY(float) translationY} property plus the current
8021     * {@link #getTop() top} property.
8022     *
8023     * @return The visual y position of this view, in pixels.
8024     */
8025    @ViewDebug.ExportedProperty(category = "drawing")
8026    public float getY() {
8027        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
8028    }
8029
8030    /**
8031     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
8032     * {@link #setTranslationY(float) translationY} property to be the difference between
8033     * the y value passed in and the current {@link #getTop() top} property.
8034     *
8035     * @param y The visual y position of this view, in pixels.
8036     */
8037    public void setY(float y) {
8038        setTranslationY(y - mTop);
8039    }
8040
8041
8042    /**
8043     * The horizontal location of this view relative to its {@link #getLeft() left} position.
8044     * This position is post-layout, in addition to wherever the object's
8045     * layout placed it.
8046     *
8047     * @return The horizontal position of this view relative to its left position, in pixels.
8048     */
8049    @ViewDebug.ExportedProperty(category = "drawing")
8050    public float getTranslationX() {
8051        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
8052    }
8053
8054    /**
8055     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
8056     * This effectively positions the object post-layout, in addition to wherever the object's
8057     * layout placed it.
8058     *
8059     * @param translationX The horizontal position of this view relative to its left position,
8060     * in pixels.
8061     *
8062     * @attr ref android.R.styleable#View_translationX
8063     */
8064    public void setTranslationX(float translationX) {
8065        ensureTransformationInfo();
8066        final TransformationInfo info = mTransformationInfo;
8067        if (info.mTranslationX != translationX) {
8068            invalidateParentCaches();
8069            // Double-invalidation is necessary to capture view's old and new areas
8070            invalidate(false);
8071            info.mTranslationX = translationX;
8072            info.mMatrixDirty = true;
8073            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8074            invalidate(false);
8075        }
8076    }
8077
8078    /**
8079     * The horizontal location of this view relative to its {@link #getTop() top} position.
8080     * This position is post-layout, in addition to wherever the object's
8081     * layout placed it.
8082     *
8083     * @return The vertical position of this view relative to its top position,
8084     * in pixels.
8085     */
8086    @ViewDebug.ExportedProperty(category = "drawing")
8087    public float getTranslationY() {
8088        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
8089    }
8090
8091    /**
8092     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
8093     * This effectively positions the object post-layout, in addition to wherever the object's
8094     * layout placed it.
8095     *
8096     * @param translationY The vertical position of this view relative to its top position,
8097     * in pixels.
8098     *
8099     * @attr ref android.R.styleable#View_translationY
8100     */
8101    public void setTranslationY(float translationY) {
8102        ensureTransformationInfo();
8103        final TransformationInfo info = mTransformationInfo;
8104        if (info.mTranslationY != translationY) {
8105            invalidateParentCaches();
8106            // Double-invalidation is necessary to capture view's old and new areas
8107            invalidate(false);
8108            info.mTranslationY = translationY;
8109            info.mMatrixDirty = true;
8110            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8111            invalidate(false);
8112        }
8113    }
8114
8115    /**
8116     * Hit rectangle in parent's coordinates
8117     *
8118     * @param outRect The hit rectangle of the view.
8119     */
8120    public void getHitRect(Rect outRect) {
8121        updateMatrix();
8122        final TransformationInfo info = mTransformationInfo;
8123        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
8124            outRect.set(mLeft, mTop, mRight, mBottom);
8125        } else {
8126            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
8127            tmpRect.set(-info.mPivotX, -info.mPivotY,
8128                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
8129            info.mMatrix.mapRect(tmpRect);
8130            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
8131                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
8132        }
8133    }
8134
8135    /**
8136     * Determines whether the given point, in local coordinates is inside the view.
8137     */
8138    /*package*/ final boolean pointInView(float localX, float localY) {
8139        return localX >= 0 && localX < (mRight - mLeft)
8140                && localY >= 0 && localY < (mBottom - mTop);
8141    }
8142
8143    /**
8144     * Utility method to determine whether the given point, in local coordinates,
8145     * is inside the view, where the area of the view is expanded by the slop factor.
8146     * This method is called while processing touch-move events to determine if the event
8147     * is still within the view.
8148     */
8149    private boolean pointInView(float localX, float localY, float slop) {
8150        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
8151                localY < ((mBottom - mTop) + slop);
8152    }
8153
8154    /**
8155     * When a view has focus and the user navigates away from it, the next view is searched for
8156     * starting from the rectangle filled in by this method.
8157     *
8158     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
8159     * of the view.  However, if your view maintains some idea of internal selection,
8160     * such as a cursor, or a selected row or column, you should override this method and
8161     * fill in a more specific rectangle.
8162     *
8163     * @param r The rectangle to fill in, in this view's coordinates.
8164     */
8165    public void getFocusedRect(Rect r) {
8166        getDrawingRect(r);
8167    }
8168
8169    /**
8170     * If some part of this view is not clipped by any of its parents, then
8171     * return that area in r in global (root) coordinates. To convert r to local
8172     * coordinates (without taking possible View rotations into account), offset
8173     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
8174     * If the view is completely clipped or translated out, return false.
8175     *
8176     * @param r If true is returned, r holds the global coordinates of the
8177     *        visible portion of this view.
8178     * @param globalOffset If true is returned, globalOffset holds the dx,dy
8179     *        between this view and its root. globalOffet may be null.
8180     * @return true if r is non-empty (i.e. part of the view is visible at the
8181     *         root level.
8182     */
8183    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
8184        int width = mRight - mLeft;
8185        int height = mBottom - mTop;
8186        if (width > 0 && height > 0) {
8187            r.set(0, 0, width, height);
8188            if (globalOffset != null) {
8189                globalOffset.set(-mScrollX, -mScrollY);
8190            }
8191            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8192        }
8193        return false;
8194    }
8195
8196    public final boolean getGlobalVisibleRect(Rect r) {
8197        return getGlobalVisibleRect(r, null);
8198    }
8199
8200    public final boolean getLocalVisibleRect(Rect r) {
8201        Point offset = new Point();
8202        if (getGlobalVisibleRect(r, offset)) {
8203            r.offset(-offset.x, -offset.y); // make r local
8204            return true;
8205        }
8206        return false;
8207    }
8208
8209    /**
8210     * Offset this view's vertical location by the specified number of pixels.
8211     *
8212     * @param offset the number of pixels to offset the view by
8213     */
8214    public void offsetTopAndBottom(int offset) {
8215        if (offset != 0) {
8216            updateMatrix();
8217            final boolean matrixIsIdentity = mTransformationInfo == null
8218                    || mTransformationInfo.mMatrixIsIdentity;
8219            if (matrixIsIdentity) {
8220                final ViewParent p = mParent;
8221                if (p != null && mAttachInfo != null) {
8222                    final Rect r = mAttachInfo.mTmpInvalRect;
8223                    int minTop;
8224                    int maxBottom;
8225                    int yLoc;
8226                    if (offset < 0) {
8227                        minTop = mTop + offset;
8228                        maxBottom = mBottom;
8229                        yLoc = offset;
8230                    } else {
8231                        minTop = mTop;
8232                        maxBottom = mBottom + offset;
8233                        yLoc = 0;
8234                    }
8235                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8236                    p.invalidateChild(this, r);
8237                }
8238            } else {
8239                invalidate(false);
8240            }
8241
8242            mTop += offset;
8243            mBottom += offset;
8244
8245            if (!matrixIsIdentity) {
8246                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8247                invalidate(false);
8248            }
8249            invalidateParentIfNeeded();
8250        }
8251    }
8252
8253    /**
8254     * Offset this view's horizontal location by the specified amount of pixels.
8255     *
8256     * @param offset the numer of pixels to offset the view by
8257     */
8258    public void offsetLeftAndRight(int offset) {
8259        if (offset != 0) {
8260            updateMatrix();
8261            final boolean matrixIsIdentity = mTransformationInfo == null
8262                    || mTransformationInfo.mMatrixIsIdentity;
8263            if (matrixIsIdentity) {
8264                final ViewParent p = mParent;
8265                if (p != null && mAttachInfo != null) {
8266                    final Rect r = mAttachInfo.mTmpInvalRect;
8267                    int minLeft;
8268                    int maxRight;
8269                    if (offset < 0) {
8270                        minLeft = mLeft + offset;
8271                        maxRight = mRight;
8272                    } else {
8273                        minLeft = mLeft;
8274                        maxRight = mRight + offset;
8275                    }
8276                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8277                    p.invalidateChild(this, r);
8278                }
8279            } else {
8280                invalidate(false);
8281            }
8282
8283            mLeft += offset;
8284            mRight += offset;
8285
8286            if (!matrixIsIdentity) {
8287                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8288                invalidate(false);
8289            }
8290            invalidateParentIfNeeded();
8291        }
8292    }
8293
8294    /**
8295     * Get the LayoutParams associated with this view. All views should have
8296     * layout parameters. These supply parameters to the <i>parent</i> of this
8297     * view specifying how it should be arranged. There are many subclasses of
8298     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8299     * of ViewGroup that are responsible for arranging their children.
8300     *
8301     * This method may return null if this View is not attached to a parent
8302     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8303     * was not invoked successfully. When a View is attached to a parent
8304     * ViewGroup, this method must not return null.
8305     *
8306     * @return The LayoutParams associated with this view, or null if no
8307     *         parameters have been set yet
8308     */
8309    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8310    public ViewGroup.LayoutParams getLayoutParams() {
8311        return mLayoutParams;
8312    }
8313
8314    /**
8315     * Set the layout parameters associated with this view. These supply
8316     * parameters to the <i>parent</i> of this view specifying how it should be
8317     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8318     * correspond to the different subclasses of ViewGroup that are responsible
8319     * for arranging their children.
8320     *
8321     * @param params The layout parameters for this view, cannot be null
8322     */
8323    public void setLayoutParams(ViewGroup.LayoutParams params) {
8324        if (params == null) {
8325            throw new NullPointerException("Layout parameters cannot be null");
8326        }
8327        mLayoutParams = params;
8328        if (mParent instanceof ViewGroup) {
8329            ((ViewGroup) mParent).onSetLayoutParams(this, params);
8330        }
8331        requestLayout();
8332    }
8333
8334    /**
8335     * Set the scrolled position of your view. This will cause a call to
8336     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8337     * invalidated.
8338     * @param x the x position to scroll to
8339     * @param y the y position to scroll to
8340     */
8341    public void scrollTo(int x, int y) {
8342        if (mScrollX != x || mScrollY != y) {
8343            int oldX = mScrollX;
8344            int oldY = mScrollY;
8345            mScrollX = x;
8346            mScrollY = y;
8347            invalidateParentCaches();
8348            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8349            if (!awakenScrollBars()) {
8350                invalidate(true);
8351            }
8352        }
8353    }
8354
8355    /**
8356     * Move the scrolled position of your view. This will cause a call to
8357     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8358     * invalidated.
8359     * @param x the amount of pixels to scroll by horizontally
8360     * @param y the amount of pixels to scroll by vertically
8361     */
8362    public void scrollBy(int x, int y) {
8363        scrollTo(mScrollX + x, mScrollY + y);
8364    }
8365
8366    /**
8367     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8368     * animation to fade the scrollbars out after a default delay. If a subclass
8369     * provides animated scrolling, the start delay should equal the duration
8370     * of the scrolling animation.</p>
8371     *
8372     * <p>The animation starts only if at least one of the scrollbars is
8373     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8374     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8375     * this method returns true, and false otherwise. If the animation is
8376     * started, this method calls {@link #invalidate()}; in that case the
8377     * caller should not call {@link #invalidate()}.</p>
8378     *
8379     * <p>This method should be invoked every time a subclass directly updates
8380     * the scroll parameters.</p>
8381     *
8382     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8383     * and {@link #scrollTo(int, int)}.</p>
8384     *
8385     * @return true if the animation is played, false otherwise
8386     *
8387     * @see #awakenScrollBars(int)
8388     * @see #scrollBy(int, int)
8389     * @see #scrollTo(int, int)
8390     * @see #isHorizontalScrollBarEnabled()
8391     * @see #isVerticalScrollBarEnabled()
8392     * @see #setHorizontalScrollBarEnabled(boolean)
8393     * @see #setVerticalScrollBarEnabled(boolean)
8394     */
8395    protected boolean awakenScrollBars() {
8396        return mScrollCache != null &&
8397                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8398    }
8399
8400    /**
8401     * Trigger the scrollbars to draw.
8402     * This method differs from awakenScrollBars() only in its default duration.
8403     * initialAwakenScrollBars() will show the scroll bars for longer than
8404     * usual to give the user more of a chance to notice them.
8405     *
8406     * @return true if the animation is played, false otherwise.
8407     */
8408    private boolean initialAwakenScrollBars() {
8409        return mScrollCache != null &&
8410                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8411    }
8412
8413    /**
8414     * <p>
8415     * Trigger the scrollbars to draw. When invoked this method starts an
8416     * animation to fade the scrollbars out after a fixed delay. If a subclass
8417     * provides animated scrolling, the start delay should equal the duration of
8418     * the scrolling animation.
8419     * </p>
8420     *
8421     * <p>
8422     * The animation starts only if at least one of the scrollbars is enabled,
8423     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8424     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8425     * this method returns true, and false otherwise. If the animation is
8426     * started, this method calls {@link #invalidate()}; in that case the caller
8427     * should not call {@link #invalidate()}.
8428     * </p>
8429     *
8430     * <p>
8431     * This method should be invoked everytime a subclass directly updates the
8432     * scroll parameters.
8433     * </p>
8434     *
8435     * @param startDelay the delay, in milliseconds, after which the animation
8436     *        should start; when the delay is 0, the animation starts
8437     *        immediately
8438     * @return true if the animation is played, false otherwise
8439     *
8440     * @see #scrollBy(int, int)
8441     * @see #scrollTo(int, int)
8442     * @see #isHorizontalScrollBarEnabled()
8443     * @see #isVerticalScrollBarEnabled()
8444     * @see #setHorizontalScrollBarEnabled(boolean)
8445     * @see #setVerticalScrollBarEnabled(boolean)
8446     */
8447    protected boolean awakenScrollBars(int startDelay) {
8448        return awakenScrollBars(startDelay, true);
8449    }
8450
8451    /**
8452     * <p>
8453     * Trigger the scrollbars to draw. When invoked this method starts an
8454     * animation to fade the scrollbars out after a fixed delay. If a subclass
8455     * provides animated scrolling, the start delay should equal the duration of
8456     * the scrolling animation.
8457     * </p>
8458     *
8459     * <p>
8460     * The animation starts only if at least one of the scrollbars is enabled,
8461     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8462     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8463     * this method returns true, and false otherwise. If the animation is
8464     * started, this method calls {@link #invalidate()} if the invalidate parameter
8465     * is set to true; in that case the caller
8466     * should not call {@link #invalidate()}.
8467     * </p>
8468     *
8469     * <p>
8470     * This method should be invoked everytime a subclass directly updates the
8471     * scroll parameters.
8472     * </p>
8473     *
8474     * @param startDelay the delay, in milliseconds, after which the animation
8475     *        should start; when the delay is 0, the animation starts
8476     *        immediately
8477     *
8478     * @param invalidate Wheter this method should call invalidate
8479     *
8480     * @return true if the animation is played, false otherwise
8481     *
8482     * @see #scrollBy(int, int)
8483     * @see #scrollTo(int, int)
8484     * @see #isHorizontalScrollBarEnabled()
8485     * @see #isVerticalScrollBarEnabled()
8486     * @see #setHorizontalScrollBarEnabled(boolean)
8487     * @see #setVerticalScrollBarEnabled(boolean)
8488     */
8489    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8490        final ScrollabilityCache scrollCache = mScrollCache;
8491
8492        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8493            return false;
8494        }
8495
8496        if (scrollCache.scrollBar == null) {
8497            scrollCache.scrollBar = new ScrollBarDrawable();
8498        }
8499
8500        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8501
8502            if (invalidate) {
8503                // Invalidate to show the scrollbars
8504                invalidate(true);
8505            }
8506
8507            if (scrollCache.state == ScrollabilityCache.OFF) {
8508                // FIXME: this is copied from WindowManagerService.
8509                // We should get this value from the system when it
8510                // is possible to do so.
8511                final int KEY_REPEAT_FIRST_DELAY = 750;
8512                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8513            }
8514
8515            // Tell mScrollCache when we should start fading. This may
8516            // extend the fade start time if one was already scheduled
8517            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8518            scrollCache.fadeStartTime = fadeStartTime;
8519            scrollCache.state = ScrollabilityCache.ON;
8520
8521            // Schedule our fader to run, unscheduling any old ones first
8522            if (mAttachInfo != null) {
8523                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8524                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8525            }
8526
8527            return true;
8528        }
8529
8530        return false;
8531    }
8532
8533    /**
8534     * Do not invalidate views which are not visible and which are not running an animation. They
8535     * will not get drawn and they should not set dirty flags as if they will be drawn
8536     */
8537    private boolean skipInvalidate() {
8538        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8539                (!(mParent instanceof ViewGroup) ||
8540                        !((ViewGroup) mParent).isViewTransitioning(this));
8541    }
8542    /**
8543     * Mark the area defined by dirty as needing to be drawn. If the view is
8544     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8545     * in the future. This must be called from a UI thread. To call from a non-UI
8546     * thread, call {@link #postInvalidate()}.
8547     *
8548     * WARNING: This method is destructive to dirty.
8549     * @param dirty the rectangle representing the bounds of the dirty region
8550     */
8551    public void invalidate(Rect dirty) {
8552        if (ViewDebug.TRACE_HIERARCHY) {
8553            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8554        }
8555
8556        if (skipInvalidate()) {
8557            return;
8558        }
8559        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8560                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8561                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8562            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8563            mPrivateFlags |= INVALIDATED;
8564            mPrivateFlags |= DIRTY;
8565            final ViewParent p = mParent;
8566            final AttachInfo ai = mAttachInfo;
8567            //noinspection PointlessBooleanExpression,ConstantConditions
8568            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8569                if (p != null && ai != null && ai.mHardwareAccelerated) {
8570                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8571                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8572                    p.invalidateChild(this, null);
8573                    return;
8574                }
8575            }
8576            if (p != null && ai != null) {
8577                final int scrollX = mScrollX;
8578                final int scrollY = mScrollY;
8579                final Rect r = ai.mTmpInvalRect;
8580                r.set(dirty.left - scrollX, dirty.top - scrollY,
8581                        dirty.right - scrollX, dirty.bottom - scrollY);
8582                mParent.invalidateChild(this, r);
8583            }
8584        }
8585    }
8586
8587    /**
8588     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
8589     * The coordinates of the dirty rect are relative to the view.
8590     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8591     * will be called at some point in the future. This must be called from
8592     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8593     * @param l the left position of the dirty region
8594     * @param t the top position of the dirty region
8595     * @param r the right position of the dirty region
8596     * @param b the bottom position of the dirty region
8597     */
8598    public void invalidate(int l, int t, int r, int b) {
8599        if (ViewDebug.TRACE_HIERARCHY) {
8600            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8601        }
8602
8603        if (skipInvalidate()) {
8604            return;
8605        }
8606        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8607                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8608                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8609            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8610            mPrivateFlags |= INVALIDATED;
8611            mPrivateFlags |= DIRTY;
8612            final ViewParent p = mParent;
8613            final AttachInfo ai = mAttachInfo;
8614            //noinspection PointlessBooleanExpression,ConstantConditions
8615            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8616                if (p != null && ai != null && ai.mHardwareAccelerated) {
8617                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8618                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8619                    p.invalidateChild(this, null);
8620                    return;
8621                }
8622            }
8623            if (p != null && ai != null && l < r && t < b) {
8624                final int scrollX = mScrollX;
8625                final int scrollY = mScrollY;
8626                final Rect tmpr = ai.mTmpInvalRect;
8627                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8628                p.invalidateChild(this, tmpr);
8629            }
8630        }
8631    }
8632
8633    /**
8634     * Invalidate the whole view. If the view is visible,
8635     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8636     * the future. This must be called from a UI thread. To call from a non-UI thread,
8637     * call {@link #postInvalidate()}.
8638     */
8639    public void invalidate() {
8640        invalidate(true);
8641    }
8642
8643    /**
8644     * This is where the invalidate() work actually happens. A full invalidate()
8645     * causes the drawing cache to be invalidated, but this function can be called with
8646     * invalidateCache set to false to skip that invalidation step for cases that do not
8647     * need it (for example, a component that remains at the same dimensions with the same
8648     * content).
8649     *
8650     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8651     * well. This is usually true for a full invalidate, but may be set to false if the
8652     * View's contents or dimensions have not changed.
8653     */
8654    void invalidate(boolean invalidateCache) {
8655        if (ViewDebug.TRACE_HIERARCHY) {
8656            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8657        }
8658
8659        if (skipInvalidate()) {
8660            return;
8661        }
8662        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8663                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8664                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8665            mLastIsOpaque = isOpaque();
8666            mPrivateFlags &= ~DRAWN;
8667            mPrivateFlags |= DIRTY;
8668            if (invalidateCache) {
8669                mPrivateFlags |= INVALIDATED;
8670                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8671            }
8672            final AttachInfo ai = mAttachInfo;
8673            final ViewParent p = mParent;
8674            //noinspection PointlessBooleanExpression,ConstantConditions
8675            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8676                if (p != null && ai != null && ai.mHardwareAccelerated) {
8677                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8678                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8679                    p.invalidateChild(this, null);
8680                    return;
8681                }
8682            }
8683
8684            if (p != null && ai != null) {
8685                final Rect r = ai.mTmpInvalRect;
8686                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8687                // Don't call invalidate -- we don't want to internally scroll
8688                // our own bounds
8689                p.invalidateChild(this, r);
8690            }
8691        }
8692    }
8693
8694    /**
8695     * Used to indicate that the parent of this view should clear its caches. This functionality
8696     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8697     * which is necessary when various parent-managed properties of the view change, such as
8698     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8699     * clears the parent caches and does not causes an invalidate event.
8700     *
8701     * @hide
8702     */
8703    protected void invalidateParentCaches() {
8704        if (mParent instanceof View) {
8705            ((View) mParent).mPrivateFlags |= INVALIDATED;
8706        }
8707    }
8708
8709    /**
8710     * Used to indicate that the parent of this view should be invalidated. This functionality
8711     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8712     * which is necessary when various parent-managed properties of the view change, such as
8713     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8714     * an invalidation event to the parent.
8715     *
8716     * @hide
8717     */
8718    protected void invalidateParentIfNeeded() {
8719        if (isHardwareAccelerated() && mParent instanceof View) {
8720            ((View) mParent).invalidate(true);
8721        }
8722    }
8723
8724    /**
8725     * Indicates whether this View is opaque. An opaque View guarantees that it will
8726     * draw all the pixels overlapping its bounds using a fully opaque color.
8727     *
8728     * Subclasses of View should override this method whenever possible to indicate
8729     * whether an instance is opaque. Opaque Views are treated in a special way by
8730     * the View hierarchy, possibly allowing it to perform optimizations during
8731     * invalidate/draw passes.
8732     *
8733     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8734     */
8735    @ViewDebug.ExportedProperty(category = "drawing")
8736    public boolean isOpaque() {
8737        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8738                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8739                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8740    }
8741
8742    /**
8743     * @hide
8744     */
8745    protected void computeOpaqueFlags() {
8746        // Opaque if:
8747        //   - Has a background
8748        //   - Background is opaque
8749        //   - Doesn't have scrollbars or scrollbars are inside overlay
8750
8751        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8752            mPrivateFlags |= OPAQUE_BACKGROUND;
8753        } else {
8754            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8755        }
8756
8757        final int flags = mViewFlags;
8758        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8759                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8760            mPrivateFlags |= OPAQUE_SCROLLBARS;
8761        } else {
8762            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8763        }
8764    }
8765
8766    /**
8767     * @hide
8768     */
8769    protected boolean hasOpaqueScrollbars() {
8770        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8771    }
8772
8773    /**
8774     * @return A handler associated with the thread running the View. This
8775     * handler can be used to pump events in the UI events queue.
8776     */
8777    public Handler getHandler() {
8778        if (mAttachInfo != null) {
8779            return mAttachInfo.mHandler;
8780        }
8781        return null;
8782    }
8783
8784    /**
8785     * Gets the view root associated with the View.
8786     * @return The view root, or null if none.
8787     * @hide
8788     */
8789    public ViewRootImpl getViewRootImpl() {
8790        if (mAttachInfo != null) {
8791            return mAttachInfo.mViewRootImpl;
8792        }
8793        return null;
8794    }
8795
8796    /**
8797     * <p>Causes the Runnable to be added to the message queue.
8798     * The runnable will be run on the user interface thread.</p>
8799     *
8800     * <p>This method can be invoked from outside of the UI thread
8801     * only when this View is attached to a window.</p>
8802     *
8803     * @param action The Runnable that will be executed.
8804     *
8805     * @return Returns true if the Runnable was successfully placed in to the
8806     *         message queue.  Returns false on failure, usually because the
8807     *         looper processing the message queue is exiting.
8808     */
8809    public boolean post(Runnable action) {
8810        final AttachInfo attachInfo = mAttachInfo;
8811        if (attachInfo != null) {
8812            return attachInfo.mHandler.post(action);
8813        }
8814        // Assume that post will succeed later
8815        ViewRootImpl.getRunQueue().post(action);
8816        return true;
8817    }
8818
8819    /**
8820     * <p>Causes the Runnable to be added to the message queue, to be run
8821     * after the specified amount of time elapses.
8822     * The runnable will be run on the user interface thread.</p>
8823     *
8824     * <p>This method can be invoked from outside of the UI thread
8825     * only when this View is attached to a window.</p>
8826     *
8827     * @param action The Runnable that will be executed.
8828     * @param delayMillis The delay (in milliseconds) until the Runnable
8829     *        will be executed.
8830     *
8831     * @return true if the Runnable was successfully placed in to the
8832     *         message queue.  Returns false on failure, usually because the
8833     *         looper processing the message queue is exiting.  Note that a
8834     *         result of true does not mean the Runnable will be processed --
8835     *         if the looper is quit before the delivery time of the message
8836     *         occurs then the message will be dropped.
8837     */
8838    public boolean postDelayed(Runnable action, long delayMillis) {
8839        final AttachInfo attachInfo = mAttachInfo;
8840        if (attachInfo != null) {
8841            return attachInfo.mHandler.postDelayed(action, delayMillis);
8842        }
8843        // Assume that post will succeed later
8844        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8845        return true;
8846    }
8847
8848    /**
8849     * <p>Causes the Runnable to execute on the next animation time step.
8850     * The runnable will be run on the user interface thread.</p>
8851     *
8852     * <p>This method can be invoked from outside of the UI thread
8853     * only when this View is attached to a window.</p>
8854     *
8855     * @param action The Runnable that will be executed.
8856     *
8857     * @hide
8858     */
8859    public void postOnAnimation(Runnable action) {
8860        final AttachInfo attachInfo = mAttachInfo;
8861        if (attachInfo != null) {
8862            attachInfo.mViewRootImpl.mChoreographer.postAnimationCallback(action, null);
8863        } else {
8864            // Assume that post will succeed later
8865            ViewRootImpl.getRunQueue().post(action);
8866        }
8867    }
8868
8869    /**
8870     * <p>Causes the Runnable to execute on the next animation time step,
8871     * after the specified amount of time elapses.
8872     * The runnable will be run on the user interface thread.</p>
8873     *
8874     * <p>This method can be invoked from outside of the UI thread
8875     * only when this View is attached to a window.</p>
8876     *
8877     * @param action The Runnable that will be executed.
8878     * @param delayMillis The delay (in milliseconds) until the Runnable
8879     *        will be executed.
8880     *
8881     * @hide
8882     */
8883    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
8884        final AttachInfo attachInfo = mAttachInfo;
8885        if (attachInfo != null) {
8886            attachInfo.mViewRootImpl.mChoreographer.postAnimationCallbackDelayed(
8887                    action, null, delayMillis);
8888        } else {
8889            // Assume that post will succeed later
8890            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8891        }
8892    }
8893
8894    /**
8895     * <p>Removes the specified Runnable from the message queue.</p>
8896     *
8897     * <p>This method can be invoked from outside of the UI thread
8898     * only when this View is attached to a window.</p>
8899     *
8900     * @param action The Runnable to remove from the message handling queue
8901     *
8902     * @return true if this view could ask the Handler to remove the Runnable,
8903     *         false otherwise. When the returned value is true, the Runnable
8904     *         may or may not have been actually removed from the message queue
8905     *         (for instance, if the Runnable was not in the queue already.)
8906     */
8907    public boolean removeCallbacks(Runnable action) {
8908        if (action != null) {
8909            final AttachInfo attachInfo = mAttachInfo;
8910            if (attachInfo != null) {
8911                attachInfo.mHandler.removeCallbacks(action);
8912                attachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(action, null);
8913            } else {
8914                // Assume that post will succeed later
8915                ViewRootImpl.getRunQueue().removeCallbacks(action);
8916            }
8917        }
8918        return true;
8919    }
8920
8921    /**
8922     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8923     * Use this to invalidate the View from a non-UI thread.</p>
8924     *
8925     * <p>This method can be invoked from outside of the UI thread
8926     * only when this View is attached to a window.</p>
8927     *
8928     * @see #invalidate()
8929     */
8930    public void postInvalidate() {
8931        postInvalidateDelayed(0);
8932    }
8933
8934    /**
8935     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8936     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8937     *
8938     * <p>This method can be invoked from outside of the UI thread
8939     * only when this View is attached to a window.</p>
8940     *
8941     * @param left The left coordinate of the rectangle to invalidate.
8942     * @param top The top coordinate of the rectangle to invalidate.
8943     * @param right The right coordinate of the rectangle to invalidate.
8944     * @param bottom The bottom coordinate of the rectangle to invalidate.
8945     *
8946     * @see #invalidate(int, int, int, int)
8947     * @see #invalidate(Rect)
8948     */
8949    public void postInvalidate(int left, int top, int right, int bottom) {
8950        postInvalidateDelayed(0, left, top, right, bottom);
8951    }
8952
8953    /**
8954     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8955     * loop. Waits for the specified amount of time.</p>
8956     *
8957     * <p>This method can be invoked from outside of the UI thread
8958     * only when this View is attached to a window.</p>
8959     *
8960     * @param delayMilliseconds the duration in milliseconds to delay the
8961     *         invalidation by
8962     */
8963    public void postInvalidateDelayed(long delayMilliseconds) {
8964        // We try only with the AttachInfo because there's no point in invalidating
8965        // if we are not attached to our window
8966        final AttachInfo attachInfo = mAttachInfo;
8967        if (attachInfo != null) {
8968            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
8969        }
8970    }
8971
8972    /**
8973     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8974     * through the event loop. Waits for the specified amount of time.</p>
8975     *
8976     * <p>This method can be invoked from outside of the UI thread
8977     * only when this View is attached to a window.</p>
8978     *
8979     * @param delayMilliseconds the duration in milliseconds to delay the
8980     *         invalidation by
8981     * @param left The left coordinate of the rectangle to invalidate.
8982     * @param top The top coordinate of the rectangle to invalidate.
8983     * @param right The right coordinate of the rectangle to invalidate.
8984     * @param bottom The bottom coordinate of the rectangle to invalidate.
8985     */
8986    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8987            int right, int bottom) {
8988
8989        // We try only with the AttachInfo because there's no point in invalidating
8990        // if we are not attached to our window
8991        final AttachInfo attachInfo = mAttachInfo;
8992        if (attachInfo != null) {
8993            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8994            info.target = this;
8995            info.left = left;
8996            info.top = top;
8997            info.right = right;
8998            info.bottom = bottom;
8999
9000            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
9001        }
9002    }
9003
9004    /**
9005     * <p>Cause an invalidate to happen on the next animation time step, typically the
9006     * next display frame.</p>
9007     *
9008     * <p>This method can be invoked from outside of the UI thread
9009     * only when this View is attached to a window.</p>
9010     *
9011     * @hide
9012     */
9013    public void postInvalidateOnAnimation() {
9014        // We try only with the AttachInfo because there's no point in invalidating
9015        // if we are not attached to our window
9016        final AttachInfo attachInfo = mAttachInfo;
9017        if (attachInfo != null) {
9018            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
9019        }
9020    }
9021
9022    /**
9023     * <p>Cause an invalidate of the specified area to happen on the next animation
9024     * time step, typically the next display frame.</p>
9025     *
9026     * <p>This method can be invoked from outside of the UI thread
9027     * only when this View is attached to a window.</p>
9028     *
9029     * @param left The left coordinate of the rectangle to invalidate.
9030     * @param top The top coordinate of the rectangle to invalidate.
9031     * @param right The right coordinate of the rectangle to invalidate.
9032     * @param bottom The bottom coordinate of the rectangle to invalidate.
9033     *
9034     * @hide
9035     */
9036    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
9037        // We try only with the AttachInfo because there's no point in invalidating
9038        // if we are not attached to our window
9039        final AttachInfo attachInfo = mAttachInfo;
9040        if (attachInfo != null) {
9041            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9042            info.target = this;
9043            info.left = left;
9044            info.top = top;
9045            info.right = right;
9046            info.bottom = bottom;
9047
9048            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
9049        }
9050    }
9051
9052    /**
9053     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
9054     * This event is sent at most once every
9055     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
9056     */
9057    private void postSendViewScrolledAccessibilityEventCallback() {
9058        if (mSendViewScrolledAccessibilityEvent == null) {
9059            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
9060        }
9061        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
9062            mSendViewScrolledAccessibilityEvent.mIsPending = true;
9063            postDelayed(mSendViewScrolledAccessibilityEvent,
9064                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
9065        }
9066    }
9067
9068    /**
9069     * Called by a parent to request that a child update its values for mScrollX
9070     * and mScrollY if necessary. This will typically be done if the child is
9071     * animating a scroll using a {@link android.widget.Scroller Scroller}
9072     * object.
9073     */
9074    public void computeScroll() {
9075    }
9076
9077    /**
9078     * <p>Indicate whether the horizontal edges are faded when the view is
9079     * scrolled horizontally.</p>
9080     *
9081     * @return true if the horizontal edges should are faded on scroll, false
9082     *         otherwise
9083     *
9084     * @see #setHorizontalFadingEdgeEnabled(boolean)
9085     * @attr ref android.R.styleable#View_requiresFadingEdge
9086     */
9087    public boolean isHorizontalFadingEdgeEnabled() {
9088        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
9089    }
9090
9091    /**
9092     * <p>Define whether the horizontal edges should be faded when this view
9093     * is scrolled horizontally.</p>
9094     *
9095     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
9096     *                                    be faded when the view is scrolled
9097     *                                    horizontally
9098     *
9099     * @see #isHorizontalFadingEdgeEnabled()
9100     * @attr ref android.R.styleable#View_requiresFadingEdge
9101     */
9102    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
9103        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
9104            if (horizontalFadingEdgeEnabled) {
9105                initScrollCache();
9106            }
9107
9108            mViewFlags ^= FADING_EDGE_HORIZONTAL;
9109        }
9110    }
9111
9112    /**
9113     * <p>Indicate whether the vertical edges are faded when the view is
9114     * scrolled horizontally.</p>
9115     *
9116     * @return true if the vertical edges should are faded on scroll, false
9117     *         otherwise
9118     *
9119     * @see #setVerticalFadingEdgeEnabled(boolean)
9120     * @attr ref android.R.styleable#View_requiresFadingEdge
9121     */
9122    public boolean isVerticalFadingEdgeEnabled() {
9123        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
9124    }
9125
9126    /**
9127     * <p>Define whether the vertical edges should be faded when this view
9128     * is scrolled vertically.</p>
9129     *
9130     * @param verticalFadingEdgeEnabled true if the vertical edges should
9131     *                                  be faded when the view is scrolled
9132     *                                  vertically
9133     *
9134     * @see #isVerticalFadingEdgeEnabled()
9135     * @attr ref android.R.styleable#View_requiresFadingEdge
9136     */
9137    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
9138        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
9139            if (verticalFadingEdgeEnabled) {
9140                initScrollCache();
9141            }
9142
9143            mViewFlags ^= FADING_EDGE_VERTICAL;
9144        }
9145    }
9146
9147    /**
9148     * Returns the strength, or intensity, of the top faded edge. The strength is
9149     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9150     * returns 0.0 or 1.0 but no value in between.
9151     *
9152     * Subclasses should override this method to provide a smoother fade transition
9153     * when scrolling occurs.
9154     *
9155     * @return the intensity of the top fade as a float between 0.0f and 1.0f
9156     */
9157    protected float getTopFadingEdgeStrength() {
9158        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
9159    }
9160
9161    /**
9162     * Returns the strength, or intensity, of the bottom faded edge. The strength is
9163     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9164     * returns 0.0 or 1.0 but no value in between.
9165     *
9166     * Subclasses should override this method to provide a smoother fade transition
9167     * when scrolling occurs.
9168     *
9169     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
9170     */
9171    protected float getBottomFadingEdgeStrength() {
9172        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
9173                computeVerticalScrollRange() ? 1.0f : 0.0f;
9174    }
9175
9176    /**
9177     * Returns the strength, or intensity, of the left faded edge. The strength is
9178     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9179     * returns 0.0 or 1.0 but no value in between.
9180     *
9181     * Subclasses should override this method to provide a smoother fade transition
9182     * when scrolling occurs.
9183     *
9184     * @return the intensity of the left fade as a float between 0.0f and 1.0f
9185     */
9186    protected float getLeftFadingEdgeStrength() {
9187        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
9188    }
9189
9190    /**
9191     * Returns the strength, or intensity, of the right faded edge. The strength is
9192     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9193     * returns 0.0 or 1.0 but no value in between.
9194     *
9195     * Subclasses should override this method to provide a smoother fade transition
9196     * when scrolling occurs.
9197     *
9198     * @return the intensity of the right fade as a float between 0.0f and 1.0f
9199     */
9200    protected float getRightFadingEdgeStrength() {
9201        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
9202                computeHorizontalScrollRange() ? 1.0f : 0.0f;
9203    }
9204
9205    /**
9206     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
9207     * scrollbar is not drawn by default.</p>
9208     *
9209     * @return true if the horizontal scrollbar should be painted, false
9210     *         otherwise
9211     *
9212     * @see #setHorizontalScrollBarEnabled(boolean)
9213     */
9214    public boolean isHorizontalScrollBarEnabled() {
9215        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9216    }
9217
9218    /**
9219     * <p>Define whether the horizontal scrollbar should be drawn or not. The
9220     * scrollbar is not drawn by default.</p>
9221     *
9222     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
9223     *                                   be painted
9224     *
9225     * @see #isHorizontalScrollBarEnabled()
9226     */
9227    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
9228        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
9229            mViewFlags ^= SCROLLBARS_HORIZONTAL;
9230            computeOpaqueFlags();
9231            resolvePadding();
9232        }
9233    }
9234
9235    /**
9236     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
9237     * scrollbar is not drawn by default.</p>
9238     *
9239     * @return true if the vertical scrollbar should be painted, false
9240     *         otherwise
9241     *
9242     * @see #setVerticalScrollBarEnabled(boolean)
9243     */
9244    public boolean isVerticalScrollBarEnabled() {
9245        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
9246    }
9247
9248    /**
9249     * <p>Define whether the vertical scrollbar should be drawn or not. The
9250     * scrollbar is not drawn by default.</p>
9251     *
9252     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9253     *                                 be painted
9254     *
9255     * @see #isVerticalScrollBarEnabled()
9256     */
9257    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9258        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9259            mViewFlags ^= SCROLLBARS_VERTICAL;
9260            computeOpaqueFlags();
9261            resolvePadding();
9262        }
9263    }
9264
9265    /**
9266     * @hide
9267     */
9268    protected void recomputePadding() {
9269        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9270    }
9271
9272    /**
9273     * Define whether scrollbars will fade when the view is not scrolling.
9274     *
9275     * @param fadeScrollbars wheter to enable fading
9276     *
9277     */
9278    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9279        initScrollCache();
9280        final ScrollabilityCache scrollabilityCache = mScrollCache;
9281        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9282        if (fadeScrollbars) {
9283            scrollabilityCache.state = ScrollabilityCache.OFF;
9284        } else {
9285            scrollabilityCache.state = ScrollabilityCache.ON;
9286        }
9287    }
9288
9289    /**
9290     *
9291     * Returns true if scrollbars will fade when this view is not scrolling
9292     *
9293     * @return true if scrollbar fading is enabled
9294     */
9295    public boolean isScrollbarFadingEnabled() {
9296        return mScrollCache != null && mScrollCache.fadeScrollBars;
9297    }
9298
9299    /**
9300     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9301     * inset. When inset, they add to the padding of the view. And the scrollbars
9302     * can be drawn inside the padding area or on the edge of the view. For example,
9303     * if a view has a background drawable and you want to draw the scrollbars
9304     * inside the padding specified by the drawable, you can use
9305     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9306     * appear at the edge of the view, ignoring the padding, then you can use
9307     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9308     * @param style the style of the scrollbars. Should be one of
9309     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9310     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9311     * @see #SCROLLBARS_INSIDE_OVERLAY
9312     * @see #SCROLLBARS_INSIDE_INSET
9313     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9314     * @see #SCROLLBARS_OUTSIDE_INSET
9315     */
9316    public void setScrollBarStyle(int style) {
9317        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9318            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9319            computeOpaqueFlags();
9320            resolvePadding();
9321        }
9322    }
9323
9324    /**
9325     * <p>Returns the current scrollbar style.</p>
9326     * @return the current scrollbar style
9327     * @see #SCROLLBARS_INSIDE_OVERLAY
9328     * @see #SCROLLBARS_INSIDE_INSET
9329     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9330     * @see #SCROLLBARS_OUTSIDE_INSET
9331     */
9332    @ViewDebug.ExportedProperty(mapping = {
9333            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9334            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9335            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9336            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9337    })
9338    public int getScrollBarStyle() {
9339        return mViewFlags & SCROLLBARS_STYLE_MASK;
9340    }
9341
9342    /**
9343     * <p>Compute the horizontal range that the horizontal scrollbar
9344     * represents.</p>
9345     *
9346     * <p>The range is expressed in arbitrary units that must be the same as the
9347     * units used by {@link #computeHorizontalScrollExtent()} and
9348     * {@link #computeHorizontalScrollOffset()}.</p>
9349     *
9350     * <p>The default range is the drawing width of this view.</p>
9351     *
9352     * @return the total horizontal range represented by the horizontal
9353     *         scrollbar
9354     *
9355     * @see #computeHorizontalScrollExtent()
9356     * @see #computeHorizontalScrollOffset()
9357     * @see android.widget.ScrollBarDrawable
9358     */
9359    protected int computeHorizontalScrollRange() {
9360        return getWidth();
9361    }
9362
9363    /**
9364     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9365     * within the horizontal range. This value is used to compute the position
9366     * of the thumb within the scrollbar's track.</p>
9367     *
9368     * <p>The range is expressed in arbitrary units that must be the same as the
9369     * units used by {@link #computeHorizontalScrollRange()} and
9370     * {@link #computeHorizontalScrollExtent()}.</p>
9371     *
9372     * <p>The default offset is the scroll offset of this view.</p>
9373     *
9374     * @return the horizontal offset of the scrollbar's thumb
9375     *
9376     * @see #computeHorizontalScrollRange()
9377     * @see #computeHorizontalScrollExtent()
9378     * @see android.widget.ScrollBarDrawable
9379     */
9380    protected int computeHorizontalScrollOffset() {
9381        return mScrollX;
9382    }
9383
9384    /**
9385     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9386     * within the horizontal range. This value is used to compute the length
9387     * of the thumb within the scrollbar's track.</p>
9388     *
9389     * <p>The range is expressed in arbitrary units that must be the same as the
9390     * units used by {@link #computeHorizontalScrollRange()} and
9391     * {@link #computeHorizontalScrollOffset()}.</p>
9392     *
9393     * <p>The default extent is the drawing width of this view.</p>
9394     *
9395     * @return the horizontal extent of the scrollbar's thumb
9396     *
9397     * @see #computeHorizontalScrollRange()
9398     * @see #computeHorizontalScrollOffset()
9399     * @see android.widget.ScrollBarDrawable
9400     */
9401    protected int computeHorizontalScrollExtent() {
9402        return getWidth();
9403    }
9404
9405    /**
9406     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9407     *
9408     * <p>The range is expressed in arbitrary units that must be the same as the
9409     * units used by {@link #computeVerticalScrollExtent()} and
9410     * {@link #computeVerticalScrollOffset()}.</p>
9411     *
9412     * @return the total vertical range represented by the vertical scrollbar
9413     *
9414     * <p>The default range is the drawing height of this view.</p>
9415     *
9416     * @see #computeVerticalScrollExtent()
9417     * @see #computeVerticalScrollOffset()
9418     * @see android.widget.ScrollBarDrawable
9419     */
9420    protected int computeVerticalScrollRange() {
9421        return getHeight();
9422    }
9423
9424    /**
9425     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9426     * within the horizontal range. This value is used to compute the position
9427     * of the thumb within the scrollbar's track.</p>
9428     *
9429     * <p>The range is expressed in arbitrary units that must be the same as the
9430     * units used by {@link #computeVerticalScrollRange()} and
9431     * {@link #computeVerticalScrollExtent()}.</p>
9432     *
9433     * <p>The default offset is the scroll offset of this view.</p>
9434     *
9435     * @return the vertical offset of the scrollbar's thumb
9436     *
9437     * @see #computeVerticalScrollRange()
9438     * @see #computeVerticalScrollExtent()
9439     * @see android.widget.ScrollBarDrawable
9440     */
9441    protected int computeVerticalScrollOffset() {
9442        return mScrollY;
9443    }
9444
9445    /**
9446     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9447     * within the vertical range. This value is used to compute the length
9448     * of the thumb within the scrollbar's track.</p>
9449     *
9450     * <p>The range is expressed in arbitrary units that must be the same as the
9451     * units used by {@link #computeVerticalScrollRange()} and
9452     * {@link #computeVerticalScrollOffset()}.</p>
9453     *
9454     * <p>The default extent is the drawing height of this view.</p>
9455     *
9456     * @return the vertical extent of the scrollbar's thumb
9457     *
9458     * @see #computeVerticalScrollRange()
9459     * @see #computeVerticalScrollOffset()
9460     * @see android.widget.ScrollBarDrawable
9461     */
9462    protected int computeVerticalScrollExtent() {
9463        return getHeight();
9464    }
9465
9466    /**
9467     * Check if this view can be scrolled horizontally in a certain direction.
9468     *
9469     * @param direction Negative to check scrolling left, positive to check scrolling right.
9470     * @return true if this view can be scrolled in the specified direction, false otherwise.
9471     */
9472    public boolean canScrollHorizontally(int direction) {
9473        final int offset = computeHorizontalScrollOffset();
9474        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9475        if (range == 0) return false;
9476        if (direction < 0) {
9477            return offset > 0;
9478        } else {
9479            return offset < range - 1;
9480        }
9481    }
9482
9483    /**
9484     * Check if this view can be scrolled vertically in a certain direction.
9485     *
9486     * @param direction Negative to check scrolling up, positive to check scrolling down.
9487     * @return true if this view can be scrolled in the specified direction, false otherwise.
9488     */
9489    public boolean canScrollVertically(int direction) {
9490        final int offset = computeVerticalScrollOffset();
9491        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9492        if (range == 0) return false;
9493        if (direction < 0) {
9494            return offset > 0;
9495        } else {
9496            return offset < range - 1;
9497        }
9498    }
9499
9500    /**
9501     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9502     * scrollbars are painted only if they have been awakened first.</p>
9503     *
9504     * @param canvas the canvas on which to draw the scrollbars
9505     *
9506     * @see #awakenScrollBars(int)
9507     */
9508    protected final void onDrawScrollBars(Canvas canvas) {
9509        // scrollbars are drawn only when the animation is running
9510        final ScrollabilityCache cache = mScrollCache;
9511        if (cache != null) {
9512
9513            int state = cache.state;
9514
9515            if (state == ScrollabilityCache.OFF) {
9516                return;
9517            }
9518
9519            boolean invalidate = false;
9520
9521            if (state == ScrollabilityCache.FADING) {
9522                // We're fading -- get our fade interpolation
9523                if (cache.interpolatorValues == null) {
9524                    cache.interpolatorValues = new float[1];
9525                }
9526
9527                float[] values = cache.interpolatorValues;
9528
9529                // Stops the animation if we're done
9530                if (cache.scrollBarInterpolator.timeToValues(values) ==
9531                        Interpolator.Result.FREEZE_END) {
9532                    cache.state = ScrollabilityCache.OFF;
9533                } else {
9534                    cache.scrollBar.setAlpha(Math.round(values[0]));
9535                }
9536
9537                // This will make the scroll bars inval themselves after
9538                // drawing. We only want this when we're fading so that
9539                // we prevent excessive redraws
9540                invalidate = true;
9541            } else {
9542                // We're just on -- but we may have been fading before so
9543                // reset alpha
9544                cache.scrollBar.setAlpha(255);
9545            }
9546
9547
9548            final int viewFlags = mViewFlags;
9549
9550            final boolean drawHorizontalScrollBar =
9551                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9552            final boolean drawVerticalScrollBar =
9553                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9554                && !isVerticalScrollBarHidden();
9555
9556            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9557                final int width = mRight - mLeft;
9558                final int height = mBottom - mTop;
9559
9560                final ScrollBarDrawable scrollBar = cache.scrollBar;
9561
9562                final int scrollX = mScrollX;
9563                final int scrollY = mScrollY;
9564                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9565
9566                int left, top, right, bottom;
9567
9568                if (drawHorizontalScrollBar) {
9569                    int size = scrollBar.getSize(false);
9570                    if (size <= 0) {
9571                        size = cache.scrollBarSize;
9572                    }
9573
9574                    scrollBar.setParameters(computeHorizontalScrollRange(),
9575                                            computeHorizontalScrollOffset(),
9576                                            computeHorizontalScrollExtent(), false);
9577                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9578                            getVerticalScrollbarWidth() : 0;
9579                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9580                    left = scrollX + (mPaddingLeft & inside);
9581                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9582                    bottom = top + size;
9583                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9584                    if (invalidate) {
9585                        invalidate(left, top, right, bottom);
9586                    }
9587                }
9588
9589                if (drawVerticalScrollBar) {
9590                    int size = scrollBar.getSize(true);
9591                    if (size <= 0) {
9592                        size = cache.scrollBarSize;
9593                    }
9594
9595                    scrollBar.setParameters(computeVerticalScrollRange(),
9596                                            computeVerticalScrollOffset(),
9597                                            computeVerticalScrollExtent(), true);
9598                    switch (mVerticalScrollbarPosition) {
9599                        default:
9600                        case SCROLLBAR_POSITION_DEFAULT:
9601                        case SCROLLBAR_POSITION_RIGHT:
9602                            left = scrollX + width - size - (mUserPaddingRight & inside);
9603                            break;
9604                        case SCROLLBAR_POSITION_LEFT:
9605                            left = scrollX + (mUserPaddingLeft & inside);
9606                            break;
9607                    }
9608                    top = scrollY + (mPaddingTop & inside);
9609                    right = left + size;
9610                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9611                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9612                    if (invalidate) {
9613                        invalidate(left, top, right, bottom);
9614                    }
9615                }
9616            }
9617        }
9618    }
9619
9620    /**
9621     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9622     * FastScroller is visible.
9623     * @return whether to temporarily hide the vertical scrollbar
9624     * @hide
9625     */
9626    protected boolean isVerticalScrollBarHidden() {
9627        return false;
9628    }
9629
9630    /**
9631     * <p>Draw the horizontal scrollbar if
9632     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9633     *
9634     * @param canvas the canvas on which to draw the scrollbar
9635     * @param scrollBar the scrollbar's drawable
9636     *
9637     * @see #isHorizontalScrollBarEnabled()
9638     * @see #computeHorizontalScrollRange()
9639     * @see #computeHorizontalScrollExtent()
9640     * @see #computeHorizontalScrollOffset()
9641     * @see android.widget.ScrollBarDrawable
9642     * @hide
9643     */
9644    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9645            int l, int t, int r, int b) {
9646        scrollBar.setBounds(l, t, r, b);
9647        scrollBar.draw(canvas);
9648    }
9649
9650    /**
9651     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9652     * returns true.</p>
9653     *
9654     * @param canvas the canvas on which to draw the scrollbar
9655     * @param scrollBar the scrollbar's drawable
9656     *
9657     * @see #isVerticalScrollBarEnabled()
9658     * @see #computeVerticalScrollRange()
9659     * @see #computeVerticalScrollExtent()
9660     * @see #computeVerticalScrollOffset()
9661     * @see android.widget.ScrollBarDrawable
9662     * @hide
9663     */
9664    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9665            int l, int t, int r, int b) {
9666        scrollBar.setBounds(l, t, r, b);
9667        scrollBar.draw(canvas);
9668    }
9669
9670    /**
9671     * Implement this to do your drawing.
9672     *
9673     * @param canvas the canvas on which the background will be drawn
9674     */
9675    protected void onDraw(Canvas canvas) {
9676    }
9677
9678    /*
9679     * Caller is responsible for calling requestLayout if necessary.
9680     * (This allows addViewInLayout to not request a new layout.)
9681     */
9682    void assignParent(ViewParent parent) {
9683        if (mParent == null) {
9684            mParent = parent;
9685        } else if (parent == null) {
9686            mParent = null;
9687        } else {
9688            throw new RuntimeException("view " + this + " being added, but"
9689                    + " it already has a parent");
9690        }
9691    }
9692
9693    /**
9694     * This is called when the view is attached to a window.  At this point it
9695     * has a Surface and will start drawing.  Note that this function is
9696     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9697     * however it may be called any time before the first onDraw -- including
9698     * before or after {@link #onMeasure(int, int)}.
9699     *
9700     * @see #onDetachedFromWindow()
9701     */
9702    protected void onAttachedToWindow() {
9703        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9704            mParent.requestTransparentRegion(this);
9705        }
9706        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9707            initialAwakenScrollBars();
9708            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9709        }
9710        jumpDrawablesToCurrentState();
9711        // Order is important here: LayoutDirection MUST be resolved before Padding
9712        // and TextDirection
9713        resolveLayoutDirectionIfNeeded();
9714        resolvePadding();
9715        resolveTextDirection();
9716        if (isFocused()) {
9717            InputMethodManager imm = InputMethodManager.peekInstance();
9718            imm.focusIn(this);
9719        }
9720    }
9721
9722    /**
9723     * @see #onScreenStateChanged(int)
9724     */
9725    void dispatchScreenStateChanged(int screenState) {
9726        onScreenStateChanged(screenState);
9727    }
9728
9729    /**
9730     * This method is called whenever the state of the screen this view is
9731     * attached to changes. A state change will usually occurs when the screen
9732     * turns on or off (whether it happens automatically or the user does it
9733     * manually.)
9734     *
9735     * @param screenState The new state of the screen. Can be either
9736     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
9737     */
9738    public void onScreenStateChanged(int screenState) {
9739    }
9740
9741    /**
9742     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9743     * that the parent directionality can and will be resolved before its children.
9744     */
9745    private void resolveLayoutDirectionIfNeeded() {
9746        // Do not resolve if it is not needed
9747        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9748
9749        // Clear any previous layout direction resolution
9750        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
9751
9752        // Set resolved depending on layout direction
9753        switch (getLayoutDirection()) {
9754            case LAYOUT_DIRECTION_INHERIT:
9755                // We cannot do the resolution if there is no parent
9756                if (mParent == null) return;
9757
9758                // If this is root view, no need to look at parent's layout dir.
9759                if (mParent instanceof ViewGroup) {
9760                    ViewGroup viewGroup = ((ViewGroup) mParent);
9761
9762                    // Check if the parent view group can resolve
9763                    if (! viewGroup.canResolveLayoutDirection()) {
9764                        return;
9765                    }
9766                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9767                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9768                    }
9769                }
9770                break;
9771            case LAYOUT_DIRECTION_RTL:
9772                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9773                break;
9774            case LAYOUT_DIRECTION_LOCALE:
9775                if(isLayoutDirectionRtl(Locale.getDefault())) {
9776                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9777                }
9778                break;
9779            default:
9780                // Nothing to do, LTR by default
9781        }
9782
9783        // Set to resolved
9784        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9785        onResolvedLayoutDirectionChanged();
9786        // Resolve padding
9787        resolvePadding();
9788    }
9789
9790    /**
9791     * Called when layout direction has been resolved.
9792     *
9793     * The default implementation does nothing.
9794     */
9795    public void onResolvedLayoutDirectionChanged() {
9796    }
9797
9798    /**
9799     * Resolve padding depending on layout direction.
9800     */
9801    public void resolvePadding() {
9802        // If the user specified the absolute padding (either with android:padding or
9803        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9804        // use the default padding or the padding from the background drawable
9805        // (stored at this point in mPadding*)
9806        int resolvedLayoutDirection = getResolvedLayoutDirection();
9807        switch (resolvedLayoutDirection) {
9808            case LAYOUT_DIRECTION_RTL:
9809                // Start user padding override Right user padding. Otherwise, if Right user
9810                // padding is not defined, use the default Right padding. If Right user padding
9811                // is defined, just use it.
9812                if (mUserPaddingStart >= 0) {
9813                    mUserPaddingRight = mUserPaddingStart;
9814                } else if (mUserPaddingRight < 0) {
9815                    mUserPaddingRight = mPaddingRight;
9816                }
9817                if (mUserPaddingEnd >= 0) {
9818                    mUserPaddingLeft = mUserPaddingEnd;
9819                } else if (mUserPaddingLeft < 0) {
9820                    mUserPaddingLeft = mPaddingLeft;
9821                }
9822                break;
9823            case LAYOUT_DIRECTION_LTR:
9824            default:
9825                // Start user padding override Left user padding. Otherwise, if Left user
9826                // padding is not defined, use the default left padding. If Left user padding
9827                // is defined, just use it.
9828                if (mUserPaddingStart >= 0) {
9829                    mUserPaddingLeft = mUserPaddingStart;
9830                } else if (mUserPaddingLeft < 0) {
9831                    mUserPaddingLeft = mPaddingLeft;
9832                }
9833                if (mUserPaddingEnd >= 0) {
9834                    mUserPaddingRight = mUserPaddingEnd;
9835                } else if (mUserPaddingRight < 0) {
9836                    mUserPaddingRight = mPaddingRight;
9837                }
9838        }
9839
9840        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9841
9842        if(isPaddingRelative()) {
9843            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
9844        } else {
9845            recomputePadding();
9846        }
9847        onPaddingChanged(resolvedLayoutDirection);
9848    }
9849
9850    /**
9851     * Resolve padding depending on the layout direction. Subclasses that care about
9852     * padding resolution should override this method. The default implementation does
9853     * nothing.
9854     *
9855     * @param layoutDirection the direction of the layout
9856     *
9857     * @see {@link #LAYOUT_DIRECTION_LTR}
9858     * @see {@link #LAYOUT_DIRECTION_RTL}
9859     */
9860    public void onPaddingChanged(int layoutDirection) {
9861    }
9862
9863    /**
9864     * Check if layout direction resolution can be done.
9865     *
9866     * @return true if layout direction resolution can be done otherwise return false.
9867     */
9868    public boolean canResolveLayoutDirection() {
9869        switch (getLayoutDirection()) {
9870            case LAYOUT_DIRECTION_INHERIT:
9871                return (mParent != null);
9872            default:
9873                return true;
9874        }
9875    }
9876
9877    /**
9878     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
9879     * when reset is done.
9880     */
9881    public void resetResolvedLayoutDirection() {
9882        // Reset the current resolved bits
9883        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
9884        onResolvedLayoutDirectionReset();
9885        // Reset also the text direction
9886        resetResolvedTextDirection();
9887    }
9888
9889    /**
9890     * Called during reset of resolved layout direction.
9891     *
9892     * Subclasses need to override this method to clear cached information that depends on the
9893     * resolved layout direction, or to inform child views that inherit their layout direction.
9894     *
9895     * The default implementation does nothing.
9896     */
9897    public void onResolvedLayoutDirectionReset() {
9898    }
9899
9900    /**
9901     * Check if a Locale uses an RTL script.
9902     *
9903     * @param locale Locale to check
9904     * @return true if the Locale uses an RTL script.
9905     */
9906    protected static boolean isLayoutDirectionRtl(Locale locale) {
9907        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
9908    }
9909
9910    /**
9911     * This is called when the view is detached from a window.  At this point it
9912     * no longer has a surface for drawing.
9913     *
9914     * @see #onAttachedToWindow()
9915     */
9916    protected void onDetachedFromWindow() {
9917        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9918
9919        removeUnsetPressCallback();
9920        removeLongPressCallback();
9921        removePerformClickCallback();
9922        removeSendViewScrolledAccessibilityEventCallback();
9923
9924        destroyDrawingCache();
9925
9926        destroyLayer();
9927
9928        if (mDisplayList != null) {
9929            mDisplayList.invalidate();
9930        }
9931
9932        if (mAttachInfo != null) {
9933            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
9934        }
9935
9936        mCurrentAnimation = null;
9937
9938        resetResolvedLayoutDirection();
9939    }
9940
9941    /**
9942     * @return The number of times this view has been attached to a window
9943     */
9944    protected int getWindowAttachCount() {
9945        return mWindowAttachCount;
9946    }
9947
9948    /**
9949     * Retrieve a unique token identifying the window this view is attached to.
9950     * @return Return the window's token for use in
9951     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9952     */
9953    public IBinder getWindowToken() {
9954        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9955    }
9956
9957    /**
9958     * Retrieve a unique token identifying the top-level "real" window of
9959     * the window that this view is attached to.  That is, this is like
9960     * {@link #getWindowToken}, except if the window this view in is a panel
9961     * window (attached to another containing window), then the token of
9962     * the containing window is returned instead.
9963     *
9964     * @return Returns the associated window token, either
9965     * {@link #getWindowToken()} or the containing window's token.
9966     */
9967    public IBinder getApplicationWindowToken() {
9968        AttachInfo ai = mAttachInfo;
9969        if (ai != null) {
9970            IBinder appWindowToken = ai.mPanelParentWindowToken;
9971            if (appWindowToken == null) {
9972                appWindowToken = ai.mWindowToken;
9973            }
9974            return appWindowToken;
9975        }
9976        return null;
9977    }
9978
9979    /**
9980     * Retrieve private session object this view hierarchy is using to
9981     * communicate with the window manager.
9982     * @return the session object to communicate with the window manager
9983     */
9984    /*package*/ IWindowSession getWindowSession() {
9985        return mAttachInfo != null ? mAttachInfo.mSession : null;
9986    }
9987
9988    /**
9989     * @param info the {@link android.view.View.AttachInfo} to associated with
9990     *        this view
9991     */
9992    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9993        //System.out.println("Attached! " + this);
9994        mAttachInfo = info;
9995        mWindowAttachCount++;
9996        // We will need to evaluate the drawable state at least once.
9997        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9998        if (mFloatingTreeObserver != null) {
9999            info.mTreeObserver.merge(mFloatingTreeObserver);
10000            mFloatingTreeObserver = null;
10001        }
10002        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
10003            mAttachInfo.mScrollContainers.add(this);
10004            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
10005        }
10006        performCollectViewAttributes(visibility);
10007        onAttachedToWindow();
10008
10009        ListenerInfo li = mListenerInfo;
10010        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10011                li != null ? li.mOnAttachStateChangeListeners : null;
10012        if (listeners != null && listeners.size() > 0) {
10013            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10014            // perform the dispatching. The iterator is a safe guard against listeners that
10015            // could mutate the list by calling the various add/remove methods. This prevents
10016            // the array from being modified while we iterate it.
10017            for (OnAttachStateChangeListener listener : listeners) {
10018                listener.onViewAttachedToWindow(this);
10019            }
10020        }
10021
10022        int vis = info.mWindowVisibility;
10023        if (vis != GONE) {
10024            onWindowVisibilityChanged(vis);
10025        }
10026        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
10027            // If nobody has evaluated the drawable state yet, then do it now.
10028            refreshDrawableState();
10029        }
10030    }
10031
10032    void dispatchDetachedFromWindow() {
10033        AttachInfo info = mAttachInfo;
10034        if (info != null) {
10035            int vis = info.mWindowVisibility;
10036            if (vis != GONE) {
10037                onWindowVisibilityChanged(GONE);
10038            }
10039        }
10040
10041        onDetachedFromWindow();
10042
10043        ListenerInfo li = mListenerInfo;
10044        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10045                li != null ? li.mOnAttachStateChangeListeners : null;
10046        if (listeners != null && listeners.size() > 0) {
10047            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10048            // perform the dispatching. The iterator is a safe guard against listeners that
10049            // could mutate the list by calling the various add/remove methods. This prevents
10050            // the array from being modified while we iterate it.
10051            for (OnAttachStateChangeListener listener : listeners) {
10052                listener.onViewDetachedFromWindow(this);
10053            }
10054        }
10055
10056        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
10057            mAttachInfo.mScrollContainers.remove(this);
10058            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
10059        }
10060
10061        mAttachInfo = null;
10062    }
10063
10064    /**
10065     * Store this view hierarchy's frozen state into the given container.
10066     *
10067     * @param container The SparseArray in which to save the view's state.
10068     *
10069     * @see #restoreHierarchyState(android.util.SparseArray)
10070     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10071     * @see #onSaveInstanceState()
10072     */
10073    public void saveHierarchyState(SparseArray<Parcelable> container) {
10074        dispatchSaveInstanceState(container);
10075    }
10076
10077    /**
10078     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
10079     * this view and its children. May be overridden to modify how freezing happens to a
10080     * view's children; for example, some views may want to not store state for their children.
10081     *
10082     * @param container The SparseArray in which to save the view's state.
10083     *
10084     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10085     * @see #saveHierarchyState(android.util.SparseArray)
10086     * @see #onSaveInstanceState()
10087     */
10088    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
10089        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
10090            mPrivateFlags &= ~SAVE_STATE_CALLED;
10091            Parcelable state = onSaveInstanceState();
10092            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10093                throw new IllegalStateException(
10094                        "Derived class did not call super.onSaveInstanceState()");
10095            }
10096            if (state != null) {
10097                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
10098                // + ": " + state);
10099                container.put(mID, state);
10100            }
10101        }
10102    }
10103
10104    /**
10105     * Hook allowing a view to generate a representation of its internal state
10106     * that can later be used to create a new instance with that same state.
10107     * This state should only contain information that is not persistent or can
10108     * not be reconstructed later. For example, you will never store your
10109     * current position on screen because that will be computed again when a
10110     * new instance of the view is placed in its view hierarchy.
10111     * <p>
10112     * Some examples of things you may store here: the current cursor position
10113     * in a text view (but usually not the text itself since that is stored in a
10114     * content provider or other persistent storage), the currently selected
10115     * item in a list view.
10116     *
10117     * @return Returns a Parcelable object containing the view's current dynamic
10118     *         state, or null if there is nothing interesting to save. The
10119     *         default implementation returns null.
10120     * @see #onRestoreInstanceState(android.os.Parcelable)
10121     * @see #saveHierarchyState(android.util.SparseArray)
10122     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10123     * @see #setSaveEnabled(boolean)
10124     */
10125    protected Parcelable onSaveInstanceState() {
10126        mPrivateFlags |= SAVE_STATE_CALLED;
10127        return BaseSavedState.EMPTY_STATE;
10128    }
10129
10130    /**
10131     * Restore this view hierarchy's frozen state from the given container.
10132     *
10133     * @param container The SparseArray which holds previously frozen states.
10134     *
10135     * @see #saveHierarchyState(android.util.SparseArray)
10136     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10137     * @see #onRestoreInstanceState(android.os.Parcelable)
10138     */
10139    public void restoreHierarchyState(SparseArray<Parcelable> container) {
10140        dispatchRestoreInstanceState(container);
10141    }
10142
10143    /**
10144     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
10145     * state for this view and its children. May be overridden to modify how restoring
10146     * happens to a view's children; for example, some views may want to not store state
10147     * for their children.
10148     *
10149     * @param container The SparseArray which holds previously saved state.
10150     *
10151     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10152     * @see #restoreHierarchyState(android.util.SparseArray)
10153     * @see #onRestoreInstanceState(android.os.Parcelable)
10154     */
10155    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
10156        if (mID != NO_ID) {
10157            Parcelable state = container.get(mID);
10158            if (state != null) {
10159                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
10160                // + ": " + state);
10161                mPrivateFlags &= ~SAVE_STATE_CALLED;
10162                onRestoreInstanceState(state);
10163                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10164                    throw new IllegalStateException(
10165                            "Derived class did not call super.onRestoreInstanceState()");
10166                }
10167            }
10168        }
10169    }
10170
10171    /**
10172     * Hook allowing a view to re-apply a representation of its internal state that had previously
10173     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
10174     * null state.
10175     *
10176     * @param state The frozen state that had previously been returned by
10177     *        {@link #onSaveInstanceState}.
10178     *
10179     * @see #onSaveInstanceState()
10180     * @see #restoreHierarchyState(android.util.SparseArray)
10181     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10182     */
10183    protected void onRestoreInstanceState(Parcelable state) {
10184        mPrivateFlags |= SAVE_STATE_CALLED;
10185        if (state != BaseSavedState.EMPTY_STATE && state != null) {
10186            throw new IllegalArgumentException("Wrong state class, expecting View State but "
10187                    + "received " + state.getClass().toString() + " instead. This usually happens "
10188                    + "when two views of different type have the same id in the same hierarchy. "
10189                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
10190                    + "other views do not use the same id.");
10191        }
10192    }
10193
10194    /**
10195     * <p>Return the time at which the drawing of the view hierarchy started.</p>
10196     *
10197     * @return the drawing start time in milliseconds
10198     */
10199    public long getDrawingTime() {
10200        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
10201    }
10202
10203    /**
10204     * <p>Enables or disables the duplication of the parent's state into this view. When
10205     * duplication is enabled, this view gets its drawable state from its parent rather
10206     * than from its own internal properties.</p>
10207     *
10208     * <p>Note: in the current implementation, setting this property to true after the
10209     * view was added to a ViewGroup might have no effect at all. This property should
10210     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
10211     *
10212     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
10213     * property is enabled, an exception will be thrown.</p>
10214     *
10215     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
10216     * parent, these states should not be affected by this method.</p>
10217     *
10218     * @param enabled True to enable duplication of the parent's drawable state, false
10219     *                to disable it.
10220     *
10221     * @see #getDrawableState()
10222     * @see #isDuplicateParentStateEnabled()
10223     */
10224    public void setDuplicateParentStateEnabled(boolean enabled) {
10225        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
10226    }
10227
10228    /**
10229     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
10230     *
10231     * @return True if this view's drawable state is duplicated from the parent,
10232     *         false otherwise
10233     *
10234     * @see #getDrawableState()
10235     * @see #setDuplicateParentStateEnabled(boolean)
10236     */
10237    public boolean isDuplicateParentStateEnabled() {
10238        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
10239    }
10240
10241    /**
10242     * <p>Specifies the type of layer backing this view. The layer can be
10243     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
10244     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
10245     *
10246     * <p>A layer is associated with an optional {@link android.graphics.Paint}
10247     * instance that controls how the layer is composed on screen. The following
10248     * properties of the paint are taken into account when composing the layer:</p>
10249     * <ul>
10250     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
10251     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
10252     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
10253     * </ul>
10254     *
10255     * <p>If this view has an alpha value set to < 1.0 by calling
10256     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
10257     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
10258     * equivalent to setting a hardware layer on this view and providing a paint with
10259     * the desired alpha value.<p>
10260     *
10261     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
10262     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
10263     * for more information on when and how to use layers.</p>
10264     *
10265     * @param layerType The ype of layer to use with this view, must be one of
10266     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10267     *        {@link #LAYER_TYPE_HARDWARE}
10268     * @param paint The paint used to compose the layer. This argument is optional
10269     *        and can be null. It is ignored when the layer type is
10270     *        {@link #LAYER_TYPE_NONE}
10271     *
10272     * @see #getLayerType()
10273     * @see #LAYER_TYPE_NONE
10274     * @see #LAYER_TYPE_SOFTWARE
10275     * @see #LAYER_TYPE_HARDWARE
10276     * @see #setAlpha(float)
10277     *
10278     * @attr ref android.R.styleable#View_layerType
10279     */
10280    public void setLayerType(int layerType, Paint paint) {
10281        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
10282            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
10283                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
10284        }
10285
10286        if (layerType == mLayerType) {
10287            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
10288                mLayerPaint = paint == null ? new Paint() : paint;
10289                invalidateParentCaches();
10290                invalidate(true);
10291            }
10292            return;
10293        }
10294
10295        // Destroy any previous software drawing cache if needed
10296        switch (mLayerType) {
10297            case LAYER_TYPE_HARDWARE:
10298                destroyLayer();
10299                // fall through - non-accelerated views may use software layer mechanism instead
10300            case LAYER_TYPE_SOFTWARE:
10301                destroyDrawingCache();
10302                break;
10303            default:
10304                break;
10305        }
10306
10307        mLayerType = layerType;
10308        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10309        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10310        mLocalDirtyRect = layerDisabled ? null : new Rect();
10311
10312        invalidateParentCaches();
10313        invalidate(true);
10314    }
10315
10316    /**
10317     * Indicates whether this view has a static layer. A view with layer type
10318     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10319     * dynamic.
10320     */
10321    boolean hasStaticLayer() {
10322        return true;
10323    }
10324
10325    /**
10326     * Indicates what type of layer is currently associated with this view. By default
10327     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10328     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10329     * for more information on the different types of layers.
10330     *
10331     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10332     *         {@link #LAYER_TYPE_HARDWARE}
10333     *
10334     * @see #setLayerType(int, android.graphics.Paint)
10335     * @see #buildLayer()
10336     * @see #LAYER_TYPE_NONE
10337     * @see #LAYER_TYPE_SOFTWARE
10338     * @see #LAYER_TYPE_HARDWARE
10339     */
10340    public int getLayerType() {
10341        return mLayerType;
10342    }
10343
10344    /**
10345     * Forces this view's layer to be created and this view to be rendered
10346     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10347     * invoking this method will have no effect.
10348     *
10349     * This method can for instance be used to render a view into its layer before
10350     * starting an animation. If this view is complex, rendering into the layer
10351     * before starting the animation will avoid skipping frames.
10352     *
10353     * @throws IllegalStateException If this view is not attached to a window
10354     *
10355     * @see #setLayerType(int, android.graphics.Paint)
10356     */
10357    public void buildLayer() {
10358        if (mLayerType == LAYER_TYPE_NONE) return;
10359
10360        if (mAttachInfo == null) {
10361            throw new IllegalStateException("This view must be attached to a window first");
10362        }
10363
10364        switch (mLayerType) {
10365            case LAYER_TYPE_HARDWARE:
10366                if (mAttachInfo.mHardwareRenderer != null &&
10367                        mAttachInfo.mHardwareRenderer.isEnabled() &&
10368                        mAttachInfo.mHardwareRenderer.validate()) {
10369                    getHardwareLayer();
10370                }
10371                break;
10372            case LAYER_TYPE_SOFTWARE:
10373                buildDrawingCache(true);
10374                break;
10375        }
10376    }
10377
10378    // Make sure the HardwareRenderer.validate() was invoked before calling this method
10379    void flushLayer() {
10380        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
10381            mHardwareLayer.flush();
10382        }
10383    }
10384
10385    /**
10386     * <p>Returns a hardware layer that can be used to draw this view again
10387     * without executing its draw method.</p>
10388     *
10389     * @return A HardwareLayer ready to render, or null if an error occurred.
10390     */
10391    HardwareLayer getHardwareLayer() {
10392        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10393                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10394            return null;
10395        }
10396
10397        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
10398
10399        final int width = mRight - mLeft;
10400        final int height = mBottom - mTop;
10401
10402        if (width == 0 || height == 0) {
10403            return null;
10404        }
10405
10406        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10407            if (mHardwareLayer == null) {
10408                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10409                        width, height, isOpaque());
10410                mLocalDirtyRect.setEmpty();
10411            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10412                mHardwareLayer.resize(width, height);
10413                mLocalDirtyRect.setEmpty();
10414            }
10415
10416            // The layer is not valid if the underlying GPU resources cannot be allocated
10417            if (!mHardwareLayer.isValid()) {
10418                return null;
10419            }
10420
10421            mHardwareLayer.redraw(getDisplayList(), mLocalDirtyRect);
10422            mLocalDirtyRect.setEmpty();
10423        }
10424
10425        return mHardwareLayer;
10426    }
10427
10428    /**
10429     * Destroys this View's hardware layer if possible.
10430     *
10431     * @return True if the layer was destroyed, false otherwise.
10432     *
10433     * @see #setLayerType(int, android.graphics.Paint)
10434     * @see #LAYER_TYPE_HARDWARE
10435     */
10436    boolean destroyLayer() {
10437        if (mHardwareLayer != null) {
10438            AttachInfo info = mAttachInfo;
10439            if (info != null && info.mHardwareRenderer != null &&
10440                    info.mHardwareRenderer.isEnabled() && info.mHardwareRenderer.validate()) {
10441                mHardwareLayer.destroy();
10442                mHardwareLayer = null;
10443
10444                invalidate(true);
10445                invalidateParentCaches();
10446            }
10447            return true;
10448        }
10449        return false;
10450    }
10451
10452    /**
10453     * Destroys all hardware rendering resources. This method is invoked
10454     * when the system needs to reclaim resources. Upon execution of this
10455     * method, you should free any OpenGL resources created by the view.
10456     *
10457     * Note: you <strong>must</strong> call
10458     * <code>super.destroyHardwareResources()</code> when overriding
10459     * this method.
10460     *
10461     * @hide
10462     */
10463    protected void destroyHardwareResources() {
10464        destroyLayer();
10465    }
10466
10467    /**
10468     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10469     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10470     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10471     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10472     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10473     * null.</p>
10474     *
10475     * <p>Enabling the drawing cache is similar to
10476     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10477     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10478     * drawing cache has no effect on rendering because the system uses a different mechanism
10479     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10480     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10481     * for information on how to enable software and hardware layers.</p>
10482     *
10483     * <p>This API can be used to manually generate
10484     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10485     * {@link #getDrawingCache()}.</p>
10486     *
10487     * @param enabled true to enable the drawing cache, false otherwise
10488     *
10489     * @see #isDrawingCacheEnabled()
10490     * @see #getDrawingCache()
10491     * @see #buildDrawingCache()
10492     * @see #setLayerType(int, android.graphics.Paint)
10493     */
10494    public void setDrawingCacheEnabled(boolean enabled) {
10495        mCachingFailed = false;
10496        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10497    }
10498
10499    /**
10500     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10501     *
10502     * @return true if the drawing cache is enabled
10503     *
10504     * @see #setDrawingCacheEnabled(boolean)
10505     * @see #getDrawingCache()
10506     */
10507    @ViewDebug.ExportedProperty(category = "drawing")
10508    public boolean isDrawingCacheEnabled() {
10509        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10510    }
10511
10512    /**
10513     * Debugging utility which recursively outputs the dirty state of a view and its
10514     * descendants.
10515     *
10516     * @hide
10517     */
10518    @SuppressWarnings({"UnusedDeclaration"})
10519    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10520        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10521                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10522                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10523                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10524        if (clear) {
10525            mPrivateFlags &= clearMask;
10526        }
10527        if (this instanceof ViewGroup) {
10528            ViewGroup parent = (ViewGroup) this;
10529            final int count = parent.getChildCount();
10530            for (int i = 0; i < count; i++) {
10531                final View child = parent.getChildAt(i);
10532                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10533            }
10534        }
10535    }
10536
10537    /**
10538     * This method is used by ViewGroup to cause its children to restore or recreate their
10539     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10540     * to recreate its own display list, which would happen if it went through the normal
10541     * draw/dispatchDraw mechanisms.
10542     *
10543     * @hide
10544     */
10545    protected void dispatchGetDisplayList() {}
10546
10547    /**
10548     * A view that is not attached or hardware accelerated cannot create a display list.
10549     * This method checks these conditions and returns the appropriate result.
10550     *
10551     * @return true if view has the ability to create a display list, false otherwise.
10552     *
10553     * @hide
10554     */
10555    public boolean canHaveDisplayList() {
10556        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10557    }
10558
10559    /**
10560     * @return The HardwareRenderer associated with that view or null if hardware rendering
10561     * is not supported or this this has not been attached to a window.
10562     *
10563     * @hide
10564     */
10565    public HardwareRenderer getHardwareRenderer() {
10566        if (mAttachInfo != null) {
10567            return mAttachInfo.mHardwareRenderer;
10568        }
10569        return null;
10570    }
10571
10572    /**
10573     * <p>Returns a display list that can be used to draw this view again
10574     * without executing its draw method.</p>
10575     *
10576     * @return A DisplayList ready to replay, or null if caching is not enabled.
10577     *
10578     * @hide
10579     */
10580    public DisplayList getDisplayList() {
10581        if (!canHaveDisplayList()) {
10582            return null;
10583        }
10584
10585        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10586                mDisplayList == null || !mDisplayList.isValid() ||
10587                mRecreateDisplayList)) {
10588            // Don't need to recreate the display list, just need to tell our
10589            // children to restore/recreate theirs
10590            if (mDisplayList != null && mDisplayList.isValid() &&
10591                    !mRecreateDisplayList) {
10592                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10593                mPrivateFlags &= ~DIRTY_MASK;
10594                dispatchGetDisplayList();
10595
10596                return mDisplayList;
10597            }
10598
10599            // If we got here, we're recreating it. Mark it as such to ensure that
10600            // we copy in child display lists into ours in drawChild()
10601            mRecreateDisplayList = true;
10602            if (mDisplayList == null) {
10603                final String name = getClass().getSimpleName();
10604                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
10605                // If we're creating a new display list, make sure our parent gets invalidated
10606                // since they will need to recreate their display list to account for this
10607                // new child display list.
10608                invalidateParentCaches();
10609            }
10610
10611            final HardwareCanvas canvas = mDisplayList.start();
10612            int restoreCount = 0;
10613            try {
10614                int width = mRight - mLeft;
10615                int height = mBottom - mTop;
10616
10617                canvas.setViewport(width, height);
10618                // The dirty rect should always be null for a display list
10619                canvas.onPreDraw(null);
10620
10621                computeScroll();
10622
10623                restoreCount = canvas.save();
10624                canvas.translate(-mScrollX, -mScrollY);
10625                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10626                mPrivateFlags &= ~DIRTY_MASK;
10627
10628                // Fast path for layouts with no backgrounds
10629                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10630                    dispatchDraw(canvas);
10631                } else {
10632                    draw(canvas);
10633                }
10634            } finally {
10635                canvas.restoreToCount(restoreCount);
10636                canvas.onPostDraw();
10637
10638                mDisplayList.end();
10639            }
10640        } else {
10641            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10642            mPrivateFlags &= ~DIRTY_MASK;
10643        }
10644
10645        return mDisplayList;
10646    }
10647
10648    /**
10649     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10650     *
10651     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10652     *
10653     * @see #getDrawingCache(boolean)
10654     */
10655    public Bitmap getDrawingCache() {
10656        return getDrawingCache(false);
10657    }
10658
10659    /**
10660     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10661     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10662     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10663     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10664     * request the drawing cache by calling this method and draw it on screen if the
10665     * returned bitmap is not null.</p>
10666     *
10667     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10668     * this method will create a bitmap of the same size as this view. Because this bitmap
10669     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10670     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10671     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10672     * size than the view. This implies that your application must be able to handle this
10673     * size.</p>
10674     *
10675     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10676     *        the current density of the screen when the application is in compatibility
10677     *        mode.
10678     *
10679     * @return A bitmap representing this view or null if cache is disabled.
10680     *
10681     * @see #setDrawingCacheEnabled(boolean)
10682     * @see #isDrawingCacheEnabled()
10683     * @see #buildDrawingCache(boolean)
10684     * @see #destroyDrawingCache()
10685     */
10686    public Bitmap getDrawingCache(boolean autoScale) {
10687        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10688            return null;
10689        }
10690        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10691            buildDrawingCache(autoScale);
10692        }
10693        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10694    }
10695
10696    /**
10697     * <p>Frees the resources used by the drawing cache. If you call
10698     * {@link #buildDrawingCache()} manually without calling
10699     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10700     * should cleanup the cache with this method afterwards.</p>
10701     *
10702     * @see #setDrawingCacheEnabled(boolean)
10703     * @see #buildDrawingCache()
10704     * @see #getDrawingCache()
10705     */
10706    public void destroyDrawingCache() {
10707        if (mDrawingCache != null) {
10708            mDrawingCache.recycle();
10709            mDrawingCache = null;
10710        }
10711        if (mUnscaledDrawingCache != null) {
10712            mUnscaledDrawingCache.recycle();
10713            mUnscaledDrawingCache = null;
10714        }
10715    }
10716
10717    /**
10718     * Setting a solid background color for the drawing cache's bitmaps will improve
10719     * performance and memory usage. Note, though that this should only be used if this
10720     * view will always be drawn on top of a solid color.
10721     *
10722     * @param color The background color to use for the drawing cache's bitmap
10723     *
10724     * @see #setDrawingCacheEnabled(boolean)
10725     * @see #buildDrawingCache()
10726     * @see #getDrawingCache()
10727     */
10728    public void setDrawingCacheBackgroundColor(int color) {
10729        if (color != mDrawingCacheBackgroundColor) {
10730            mDrawingCacheBackgroundColor = color;
10731            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10732        }
10733    }
10734
10735    /**
10736     * @see #setDrawingCacheBackgroundColor(int)
10737     *
10738     * @return The background color to used for the drawing cache's bitmap
10739     */
10740    public int getDrawingCacheBackgroundColor() {
10741        return mDrawingCacheBackgroundColor;
10742    }
10743
10744    /**
10745     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10746     *
10747     * @see #buildDrawingCache(boolean)
10748     */
10749    public void buildDrawingCache() {
10750        buildDrawingCache(false);
10751    }
10752
10753    /**
10754     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10755     *
10756     * <p>If you call {@link #buildDrawingCache()} manually without calling
10757     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10758     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10759     *
10760     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10761     * this method will create a bitmap of the same size as this view. Because this bitmap
10762     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10763     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10764     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10765     * size than the view. This implies that your application must be able to handle this
10766     * size.</p>
10767     *
10768     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10769     * you do not need the drawing cache bitmap, calling this method will increase memory
10770     * usage and cause the view to be rendered in software once, thus negatively impacting
10771     * performance.</p>
10772     *
10773     * @see #getDrawingCache()
10774     * @see #destroyDrawingCache()
10775     */
10776    public void buildDrawingCache(boolean autoScale) {
10777        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10778                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10779            mCachingFailed = false;
10780
10781            if (ViewDebug.TRACE_HIERARCHY) {
10782                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10783            }
10784
10785            int width = mRight - mLeft;
10786            int height = mBottom - mTop;
10787
10788            final AttachInfo attachInfo = mAttachInfo;
10789            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10790
10791            if (autoScale && scalingRequired) {
10792                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10793                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10794            }
10795
10796            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10797            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10798            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10799
10800            if (width <= 0 || height <= 0 ||
10801                     // Projected bitmap size in bytes
10802                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10803                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10804                destroyDrawingCache();
10805                mCachingFailed = true;
10806                return;
10807            }
10808
10809            boolean clear = true;
10810            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10811
10812            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10813                Bitmap.Config quality;
10814                if (!opaque) {
10815                    // Never pick ARGB_4444 because it looks awful
10816                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10817                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10818                        case DRAWING_CACHE_QUALITY_AUTO:
10819                            quality = Bitmap.Config.ARGB_8888;
10820                            break;
10821                        case DRAWING_CACHE_QUALITY_LOW:
10822                            quality = Bitmap.Config.ARGB_8888;
10823                            break;
10824                        case DRAWING_CACHE_QUALITY_HIGH:
10825                            quality = Bitmap.Config.ARGB_8888;
10826                            break;
10827                        default:
10828                            quality = Bitmap.Config.ARGB_8888;
10829                            break;
10830                    }
10831                } else {
10832                    // Optimization for translucent windows
10833                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10834                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10835                }
10836
10837                // Try to cleanup memory
10838                if (bitmap != null) bitmap.recycle();
10839
10840                try {
10841                    bitmap = Bitmap.createBitmap(width, height, quality);
10842                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10843                    if (autoScale) {
10844                        mDrawingCache = bitmap;
10845                    } else {
10846                        mUnscaledDrawingCache = bitmap;
10847                    }
10848                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10849                } catch (OutOfMemoryError e) {
10850                    // If there is not enough memory to create the bitmap cache, just
10851                    // ignore the issue as bitmap caches are not required to draw the
10852                    // view hierarchy
10853                    if (autoScale) {
10854                        mDrawingCache = null;
10855                    } else {
10856                        mUnscaledDrawingCache = null;
10857                    }
10858                    mCachingFailed = true;
10859                    return;
10860                }
10861
10862                clear = drawingCacheBackgroundColor != 0;
10863            }
10864
10865            Canvas canvas;
10866            if (attachInfo != null) {
10867                canvas = attachInfo.mCanvas;
10868                if (canvas == null) {
10869                    canvas = new Canvas();
10870                }
10871                canvas.setBitmap(bitmap);
10872                // Temporarily clobber the cached Canvas in case one of our children
10873                // is also using a drawing cache. Without this, the children would
10874                // steal the canvas by attaching their own bitmap to it and bad, bad
10875                // thing would happen (invisible views, corrupted drawings, etc.)
10876                attachInfo.mCanvas = null;
10877            } else {
10878                // This case should hopefully never or seldom happen
10879                canvas = new Canvas(bitmap);
10880            }
10881
10882            if (clear) {
10883                bitmap.eraseColor(drawingCacheBackgroundColor);
10884            }
10885
10886            computeScroll();
10887            final int restoreCount = canvas.save();
10888
10889            if (autoScale && scalingRequired) {
10890                final float scale = attachInfo.mApplicationScale;
10891                canvas.scale(scale, scale);
10892            }
10893
10894            canvas.translate(-mScrollX, -mScrollY);
10895
10896            mPrivateFlags |= DRAWN;
10897            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10898                    mLayerType != LAYER_TYPE_NONE) {
10899                mPrivateFlags |= DRAWING_CACHE_VALID;
10900            }
10901
10902            // Fast path for layouts with no backgrounds
10903            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10904                if (ViewDebug.TRACE_HIERARCHY) {
10905                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10906                }
10907                mPrivateFlags &= ~DIRTY_MASK;
10908                dispatchDraw(canvas);
10909            } else {
10910                draw(canvas);
10911            }
10912
10913            canvas.restoreToCount(restoreCount);
10914            canvas.setBitmap(null);
10915
10916            if (attachInfo != null) {
10917                // Restore the cached Canvas for our siblings
10918                attachInfo.mCanvas = canvas;
10919            }
10920        }
10921    }
10922
10923    /**
10924     * Create a snapshot of the view into a bitmap.  We should probably make
10925     * some form of this public, but should think about the API.
10926     */
10927    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10928        int width = mRight - mLeft;
10929        int height = mBottom - mTop;
10930
10931        final AttachInfo attachInfo = mAttachInfo;
10932        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10933        width = (int) ((width * scale) + 0.5f);
10934        height = (int) ((height * scale) + 0.5f);
10935
10936        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10937        if (bitmap == null) {
10938            throw new OutOfMemoryError();
10939        }
10940
10941        Resources resources = getResources();
10942        if (resources != null) {
10943            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10944        }
10945
10946        Canvas canvas;
10947        if (attachInfo != null) {
10948            canvas = attachInfo.mCanvas;
10949            if (canvas == null) {
10950                canvas = new Canvas();
10951            }
10952            canvas.setBitmap(bitmap);
10953            // Temporarily clobber the cached Canvas in case one of our children
10954            // is also using a drawing cache. Without this, the children would
10955            // steal the canvas by attaching their own bitmap to it and bad, bad
10956            // things would happen (invisible views, corrupted drawings, etc.)
10957            attachInfo.mCanvas = null;
10958        } else {
10959            // This case should hopefully never or seldom happen
10960            canvas = new Canvas(bitmap);
10961        }
10962
10963        if ((backgroundColor & 0xff000000) != 0) {
10964            bitmap.eraseColor(backgroundColor);
10965        }
10966
10967        computeScroll();
10968        final int restoreCount = canvas.save();
10969        canvas.scale(scale, scale);
10970        canvas.translate(-mScrollX, -mScrollY);
10971
10972        // Temporarily remove the dirty mask
10973        int flags = mPrivateFlags;
10974        mPrivateFlags &= ~DIRTY_MASK;
10975
10976        // Fast path for layouts with no backgrounds
10977        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10978            dispatchDraw(canvas);
10979        } else {
10980            draw(canvas);
10981        }
10982
10983        mPrivateFlags = flags;
10984
10985        canvas.restoreToCount(restoreCount);
10986        canvas.setBitmap(null);
10987
10988        if (attachInfo != null) {
10989            // Restore the cached Canvas for our siblings
10990            attachInfo.mCanvas = canvas;
10991        }
10992
10993        return bitmap;
10994    }
10995
10996    /**
10997     * Indicates whether this View is currently in edit mode. A View is usually
10998     * in edit mode when displayed within a developer tool. For instance, if
10999     * this View is being drawn by a visual user interface builder, this method
11000     * should return true.
11001     *
11002     * Subclasses should check the return value of this method to provide
11003     * different behaviors if their normal behavior might interfere with the
11004     * host environment. For instance: the class spawns a thread in its
11005     * constructor, the drawing code relies on device-specific features, etc.
11006     *
11007     * This method is usually checked in the drawing code of custom widgets.
11008     *
11009     * @return True if this View is in edit mode, false otherwise.
11010     */
11011    public boolean isInEditMode() {
11012        return false;
11013    }
11014
11015    /**
11016     * If the View draws content inside its padding and enables fading edges,
11017     * it needs to support padding offsets. Padding offsets are added to the
11018     * fading edges to extend the length of the fade so that it covers pixels
11019     * drawn inside the padding.
11020     *
11021     * Subclasses of this class should override this method if they need
11022     * to draw content inside the padding.
11023     *
11024     * @return True if padding offset must be applied, false otherwise.
11025     *
11026     * @see #getLeftPaddingOffset()
11027     * @see #getRightPaddingOffset()
11028     * @see #getTopPaddingOffset()
11029     * @see #getBottomPaddingOffset()
11030     *
11031     * @since CURRENT
11032     */
11033    protected boolean isPaddingOffsetRequired() {
11034        return false;
11035    }
11036
11037    /**
11038     * Amount by which to extend the left fading region. Called only when
11039     * {@link #isPaddingOffsetRequired()} returns true.
11040     *
11041     * @return The left padding offset in pixels.
11042     *
11043     * @see #isPaddingOffsetRequired()
11044     *
11045     * @since CURRENT
11046     */
11047    protected int getLeftPaddingOffset() {
11048        return 0;
11049    }
11050
11051    /**
11052     * Amount by which to extend the right fading region. Called only when
11053     * {@link #isPaddingOffsetRequired()} returns true.
11054     *
11055     * @return The right padding offset in pixels.
11056     *
11057     * @see #isPaddingOffsetRequired()
11058     *
11059     * @since CURRENT
11060     */
11061    protected int getRightPaddingOffset() {
11062        return 0;
11063    }
11064
11065    /**
11066     * Amount by which to extend the top fading region. Called only when
11067     * {@link #isPaddingOffsetRequired()} returns true.
11068     *
11069     * @return The top padding offset in pixels.
11070     *
11071     * @see #isPaddingOffsetRequired()
11072     *
11073     * @since CURRENT
11074     */
11075    protected int getTopPaddingOffset() {
11076        return 0;
11077    }
11078
11079    /**
11080     * Amount by which to extend the bottom fading region. Called only when
11081     * {@link #isPaddingOffsetRequired()} returns true.
11082     *
11083     * @return The bottom padding offset in pixels.
11084     *
11085     * @see #isPaddingOffsetRequired()
11086     *
11087     * @since CURRENT
11088     */
11089    protected int getBottomPaddingOffset() {
11090        return 0;
11091    }
11092
11093    /**
11094     * @hide
11095     * @param offsetRequired
11096     */
11097    protected int getFadeTop(boolean offsetRequired) {
11098        int top = mPaddingTop;
11099        if (offsetRequired) top += getTopPaddingOffset();
11100        return top;
11101    }
11102
11103    /**
11104     * @hide
11105     * @param offsetRequired
11106     */
11107    protected int getFadeHeight(boolean offsetRequired) {
11108        int padding = mPaddingTop;
11109        if (offsetRequired) padding += getTopPaddingOffset();
11110        return mBottom - mTop - mPaddingBottom - padding;
11111    }
11112
11113    /**
11114     * <p>Indicates whether this view is attached to a hardware accelerated
11115     * window or not.</p>
11116     *
11117     * <p>Even if this method returns true, it does not mean that every call
11118     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
11119     * accelerated {@link android.graphics.Canvas}. For instance, if this view
11120     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
11121     * window is hardware accelerated,
11122     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
11123     * return false, and this method will return true.</p>
11124     *
11125     * @return True if the view is attached to a window and the window is
11126     *         hardware accelerated; false in any other case.
11127     */
11128    public boolean isHardwareAccelerated() {
11129        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
11130    }
11131
11132    /**
11133     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
11134     * case of an active Animation being run on the view.
11135     */
11136    private boolean drawAnimation(ViewGroup parent, long drawingTime,
11137            Animation a, boolean scalingRequired) {
11138        Transformation invalidationTransform;
11139        final int flags = parent.mGroupFlags;
11140        final boolean initialized = a.isInitialized();
11141        if (!initialized) {
11142            a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight());
11143            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
11144            onAnimationStart();
11145        }
11146
11147        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
11148        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
11149            if (parent.mInvalidationTransformation == null) {
11150                parent.mInvalidationTransformation = new Transformation();
11151            }
11152            invalidationTransform = parent.mInvalidationTransformation;
11153            a.getTransformation(drawingTime, invalidationTransform, 1f);
11154        } else {
11155            invalidationTransform = parent.mChildTransformation;
11156        }
11157        if (more) {
11158            if (!a.willChangeBounds()) {
11159                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
11160                        parent.FLAG_OPTIMIZE_INVALIDATE) {
11161                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
11162                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
11163                    // The child need to draw an animation, potentially offscreen, so
11164                    // make sure we do not cancel invalidate requests
11165                    parent.mPrivateFlags |= DRAW_ANIMATION;
11166                    parent.invalidate(mLeft, mTop, mRight, mBottom);
11167                }
11168            } else {
11169                if (parent.mInvalidateRegion == null) {
11170                    parent.mInvalidateRegion = new RectF();
11171                }
11172                final RectF region = parent.mInvalidateRegion;
11173                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
11174                        invalidationTransform);
11175
11176                // The child need to draw an animation, potentially offscreen, so
11177                // make sure we do not cancel invalidate requests
11178                parent.mPrivateFlags |= DRAW_ANIMATION;
11179
11180                final int left = mLeft + (int) region.left;
11181                final int top = mTop + (int) region.top;
11182                parent.invalidate(left, top, left + (int) (region.width() + .5f),
11183                        top + (int) (region.height() + .5f));
11184            }
11185        }
11186        return more;
11187    }
11188
11189    /**
11190     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
11191     * This draw() method is an implementation detail and is not intended to be overridden or
11192     * to be called from anywhere else other than ViewGroup.drawChild().
11193     */
11194    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
11195        boolean more = false;
11196        final boolean childHasIdentityMatrix = hasIdentityMatrix();
11197        final int flags = parent.mGroupFlags;
11198
11199        if ((flags & parent.FLAG_CLEAR_TRANSFORMATION) == parent.FLAG_CLEAR_TRANSFORMATION) {
11200            parent.mChildTransformation.clear();
11201            parent.mGroupFlags &= ~parent.FLAG_CLEAR_TRANSFORMATION;
11202        }
11203
11204        Transformation transformToApply = null;
11205        boolean concatMatrix = false;
11206
11207        boolean scalingRequired = false;
11208        boolean caching;
11209        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
11210
11211        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
11212        if ((flags & parent.FLAG_CHILDREN_DRAWN_WITH_CACHE) == parent.FLAG_CHILDREN_DRAWN_WITH_CACHE ||
11213                (flags & parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) == parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) {
11214            caching = true;
11215            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
11216        } else {
11217            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
11218        }
11219
11220        final Animation a = getAnimation();
11221        if (a != null) {
11222            more = drawAnimation(parent, drawingTime, a, scalingRequired);
11223            concatMatrix = a.willChangeTransformationMatrix();
11224            transformToApply = parent.mChildTransformation;
11225        } else if ((flags & parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) ==
11226                parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) {
11227            final boolean hasTransform =
11228                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
11229            if (hasTransform) {
11230                final int transformType = parent.mChildTransformation.getTransformationType();
11231                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
11232                        parent.mChildTransformation : null;
11233                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
11234            }
11235        }
11236
11237        concatMatrix |= !childHasIdentityMatrix;
11238
11239        // Sets the flag as early as possible to allow draw() implementations
11240        // to call invalidate() successfully when doing animations
11241        mPrivateFlags |= DRAWN;
11242
11243        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
11244                (mPrivateFlags & DRAW_ANIMATION) == 0) {
11245            return more;
11246        }
11247
11248        if (hardwareAccelerated) {
11249            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
11250            // retain the flag's value temporarily in the mRecreateDisplayList flag
11251            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
11252            mPrivateFlags &= ~INVALIDATED;
11253        }
11254
11255        computeScroll();
11256
11257        final int sx = mScrollX;
11258        final int sy = mScrollY;
11259
11260        DisplayList displayList = null;
11261        Bitmap cache = null;
11262        boolean hasDisplayList = false;
11263        if (caching) {
11264            if (!hardwareAccelerated) {
11265                if (layerType != LAYER_TYPE_NONE) {
11266                    layerType = LAYER_TYPE_SOFTWARE;
11267                    buildDrawingCache(true);
11268                }
11269                cache = getDrawingCache(true);
11270            } else {
11271                switch (layerType) {
11272                    case LAYER_TYPE_SOFTWARE:
11273                        buildDrawingCache(true);
11274                        cache = getDrawingCache(true);
11275                        break;
11276                    case LAYER_TYPE_NONE:
11277                        // Delay getting the display list until animation-driven alpha values are
11278                        // set up and possibly passed on to the view
11279                        hasDisplayList = canHaveDisplayList();
11280                        break;
11281                }
11282            }
11283        }
11284
11285        final boolean hasNoCache = cache == null || hasDisplayList;
11286        final boolean offsetForScroll = cache == null && !hasDisplayList &&
11287                layerType != LAYER_TYPE_HARDWARE;
11288
11289        final int restoreTo = canvas.save();
11290        if (offsetForScroll) {
11291            canvas.translate(mLeft - sx, mTop - sy);
11292        } else {
11293            canvas.translate(mLeft, mTop);
11294            if (scalingRequired) {
11295                // mAttachInfo cannot be null, otherwise scalingRequired == false
11296                final float scale = 1.0f / mAttachInfo.mApplicationScale;
11297                canvas.scale(scale, scale);
11298            }
11299        }
11300
11301        float alpha = getAlpha();
11302        if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) {
11303            if (transformToApply != null || !childHasIdentityMatrix) {
11304                int transX = 0;
11305                int transY = 0;
11306
11307                if (offsetForScroll) {
11308                    transX = -sx;
11309                    transY = -sy;
11310                }
11311
11312                if (transformToApply != null) {
11313                    if (concatMatrix) {
11314                        // Undo the scroll translation, apply the transformation matrix,
11315                        // then redo the scroll translate to get the correct result.
11316                        canvas.translate(-transX, -transY);
11317                        canvas.concat(transformToApply.getMatrix());
11318                        canvas.translate(transX, transY);
11319                        parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11320                    }
11321
11322                    float transformAlpha = transformToApply.getAlpha();
11323                    if (transformAlpha < 1.0f) {
11324                        alpha *= transformToApply.getAlpha();
11325                        parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11326                    }
11327                }
11328
11329                if (!childHasIdentityMatrix) {
11330                    canvas.translate(-transX, -transY);
11331                    canvas.concat(getMatrix());
11332                    canvas.translate(transX, transY);
11333                }
11334            }
11335
11336            if (alpha < 1.0f) {
11337                parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11338                if (hasNoCache) {
11339                    final int multipliedAlpha = (int) (255 * alpha);
11340                    if (!onSetAlpha(multipliedAlpha)) {
11341                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11342                        if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN ||
11343                                layerType != LAYER_TYPE_NONE) {
11344                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
11345                        }
11346                        if (layerType == LAYER_TYPE_NONE) {
11347                            final int scrollX = hasDisplayList ? 0 : sx;
11348                            final int scrollY = hasDisplayList ? 0 : sy;
11349                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
11350                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
11351                        }
11352                    } else {
11353                        // Alpha is handled by the child directly, clobber the layer's alpha
11354                        mPrivateFlags |= ALPHA_SET;
11355                    }
11356                }
11357            }
11358        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11359            onSetAlpha(255);
11360            mPrivateFlags &= ~ALPHA_SET;
11361        }
11362
11363        if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN) {
11364            if (offsetForScroll) {
11365                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
11366            } else {
11367                if (!scalingRequired || cache == null) {
11368                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
11369                } else {
11370                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
11371                }
11372            }
11373        }
11374
11375        if (hasDisplayList) {
11376            displayList = getDisplayList();
11377            if (!displayList.isValid()) {
11378                // Uncommon, but possible. If a view is removed from the hierarchy during the call
11379                // to getDisplayList(), the display list will be marked invalid and we should not
11380                // try to use it again.
11381                displayList = null;
11382                hasDisplayList = false;
11383            }
11384        }
11385
11386        if (hasNoCache) {
11387            boolean layerRendered = false;
11388            if (layerType == LAYER_TYPE_HARDWARE) {
11389                final HardwareLayer layer = getHardwareLayer();
11390                if (layer != null && layer.isValid()) {
11391                    mLayerPaint.setAlpha((int) (alpha * 255));
11392                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
11393                    layerRendered = true;
11394                } else {
11395                    final int scrollX = hasDisplayList ? 0 : sx;
11396                    final int scrollY = hasDisplayList ? 0 : sy;
11397                    canvas.saveLayer(scrollX, scrollY,
11398                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
11399                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11400                }
11401            }
11402
11403            if (!layerRendered) {
11404                if (!hasDisplayList) {
11405                    // Fast path for layouts with no backgrounds
11406                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11407                        if (ViewDebug.TRACE_HIERARCHY) {
11408                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
11409                        }
11410                        mPrivateFlags &= ~DIRTY_MASK;
11411                        dispatchDraw(canvas);
11412                    } else {
11413                        draw(canvas);
11414                    }
11415                } else {
11416                    mPrivateFlags &= ~DIRTY_MASK;
11417                    ((HardwareCanvas) canvas).drawDisplayList(displayList,
11418                            mRight - mLeft, mBottom - mTop, null, flags);
11419                }
11420            }
11421        } else if (cache != null) {
11422            mPrivateFlags &= ~DIRTY_MASK;
11423            Paint cachePaint;
11424
11425            if (layerType == LAYER_TYPE_NONE) {
11426                cachePaint = parent.mCachePaint;
11427                if (cachePaint == null) {
11428                    cachePaint = new Paint();
11429                    cachePaint.setDither(false);
11430                    parent.mCachePaint = cachePaint;
11431                }
11432                if (alpha < 1.0f) {
11433                    cachePaint.setAlpha((int) (alpha * 255));
11434                    parent.mGroupFlags |= parent.FLAG_ALPHA_LOWER_THAN_ONE;
11435                } else if  ((flags & parent.FLAG_ALPHA_LOWER_THAN_ONE) ==
11436                        parent.FLAG_ALPHA_LOWER_THAN_ONE) {
11437                    cachePaint.setAlpha(255);
11438                    parent.mGroupFlags &= ~parent.FLAG_ALPHA_LOWER_THAN_ONE;
11439                }
11440            } else {
11441                cachePaint = mLayerPaint;
11442                cachePaint.setAlpha((int) (alpha * 255));
11443            }
11444            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
11445        }
11446
11447        canvas.restoreToCount(restoreTo);
11448
11449        if (a != null && !more) {
11450            if (!hardwareAccelerated && !a.getFillAfter()) {
11451                onSetAlpha(255);
11452            }
11453            parent.finishAnimatingView(this, a);
11454        }
11455
11456        if (more && hardwareAccelerated) {
11457            // invalidation is the trigger to recreate display lists, so if we're using
11458            // display lists to render, force an invalidate to allow the animation to
11459            // continue drawing another frame
11460            parent.invalidate(true);
11461            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11462                // alpha animations should cause the child to recreate its display list
11463                invalidate(true);
11464            }
11465        }
11466
11467        mRecreateDisplayList = false;
11468
11469        return more;
11470    }
11471
11472    /**
11473     * Manually render this view (and all of its children) to the given Canvas.
11474     * The view must have already done a full layout before this function is
11475     * called.  When implementing a view, implement
11476     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
11477     * If you do need to override this method, call the superclass version.
11478     *
11479     * @param canvas The Canvas to which the View is rendered.
11480     */
11481    public void draw(Canvas canvas) {
11482        if (ViewDebug.TRACE_HIERARCHY) {
11483            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11484        }
11485
11486        final int privateFlags = mPrivateFlags;
11487        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
11488                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
11489        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
11490
11491        /*
11492         * Draw traversal performs several drawing steps which must be executed
11493         * in the appropriate order:
11494         *
11495         *      1. Draw the background
11496         *      2. If necessary, save the canvas' layers to prepare for fading
11497         *      3. Draw view's content
11498         *      4. Draw children
11499         *      5. If necessary, draw the fading edges and restore layers
11500         *      6. Draw decorations (scrollbars for instance)
11501         */
11502
11503        // Step 1, draw the background, if needed
11504        int saveCount;
11505
11506        if (!dirtyOpaque) {
11507            final Drawable background = mBGDrawable;
11508            if (background != null) {
11509                final int scrollX = mScrollX;
11510                final int scrollY = mScrollY;
11511
11512                if (mBackgroundSizeChanged) {
11513                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
11514                    mBackgroundSizeChanged = false;
11515                }
11516
11517                if ((scrollX | scrollY) == 0) {
11518                    background.draw(canvas);
11519                } else {
11520                    canvas.translate(scrollX, scrollY);
11521                    background.draw(canvas);
11522                    canvas.translate(-scrollX, -scrollY);
11523                }
11524            }
11525        }
11526
11527        // skip step 2 & 5 if possible (common case)
11528        final int viewFlags = mViewFlags;
11529        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
11530        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
11531        if (!verticalEdges && !horizontalEdges) {
11532            // Step 3, draw the content
11533            if (!dirtyOpaque) onDraw(canvas);
11534
11535            // Step 4, draw the children
11536            dispatchDraw(canvas);
11537
11538            // Step 6, draw decorations (scrollbars)
11539            onDrawScrollBars(canvas);
11540
11541            // we're done...
11542            return;
11543        }
11544
11545        /*
11546         * Here we do the full fledged routine...
11547         * (this is an uncommon case where speed matters less,
11548         * this is why we repeat some of the tests that have been
11549         * done above)
11550         */
11551
11552        boolean drawTop = false;
11553        boolean drawBottom = false;
11554        boolean drawLeft = false;
11555        boolean drawRight = false;
11556
11557        float topFadeStrength = 0.0f;
11558        float bottomFadeStrength = 0.0f;
11559        float leftFadeStrength = 0.0f;
11560        float rightFadeStrength = 0.0f;
11561
11562        // Step 2, save the canvas' layers
11563        int paddingLeft = mPaddingLeft;
11564
11565        final boolean offsetRequired = isPaddingOffsetRequired();
11566        if (offsetRequired) {
11567            paddingLeft += getLeftPaddingOffset();
11568        }
11569
11570        int left = mScrollX + paddingLeft;
11571        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
11572        int top = mScrollY + getFadeTop(offsetRequired);
11573        int bottom = top + getFadeHeight(offsetRequired);
11574
11575        if (offsetRequired) {
11576            right += getRightPaddingOffset();
11577            bottom += getBottomPaddingOffset();
11578        }
11579
11580        final ScrollabilityCache scrollabilityCache = mScrollCache;
11581        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
11582        int length = (int) fadeHeight;
11583
11584        // clip the fade length if top and bottom fades overlap
11585        // overlapping fades produce odd-looking artifacts
11586        if (verticalEdges && (top + length > bottom - length)) {
11587            length = (bottom - top) / 2;
11588        }
11589
11590        // also clip horizontal fades if necessary
11591        if (horizontalEdges && (left + length > right - length)) {
11592            length = (right - left) / 2;
11593        }
11594
11595        if (verticalEdges) {
11596            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
11597            drawTop = topFadeStrength * fadeHeight > 1.0f;
11598            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
11599            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
11600        }
11601
11602        if (horizontalEdges) {
11603            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
11604            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
11605            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
11606            drawRight = rightFadeStrength * fadeHeight > 1.0f;
11607        }
11608
11609        saveCount = canvas.getSaveCount();
11610
11611        int solidColor = getSolidColor();
11612        if (solidColor == 0) {
11613            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11614
11615            if (drawTop) {
11616                canvas.saveLayer(left, top, right, top + length, null, flags);
11617            }
11618
11619            if (drawBottom) {
11620                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
11621            }
11622
11623            if (drawLeft) {
11624                canvas.saveLayer(left, top, left + length, bottom, null, flags);
11625            }
11626
11627            if (drawRight) {
11628                canvas.saveLayer(right - length, top, right, bottom, null, flags);
11629            }
11630        } else {
11631            scrollabilityCache.setFadeColor(solidColor);
11632        }
11633
11634        // Step 3, draw the content
11635        if (!dirtyOpaque) onDraw(canvas);
11636
11637        // Step 4, draw the children
11638        dispatchDraw(canvas);
11639
11640        // Step 5, draw the fade effect and restore layers
11641        final Paint p = scrollabilityCache.paint;
11642        final Matrix matrix = scrollabilityCache.matrix;
11643        final Shader fade = scrollabilityCache.shader;
11644
11645        if (drawTop) {
11646            matrix.setScale(1, fadeHeight * topFadeStrength);
11647            matrix.postTranslate(left, top);
11648            fade.setLocalMatrix(matrix);
11649            canvas.drawRect(left, top, right, top + length, p);
11650        }
11651
11652        if (drawBottom) {
11653            matrix.setScale(1, fadeHeight * bottomFadeStrength);
11654            matrix.postRotate(180);
11655            matrix.postTranslate(left, bottom);
11656            fade.setLocalMatrix(matrix);
11657            canvas.drawRect(left, bottom - length, right, bottom, p);
11658        }
11659
11660        if (drawLeft) {
11661            matrix.setScale(1, fadeHeight * leftFadeStrength);
11662            matrix.postRotate(-90);
11663            matrix.postTranslate(left, top);
11664            fade.setLocalMatrix(matrix);
11665            canvas.drawRect(left, top, left + length, bottom, p);
11666        }
11667
11668        if (drawRight) {
11669            matrix.setScale(1, fadeHeight * rightFadeStrength);
11670            matrix.postRotate(90);
11671            matrix.postTranslate(right, top);
11672            fade.setLocalMatrix(matrix);
11673            canvas.drawRect(right - length, top, right, bottom, p);
11674        }
11675
11676        canvas.restoreToCount(saveCount);
11677
11678        // Step 6, draw decorations (scrollbars)
11679        onDrawScrollBars(canvas);
11680    }
11681
11682    /**
11683     * Override this if your view is known to always be drawn on top of a solid color background,
11684     * and needs to draw fading edges. Returning a non-zero color enables the view system to
11685     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
11686     * should be set to 0xFF.
11687     *
11688     * @see #setVerticalFadingEdgeEnabled(boolean)
11689     * @see #setHorizontalFadingEdgeEnabled(boolean)
11690     *
11691     * @return The known solid color background for this view, or 0 if the color may vary
11692     */
11693    @ViewDebug.ExportedProperty(category = "drawing")
11694    public int getSolidColor() {
11695        return 0;
11696    }
11697
11698    /**
11699     * Build a human readable string representation of the specified view flags.
11700     *
11701     * @param flags the view flags to convert to a string
11702     * @return a String representing the supplied flags
11703     */
11704    private static String printFlags(int flags) {
11705        String output = "";
11706        int numFlags = 0;
11707        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11708            output += "TAKES_FOCUS";
11709            numFlags++;
11710        }
11711
11712        switch (flags & VISIBILITY_MASK) {
11713        case INVISIBLE:
11714            if (numFlags > 0) {
11715                output += " ";
11716            }
11717            output += "INVISIBLE";
11718            // USELESS HERE numFlags++;
11719            break;
11720        case GONE:
11721            if (numFlags > 0) {
11722                output += " ";
11723            }
11724            output += "GONE";
11725            // USELESS HERE numFlags++;
11726            break;
11727        default:
11728            break;
11729        }
11730        return output;
11731    }
11732
11733    /**
11734     * Build a human readable string representation of the specified private
11735     * view flags.
11736     *
11737     * @param privateFlags the private view flags to convert to a string
11738     * @return a String representing the supplied flags
11739     */
11740    private static String printPrivateFlags(int privateFlags) {
11741        String output = "";
11742        int numFlags = 0;
11743
11744        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11745            output += "WANTS_FOCUS";
11746            numFlags++;
11747        }
11748
11749        if ((privateFlags & FOCUSED) == FOCUSED) {
11750            if (numFlags > 0) {
11751                output += " ";
11752            }
11753            output += "FOCUSED";
11754            numFlags++;
11755        }
11756
11757        if ((privateFlags & SELECTED) == SELECTED) {
11758            if (numFlags > 0) {
11759                output += " ";
11760            }
11761            output += "SELECTED";
11762            numFlags++;
11763        }
11764
11765        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11766            if (numFlags > 0) {
11767                output += " ";
11768            }
11769            output += "IS_ROOT_NAMESPACE";
11770            numFlags++;
11771        }
11772
11773        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11774            if (numFlags > 0) {
11775                output += " ";
11776            }
11777            output += "HAS_BOUNDS";
11778            numFlags++;
11779        }
11780
11781        if ((privateFlags & DRAWN) == DRAWN) {
11782            if (numFlags > 0) {
11783                output += " ";
11784            }
11785            output += "DRAWN";
11786            // USELESS HERE numFlags++;
11787        }
11788        return output;
11789    }
11790
11791    /**
11792     * <p>Indicates whether or not this view's layout will be requested during
11793     * the next hierarchy layout pass.</p>
11794     *
11795     * @return true if the layout will be forced during next layout pass
11796     */
11797    public boolean isLayoutRequested() {
11798        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
11799    }
11800
11801    /**
11802     * Assign a size and position to a view and all of its
11803     * descendants
11804     *
11805     * <p>This is the second phase of the layout mechanism.
11806     * (The first is measuring). In this phase, each parent calls
11807     * layout on all of its children to position them.
11808     * This is typically done using the child measurements
11809     * that were stored in the measure pass().</p>
11810     *
11811     * <p>Derived classes should not override this method.
11812     * Derived classes with children should override
11813     * onLayout. In that method, they should
11814     * call layout on each of their children.</p>
11815     *
11816     * @param l Left position, relative to parent
11817     * @param t Top position, relative to parent
11818     * @param r Right position, relative to parent
11819     * @param b Bottom position, relative to parent
11820     */
11821    @SuppressWarnings({"unchecked"})
11822    public void layout(int l, int t, int r, int b) {
11823        int oldL = mLeft;
11824        int oldT = mTop;
11825        int oldB = mBottom;
11826        int oldR = mRight;
11827        boolean changed = setFrame(l, t, r, b);
11828        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
11829            if (ViewDebug.TRACE_HIERARCHY) {
11830                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
11831            }
11832
11833            onLayout(changed, l, t, r, b);
11834            mPrivateFlags &= ~LAYOUT_REQUIRED;
11835
11836            ListenerInfo li = mListenerInfo;
11837            if (li != null && li.mOnLayoutChangeListeners != null) {
11838                ArrayList<OnLayoutChangeListener> listenersCopy =
11839                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
11840                int numListeners = listenersCopy.size();
11841                for (int i = 0; i < numListeners; ++i) {
11842                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
11843                }
11844            }
11845        }
11846        mPrivateFlags &= ~FORCE_LAYOUT;
11847    }
11848
11849    /**
11850     * Called from layout when this view should
11851     * assign a size and position to each of its children.
11852     *
11853     * Derived classes with children should override
11854     * this method and call layout on each of
11855     * their children.
11856     * @param changed This is a new size or position for this view
11857     * @param left Left position, relative to parent
11858     * @param top Top position, relative to parent
11859     * @param right Right position, relative to parent
11860     * @param bottom Bottom position, relative to parent
11861     */
11862    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
11863    }
11864
11865    /**
11866     * Assign a size and position to this view.
11867     *
11868     * This is called from layout.
11869     *
11870     * @param left Left position, relative to parent
11871     * @param top Top position, relative to parent
11872     * @param right Right position, relative to parent
11873     * @param bottom Bottom position, relative to parent
11874     * @return true if the new size and position are different than the
11875     *         previous ones
11876     * {@hide}
11877     */
11878    protected boolean setFrame(int left, int top, int right, int bottom) {
11879        boolean changed = false;
11880
11881        if (DBG) {
11882            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
11883                    + right + "," + bottom + ")");
11884        }
11885
11886        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
11887            changed = true;
11888
11889            // Remember our drawn bit
11890            int drawn = mPrivateFlags & DRAWN;
11891
11892            int oldWidth = mRight - mLeft;
11893            int oldHeight = mBottom - mTop;
11894            int newWidth = right - left;
11895            int newHeight = bottom - top;
11896            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
11897
11898            // Invalidate our old position
11899            invalidate(sizeChanged);
11900
11901            mLeft = left;
11902            mTop = top;
11903            mRight = right;
11904            mBottom = bottom;
11905
11906            mPrivateFlags |= HAS_BOUNDS;
11907
11908
11909            if (sizeChanged) {
11910                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
11911                    // A change in dimension means an auto-centered pivot point changes, too
11912                    if (mTransformationInfo != null) {
11913                        mTransformationInfo.mMatrixDirty = true;
11914                    }
11915                }
11916                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
11917            }
11918
11919            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
11920                // If we are visible, force the DRAWN bit to on so that
11921                // this invalidate will go through (at least to our parent).
11922                // This is because someone may have invalidated this view
11923                // before this call to setFrame came in, thereby clearing
11924                // the DRAWN bit.
11925                mPrivateFlags |= DRAWN;
11926                invalidate(sizeChanged);
11927                // parent display list may need to be recreated based on a change in the bounds
11928                // of any child
11929                invalidateParentCaches();
11930            }
11931
11932            // Reset drawn bit to original value (invalidate turns it off)
11933            mPrivateFlags |= drawn;
11934
11935            mBackgroundSizeChanged = true;
11936        }
11937        return changed;
11938    }
11939
11940    /**
11941     * Finalize inflating a view from XML.  This is called as the last phase
11942     * of inflation, after all child views have been added.
11943     *
11944     * <p>Even if the subclass overrides onFinishInflate, they should always be
11945     * sure to call the super method, so that we get called.
11946     */
11947    protected void onFinishInflate() {
11948    }
11949
11950    /**
11951     * Returns the resources associated with this view.
11952     *
11953     * @return Resources object.
11954     */
11955    public Resources getResources() {
11956        return mResources;
11957    }
11958
11959    /**
11960     * Invalidates the specified Drawable.
11961     *
11962     * @param drawable the drawable to invalidate
11963     */
11964    public void invalidateDrawable(Drawable drawable) {
11965        if (verifyDrawable(drawable)) {
11966            final Rect dirty = drawable.getBounds();
11967            final int scrollX = mScrollX;
11968            final int scrollY = mScrollY;
11969
11970            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11971                    dirty.right + scrollX, dirty.bottom + scrollY);
11972        }
11973    }
11974
11975    /**
11976     * Schedules an action on a drawable to occur at a specified time.
11977     *
11978     * @param who the recipient of the action
11979     * @param what the action to run on the drawable
11980     * @param when the time at which the action must occur. Uses the
11981     *        {@link SystemClock#uptimeMillis} timebase.
11982     */
11983    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11984        if (verifyDrawable(who) && what != null) {
11985            final long delay = when - SystemClock.uptimeMillis();
11986            if (mAttachInfo != null) {
11987                mAttachInfo.mViewRootImpl.mChoreographer.postAnimationCallbackDelayed(
11988                        what, who, Choreographer.subtractFrameDelay(delay));
11989            } else {
11990                ViewRootImpl.getRunQueue().postDelayed(what, delay);
11991            }
11992        }
11993    }
11994
11995    /**
11996     * Cancels a scheduled action on a drawable.
11997     *
11998     * @param who the recipient of the action
11999     * @param what the action to cancel
12000     */
12001    public void unscheduleDrawable(Drawable who, Runnable what) {
12002        if (verifyDrawable(who) && what != null) {
12003            if (mAttachInfo != null) {
12004                mAttachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(what, who);
12005            } else {
12006                ViewRootImpl.getRunQueue().removeCallbacks(what);
12007            }
12008        }
12009    }
12010
12011    /**
12012     * Unschedule any events associated with the given Drawable.  This can be
12013     * used when selecting a new Drawable into a view, so that the previous
12014     * one is completely unscheduled.
12015     *
12016     * @param who The Drawable to unschedule.
12017     *
12018     * @see #drawableStateChanged
12019     */
12020    public void unscheduleDrawable(Drawable who) {
12021        if (mAttachInfo != null && who != null) {
12022            mAttachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(null, who);
12023        }
12024    }
12025
12026    /**
12027    * Return the layout direction of a given Drawable.
12028    *
12029    * @param who the Drawable to query
12030    */
12031    public int getResolvedLayoutDirection(Drawable who) {
12032        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
12033    }
12034
12035    /**
12036     * If your view subclass is displaying its own Drawable objects, it should
12037     * override this function and return true for any Drawable it is
12038     * displaying.  This allows animations for those drawables to be
12039     * scheduled.
12040     *
12041     * <p>Be sure to call through to the super class when overriding this
12042     * function.
12043     *
12044     * @param who The Drawable to verify.  Return true if it is one you are
12045     *            displaying, else return the result of calling through to the
12046     *            super class.
12047     *
12048     * @return boolean If true than the Drawable is being displayed in the
12049     *         view; else false and it is not allowed to animate.
12050     *
12051     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
12052     * @see #drawableStateChanged()
12053     */
12054    protected boolean verifyDrawable(Drawable who) {
12055        return who == mBGDrawable;
12056    }
12057
12058    /**
12059     * This function is called whenever the state of the view changes in such
12060     * a way that it impacts the state of drawables being shown.
12061     *
12062     * <p>Be sure to call through to the superclass when overriding this
12063     * function.
12064     *
12065     * @see Drawable#setState(int[])
12066     */
12067    protected void drawableStateChanged() {
12068        Drawable d = mBGDrawable;
12069        if (d != null && d.isStateful()) {
12070            d.setState(getDrawableState());
12071        }
12072    }
12073
12074    /**
12075     * Call this to force a view to update its drawable state. This will cause
12076     * drawableStateChanged to be called on this view. Views that are interested
12077     * in the new state should call getDrawableState.
12078     *
12079     * @see #drawableStateChanged
12080     * @see #getDrawableState
12081     */
12082    public void refreshDrawableState() {
12083        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
12084        drawableStateChanged();
12085
12086        ViewParent parent = mParent;
12087        if (parent != null) {
12088            parent.childDrawableStateChanged(this);
12089        }
12090    }
12091
12092    /**
12093     * Return an array of resource IDs of the drawable states representing the
12094     * current state of the view.
12095     *
12096     * @return The current drawable state
12097     *
12098     * @see Drawable#setState(int[])
12099     * @see #drawableStateChanged()
12100     * @see #onCreateDrawableState(int)
12101     */
12102    public final int[] getDrawableState() {
12103        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
12104            return mDrawableState;
12105        } else {
12106            mDrawableState = onCreateDrawableState(0);
12107            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
12108            return mDrawableState;
12109        }
12110    }
12111
12112    /**
12113     * Generate the new {@link android.graphics.drawable.Drawable} state for
12114     * this view. This is called by the view
12115     * system when the cached Drawable state is determined to be invalid.  To
12116     * retrieve the current state, you should use {@link #getDrawableState}.
12117     *
12118     * @param extraSpace if non-zero, this is the number of extra entries you
12119     * would like in the returned array in which you can place your own
12120     * states.
12121     *
12122     * @return Returns an array holding the current {@link Drawable} state of
12123     * the view.
12124     *
12125     * @see #mergeDrawableStates(int[], int[])
12126     */
12127    protected int[] onCreateDrawableState(int extraSpace) {
12128        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
12129                mParent instanceof View) {
12130            return ((View) mParent).onCreateDrawableState(extraSpace);
12131        }
12132
12133        int[] drawableState;
12134
12135        int privateFlags = mPrivateFlags;
12136
12137        int viewStateIndex = 0;
12138        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
12139        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
12140        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
12141        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
12142        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
12143        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
12144        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
12145                HardwareRenderer.isAvailable()) {
12146            // This is set if HW acceleration is requested, even if the current
12147            // process doesn't allow it.  This is just to allow app preview
12148            // windows to better match their app.
12149            viewStateIndex |= VIEW_STATE_ACCELERATED;
12150        }
12151        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
12152
12153        final int privateFlags2 = mPrivateFlags2;
12154        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
12155        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
12156
12157        drawableState = VIEW_STATE_SETS[viewStateIndex];
12158
12159        //noinspection ConstantIfStatement
12160        if (false) {
12161            Log.i("View", "drawableStateIndex=" + viewStateIndex);
12162            Log.i("View", toString()
12163                    + " pressed=" + ((privateFlags & PRESSED) != 0)
12164                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
12165                    + " fo=" + hasFocus()
12166                    + " sl=" + ((privateFlags & SELECTED) != 0)
12167                    + " wf=" + hasWindowFocus()
12168                    + ": " + Arrays.toString(drawableState));
12169        }
12170
12171        if (extraSpace == 0) {
12172            return drawableState;
12173        }
12174
12175        final int[] fullState;
12176        if (drawableState != null) {
12177            fullState = new int[drawableState.length + extraSpace];
12178            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
12179        } else {
12180            fullState = new int[extraSpace];
12181        }
12182
12183        return fullState;
12184    }
12185
12186    /**
12187     * Merge your own state values in <var>additionalState</var> into the base
12188     * state values <var>baseState</var> that were returned by
12189     * {@link #onCreateDrawableState(int)}.
12190     *
12191     * @param baseState The base state values returned by
12192     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
12193     * own additional state values.
12194     *
12195     * @param additionalState The additional state values you would like
12196     * added to <var>baseState</var>; this array is not modified.
12197     *
12198     * @return As a convenience, the <var>baseState</var> array you originally
12199     * passed into the function is returned.
12200     *
12201     * @see #onCreateDrawableState(int)
12202     */
12203    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
12204        final int N = baseState.length;
12205        int i = N - 1;
12206        while (i >= 0 && baseState[i] == 0) {
12207            i--;
12208        }
12209        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
12210        return baseState;
12211    }
12212
12213    /**
12214     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
12215     * on all Drawable objects associated with this view.
12216     */
12217    public void jumpDrawablesToCurrentState() {
12218        if (mBGDrawable != null) {
12219            mBGDrawable.jumpToCurrentState();
12220        }
12221    }
12222
12223    /**
12224     * Sets the background color for this view.
12225     * @param color the color of the background
12226     */
12227    @RemotableViewMethod
12228    public void setBackgroundColor(int color) {
12229        if (mBGDrawable instanceof ColorDrawable) {
12230            ((ColorDrawable) mBGDrawable).setColor(color);
12231        } else {
12232            setBackgroundDrawable(new ColorDrawable(color));
12233        }
12234    }
12235
12236    /**
12237     * Set the background to a given resource. The resource should refer to
12238     * a Drawable object or 0 to remove the background.
12239     * @param resid The identifier of the resource.
12240     * @attr ref android.R.styleable#View_background
12241     */
12242    @RemotableViewMethod
12243    public void setBackgroundResource(int resid) {
12244        if (resid != 0 && resid == mBackgroundResource) {
12245            return;
12246        }
12247
12248        Drawable d= null;
12249        if (resid != 0) {
12250            d = mResources.getDrawable(resid);
12251        }
12252        setBackgroundDrawable(d);
12253
12254        mBackgroundResource = resid;
12255    }
12256
12257    /**
12258     * Set the background to a given Drawable, or remove the background. If the
12259     * background has padding, this View's padding is set to the background's
12260     * padding. However, when a background is removed, this View's padding isn't
12261     * touched. If setting the padding is desired, please use
12262     * {@link #setPadding(int, int, int, int)}.
12263     *
12264     * @param d The Drawable to use as the background, or null to remove the
12265     *        background
12266     */
12267    public void setBackgroundDrawable(Drawable d) {
12268        if (d == mBGDrawable) {
12269            return;
12270        }
12271
12272        boolean requestLayout = false;
12273
12274        mBackgroundResource = 0;
12275
12276        /*
12277         * Regardless of whether we're setting a new background or not, we want
12278         * to clear the previous drawable.
12279         */
12280        if (mBGDrawable != null) {
12281            mBGDrawable.setCallback(null);
12282            unscheduleDrawable(mBGDrawable);
12283        }
12284
12285        if (d != null) {
12286            Rect padding = sThreadLocal.get();
12287            if (padding == null) {
12288                padding = new Rect();
12289                sThreadLocal.set(padding);
12290            }
12291            if (d.getPadding(padding)) {
12292                switch (d.getResolvedLayoutDirectionSelf()) {
12293                    case LAYOUT_DIRECTION_RTL:
12294                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
12295                        break;
12296                    case LAYOUT_DIRECTION_LTR:
12297                    default:
12298                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
12299                }
12300            }
12301
12302            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
12303            // if it has a different minimum size, we should layout again
12304            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
12305                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
12306                requestLayout = true;
12307            }
12308
12309            d.setCallback(this);
12310            if (d.isStateful()) {
12311                d.setState(getDrawableState());
12312            }
12313            d.setVisible(getVisibility() == VISIBLE, false);
12314            mBGDrawable = d;
12315
12316            if ((mPrivateFlags & SKIP_DRAW) != 0) {
12317                mPrivateFlags &= ~SKIP_DRAW;
12318                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
12319                requestLayout = true;
12320            }
12321        } else {
12322            /* Remove the background */
12323            mBGDrawable = null;
12324
12325            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
12326                /*
12327                 * This view ONLY drew the background before and we're removing
12328                 * the background, so now it won't draw anything
12329                 * (hence we SKIP_DRAW)
12330                 */
12331                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
12332                mPrivateFlags |= SKIP_DRAW;
12333            }
12334
12335            /*
12336             * When the background is set, we try to apply its padding to this
12337             * View. When the background is removed, we don't touch this View's
12338             * padding. This is noted in the Javadocs. Hence, we don't need to
12339             * requestLayout(), the invalidate() below is sufficient.
12340             */
12341
12342            // The old background's minimum size could have affected this
12343            // View's layout, so let's requestLayout
12344            requestLayout = true;
12345        }
12346
12347        computeOpaqueFlags();
12348
12349        if (requestLayout) {
12350            requestLayout();
12351        }
12352
12353        mBackgroundSizeChanged = true;
12354        invalidate(true);
12355    }
12356
12357    /**
12358     * Gets the background drawable
12359     * @return The drawable used as the background for this view, if any.
12360     */
12361    public Drawable getBackground() {
12362        return mBGDrawable;
12363    }
12364
12365    /**
12366     * Sets the padding. The view may add on the space required to display
12367     * the scrollbars, depending on the style and visibility of the scrollbars.
12368     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
12369     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
12370     * from the values set in this call.
12371     *
12372     * @attr ref android.R.styleable#View_padding
12373     * @attr ref android.R.styleable#View_paddingBottom
12374     * @attr ref android.R.styleable#View_paddingLeft
12375     * @attr ref android.R.styleable#View_paddingRight
12376     * @attr ref android.R.styleable#View_paddingTop
12377     * @param left the left padding in pixels
12378     * @param top the top padding in pixels
12379     * @param right the right padding in pixels
12380     * @param bottom the bottom padding in pixels
12381     */
12382    public void setPadding(int left, int top, int right, int bottom) {
12383        mUserPaddingStart = -1;
12384        mUserPaddingEnd = -1;
12385        mUserPaddingRelative = false;
12386
12387        internalSetPadding(left, top, right, bottom);
12388    }
12389
12390    private void internalSetPadding(int left, int top, int right, int bottom) {
12391        mUserPaddingLeft = left;
12392        mUserPaddingRight = right;
12393        mUserPaddingBottom = bottom;
12394
12395        final int viewFlags = mViewFlags;
12396        boolean changed = false;
12397
12398        // Common case is there are no scroll bars.
12399        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
12400            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
12401                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
12402                        ? 0 : getVerticalScrollbarWidth();
12403                switch (mVerticalScrollbarPosition) {
12404                    case SCROLLBAR_POSITION_DEFAULT:
12405                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12406                            left += offset;
12407                        } else {
12408                            right += offset;
12409                        }
12410                        break;
12411                    case SCROLLBAR_POSITION_RIGHT:
12412                        right += offset;
12413                        break;
12414                    case SCROLLBAR_POSITION_LEFT:
12415                        left += offset;
12416                        break;
12417                }
12418            }
12419            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
12420                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
12421                        ? 0 : getHorizontalScrollbarHeight();
12422            }
12423        }
12424
12425        if (mPaddingLeft != left) {
12426            changed = true;
12427            mPaddingLeft = left;
12428        }
12429        if (mPaddingTop != top) {
12430            changed = true;
12431            mPaddingTop = top;
12432        }
12433        if (mPaddingRight != right) {
12434            changed = true;
12435            mPaddingRight = right;
12436        }
12437        if (mPaddingBottom != bottom) {
12438            changed = true;
12439            mPaddingBottom = bottom;
12440        }
12441
12442        if (changed) {
12443            requestLayout();
12444        }
12445    }
12446
12447    /**
12448     * Sets the relative padding. The view may add on the space required to display
12449     * the scrollbars, depending on the style and visibility of the scrollbars.
12450     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
12451     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
12452     * from the values set in this call.
12453     *
12454     * @attr ref android.R.styleable#View_padding
12455     * @attr ref android.R.styleable#View_paddingBottom
12456     * @attr ref android.R.styleable#View_paddingStart
12457     * @attr ref android.R.styleable#View_paddingEnd
12458     * @attr ref android.R.styleable#View_paddingTop
12459     * @param start the start padding in pixels
12460     * @param top the top padding in pixels
12461     * @param end the end padding in pixels
12462     * @param bottom the bottom padding in pixels
12463     */
12464    public void setPaddingRelative(int start, int top, int end, int bottom) {
12465        mUserPaddingStart = start;
12466        mUserPaddingEnd = end;
12467        mUserPaddingRelative = true;
12468
12469        switch(getResolvedLayoutDirection()) {
12470            case LAYOUT_DIRECTION_RTL:
12471                internalSetPadding(end, top, start, bottom);
12472                break;
12473            case LAYOUT_DIRECTION_LTR:
12474            default:
12475                internalSetPadding(start, top, end, bottom);
12476        }
12477    }
12478
12479    /**
12480     * Returns the top padding of this view.
12481     *
12482     * @return the top padding in pixels
12483     */
12484    public int getPaddingTop() {
12485        return mPaddingTop;
12486    }
12487
12488    /**
12489     * Returns the bottom padding of this view. If there are inset and enabled
12490     * scrollbars, this value may include the space required to display the
12491     * scrollbars as well.
12492     *
12493     * @return the bottom padding in pixels
12494     */
12495    public int getPaddingBottom() {
12496        return mPaddingBottom;
12497    }
12498
12499    /**
12500     * Returns the left padding of this view. If there are inset and enabled
12501     * scrollbars, this value may include the space required to display the
12502     * scrollbars as well.
12503     *
12504     * @return the left padding in pixels
12505     */
12506    public int getPaddingLeft() {
12507        return mPaddingLeft;
12508    }
12509
12510    /**
12511     * Returns the start padding of this view. If there are inset and enabled
12512     * scrollbars, this value may include the space required to display the
12513     * scrollbars as well.
12514     *
12515     * @return the start padding in pixels
12516     */
12517    public int getPaddingStart() {
12518        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12519                mPaddingRight : mPaddingLeft;
12520    }
12521
12522    /**
12523     * Returns the right padding of this view. If there are inset and enabled
12524     * scrollbars, this value may include the space required to display the
12525     * scrollbars as well.
12526     *
12527     * @return the right padding in pixels
12528     */
12529    public int getPaddingRight() {
12530        return mPaddingRight;
12531    }
12532
12533    /**
12534     * Returns the end padding of this view. If there are inset and enabled
12535     * scrollbars, this value may include the space required to display the
12536     * scrollbars as well.
12537     *
12538     * @return the end padding in pixels
12539     */
12540    public int getPaddingEnd() {
12541        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12542                mPaddingLeft : mPaddingRight;
12543    }
12544
12545    /**
12546     * Return if the padding as been set thru relative values
12547     * {@link #setPaddingRelative(int, int, int, int)} or thru
12548     * @attr ref android.R.styleable#View_paddingStart or
12549     * @attr ref android.R.styleable#View_paddingEnd
12550     *
12551     * @return true if the padding is relative or false if it is not.
12552     */
12553    public boolean isPaddingRelative() {
12554        return mUserPaddingRelative;
12555    }
12556
12557    /**
12558     * Changes the selection state of this view. A view can be selected or not.
12559     * Note that selection is not the same as focus. Views are typically
12560     * selected in the context of an AdapterView like ListView or GridView;
12561     * the selected view is the view that is highlighted.
12562     *
12563     * @param selected true if the view must be selected, false otherwise
12564     */
12565    public void setSelected(boolean selected) {
12566        if (((mPrivateFlags & SELECTED) != 0) != selected) {
12567            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
12568            if (!selected) resetPressedState();
12569            invalidate(true);
12570            refreshDrawableState();
12571            dispatchSetSelected(selected);
12572        }
12573    }
12574
12575    /**
12576     * Dispatch setSelected to all of this View's children.
12577     *
12578     * @see #setSelected(boolean)
12579     *
12580     * @param selected The new selected state
12581     */
12582    protected void dispatchSetSelected(boolean selected) {
12583    }
12584
12585    /**
12586     * Indicates the selection state of this view.
12587     *
12588     * @return true if the view is selected, false otherwise
12589     */
12590    @ViewDebug.ExportedProperty
12591    public boolean isSelected() {
12592        return (mPrivateFlags & SELECTED) != 0;
12593    }
12594
12595    /**
12596     * Changes the activated state of this view. A view can be activated or not.
12597     * Note that activation is not the same as selection.  Selection is
12598     * a transient property, representing the view (hierarchy) the user is
12599     * currently interacting with.  Activation is a longer-term state that the
12600     * user can move views in and out of.  For example, in a list view with
12601     * single or multiple selection enabled, the views in the current selection
12602     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
12603     * here.)  The activated state is propagated down to children of the view it
12604     * is set on.
12605     *
12606     * @param activated true if the view must be activated, false otherwise
12607     */
12608    public void setActivated(boolean activated) {
12609        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
12610            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
12611            invalidate(true);
12612            refreshDrawableState();
12613            dispatchSetActivated(activated);
12614        }
12615    }
12616
12617    /**
12618     * Dispatch setActivated to all of this View's children.
12619     *
12620     * @see #setActivated(boolean)
12621     *
12622     * @param activated The new activated state
12623     */
12624    protected void dispatchSetActivated(boolean activated) {
12625    }
12626
12627    /**
12628     * Indicates the activation state of this view.
12629     *
12630     * @return true if the view is activated, false otherwise
12631     */
12632    @ViewDebug.ExportedProperty
12633    public boolean isActivated() {
12634        return (mPrivateFlags & ACTIVATED) != 0;
12635    }
12636
12637    /**
12638     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
12639     * observer can be used to get notifications when global events, like
12640     * layout, happen.
12641     *
12642     * The returned ViewTreeObserver observer is not guaranteed to remain
12643     * valid for the lifetime of this View. If the caller of this method keeps
12644     * a long-lived reference to ViewTreeObserver, it should always check for
12645     * the return value of {@link ViewTreeObserver#isAlive()}.
12646     *
12647     * @return The ViewTreeObserver for this view's hierarchy.
12648     */
12649    public ViewTreeObserver getViewTreeObserver() {
12650        if (mAttachInfo != null) {
12651            return mAttachInfo.mTreeObserver;
12652        }
12653        if (mFloatingTreeObserver == null) {
12654            mFloatingTreeObserver = new ViewTreeObserver();
12655        }
12656        return mFloatingTreeObserver;
12657    }
12658
12659    /**
12660     * <p>Finds the topmost view in the current view hierarchy.</p>
12661     *
12662     * @return the topmost view containing this view
12663     */
12664    public View getRootView() {
12665        if (mAttachInfo != null) {
12666            final View v = mAttachInfo.mRootView;
12667            if (v != null) {
12668                return v;
12669            }
12670        }
12671
12672        View parent = this;
12673
12674        while (parent.mParent != null && parent.mParent instanceof View) {
12675            parent = (View) parent.mParent;
12676        }
12677
12678        return parent;
12679    }
12680
12681    /**
12682     * <p>Computes the coordinates of this view on the screen. The argument
12683     * must be an array of two integers. After the method returns, the array
12684     * contains the x and y location in that order.</p>
12685     *
12686     * @param location an array of two integers in which to hold the coordinates
12687     */
12688    public void getLocationOnScreen(int[] location) {
12689        getLocationInWindow(location);
12690
12691        final AttachInfo info = mAttachInfo;
12692        if (info != null) {
12693            location[0] += info.mWindowLeft;
12694            location[1] += info.mWindowTop;
12695        }
12696    }
12697
12698    /**
12699     * <p>Computes the coordinates of this view in its window. The argument
12700     * must be an array of two integers. After the method returns, the array
12701     * contains the x and y location in that order.</p>
12702     *
12703     * @param location an array of two integers in which to hold the coordinates
12704     */
12705    public void getLocationInWindow(int[] location) {
12706        if (location == null || location.length < 2) {
12707            throw new IllegalArgumentException("location must be an array of two integers");
12708        }
12709
12710        if (mAttachInfo == null) {
12711            // When the view is not attached to a window, this method does not make sense
12712            location[0] = location[1] = 0;
12713            return;
12714        }
12715
12716        float[] position = mAttachInfo.mTmpTransformLocation;
12717        position[0] = position[1] = 0.0f;
12718
12719        if (!hasIdentityMatrix()) {
12720            getMatrix().mapPoints(position);
12721        }
12722
12723        position[0] += mLeft;
12724        position[1] += mTop;
12725
12726        ViewParent viewParent = mParent;
12727        while (viewParent instanceof View) {
12728            final View view = (View) viewParent;
12729
12730            position[0] -= view.mScrollX;
12731            position[1] -= view.mScrollY;
12732
12733            if (!view.hasIdentityMatrix()) {
12734                view.getMatrix().mapPoints(position);
12735            }
12736
12737            position[0] += view.mLeft;
12738            position[1] += view.mTop;
12739
12740            viewParent = view.mParent;
12741        }
12742
12743        if (viewParent instanceof ViewRootImpl) {
12744            // *cough*
12745            final ViewRootImpl vr = (ViewRootImpl) viewParent;
12746            position[1] -= vr.mCurScrollY;
12747        }
12748
12749        location[0] = (int) (position[0] + 0.5f);
12750        location[1] = (int) (position[1] + 0.5f);
12751    }
12752
12753    /**
12754     * {@hide}
12755     * @param id the id of the view to be found
12756     * @return the view of the specified id, null if cannot be found
12757     */
12758    protected View findViewTraversal(int id) {
12759        if (id == mID) {
12760            return this;
12761        }
12762        return null;
12763    }
12764
12765    /**
12766     * {@hide}
12767     * @param tag the tag of the view to be found
12768     * @return the view of specified tag, null if cannot be found
12769     */
12770    protected View findViewWithTagTraversal(Object tag) {
12771        if (tag != null && tag.equals(mTag)) {
12772            return this;
12773        }
12774        return null;
12775    }
12776
12777    /**
12778     * {@hide}
12779     * @param predicate The predicate to evaluate.
12780     * @param childToSkip If not null, ignores this child during the recursive traversal.
12781     * @return The first view that matches the predicate or null.
12782     */
12783    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
12784        if (predicate.apply(this)) {
12785            return this;
12786        }
12787        return null;
12788    }
12789
12790    /**
12791     * Look for a child view with the given id.  If this view has the given
12792     * id, return this view.
12793     *
12794     * @param id The id to search for.
12795     * @return The view that has the given id in the hierarchy or null
12796     */
12797    public final View findViewById(int id) {
12798        if (id < 0) {
12799            return null;
12800        }
12801        return findViewTraversal(id);
12802    }
12803
12804    /**
12805     * Finds a view by its unuque and stable accessibility id.
12806     *
12807     * @param accessibilityId The searched accessibility id.
12808     * @return The found view.
12809     */
12810    final View findViewByAccessibilityId(int accessibilityId) {
12811        if (accessibilityId < 0) {
12812            return null;
12813        }
12814        return findViewByAccessibilityIdTraversal(accessibilityId);
12815    }
12816
12817    /**
12818     * Performs the traversal to find a view by its unuque and stable accessibility id.
12819     *
12820     * <strong>Note:</strong>This method does not stop at the root namespace
12821     * boundary since the user can touch the screen at an arbitrary location
12822     * potentially crossing the root namespace bounday which will send an
12823     * accessibility event to accessibility services and they should be able
12824     * to obtain the event source. Also accessibility ids are guaranteed to be
12825     * unique in the window.
12826     *
12827     * @param accessibilityId The accessibility id.
12828     * @return The found view.
12829     */
12830    View findViewByAccessibilityIdTraversal(int accessibilityId) {
12831        if (getAccessibilityViewId() == accessibilityId) {
12832            return this;
12833        }
12834        return null;
12835    }
12836
12837    /**
12838     * Look for a child view with the given tag.  If this view has the given
12839     * tag, return this view.
12840     *
12841     * @param tag The tag to search for, using "tag.equals(getTag())".
12842     * @return The View that has the given tag in the hierarchy or null
12843     */
12844    public final View findViewWithTag(Object tag) {
12845        if (tag == null) {
12846            return null;
12847        }
12848        return findViewWithTagTraversal(tag);
12849    }
12850
12851    /**
12852     * {@hide}
12853     * Look for a child view that matches the specified predicate.
12854     * If this view matches the predicate, return this view.
12855     *
12856     * @param predicate The predicate to evaluate.
12857     * @return The first view that matches the predicate or null.
12858     */
12859    public final View findViewByPredicate(Predicate<View> predicate) {
12860        return findViewByPredicateTraversal(predicate, null);
12861    }
12862
12863    /**
12864     * {@hide}
12865     * Look for a child view that matches the specified predicate,
12866     * starting with the specified view and its descendents and then
12867     * recusively searching the ancestors and siblings of that view
12868     * until this view is reached.
12869     *
12870     * This method is useful in cases where the predicate does not match
12871     * a single unique view (perhaps multiple views use the same id)
12872     * and we are trying to find the view that is "closest" in scope to the
12873     * starting view.
12874     *
12875     * @param start The view to start from.
12876     * @param predicate The predicate to evaluate.
12877     * @return The first view that matches the predicate or null.
12878     */
12879    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
12880        View childToSkip = null;
12881        for (;;) {
12882            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
12883            if (view != null || start == this) {
12884                return view;
12885            }
12886
12887            ViewParent parent = start.getParent();
12888            if (parent == null || !(parent instanceof View)) {
12889                return null;
12890            }
12891
12892            childToSkip = start;
12893            start = (View) parent;
12894        }
12895    }
12896
12897    /**
12898     * Sets the identifier for this view. The identifier does not have to be
12899     * unique in this view's hierarchy. The identifier should be a positive
12900     * number.
12901     *
12902     * @see #NO_ID
12903     * @see #getId()
12904     * @see #findViewById(int)
12905     *
12906     * @param id a number used to identify the view
12907     *
12908     * @attr ref android.R.styleable#View_id
12909     */
12910    public void setId(int id) {
12911        mID = id;
12912    }
12913
12914    /**
12915     * {@hide}
12916     *
12917     * @param isRoot true if the view belongs to the root namespace, false
12918     *        otherwise
12919     */
12920    public void setIsRootNamespace(boolean isRoot) {
12921        if (isRoot) {
12922            mPrivateFlags |= IS_ROOT_NAMESPACE;
12923        } else {
12924            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
12925        }
12926    }
12927
12928    /**
12929     * {@hide}
12930     *
12931     * @return true if the view belongs to the root namespace, false otherwise
12932     */
12933    public boolean isRootNamespace() {
12934        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
12935    }
12936
12937    /**
12938     * Returns this view's identifier.
12939     *
12940     * @return a positive integer used to identify the view or {@link #NO_ID}
12941     *         if the view has no ID
12942     *
12943     * @see #setId(int)
12944     * @see #findViewById(int)
12945     * @attr ref android.R.styleable#View_id
12946     */
12947    @ViewDebug.CapturedViewProperty
12948    public int getId() {
12949        return mID;
12950    }
12951
12952    /**
12953     * Returns this view's tag.
12954     *
12955     * @return the Object stored in this view as a tag
12956     *
12957     * @see #setTag(Object)
12958     * @see #getTag(int)
12959     */
12960    @ViewDebug.ExportedProperty
12961    public Object getTag() {
12962        return mTag;
12963    }
12964
12965    /**
12966     * Sets the tag associated with this view. A tag can be used to mark
12967     * a view in its hierarchy and does not have to be unique within the
12968     * hierarchy. Tags can also be used to store data within a view without
12969     * resorting to another data structure.
12970     *
12971     * @param tag an Object to tag the view with
12972     *
12973     * @see #getTag()
12974     * @see #setTag(int, Object)
12975     */
12976    public void setTag(final Object tag) {
12977        mTag = tag;
12978    }
12979
12980    /**
12981     * Returns the tag associated with this view and the specified key.
12982     *
12983     * @param key The key identifying the tag
12984     *
12985     * @return the Object stored in this view as a tag
12986     *
12987     * @see #setTag(int, Object)
12988     * @see #getTag()
12989     */
12990    public Object getTag(int key) {
12991        if (mKeyedTags != null) return mKeyedTags.get(key);
12992        return null;
12993    }
12994
12995    /**
12996     * Sets a tag associated with this view and a key. A tag can be used
12997     * to mark a view in its hierarchy and does not have to be unique within
12998     * the hierarchy. Tags can also be used to store data within a view
12999     * without resorting to another data structure.
13000     *
13001     * The specified key should be an id declared in the resources of the
13002     * application to ensure it is unique (see the <a
13003     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
13004     * Keys identified as belonging to
13005     * the Android framework or not associated with any package will cause
13006     * an {@link IllegalArgumentException} to be thrown.
13007     *
13008     * @param key The key identifying the tag
13009     * @param tag An Object to tag the view with
13010     *
13011     * @throws IllegalArgumentException If they specified key is not valid
13012     *
13013     * @see #setTag(Object)
13014     * @see #getTag(int)
13015     */
13016    public void setTag(int key, final Object tag) {
13017        // If the package id is 0x00 or 0x01, it's either an undefined package
13018        // or a framework id
13019        if ((key >>> 24) < 2) {
13020            throw new IllegalArgumentException("The key must be an application-specific "
13021                    + "resource id.");
13022        }
13023
13024        setKeyedTag(key, tag);
13025    }
13026
13027    /**
13028     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
13029     * framework id.
13030     *
13031     * @hide
13032     */
13033    public void setTagInternal(int key, Object tag) {
13034        if ((key >>> 24) != 0x1) {
13035            throw new IllegalArgumentException("The key must be a framework-specific "
13036                    + "resource id.");
13037        }
13038
13039        setKeyedTag(key, tag);
13040    }
13041
13042    private void setKeyedTag(int key, Object tag) {
13043        if (mKeyedTags == null) {
13044            mKeyedTags = new SparseArray<Object>();
13045        }
13046
13047        mKeyedTags.put(key, tag);
13048    }
13049
13050    /**
13051     * @param consistency The type of consistency. See ViewDebug for more information.
13052     *
13053     * @hide
13054     */
13055    protected boolean dispatchConsistencyCheck(int consistency) {
13056        return onConsistencyCheck(consistency);
13057    }
13058
13059    /**
13060     * Method that subclasses should implement to check their consistency. The type of
13061     * consistency check is indicated by the bit field passed as a parameter.
13062     *
13063     * @param consistency The type of consistency. See ViewDebug for more information.
13064     *
13065     * @throws IllegalStateException if the view is in an inconsistent state.
13066     *
13067     * @hide
13068     */
13069    protected boolean onConsistencyCheck(int consistency) {
13070        boolean result = true;
13071
13072        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
13073        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
13074
13075        if (checkLayout) {
13076            if (getParent() == null) {
13077                result = false;
13078                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13079                        "View " + this + " does not have a parent.");
13080            }
13081
13082            if (mAttachInfo == null) {
13083                result = false;
13084                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13085                        "View " + this + " is not attached to a window.");
13086            }
13087        }
13088
13089        if (checkDrawing) {
13090            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
13091            // from their draw() method
13092
13093            if ((mPrivateFlags & DRAWN) != DRAWN &&
13094                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
13095                result = false;
13096                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13097                        "View " + this + " was invalidated but its drawing cache is valid.");
13098            }
13099        }
13100
13101        return result;
13102    }
13103
13104    /**
13105     * Prints information about this view in the log output, with the tag
13106     * {@link #VIEW_LOG_TAG}.
13107     *
13108     * @hide
13109     */
13110    public void debug() {
13111        debug(0);
13112    }
13113
13114    /**
13115     * Prints information about this view in the log output, with the tag
13116     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
13117     * indentation defined by the <code>depth</code>.
13118     *
13119     * @param depth the indentation level
13120     *
13121     * @hide
13122     */
13123    protected void debug(int depth) {
13124        String output = debugIndent(depth - 1);
13125
13126        output += "+ " + this;
13127        int id = getId();
13128        if (id != -1) {
13129            output += " (id=" + id + ")";
13130        }
13131        Object tag = getTag();
13132        if (tag != null) {
13133            output += " (tag=" + tag + ")";
13134        }
13135        Log.d(VIEW_LOG_TAG, output);
13136
13137        if ((mPrivateFlags & FOCUSED) != 0) {
13138            output = debugIndent(depth) + " FOCUSED";
13139            Log.d(VIEW_LOG_TAG, output);
13140        }
13141
13142        output = debugIndent(depth);
13143        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
13144                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
13145                + "} ";
13146        Log.d(VIEW_LOG_TAG, output);
13147
13148        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
13149                || mPaddingBottom != 0) {
13150            output = debugIndent(depth);
13151            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
13152                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
13153            Log.d(VIEW_LOG_TAG, output);
13154        }
13155
13156        output = debugIndent(depth);
13157        output += "mMeasureWidth=" + mMeasuredWidth +
13158                " mMeasureHeight=" + mMeasuredHeight;
13159        Log.d(VIEW_LOG_TAG, output);
13160
13161        output = debugIndent(depth);
13162        if (mLayoutParams == null) {
13163            output += "BAD! no layout params";
13164        } else {
13165            output = mLayoutParams.debug(output);
13166        }
13167        Log.d(VIEW_LOG_TAG, output);
13168
13169        output = debugIndent(depth);
13170        output += "flags={";
13171        output += View.printFlags(mViewFlags);
13172        output += "}";
13173        Log.d(VIEW_LOG_TAG, output);
13174
13175        output = debugIndent(depth);
13176        output += "privateFlags={";
13177        output += View.printPrivateFlags(mPrivateFlags);
13178        output += "}";
13179        Log.d(VIEW_LOG_TAG, output);
13180    }
13181
13182    /**
13183     * Creates a string of whitespaces used for indentation.
13184     *
13185     * @param depth the indentation level
13186     * @return a String containing (depth * 2 + 3) * 2 white spaces
13187     *
13188     * @hide
13189     */
13190    protected static String debugIndent(int depth) {
13191        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
13192        for (int i = 0; i < (depth * 2) + 3; i++) {
13193            spaces.append(' ').append(' ');
13194        }
13195        return spaces.toString();
13196    }
13197
13198    /**
13199     * <p>Return the offset of the widget's text baseline from the widget's top
13200     * boundary. If this widget does not support baseline alignment, this
13201     * method returns -1. </p>
13202     *
13203     * @return the offset of the baseline within the widget's bounds or -1
13204     *         if baseline alignment is not supported
13205     */
13206    @ViewDebug.ExportedProperty(category = "layout")
13207    public int getBaseline() {
13208        return -1;
13209    }
13210
13211    /**
13212     * Call this when something has changed which has invalidated the
13213     * layout of this view. This will schedule a layout pass of the view
13214     * tree.
13215     */
13216    public void requestLayout() {
13217        if (ViewDebug.TRACE_HIERARCHY) {
13218            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
13219        }
13220
13221        mPrivateFlags |= FORCE_LAYOUT;
13222        mPrivateFlags |= INVALIDATED;
13223
13224        if (mParent != null) {
13225            if (mLayoutParams != null) {
13226                mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
13227            }
13228            if (!mParent.isLayoutRequested()) {
13229                mParent.requestLayout();
13230            }
13231        }
13232    }
13233
13234    /**
13235     * Forces this view to be laid out during the next layout pass.
13236     * This method does not call requestLayout() or forceLayout()
13237     * on the parent.
13238     */
13239    public void forceLayout() {
13240        mPrivateFlags |= FORCE_LAYOUT;
13241        mPrivateFlags |= INVALIDATED;
13242    }
13243
13244    /**
13245     * <p>
13246     * This is called to find out how big a view should be. The parent
13247     * supplies constraint information in the width and height parameters.
13248     * </p>
13249     *
13250     * <p>
13251     * The actual measurement work of a view is performed in
13252     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
13253     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
13254     * </p>
13255     *
13256     *
13257     * @param widthMeasureSpec Horizontal space requirements as imposed by the
13258     *        parent
13259     * @param heightMeasureSpec Vertical space requirements as imposed by the
13260     *        parent
13261     *
13262     * @see #onMeasure(int, int)
13263     */
13264    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
13265        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
13266                widthMeasureSpec != mOldWidthMeasureSpec ||
13267                heightMeasureSpec != mOldHeightMeasureSpec) {
13268
13269            // first clears the measured dimension flag
13270            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
13271
13272            if (ViewDebug.TRACE_HIERARCHY) {
13273                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
13274            }
13275
13276            // measure ourselves, this should set the measured dimension flag back
13277            onMeasure(widthMeasureSpec, heightMeasureSpec);
13278
13279            // flag not set, setMeasuredDimension() was not invoked, we raise
13280            // an exception to warn the developer
13281            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
13282                throw new IllegalStateException("onMeasure() did not set the"
13283                        + " measured dimension by calling"
13284                        + " setMeasuredDimension()");
13285            }
13286
13287            mPrivateFlags |= LAYOUT_REQUIRED;
13288        }
13289
13290        mOldWidthMeasureSpec = widthMeasureSpec;
13291        mOldHeightMeasureSpec = heightMeasureSpec;
13292    }
13293
13294    /**
13295     * <p>
13296     * Measure the view and its content to determine the measured width and the
13297     * measured height. This method is invoked by {@link #measure(int, int)} and
13298     * should be overriden by subclasses to provide accurate and efficient
13299     * measurement of their contents.
13300     * </p>
13301     *
13302     * <p>
13303     * <strong>CONTRACT:</strong> When overriding this method, you
13304     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
13305     * measured width and height of this view. Failure to do so will trigger an
13306     * <code>IllegalStateException</code>, thrown by
13307     * {@link #measure(int, int)}. Calling the superclass'
13308     * {@link #onMeasure(int, int)} is a valid use.
13309     * </p>
13310     *
13311     * <p>
13312     * The base class implementation of measure defaults to the background size,
13313     * unless a larger size is allowed by the MeasureSpec. Subclasses should
13314     * override {@link #onMeasure(int, int)} to provide better measurements of
13315     * their content.
13316     * </p>
13317     *
13318     * <p>
13319     * If this method is overridden, it is the subclass's responsibility to make
13320     * sure the measured height and width are at least the view's minimum height
13321     * and width ({@link #getSuggestedMinimumHeight()} and
13322     * {@link #getSuggestedMinimumWidth()}).
13323     * </p>
13324     *
13325     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
13326     *                         The requirements are encoded with
13327     *                         {@link android.view.View.MeasureSpec}.
13328     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
13329     *                         The requirements are encoded with
13330     *                         {@link android.view.View.MeasureSpec}.
13331     *
13332     * @see #getMeasuredWidth()
13333     * @see #getMeasuredHeight()
13334     * @see #setMeasuredDimension(int, int)
13335     * @see #getSuggestedMinimumHeight()
13336     * @see #getSuggestedMinimumWidth()
13337     * @see android.view.View.MeasureSpec#getMode(int)
13338     * @see android.view.View.MeasureSpec#getSize(int)
13339     */
13340    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
13341        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
13342                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
13343    }
13344
13345    /**
13346     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
13347     * measured width and measured height. Failing to do so will trigger an
13348     * exception at measurement time.</p>
13349     *
13350     * @param measuredWidth The measured width of this view.  May be a complex
13351     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13352     * {@link #MEASURED_STATE_TOO_SMALL}.
13353     * @param measuredHeight The measured height of this view.  May be a complex
13354     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13355     * {@link #MEASURED_STATE_TOO_SMALL}.
13356     */
13357    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
13358        mMeasuredWidth = measuredWidth;
13359        mMeasuredHeight = measuredHeight;
13360
13361        mPrivateFlags |= MEASURED_DIMENSION_SET;
13362    }
13363
13364    /**
13365     * Merge two states as returned by {@link #getMeasuredState()}.
13366     * @param curState The current state as returned from a view or the result
13367     * of combining multiple views.
13368     * @param newState The new view state to combine.
13369     * @return Returns a new integer reflecting the combination of the two
13370     * states.
13371     */
13372    public static int combineMeasuredStates(int curState, int newState) {
13373        return curState | newState;
13374    }
13375
13376    /**
13377     * Version of {@link #resolveSizeAndState(int, int, int)}
13378     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
13379     */
13380    public static int resolveSize(int size, int measureSpec) {
13381        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
13382    }
13383
13384    /**
13385     * Utility to reconcile a desired size and state, with constraints imposed
13386     * by a MeasureSpec.  Will take the desired size, unless a different size
13387     * is imposed by the constraints.  The returned value is a compound integer,
13388     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
13389     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
13390     * size is smaller than the size the view wants to be.
13391     *
13392     * @param size How big the view wants to be
13393     * @param measureSpec Constraints imposed by the parent
13394     * @return Size information bit mask as defined by
13395     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13396     */
13397    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
13398        int result = size;
13399        int specMode = MeasureSpec.getMode(measureSpec);
13400        int specSize =  MeasureSpec.getSize(measureSpec);
13401        switch (specMode) {
13402        case MeasureSpec.UNSPECIFIED:
13403            result = size;
13404            break;
13405        case MeasureSpec.AT_MOST:
13406            if (specSize < size) {
13407                result = specSize | MEASURED_STATE_TOO_SMALL;
13408            } else {
13409                result = size;
13410            }
13411            break;
13412        case MeasureSpec.EXACTLY:
13413            result = specSize;
13414            break;
13415        }
13416        return result | (childMeasuredState&MEASURED_STATE_MASK);
13417    }
13418
13419    /**
13420     * Utility to return a default size. Uses the supplied size if the
13421     * MeasureSpec imposed no constraints. Will get larger if allowed
13422     * by the MeasureSpec.
13423     *
13424     * @param size Default size for this view
13425     * @param measureSpec Constraints imposed by the parent
13426     * @return The size this view should be.
13427     */
13428    public static int getDefaultSize(int size, int measureSpec) {
13429        int result = size;
13430        int specMode = MeasureSpec.getMode(measureSpec);
13431        int specSize = MeasureSpec.getSize(measureSpec);
13432
13433        switch (specMode) {
13434        case MeasureSpec.UNSPECIFIED:
13435            result = size;
13436            break;
13437        case MeasureSpec.AT_MOST:
13438        case MeasureSpec.EXACTLY:
13439            result = specSize;
13440            break;
13441        }
13442        return result;
13443    }
13444
13445    /**
13446     * Returns the suggested minimum height that the view should use. This
13447     * returns the maximum of the view's minimum height
13448     * and the background's minimum height
13449     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
13450     * <p>
13451     * When being used in {@link #onMeasure(int, int)}, the caller should still
13452     * ensure the returned height is within the requirements of the parent.
13453     *
13454     * @return The suggested minimum height of the view.
13455     */
13456    protected int getSuggestedMinimumHeight() {
13457        int suggestedMinHeight = mMinHeight;
13458
13459        if (mBGDrawable != null) {
13460            final int bgMinHeight = mBGDrawable.getMinimumHeight();
13461            if (suggestedMinHeight < bgMinHeight) {
13462                suggestedMinHeight = bgMinHeight;
13463            }
13464        }
13465
13466        return suggestedMinHeight;
13467    }
13468
13469    /**
13470     * Returns the suggested minimum width that the view should use. This
13471     * returns the maximum of the view's minimum width)
13472     * and the background's minimum width
13473     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
13474     * <p>
13475     * When being used in {@link #onMeasure(int, int)}, the caller should still
13476     * ensure the returned width is within the requirements of the parent.
13477     *
13478     * @return The suggested minimum width of the view.
13479     */
13480    protected int getSuggestedMinimumWidth() {
13481        int suggestedMinWidth = mMinWidth;
13482
13483        if (mBGDrawable != null) {
13484            final int bgMinWidth = mBGDrawable.getMinimumWidth();
13485            if (suggestedMinWidth < bgMinWidth) {
13486                suggestedMinWidth = bgMinWidth;
13487            }
13488        }
13489
13490        return suggestedMinWidth;
13491    }
13492
13493    /**
13494     * Sets the minimum height of the view. It is not guaranteed the view will
13495     * be able to achieve this minimum height (for example, if its parent layout
13496     * constrains it with less available height).
13497     *
13498     * @param minHeight The minimum height the view will try to be.
13499     */
13500    public void setMinimumHeight(int minHeight) {
13501        mMinHeight = minHeight;
13502    }
13503
13504    /**
13505     * Sets the minimum width of the view. It is not guaranteed the view will
13506     * be able to achieve this minimum width (for example, if its parent layout
13507     * constrains it with less available width).
13508     *
13509     * @param minWidth The minimum width the view will try to be.
13510     */
13511    public void setMinimumWidth(int minWidth) {
13512        mMinWidth = minWidth;
13513    }
13514
13515    /**
13516     * Get the animation currently associated with this view.
13517     *
13518     * @return The animation that is currently playing or
13519     *         scheduled to play for this view.
13520     */
13521    public Animation getAnimation() {
13522        return mCurrentAnimation;
13523    }
13524
13525    /**
13526     * Start the specified animation now.
13527     *
13528     * @param animation the animation to start now
13529     */
13530    public void startAnimation(Animation animation) {
13531        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
13532        setAnimation(animation);
13533        invalidateParentCaches();
13534        invalidate(true);
13535    }
13536
13537    /**
13538     * Cancels any animations for this view.
13539     */
13540    public void clearAnimation() {
13541        if (mCurrentAnimation != null) {
13542            mCurrentAnimation.detach();
13543        }
13544        mCurrentAnimation = null;
13545        invalidateParentIfNeeded();
13546    }
13547
13548    /**
13549     * Sets the next animation to play for this view.
13550     * If you want the animation to play immediately, use
13551     * startAnimation. This method provides allows fine-grained
13552     * control over the start time and invalidation, but you
13553     * must make sure that 1) the animation has a start time set, and
13554     * 2) the view will be invalidated when the animation is supposed to
13555     * start.
13556     *
13557     * @param animation The next animation, or null.
13558     */
13559    public void setAnimation(Animation animation) {
13560        mCurrentAnimation = animation;
13561        if (animation != null) {
13562            animation.reset();
13563        }
13564    }
13565
13566    /**
13567     * Invoked by a parent ViewGroup to notify the start of the animation
13568     * currently associated with this view. If you override this method,
13569     * always call super.onAnimationStart();
13570     *
13571     * @see #setAnimation(android.view.animation.Animation)
13572     * @see #getAnimation()
13573     */
13574    protected void onAnimationStart() {
13575        mPrivateFlags |= ANIMATION_STARTED;
13576    }
13577
13578    /**
13579     * Invoked by a parent ViewGroup to notify the end of the animation
13580     * currently associated with this view. If you override this method,
13581     * always call super.onAnimationEnd();
13582     *
13583     * @see #setAnimation(android.view.animation.Animation)
13584     * @see #getAnimation()
13585     */
13586    protected void onAnimationEnd() {
13587        mPrivateFlags &= ~ANIMATION_STARTED;
13588    }
13589
13590    /**
13591     * Invoked if there is a Transform that involves alpha. Subclass that can
13592     * draw themselves with the specified alpha should return true, and then
13593     * respect that alpha when their onDraw() is called. If this returns false
13594     * then the view may be redirected to draw into an offscreen buffer to
13595     * fulfill the request, which will look fine, but may be slower than if the
13596     * subclass handles it internally. The default implementation returns false.
13597     *
13598     * @param alpha The alpha (0..255) to apply to the view's drawing
13599     * @return true if the view can draw with the specified alpha.
13600     */
13601    protected boolean onSetAlpha(int alpha) {
13602        return false;
13603    }
13604
13605    /**
13606     * This is used by the RootView to perform an optimization when
13607     * the view hierarchy contains one or several SurfaceView.
13608     * SurfaceView is always considered transparent, but its children are not,
13609     * therefore all View objects remove themselves from the global transparent
13610     * region (passed as a parameter to this function).
13611     *
13612     * @param region The transparent region for this ViewAncestor (window).
13613     *
13614     * @return Returns true if the effective visibility of the view at this
13615     * point is opaque, regardless of the transparent region; returns false
13616     * if it is possible for underlying windows to be seen behind the view.
13617     *
13618     * {@hide}
13619     */
13620    public boolean gatherTransparentRegion(Region region) {
13621        final AttachInfo attachInfo = mAttachInfo;
13622        if (region != null && attachInfo != null) {
13623            final int pflags = mPrivateFlags;
13624            if ((pflags & SKIP_DRAW) == 0) {
13625                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
13626                // remove it from the transparent region.
13627                final int[] location = attachInfo.mTransparentLocation;
13628                getLocationInWindow(location);
13629                region.op(location[0], location[1], location[0] + mRight - mLeft,
13630                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
13631            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
13632                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
13633                // exists, so we remove the background drawable's non-transparent
13634                // parts from this transparent region.
13635                applyDrawableToTransparentRegion(mBGDrawable, region);
13636            }
13637        }
13638        return true;
13639    }
13640
13641    /**
13642     * Play a sound effect for this view.
13643     *
13644     * <p>The framework will play sound effects for some built in actions, such as
13645     * clicking, but you may wish to play these effects in your widget,
13646     * for instance, for internal navigation.
13647     *
13648     * <p>The sound effect will only be played if sound effects are enabled by the user, and
13649     * {@link #isSoundEffectsEnabled()} is true.
13650     *
13651     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
13652     */
13653    public void playSoundEffect(int soundConstant) {
13654        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
13655            return;
13656        }
13657        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
13658    }
13659
13660    /**
13661     * BZZZTT!!1!
13662     *
13663     * <p>Provide haptic feedback to the user for this view.
13664     *
13665     * <p>The framework will provide haptic feedback for some built in actions,
13666     * such as long presses, but you may wish to provide feedback for your
13667     * own widget.
13668     *
13669     * <p>The feedback will only be performed if
13670     * {@link #isHapticFeedbackEnabled()} is true.
13671     *
13672     * @param feedbackConstant One of the constants defined in
13673     * {@link HapticFeedbackConstants}
13674     */
13675    public boolean performHapticFeedback(int feedbackConstant) {
13676        return performHapticFeedback(feedbackConstant, 0);
13677    }
13678
13679    /**
13680     * BZZZTT!!1!
13681     *
13682     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
13683     *
13684     * @param feedbackConstant One of the constants defined in
13685     * {@link HapticFeedbackConstants}
13686     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
13687     */
13688    public boolean performHapticFeedback(int feedbackConstant, int flags) {
13689        if (mAttachInfo == null) {
13690            return false;
13691        }
13692        //noinspection SimplifiableIfStatement
13693        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
13694                && !isHapticFeedbackEnabled()) {
13695            return false;
13696        }
13697        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
13698                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
13699    }
13700
13701    /**
13702     * Request that the visibility of the status bar be changed.
13703     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13704     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13705     */
13706    public void setSystemUiVisibility(int visibility) {
13707        if (visibility != mSystemUiVisibility) {
13708            mSystemUiVisibility = visibility;
13709            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13710                mParent.recomputeViewAttributes(this);
13711            }
13712        }
13713    }
13714
13715    /**
13716     * Returns the status bar visibility that this view has requested.
13717     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13718     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13719     */
13720    public int getSystemUiVisibility() {
13721        return mSystemUiVisibility;
13722    }
13723
13724    /**
13725     * Set a listener to receive callbacks when the visibility of the system bar changes.
13726     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
13727     */
13728    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
13729        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
13730        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13731            mParent.recomputeViewAttributes(this);
13732        }
13733    }
13734
13735    /**
13736     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
13737     * the view hierarchy.
13738     */
13739    public void dispatchSystemUiVisibilityChanged(int visibility) {
13740        ListenerInfo li = mListenerInfo;
13741        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
13742            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
13743                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
13744        }
13745    }
13746
13747    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
13748        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
13749        if (val != mSystemUiVisibility) {
13750            setSystemUiVisibility(val);
13751        }
13752    }
13753
13754    /**
13755     * Creates an image that the system displays during the drag and drop
13756     * operation. This is called a &quot;drag shadow&quot;. The default implementation
13757     * for a DragShadowBuilder based on a View returns an image that has exactly the same
13758     * appearance as the given View. The default also positions the center of the drag shadow
13759     * directly under the touch point. If no View is provided (the constructor with no parameters
13760     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13761     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13762     * default is an invisible drag shadow.
13763     * <p>
13764     * You are not required to use the View you provide to the constructor as the basis of the
13765     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13766     * anything you want as the drag shadow.
13767     * </p>
13768     * <p>
13769     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13770     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13771     *  size and position of the drag shadow. It uses this data to construct a
13772     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13773     *  so that your application can draw the shadow image in the Canvas.
13774     * </p>
13775     *
13776     * <div class="special reference">
13777     * <h3>Developer Guides</h3>
13778     * <p>For a guide to implementing drag and drop features, read the
13779     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
13780     * </div>
13781     */
13782    public static class DragShadowBuilder {
13783        private final WeakReference<View> mView;
13784
13785        /**
13786         * Constructs a shadow image builder based on a View. By default, the resulting drag
13787         * shadow will have the same appearance and dimensions as the View, with the touch point
13788         * over the center of the View.
13789         * @param view A View. Any View in scope can be used.
13790         */
13791        public DragShadowBuilder(View view) {
13792            mView = new WeakReference<View>(view);
13793        }
13794
13795        /**
13796         * Construct a shadow builder object with no associated View.  This
13797         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
13798         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
13799         * to supply the drag shadow's dimensions and appearance without
13800         * reference to any View object. If they are not overridden, then the result is an
13801         * invisible drag shadow.
13802         */
13803        public DragShadowBuilder() {
13804            mView = new WeakReference<View>(null);
13805        }
13806
13807        /**
13808         * Returns the View object that had been passed to the
13809         * {@link #View.DragShadowBuilder(View)}
13810         * constructor.  If that View parameter was {@code null} or if the
13811         * {@link #View.DragShadowBuilder()}
13812         * constructor was used to instantiate the builder object, this method will return
13813         * null.
13814         *
13815         * @return The View object associate with this builder object.
13816         */
13817        @SuppressWarnings({"JavadocReference"})
13818        final public View getView() {
13819            return mView.get();
13820        }
13821
13822        /**
13823         * Provides the metrics for the shadow image. These include the dimensions of
13824         * the shadow image, and the point within that shadow that should
13825         * be centered under the touch location while dragging.
13826         * <p>
13827         * The default implementation sets the dimensions of the shadow to be the
13828         * same as the dimensions of the View itself and centers the shadow under
13829         * the touch point.
13830         * </p>
13831         *
13832         * @param shadowSize A {@link android.graphics.Point} containing the width and height
13833         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
13834         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
13835         * image.
13836         *
13837         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
13838         * shadow image that should be underneath the touch point during the drag and drop
13839         * operation. Your application must set {@link android.graphics.Point#x} to the
13840         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
13841         */
13842        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
13843            final View view = mView.get();
13844            if (view != null) {
13845                shadowSize.set(view.getWidth(), view.getHeight());
13846                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
13847            } else {
13848                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
13849            }
13850        }
13851
13852        /**
13853         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
13854         * based on the dimensions it received from the
13855         * {@link #onProvideShadowMetrics(Point, Point)} callback.
13856         *
13857         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
13858         */
13859        public void onDrawShadow(Canvas canvas) {
13860            final View view = mView.get();
13861            if (view != null) {
13862                view.draw(canvas);
13863            } else {
13864                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
13865            }
13866        }
13867    }
13868
13869    /**
13870     * Starts a drag and drop operation. When your application calls this method, it passes a
13871     * {@link android.view.View.DragShadowBuilder} object to the system. The
13872     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
13873     * to get metrics for the drag shadow, and then calls the object's
13874     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
13875     * <p>
13876     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
13877     *  drag events to all the View objects in your application that are currently visible. It does
13878     *  this either by calling the View object's drag listener (an implementation of
13879     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
13880     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
13881     *  Both are passed a {@link android.view.DragEvent} object that has a
13882     *  {@link android.view.DragEvent#getAction()} value of
13883     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
13884     * </p>
13885     * <p>
13886     * Your application can invoke startDrag() on any attached View object. The View object does not
13887     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
13888     * be related to the View the user selected for dragging.
13889     * </p>
13890     * @param data A {@link android.content.ClipData} object pointing to the data to be
13891     * transferred by the drag and drop operation.
13892     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
13893     * drag shadow.
13894     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
13895     * drop operation. This Object is put into every DragEvent object sent by the system during the
13896     * current drag.
13897     * <p>
13898     * myLocalState is a lightweight mechanism for the sending information from the dragged View
13899     * to the target Views. For example, it can contain flags that differentiate between a
13900     * a copy operation and a move operation.
13901     * </p>
13902     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
13903     * so the parameter should be set to 0.
13904     * @return {@code true} if the method completes successfully, or
13905     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
13906     * do a drag, and so no drag operation is in progress.
13907     */
13908    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
13909            Object myLocalState, int flags) {
13910        if (ViewDebug.DEBUG_DRAG) {
13911            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
13912        }
13913        boolean okay = false;
13914
13915        Point shadowSize = new Point();
13916        Point shadowTouchPoint = new Point();
13917        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
13918
13919        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
13920                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
13921            throw new IllegalStateException("Drag shadow dimensions must not be negative");
13922        }
13923
13924        if (ViewDebug.DEBUG_DRAG) {
13925            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
13926                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
13927        }
13928        Surface surface = new Surface();
13929        try {
13930            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
13931                    flags, shadowSize.x, shadowSize.y, surface);
13932            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
13933                    + " surface=" + surface);
13934            if (token != null) {
13935                Canvas canvas = surface.lockCanvas(null);
13936                try {
13937                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
13938                    shadowBuilder.onDrawShadow(canvas);
13939                } finally {
13940                    surface.unlockCanvasAndPost(canvas);
13941                }
13942
13943                final ViewRootImpl root = getViewRootImpl();
13944
13945                // Cache the local state object for delivery with DragEvents
13946                root.setLocalDragState(myLocalState);
13947
13948                // repurpose 'shadowSize' for the last touch point
13949                root.getLastTouchPoint(shadowSize);
13950
13951                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
13952                        shadowSize.x, shadowSize.y,
13953                        shadowTouchPoint.x, shadowTouchPoint.y, data);
13954                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
13955
13956                // Off and running!  Release our local surface instance; the drag
13957                // shadow surface is now managed by the system process.
13958                surface.release();
13959            }
13960        } catch (Exception e) {
13961            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
13962            surface.destroy();
13963        }
13964
13965        return okay;
13966    }
13967
13968    /**
13969     * Handles drag events sent by the system following a call to
13970     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
13971     *<p>
13972     * When the system calls this method, it passes a
13973     * {@link android.view.DragEvent} object. A call to
13974     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
13975     * in DragEvent. The method uses these to determine what is happening in the drag and drop
13976     * operation.
13977     * @param event The {@link android.view.DragEvent} sent by the system.
13978     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
13979     * in DragEvent, indicating the type of drag event represented by this object.
13980     * @return {@code true} if the method was successful, otherwise {@code false}.
13981     * <p>
13982     *  The method should return {@code true} in response to an action type of
13983     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
13984     *  operation.
13985     * </p>
13986     * <p>
13987     *  The method should also return {@code true} in response to an action type of
13988     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
13989     *  {@code false} if it didn't.
13990     * </p>
13991     */
13992    public boolean onDragEvent(DragEvent event) {
13993        return false;
13994    }
13995
13996    /**
13997     * Detects if this View is enabled and has a drag event listener.
13998     * If both are true, then it calls the drag event listener with the
13999     * {@link android.view.DragEvent} it received. If the drag event listener returns
14000     * {@code true}, then dispatchDragEvent() returns {@code true}.
14001     * <p>
14002     * For all other cases, the method calls the
14003     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
14004     * method and returns its result.
14005     * </p>
14006     * <p>
14007     * This ensures that a drag event is always consumed, even if the View does not have a drag
14008     * event listener. However, if the View has a listener and the listener returns true, then
14009     * onDragEvent() is not called.
14010     * </p>
14011     */
14012    public boolean dispatchDragEvent(DragEvent event) {
14013        //noinspection SimplifiableIfStatement
14014        ListenerInfo li = mListenerInfo;
14015        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
14016                && li.mOnDragListener.onDrag(this, event)) {
14017            return true;
14018        }
14019        return onDragEvent(event);
14020    }
14021
14022    boolean canAcceptDrag() {
14023        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
14024    }
14025
14026    /**
14027     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
14028     * it is ever exposed at all.
14029     * @hide
14030     */
14031    public void onCloseSystemDialogs(String reason) {
14032    }
14033
14034    /**
14035     * Given a Drawable whose bounds have been set to draw into this view,
14036     * update a Region being computed for
14037     * {@link #gatherTransparentRegion(android.graphics.Region)} so
14038     * that any non-transparent parts of the Drawable are removed from the
14039     * given transparent region.
14040     *
14041     * @param dr The Drawable whose transparency is to be applied to the region.
14042     * @param region A Region holding the current transparency information,
14043     * where any parts of the region that are set are considered to be
14044     * transparent.  On return, this region will be modified to have the
14045     * transparency information reduced by the corresponding parts of the
14046     * Drawable that are not transparent.
14047     * {@hide}
14048     */
14049    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
14050        if (DBG) {
14051            Log.i("View", "Getting transparent region for: " + this);
14052        }
14053        final Region r = dr.getTransparentRegion();
14054        final Rect db = dr.getBounds();
14055        final AttachInfo attachInfo = mAttachInfo;
14056        if (r != null && attachInfo != null) {
14057            final int w = getRight()-getLeft();
14058            final int h = getBottom()-getTop();
14059            if (db.left > 0) {
14060                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
14061                r.op(0, 0, db.left, h, Region.Op.UNION);
14062            }
14063            if (db.right < w) {
14064                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
14065                r.op(db.right, 0, w, h, Region.Op.UNION);
14066            }
14067            if (db.top > 0) {
14068                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
14069                r.op(0, 0, w, db.top, Region.Op.UNION);
14070            }
14071            if (db.bottom < h) {
14072                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
14073                r.op(0, db.bottom, w, h, Region.Op.UNION);
14074            }
14075            final int[] location = attachInfo.mTransparentLocation;
14076            getLocationInWindow(location);
14077            r.translate(location[0], location[1]);
14078            region.op(r, Region.Op.INTERSECT);
14079        } else {
14080            region.op(db, Region.Op.DIFFERENCE);
14081        }
14082    }
14083
14084    private void checkForLongClick(int delayOffset) {
14085        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
14086            mHasPerformedLongPress = false;
14087
14088            if (mPendingCheckForLongPress == null) {
14089                mPendingCheckForLongPress = new CheckForLongPress();
14090            }
14091            mPendingCheckForLongPress.rememberWindowAttachCount();
14092            postDelayed(mPendingCheckForLongPress,
14093                    ViewConfiguration.getLongPressTimeout() - delayOffset);
14094        }
14095    }
14096
14097    /**
14098     * Inflate a view from an XML resource.  This convenience method wraps the {@link
14099     * LayoutInflater} class, which provides a full range of options for view inflation.
14100     *
14101     * @param context The Context object for your activity or application.
14102     * @param resource The resource ID to inflate
14103     * @param root A view group that will be the parent.  Used to properly inflate the
14104     * layout_* parameters.
14105     * @see LayoutInflater
14106     */
14107    public static View inflate(Context context, int resource, ViewGroup root) {
14108        LayoutInflater factory = LayoutInflater.from(context);
14109        return factory.inflate(resource, root);
14110    }
14111
14112    /**
14113     * Scroll the view with standard behavior for scrolling beyond the normal
14114     * content boundaries. Views that call this method should override
14115     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
14116     * results of an over-scroll operation.
14117     *
14118     * Views can use this method to handle any touch or fling-based scrolling.
14119     *
14120     * @param deltaX Change in X in pixels
14121     * @param deltaY Change in Y in pixels
14122     * @param scrollX Current X scroll value in pixels before applying deltaX
14123     * @param scrollY Current Y scroll value in pixels before applying deltaY
14124     * @param scrollRangeX Maximum content scroll range along the X axis
14125     * @param scrollRangeY Maximum content scroll range along the Y axis
14126     * @param maxOverScrollX Number of pixels to overscroll by in either direction
14127     *          along the X axis.
14128     * @param maxOverScrollY Number of pixels to overscroll by in either direction
14129     *          along the Y axis.
14130     * @param isTouchEvent true if this scroll operation is the result of a touch event.
14131     * @return true if scrolling was clamped to an over-scroll boundary along either
14132     *          axis, false otherwise.
14133     */
14134    @SuppressWarnings({"UnusedParameters"})
14135    protected boolean overScrollBy(int deltaX, int deltaY,
14136            int scrollX, int scrollY,
14137            int scrollRangeX, int scrollRangeY,
14138            int maxOverScrollX, int maxOverScrollY,
14139            boolean isTouchEvent) {
14140        final int overScrollMode = mOverScrollMode;
14141        final boolean canScrollHorizontal =
14142                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
14143        final boolean canScrollVertical =
14144                computeVerticalScrollRange() > computeVerticalScrollExtent();
14145        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
14146                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
14147        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
14148                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
14149
14150        int newScrollX = scrollX + deltaX;
14151        if (!overScrollHorizontal) {
14152            maxOverScrollX = 0;
14153        }
14154
14155        int newScrollY = scrollY + deltaY;
14156        if (!overScrollVertical) {
14157            maxOverScrollY = 0;
14158        }
14159
14160        // Clamp values if at the limits and record
14161        final int left = -maxOverScrollX;
14162        final int right = maxOverScrollX + scrollRangeX;
14163        final int top = -maxOverScrollY;
14164        final int bottom = maxOverScrollY + scrollRangeY;
14165
14166        boolean clampedX = false;
14167        if (newScrollX > right) {
14168            newScrollX = right;
14169            clampedX = true;
14170        } else if (newScrollX < left) {
14171            newScrollX = left;
14172            clampedX = true;
14173        }
14174
14175        boolean clampedY = false;
14176        if (newScrollY > bottom) {
14177            newScrollY = bottom;
14178            clampedY = true;
14179        } else if (newScrollY < top) {
14180            newScrollY = top;
14181            clampedY = true;
14182        }
14183
14184        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
14185
14186        return clampedX || clampedY;
14187    }
14188
14189    /**
14190     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
14191     * respond to the results of an over-scroll operation.
14192     *
14193     * @param scrollX New X scroll value in pixels
14194     * @param scrollY New Y scroll value in pixels
14195     * @param clampedX True if scrollX was clamped to an over-scroll boundary
14196     * @param clampedY True if scrollY was clamped to an over-scroll boundary
14197     */
14198    protected void onOverScrolled(int scrollX, int scrollY,
14199            boolean clampedX, boolean clampedY) {
14200        // Intentionally empty.
14201    }
14202
14203    /**
14204     * Returns the over-scroll mode for this view. The result will be
14205     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14206     * (allow over-scrolling only if the view content is larger than the container),
14207     * or {@link #OVER_SCROLL_NEVER}.
14208     *
14209     * @return This view's over-scroll mode.
14210     */
14211    public int getOverScrollMode() {
14212        return mOverScrollMode;
14213    }
14214
14215    /**
14216     * Set the over-scroll mode for this view. Valid over-scroll modes are
14217     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14218     * (allow over-scrolling only if the view content is larger than the container),
14219     * or {@link #OVER_SCROLL_NEVER}.
14220     *
14221     * Setting the over-scroll mode of a view will have an effect only if the
14222     * view is capable of scrolling.
14223     *
14224     * @param overScrollMode The new over-scroll mode for this view.
14225     */
14226    public void setOverScrollMode(int overScrollMode) {
14227        if (overScrollMode != OVER_SCROLL_ALWAYS &&
14228                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
14229                overScrollMode != OVER_SCROLL_NEVER) {
14230            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
14231        }
14232        mOverScrollMode = overScrollMode;
14233    }
14234
14235    /**
14236     * Gets a scale factor that determines the distance the view should scroll
14237     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
14238     * @return The vertical scroll scale factor.
14239     * @hide
14240     */
14241    protected float getVerticalScrollFactor() {
14242        if (mVerticalScrollFactor == 0) {
14243            TypedValue outValue = new TypedValue();
14244            if (!mContext.getTheme().resolveAttribute(
14245                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
14246                throw new IllegalStateException(
14247                        "Expected theme to define listPreferredItemHeight.");
14248            }
14249            mVerticalScrollFactor = outValue.getDimension(
14250                    mContext.getResources().getDisplayMetrics());
14251        }
14252        return mVerticalScrollFactor;
14253    }
14254
14255    /**
14256     * Gets a scale factor that determines the distance the view should scroll
14257     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
14258     * @return The horizontal scroll scale factor.
14259     * @hide
14260     */
14261    protected float getHorizontalScrollFactor() {
14262        // TODO: Should use something else.
14263        return getVerticalScrollFactor();
14264    }
14265
14266    /**
14267     * Return the value specifying the text direction or policy that was set with
14268     * {@link #setTextDirection(int)}.
14269     *
14270     * @return the defined text direction. It can be one of:
14271     *
14272     * {@link #TEXT_DIRECTION_INHERIT},
14273     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14274     * {@link #TEXT_DIRECTION_ANY_RTL},
14275     * {@link #TEXT_DIRECTION_LTR},
14276     * {@link #TEXT_DIRECTION_RTL},
14277     * {@link #TEXT_DIRECTION_LOCALE},
14278     */
14279    @ViewDebug.ExportedProperty(category = "text", mapping = {
14280            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
14281            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
14282            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
14283            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
14284            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
14285            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
14286    })
14287    public int getTextDirection() {
14288        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
14289    }
14290
14291    /**
14292     * Set the text direction.
14293     *
14294     * @param textDirection the direction to set. Should be one of:
14295     *
14296     * {@link #TEXT_DIRECTION_INHERIT},
14297     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14298     * {@link #TEXT_DIRECTION_ANY_RTL},
14299     * {@link #TEXT_DIRECTION_LTR},
14300     * {@link #TEXT_DIRECTION_RTL},
14301     * {@link #TEXT_DIRECTION_LOCALE},
14302     */
14303    public void setTextDirection(int textDirection) {
14304        if (getTextDirection() != textDirection) {
14305            // Reset the current text direction
14306            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
14307            // Set the new text direction
14308            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
14309            // Reset the current resolved text direction
14310            resetResolvedTextDirection();
14311            // Ask for a layout pass
14312            requestLayout();
14313        }
14314    }
14315
14316    /**
14317     * Return the resolved text direction.
14318     *
14319     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
14320     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
14321     * up the parent chain of the view. if there is no parent, then it will return the default
14322     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
14323     *
14324     * @return the resolved text direction. Returns one of:
14325     *
14326     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14327     * {@link #TEXT_DIRECTION_ANY_RTL},
14328     * {@link #TEXT_DIRECTION_LTR},
14329     * {@link #TEXT_DIRECTION_RTL},
14330     * {@link #TEXT_DIRECTION_LOCALE},
14331     */
14332    public int getResolvedTextDirection() {
14333        // The text direction is not inherited so return it back
14334        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
14335            resolveTextDirection();
14336        }
14337        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
14338    }
14339
14340    /**
14341     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
14342     * resolution is done.
14343     */
14344    public void resolveTextDirection() {
14345        // Reset any previous text direction resolution
14346        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
14347
14348        // Set resolved text direction flag depending on text direction flag
14349        final int textDirection = getTextDirection();
14350        switch(textDirection) {
14351            case TEXT_DIRECTION_INHERIT:
14352                if (canResolveTextDirection()) {
14353                    ViewGroup viewGroup = ((ViewGroup) mParent);
14354
14355                    // Set current resolved direction to the same value as the parent's one
14356                    final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
14357                    switch (parentResolvedDirection) {
14358                        case TEXT_DIRECTION_FIRST_STRONG:
14359                        case TEXT_DIRECTION_ANY_RTL:
14360                        case TEXT_DIRECTION_LTR:
14361                        case TEXT_DIRECTION_RTL:
14362                        case TEXT_DIRECTION_LOCALE:
14363                            mPrivateFlags2 |=
14364                                    (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
14365                            break;
14366                        default:
14367                            // Default resolved direction is "first strong" heuristic
14368                            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
14369                    }
14370                } else {
14371                    // We cannot do the resolution if there is no parent, so use the default one
14372                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
14373                }
14374                break;
14375            case TEXT_DIRECTION_FIRST_STRONG:
14376            case TEXT_DIRECTION_ANY_RTL:
14377            case TEXT_DIRECTION_LTR:
14378            case TEXT_DIRECTION_RTL:
14379            case TEXT_DIRECTION_LOCALE:
14380                // Resolved direction is the same as text direction
14381                mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
14382                break;
14383            default:
14384                // Default resolved direction is "first strong" heuristic
14385                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
14386        }
14387
14388        // Set to resolved
14389        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
14390        onResolvedTextDirectionChanged();
14391    }
14392
14393    /**
14394     * Called when text direction has been resolved. Subclasses that care about text direction
14395     * resolution should override this method.
14396     *
14397     * The default implementation does nothing.
14398     */
14399    public void onResolvedTextDirectionChanged() {
14400    }
14401
14402    /**
14403     * Check if text direction resolution can be done.
14404     *
14405     * @return true if text direction resolution can be done otherwise return false.
14406     */
14407    public boolean canResolveTextDirection() {
14408        switch (getTextDirection()) {
14409            case TEXT_DIRECTION_INHERIT:
14410                return (mParent != null) && (mParent instanceof ViewGroup);
14411            default:
14412                return true;
14413        }
14414    }
14415
14416    /**
14417     * Reset resolved text direction. Text direction can be resolved with a call to
14418     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
14419     * reset is done.
14420     */
14421    public void resetResolvedTextDirection() {
14422        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
14423        onResolvedTextDirectionReset();
14424    }
14425
14426    /**
14427     * Called when text direction is reset. Subclasses that care about text direction reset should
14428     * override this method and do a reset of the text direction of their children. The default
14429     * implementation does nothing.
14430     */
14431    public void onResolvedTextDirectionReset() {
14432    }
14433
14434    //
14435    // Properties
14436    //
14437    /**
14438     * A Property wrapper around the <code>alpha</code> functionality handled by the
14439     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
14440     */
14441    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
14442        @Override
14443        public void setValue(View object, float value) {
14444            object.setAlpha(value);
14445        }
14446
14447        @Override
14448        public Float get(View object) {
14449            return object.getAlpha();
14450        }
14451    };
14452
14453    /**
14454     * A Property wrapper around the <code>translationX</code> functionality handled by the
14455     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
14456     */
14457    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
14458        @Override
14459        public void setValue(View object, float value) {
14460            object.setTranslationX(value);
14461        }
14462
14463                @Override
14464        public Float get(View object) {
14465            return object.getTranslationX();
14466        }
14467    };
14468
14469    /**
14470     * A Property wrapper around the <code>translationY</code> functionality handled by the
14471     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
14472     */
14473    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
14474        @Override
14475        public void setValue(View object, float value) {
14476            object.setTranslationY(value);
14477        }
14478
14479        @Override
14480        public Float get(View object) {
14481            return object.getTranslationY();
14482        }
14483    };
14484
14485    /**
14486     * A Property wrapper around the <code>x</code> functionality handled by the
14487     * {@link View#setX(float)} and {@link View#getX()} methods.
14488     */
14489    public static final Property<View, Float> X = new FloatProperty<View>("x") {
14490        @Override
14491        public void setValue(View object, float value) {
14492            object.setX(value);
14493        }
14494
14495        @Override
14496        public Float get(View object) {
14497            return object.getX();
14498        }
14499    };
14500
14501    /**
14502     * A Property wrapper around the <code>y</code> functionality handled by the
14503     * {@link View#setY(float)} and {@link View#getY()} methods.
14504     */
14505    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
14506        @Override
14507        public void setValue(View object, float value) {
14508            object.setY(value);
14509        }
14510
14511        @Override
14512        public Float get(View object) {
14513            return object.getY();
14514        }
14515    };
14516
14517    /**
14518     * A Property wrapper around the <code>rotation</code> functionality handled by the
14519     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
14520     */
14521    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
14522        @Override
14523        public void setValue(View object, float value) {
14524            object.setRotation(value);
14525        }
14526
14527        @Override
14528        public Float get(View object) {
14529            return object.getRotation();
14530        }
14531    };
14532
14533    /**
14534     * A Property wrapper around the <code>rotationX</code> functionality handled by the
14535     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
14536     */
14537    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
14538        @Override
14539        public void setValue(View object, float value) {
14540            object.setRotationX(value);
14541        }
14542
14543        @Override
14544        public Float get(View object) {
14545            return object.getRotationX();
14546        }
14547    };
14548
14549    /**
14550     * A Property wrapper around the <code>rotationY</code> functionality handled by the
14551     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
14552     */
14553    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
14554        @Override
14555        public void setValue(View object, float value) {
14556            object.setRotationY(value);
14557        }
14558
14559        @Override
14560        public Float get(View object) {
14561            return object.getRotationY();
14562        }
14563    };
14564
14565    /**
14566     * A Property wrapper around the <code>scaleX</code> functionality handled by the
14567     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
14568     */
14569    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
14570        @Override
14571        public void setValue(View object, float value) {
14572            object.setScaleX(value);
14573        }
14574
14575        @Override
14576        public Float get(View object) {
14577            return object.getScaleX();
14578        }
14579    };
14580
14581    /**
14582     * A Property wrapper around the <code>scaleY</code> functionality handled by the
14583     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
14584     */
14585    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
14586        @Override
14587        public void setValue(View object, float value) {
14588            object.setScaleY(value);
14589        }
14590
14591        @Override
14592        public Float get(View object) {
14593            return object.getScaleY();
14594        }
14595    };
14596
14597    /**
14598     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
14599     * Each MeasureSpec represents a requirement for either the width or the height.
14600     * A MeasureSpec is comprised of a size and a mode. There are three possible
14601     * modes:
14602     * <dl>
14603     * <dt>UNSPECIFIED</dt>
14604     * <dd>
14605     * The parent has not imposed any constraint on the child. It can be whatever size
14606     * it wants.
14607     * </dd>
14608     *
14609     * <dt>EXACTLY</dt>
14610     * <dd>
14611     * The parent has determined an exact size for the child. The child is going to be
14612     * given those bounds regardless of how big it wants to be.
14613     * </dd>
14614     *
14615     * <dt>AT_MOST</dt>
14616     * <dd>
14617     * The child can be as large as it wants up to the specified size.
14618     * </dd>
14619     * </dl>
14620     *
14621     * MeasureSpecs are implemented as ints to reduce object allocation. This class
14622     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
14623     */
14624    public static class MeasureSpec {
14625        private static final int MODE_SHIFT = 30;
14626        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
14627
14628        /**
14629         * Measure specification mode: The parent has not imposed any constraint
14630         * on the child. It can be whatever size it wants.
14631         */
14632        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
14633
14634        /**
14635         * Measure specification mode: The parent has determined an exact size
14636         * for the child. The child is going to be given those bounds regardless
14637         * of how big it wants to be.
14638         */
14639        public static final int EXACTLY     = 1 << MODE_SHIFT;
14640
14641        /**
14642         * Measure specification mode: The child can be as large as it wants up
14643         * to the specified size.
14644         */
14645        public static final int AT_MOST     = 2 << MODE_SHIFT;
14646
14647        /**
14648         * Creates a measure specification based on the supplied size and mode.
14649         *
14650         * The mode must always be one of the following:
14651         * <ul>
14652         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
14653         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
14654         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
14655         * </ul>
14656         *
14657         * @param size the size of the measure specification
14658         * @param mode the mode of the measure specification
14659         * @return the measure specification based on size and mode
14660         */
14661        public static int makeMeasureSpec(int size, int mode) {
14662            return size + mode;
14663        }
14664
14665        /**
14666         * Extracts the mode from the supplied measure specification.
14667         *
14668         * @param measureSpec the measure specification to extract the mode from
14669         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
14670         *         {@link android.view.View.MeasureSpec#AT_MOST} or
14671         *         {@link android.view.View.MeasureSpec#EXACTLY}
14672         */
14673        public static int getMode(int measureSpec) {
14674            return (measureSpec & MODE_MASK);
14675        }
14676
14677        /**
14678         * Extracts the size from the supplied measure specification.
14679         *
14680         * @param measureSpec the measure specification to extract the size from
14681         * @return the size in pixels defined in the supplied measure specification
14682         */
14683        public static int getSize(int measureSpec) {
14684            return (measureSpec & ~MODE_MASK);
14685        }
14686
14687        /**
14688         * Returns a String representation of the specified measure
14689         * specification.
14690         *
14691         * @param measureSpec the measure specification to convert to a String
14692         * @return a String with the following format: "MeasureSpec: MODE SIZE"
14693         */
14694        public static String toString(int measureSpec) {
14695            int mode = getMode(measureSpec);
14696            int size = getSize(measureSpec);
14697
14698            StringBuilder sb = new StringBuilder("MeasureSpec: ");
14699
14700            if (mode == UNSPECIFIED)
14701                sb.append("UNSPECIFIED ");
14702            else if (mode == EXACTLY)
14703                sb.append("EXACTLY ");
14704            else if (mode == AT_MOST)
14705                sb.append("AT_MOST ");
14706            else
14707                sb.append(mode).append(" ");
14708
14709            sb.append(size);
14710            return sb.toString();
14711        }
14712    }
14713
14714    class CheckForLongPress implements Runnable {
14715
14716        private int mOriginalWindowAttachCount;
14717
14718        public void run() {
14719            if (isPressed() && (mParent != null)
14720                    && mOriginalWindowAttachCount == mWindowAttachCount) {
14721                if (performLongClick()) {
14722                    mHasPerformedLongPress = true;
14723                }
14724            }
14725        }
14726
14727        public void rememberWindowAttachCount() {
14728            mOriginalWindowAttachCount = mWindowAttachCount;
14729        }
14730    }
14731
14732    private final class CheckForTap implements Runnable {
14733        public void run() {
14734            mPrivateFlags &= ~PREPRESSED;
14735            setPressed(true);
14736            checkForLongClick(ViewConfiguration.getTapTimeout());
14737        }
14738    }
14739
14740    private final class PerformClick implements Runnable {
14741        public void run() {
14742            performClick();
14743        }
14744    }
14745
14746    /** @hide */
14747    public void hackTurnOffWindowResizeAnim(boolean off) {
14748        mAttachInfo.mTurnOffWindowResizeAnim = off;
14749    }
14750
14751    /**
14752     * This method returns a ViewPropertyAnimator object, which can be used to animate
14753     * specific properties on this View.
14754     *
14755     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
14756     */
14757    public ViewPropertyAnimator animate() {
14758        if (mAnimator == null) {
14759            mAnimator = new ViewPropertyAnimator(this);
14760        }
14761        return mAnimator;
14762    }
14763
14764    /**
14765     * Interface definition for a callback to be invoked when a key event is
14766     * dispatched to this view. The callback will be invoked before the key
14767     * event is given to the view.
14768     */
14769    public interface OnKeyListener {
14770        /**
14771         * Called when a key is dispatched to a view. This allows listeners to
14772         * get a chance to respond before the target view.
14773         *
14774         * @param v The view the key has been dispatched to.
14775         * @param keyCode The code for the physical key that was pressed
14776         * @param event The KeyEvent object containing full information about
14777         *        the event.
14778         * @return True if the listener has consumed the event, false otherwise.
14779         */
14780        boolean onKey(View v, int keyCode, KeyEvent event);
14781    }
14782
14783    /**
14784     * Interface definition for a callback to be invoked when a touch event is
14785     * dispatched to this view. The callback will be invoked before the touch
14786     * event is given to the view.
14787     */
14788    public interface OnTouchListener {
14789        /**
14790         * Called when a touch event is dispatched to a view. This allows listeners to
14791         * get a chance to respond before the target view.
14792         *
14793         * @param v The view the touch event has been dispatched to.
14794         * @param event The MotionEvent object containing full information about
14795         *        the event.
14796         * @return True if the listener has consumed the event, false otherwise.
14797         */
14798        boolean onTouch(View v, MotionEvent event);
14799    }
14800
14801    /**
14802     * Interface definition for a callback to be invoked when a hover event is
14803     * dispatched to this view. The callback will be invoked before the hover
14804     * event is given to the view.
14805     */
14806    public interface OnHoverListener {
14807        /**
14808         * Called when a hover event is dispatched to a view. This allows listeners to
14809         * get a chance to respond before the target view.
14810         *
14811         * @param v The view the hover event has been dispatched to.
14812         * @param event The MotionEvent object containing full information about
14813         *        the event.
14814         * @return True if the listener has consumed the event, false otherwise.
14815         */
14816        boolean onHover(View v, MotionEvent event);
14817    }
14818
14819    /**
14820     * Interface definition for a callback to be invoked when a generic motion event is
14821     * dispatched to this view. The callback will be invoked before the generic motion
14822     * event is given to the view.
14823     */
14824    public interface OnGenericMotionListener {
14825        /**
14826         * Called when a generic motion event is dispatched to a view. This allows listeners to
14827         * get a chance to respond before the target view.
14828         *
14829         * @param v The view the generic motion event has been dispatched to.
14830         * @param event The MotionEvent object containing full information about
14831         *        the event.
14832         * @return True if the listener has consumed the event, false otherwise.
14833         */
14834        boolean onGenericMotion(View v, MotionEvent event);
14835    }
14836
14837    /**
14838     * Interface definition for a callback to be invoked when a view has been clicked and held.
14839     */
14840    public interface OnLongClickListener {
14841        /**
14842         * Called when a view has been clicked and held.
14843         *
14844         * @param v The view that was clicked and held.
14845         *
14846         * @return true if the callback consumed the long click, false otherwise.
14847         */
14848        boolean onLongClick(View v);
14849    }
14850
14851    /**
14852     * Interface definition for a callback to be invoked when a drag is being dispatched
14853     * to this view.  The callback will be invoked before the hosting view's own
14854     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
14855     * onDrag(event) behavior, it should return 'false' from this callback.
14856     *
14857     * <div class="special reference">
14858     * <h3>Developer Guides</h3>
14859     * <p>For a guide to implementing drag and drop features, read the
14860     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
14861     * </div>
14862     */
14863    public interface OnDragListener {
14864        /**
14865         * Called when a drag event is dispatched to a view. This allows listeners
14866         * to get a chance to override base View behavior.
14867         *
14868         * @param v The View that received the drag event.
14869         * @param event The {@link android.view.DragEvent} object for the drag event.
14870         * @return {@code true} if the drag event was handled successfully, or {@code false}
14871         * if the drag event was not handled. Note that {@code false} will trigger the View
14872         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
14873         */
14874        boolean onDrag(View v, DragEvent event);
14875    }
14876
14877    /**
14878     * Interface definition for a callback to be invoked when the focus state of
14879     * a view changed.
14880     */
14881    public interface OnFocusChangeListener {
14882        /**
14883         * Called when the focus state of a view has changed.
14884         *
14885         * @param v The view whose state has changed.
14886         * @param hasFocus The new focus state of v.
14887         */
14888        void onFocusChange(View v, boolean hasFocus);
14889    }
14890
14891    /**
14892     * Interface definition for a callback to be invoked when a view is clicked.
14893     */
14894    public interface OnClickListener {
14895        /**
14896         * Called when a view has been clicked.
14897         *
14898         * @param v The view that was clicked.
14899         */
14900        void onClick(View v);
14901    }
14902
14903    /**
14904     * Interface definition for a callback to be invoked when the context menu
14905     * for this view is being built.
14906     */
14907    public interface OnCreateContextMenuListener {
14908        /**
14909         * Called when the context menu for this view is being built. It is not
14910         * safe to hold onto the menu after this method returns.
14911         *
14912         * @param menu The context menu that is being built
14913         * @param v The view for which the context menu is being built
14914         * @param menuInfo Extra information about the item for which the
14915         *            context menu should be shown. This information will vary
14916         *            depending on the class of v.
14917         */
14918        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
14919    }
14920
14921    /**
14922     * Interface definition for a callback to be invoked when the status bar changes
14923     * visibility.  This reports <strong>global</strong> changes to the system UI
14924     * state, not just what the application is requesting.
14925     *
14926     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
14927     */
14928    public interface OnSystemUiVisibilityChangeListener {
14929        /**
14930         * Called when the status bar changes visibility because of a call to
14931         * {@link View#setSystemUiVisibility(int)}.
14932         *
14933         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14934         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
14935         * <strong>global</strong> state of the UI visibility flags, not what your
14936         * app is currently applying.
14937         */
14938        public void onSystemUiVisibilityChange(int visibility);
14939    }
14940
14941    /**
14942     * Interface definition for a callback to be invoked when this view is attached
14943     * or detached from its window.
14944     */
14945    public interface OnAttachStateChangeListener {
14946        /**
14947         * Called when the view is attached to a window.
14948         * @param v The view that was attached
14949         */
14950        public void onViewAttachedToWindow(View v);
14951        /**
14952         * Called when the view is detached from a window.
14953         * @param v The view that was detached
14954         */
14955        public void onViewDetachedFromWindow(View v);
14956    }
14957
14958    private final class UnsetPressedState implements Runnable {
14959        public void run() {
14960            setPressed(false);
14961        }
14962    }
14963
14964    /**
14965     * Base class for derived classes that want to save and restore their own
14966     * state in {@link android.view.View#onSaveInstanceState()}.
14967     */
14968    public static class BaseSavedState extends AbsSavedState {
14969        /**
14970         * Constructor used when reading from a parcel. Reads the state of the superclass.
14971         *
14972         * @param source
14973         */
14974        public BaseSavedState(Parcel source) {
14975            super(source);
14976        }
14977
14978        /**
14979         * Constructor called by derived classes when creating their SavedState objects
14980         *
14981         * @param superState The state of the superclass of this view
14982         */
14983        public BaseSavedState(Parcelable superState) {
14984            super(superState);
14985        }
14986
14987        public static final Parcelable.Creator<BaseSavedState> CREATOR =
14988                new Parcelable.Creator<BaseSavedState>() {
14989            public BaseSavedState createFromParcel(Parcel in) {
14990                return new BaseSavedState(in);
14991            }
14992
14993            public BaseSavedState[] newArray(int size) {
14994                return new BaseSavedState[size];
14995            }
14996        };
14997    }
14998
14999    /**
15000     * A set of information given to a view when it is attached to its parent
15001     * window.
15002     */
15003    static class AttachInfo {
15004        interface Callbacks {
15005            void playSoundEffect(int effectId);
15006            boolean performHapticFeedback(int effectId, boolean always);
15007        }
15008
15009        /**
15010         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
15011         * to a Handler. This class contains the target (View) to invalidate and
15012         * the coordinates of the dirty rectangle.
15013         *
15014         * For performance purposes, this class also implements a pool of up to
15015         * POOL_LIMIT objects that get reused. This reduces memory allocations
15016         * whenever possible.
15017         */
15018        static class InvalidateInfo implements Poolable<InvalidateInfo> {
15019            private static final int POOL_LIMIT = 10;
15020            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
15021                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
15022                        public InvalidateInfo newInstance() {
15023                            return new InvalidateInfo();
15024                        }
15025
15026                        public void onAcquired(InvalidateInfo element) {
15027                        }
15028
15029                        public void onReleased(InvalidateInfo element) {
15030                            element.target = null;
15031                        }
15032                    }, POOL_LIMIT)
15033            );
15034
15035            private InvalidateInfo mNext;
15036            private boolean mIsPooled;
15037
15038            View target;
15039
15040            int left;
15041            int top;
15042            int right;
15043            int bottom;
15044
15045            public void setNextPoolable(InvalidateInfo element) {
15046                mNext = element;
15047            }
15048
15049            public InvalidateInfo getNextPoolable() {
15050                return mNext;
15051            }
15052
15053            static InvalidateInfo acquire() {
15054                return sPool.acquire();
15055            }
15056
15057            void release() {
15058                sPool.release(this);
15059            }
15060
15061            public boolean isPooled() {
15062                return mIsPooled;
15063            }
15064
15065            public void setPooled(boolean isPooled) {
15066                mIsPooled = isPooled;
15067            }
15068        }
15069
15070        final IWindowSession mSession;
15071
15072        final IWindow mWindow;
15073
15074        final IBinder mWindowToken;
15075
15076        final Callbacks mRootCallbacks;
15077
15078        HardwareCanvas mHardwareCanvas;
15079
15080        /**
15081         * The top view of the hierarchy.
15082         */
15083        View mRootView;
15084
15085        IBinder mPanelParentWindowToken;
15086        Surface mSurface;
15087
15088        boolean mHardwareAccelerated;
15089        boolean mHardwareAccelerationRequested;
15090        HardwareRenderer mHardwareRenderer;
15091
15092        boolean mScreenOn;
15093
15094        /**
15095         * Scale factor used by the compatibility mode
15096         */
15097        float mApplicationScale;
15098
15099        /**
15100         * Indicates whether the application is in compatibility mode
15101         */
15102        boolean mScalingRequired;
15103
15104        /**
15105         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
15106         */
15107        boolean mTurnOffWindowResizeAnim;
15108
15109        /**
15110         * Left position of this view's window
15111         */
15112        int mWindowLeft;
15113
15114        /**
15115         * Top position of this view's window
15116         */
15117        int mWindowTop;
15118
15119        /**
15120         * Indicates whether views need to use 32-bit drawing caches
15121         */
15122        boolean mUse32BitDrawingCache;
15123
15124        /**
15125         * For windows that are full-screen but using insets to layout inside
15126         * of the screen decorations, these are the current insets for the
15127         * content of the window.
15128         */
15129        final Rect mContentInsets = new Rect();
15130
15131        /**
15132         * For windows that are full-screen but using insets to layout inside
15133         * of the screen decorations, these are the current insets for the
15134         * actual visible parts of the window.
15135         */
15136        final Rect mVisibleInsets = new Rect();
15137
15138        /**
15139         * The internal insets given by this window.  This value is
15140         * supplied by the client (through
15141         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
15142         * be given to the window manager when changed to be used in laying
15143         * out windows behind it.
15144         */
15145        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
15146                = new ViewTreeObserver.InternalInsetsInfo();
15147
15148        /**
15149         * All views in the window's hierarchy that serve as scroll containers,
15150         * used to determine if the window can be resized or must be panned
15151         * to adjust for a soft input area.
15152         */
15153        final ArrayList<View> mScrollContainers = new ArrayList<View>();
15154
15155        final KeyEvent.DispatcherState mKeyDispatchState
15156                = new KeyEvent.DispatcherState();
15157
15158        /**
15159         * Indicates whether the view's window currently has the focus.
15160         */
15161        boolean mHasWindowFocus;
15162
15163        /**
15164         * The current visibility of the window.
15165         */
15166        int mWindowVisibility;
15167
15168        /**
15169         * Indicates the time at which drawing started to occur.
15170         */
15171        long mDrawingTime;
15172
15173        /**
15174         * Indicates whether or not ignoring the DIRTY_MASK flags.
15175         */
15176        boolean mIgnoreDirtyState;
15177
15178        /**
15179         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
15180         * to avoid clearing that flag prematurely.
15181         */
15182        boolean mSetIgnoreDirtyState = false;
15183
15184        /**
15185         * Indicates whether the view's window is currently in touch mode.
15186         */
15187        boolean mInTouchMode;
15188
15189        /**
15190         * Indicates that ViewAncestor should trigger a global layout change
15191         * the next time it performs a traversal
15192         */
15193        boolean mRecomputeGlobalAttributes;
15194
15195        /**
15196         * Always report new attributes at next traversal.
15197         */
15198        boolean mForceReportNewAttributes;
15199
15200        /**
15201         * Set during a traveral if any views want to keep the screen on.
15202         */
15203        boolean mKeepScreenOn;
15204
15205        /**
15206         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
15207         */
15208        int mSystemUiVisibility;
15209
15210        /**
15211         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
15212         * attached.
15213         */
15214        boolean mHasSystemUiListeners;
15215
15216        /**
15217         * Set if the visibility of any views has changed.
15218         */
15219        boolean mViewVisibilityChanged;
15220
15221        /**
15222         * Set to true if a view has been scrolled.
15223         */
15224        boolean mViewScrollChanged;
15225
15226        /**
15227         * Global to the view hierarchy used as a temporary for dealing with
15228         * x/y points in the transparent region computations.
15229         */
15230        final int[] mTransparentLocation = new int[2];
15231
15232        /**
15233         * Global to the view hierarchy used as a temporary for dealing with
15234         * x/y points in the ViewGroup.invalidateChild implementation.
15235         */
15236        final int[] mInvalidateChildLocation = new int[2];
15237
15238
15239        /**
15240         * Global to the view hierarchy used as a temporary for dealing with
15241         * x/y location when view is transformed.
15242         */
15243        final float[] mTmpTransformLocation = new float[2];
15244
15245        /**
15246         * The view tree observer used to dispatch global events like
15247         * layout, pre-draw, touch mode change, etc.
15248         */
15249        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
15250
15251        /**
15252         * A Canvas used by the view hierarchy to perform bitmap caching.
15253         */
15254        Canvas mCanvas;
15255
15256        /**
15257         * The view root impl.
15258         */
15259        final ViewRootImpl mViewRootImpl;
15260
15261        /**
15262         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
15263         * handler can be used to pump events in the UI events queue.
15264         */
15265        final Handler mHandler;
15266
15267        /**
15268         * Temporary for use in computing invalidate rectangles while
15269         * calling up the hierarchy.
15270         */
15271        final Rect mTmpInvalRect = new Rect();
15272
15273        /**
15274         * Temporary for use in computing hit areas with transformed views
15275         */
15276        final RectF mTmpTransformRect = new RectF();
15277
15278        /**
15279         * Temporary list for use in collecting focusable descendents of a view.
15280         */
15281        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
15282
15283        /**
15284         * The id of the window for accessibility purposes.
15285         */
15286        int mAccessibilityWindowId = View.NO_ID;
15287
15288        /**
15289         * Creates a new set of attachment information with the specified
15290         * events handler and thread.
15291         *
15292         * @param handler the events handler the view must use
15293         */
15294        AttachInfo(IWindowSession session, IWindow window,
15295                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
15296            mSession = session;
15297            mWindow = window;
15298            mWindowToken = window.asBinder();
15299            mViewRootImpl = viewRootImpl;
15300            mHandler = handler;
15301            mRootCallbacks = effectPlayer;
15302        }
15303    }
15304
15305    /**
15306     * <p>ScrollabilityCache holds various fields used by a View when scrolling
15307     * is supported. This avoids keeping too many unused fields in most
15308     * instances of View.</p>
15309     */
15310    private static class ScrollabilityCache implements Runnable {
15311
15312        /**
15313         * Scrollbars are not visible
15314         */
15315        public static final int OFF = 0;
15316
15317        /**
15318         * Scrollbars are visible
15319         */
15320        public static final int ON = 1;
15321
15322        /**
15323         * Scrollbars are fading away
15324         */
15325        public static final int FADING = 2;
15326
15327        public boolean fadeScrollBars;
15328
15329        public int fadingEdgeLength;
15330        public int scrollBarDefaultDelayBeforeFade;
15331        public int scrollBarFadeDuration;
15332
15333        public int scrollBarSize;
15334        public ScrollBarDrawable scrollBar;
15335        public float[] interpolatorValues;
15336        public View host;
15337
15338        public final Paint paint;
15339        public final Matrix matrix;
15340        public Shader shader;
15341
15342        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
15343
15344        private static final float[] OPAQUE = { 255 };
15345        private static final float[] TRANSPARENT = { 0.0f };
15346
15347        /**
15348         * When fading should start. This time moves into the future every time
15349         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
15350         */
15351        public long fadeStartTime;
15352
15353
15354        /**
15355         * The current state of the scrollbars: ON, OFF, or FADING
15356         */
15357        public int state = OFF;
15358
15359        private int mLastColor;
15360
15361        public ScrollabilityCache(ViewConfiguration configuration, View host) {
15362            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
15363            scrollBarSize = configuration.getScaledScrollBarSize();
15364            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
15365            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
15366
15367            paint = new Paint();
15368            matrix = new Matrix();
15369            // use use a height of 1, and then wack the matrix each time we
15370            // actually use it.
15371            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
15372
15373            paint.setShader(shader);
15374            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
15375            this.host = host;
15376        }
15377
15378        public void setFadeColor(int color) {
15379            if (color != 0 && color != mLastColor) {
15380                mLastColor = color;
15381                color |= 0xFF000000;
15382
15383                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
15384                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
15385
15386                paint.setShader(shader);
15387                // Restore the default transfer mode (src_over)
15388                paint.setXfermode(null);
15389            }
15390        }
15391
15392        public void run() {
15393            long now = AnimationUtils.currentAnimationTimeMillis();
15394            if (now >= fadeStartTime) {
15395
15396                // the animation fades the scrollbars out by changing
15397                // the opacity (alpha) from fully opaque to fully
15398                // transparent
15399                int nextFrame = (int) now;
15400                int framesCount = 0;
15401
15402                Interpolator interpolator = scrollBarInterpolator;
15403
15404                // Start opaque
15405                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
15406
15407                // End transparent
15408                nextFrame += scrollBarFadeDuration;
15409                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
15410
15411                state = FADING;
15412
15413                // Kick off the fade animation
15414                host.invalidate(true);
15415            }
15416        }
15417    }
15418
15419    /**
15420     * Resuable callback for sending
15421     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
15422     */
15423    private class SendViewScrolledAccessibilityEvent implements Runnable {
15424        public volatile boolean mIsPending;
15425
15426        public void run() {
15427            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
15428            mIsPending = false;
15429        }
15430    }
15431
15432    /**
15433     * <p>
15434     * This class represents a delegate that can be registered in a {@link View}
15435     * to enhance accessibility support via composition rather via inheritance.
15436     * It is specifically targeted to widget developers that extend basic View
15437     * classes i.e. classes in package android.view, that would like their
15438     * applications to be backwards compatible.
15439     * </p>
15440     * <p>
15441     * A scenario in which a developer would like to use an accessibility delegate
15442     * is overriding a method introduced in a later API version then the minimal API
15443     * version supported by the application. For example, the method
15444     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
15445     * in API version 4 when the accessibility APIs were first introduced. If a
15446     * developer would like his application to run on API version 4 devices (assuming
15447     * all other APIs used by the application are version 4 or lower) and take advantage
15448     * of this method, instead of overriding the method which would break the application's
15449     * backwards compatibility, he can override the corresponding method in this
15450     * delegate and register the delegate in the target View if the API version of
15451     * the system is high enough i.e. the API version is same or higher to the API
15452     * version that introduced
15453     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
15454     * </p>
15455     * <p>
15456     * Here is an example implementation:
15457     * </p>
15458     * <code><pre><p>
15459     * if (Build.VERSION.SDK_INT >= 14) {
15460     *     // If the API version is equal of higher than the version in
15461     *     // which onInitializeAccessibilityNodeInfo was introduced we
15462     *     // register a delegate with a customized implementation.
15463     *     View view = findViewById(R.id.view_id);
15464     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
15465     *         public void onInitializeAccessibilityNodeInfo(View host,
15466     *                 AccessibilityNodeInfo info) {
15467     *             // Let the default implementation populate the info.
15468     *             super.onInitializeAccessibilityNodeInfo(host, info);
15469     *             // Set some other information.
15470     *             info.setEnabled(host.isEnabled());
15471     *         }
15472     *     });
15473     * }
15474     * </code></pre></p>
15475     * <p>
15476     * This delegate contains methods that correspond to the accessibility methods
15477     * in View. If a delegate has been specified the implementation in View hands
15478     * off handling to the corresponding method in this delegate. The default
15479     * implementation the delegate methods behaves exactly as the corresponding
15480     * method in View for the case of no accessibility delegate been set. Hence,
15481     * to customize the behavior of a View method, clients can override only the
15482     * corresponding delegate method without altering the behavior of the rest
15483     * accessibility related methods of the host view.
15484     * </p>
15485     */
15486    public static class AccessibilityDelegate {
15487
15488        /**
15489         * Sends an accessibility event of the given type. If accessibility is not
15490         * enabled this method has no effect.
15491         * <p>
15492         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
15493         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
15494         * been set.
15495         * </p>
15496         *
15497         * @param host The View hosting the delegate.
15498         * @param eventType The type of the event to send.
15499         *
15500         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
15501         */
15502        public void sendAccessibilityEvent(View host, int eventType) {
15503            host.sendAccessibilityEventInternal(eventType);
15504        }
15505
15506        /**
15507         * Sends an accessibility event. This method behaves exactly as
15508         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
15509         * empty {@link AccessibilityEvent} and does not perform a check whether
15510         * accessibility is enabled.
15511         * <p>
15512         * The default implementation behaves as
15513         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15514         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
15515         * the case of no accessibility delegate been set.
15516         * </p>
15517         *
15518         * @param host The View hosting the delegate.
15519         * @param event The event to send.
15520         *
15521         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15522         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15523         */
15524        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
15525            host.sendAccessibilityEventUncheckedInternal(event);
15526        }
15527
15528        /**
15529         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
15530         * to its children for adding their text content to the event.
15531         * <p>
15532         * The default implementation behaves as
15533         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15534         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
15535         * the case of no accessibility delegate been set.
15536         * </p>
15537         *
15538         * @param host The View hosting the delegate.
15539         * @param event The event.
15540         * @return True if the event population was completed.
15541         *
15542         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15543         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15544         */
15545        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15546            return host.dispatchPopulateAccessibilityEventInternal(event);
15547        }
15548
15549        /**
15550         * Gives a chance to the host View to populate the accessibility event with its
15551         * text content.
15552         * <p>
15553         * The default implementation behaves as
15554         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
15555         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
15556         * the case of no accessibility delegate been set.
15557         * </p>
15558         *
15559         * @param host The View hosting the delegate.
15560         * @param event The accessibility event which to populate.
15561         *
15562         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
15563         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
15564         */
15565        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15566            host.onPopulateAccessibilityEventInternal(event);
15567        }
15568
15569        /**
15570         * Initializes an {@link AccessibilityEvent} with information about the
15571         * the host View which is the event source.
15572         * <p>
15573         * The default implementation behaves as
15574         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
15575         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
15576         * the case of no accessibility delegate been set.
15577         * </p>
15578         *
15579         * @param host The View hosting the delegate.
15580         * @param event The event to initialize.
15581         *
15582         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
15583         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
15584         */
15585        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
15586            host.onInitializeAccessibilityEventInternal(event);
15587        }
15588
15589        /**
15590         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
15591         * <p>
15592         * The default implementation behaves as
15593         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15594         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
15595         * the case of no accessibility delegate been set.
15596         * </p>
15597         *
15598         * @param host The View hosting the delegate.
15599         * @param info The instance to initialize.
15600         *
15601         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15602         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15603         */
15604        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
15605            host.onInitializeAccessibilityNodeInfoInternal(info);
15606        }
15607
15608        /**
15609         * Called when a child of the host View has requested sending an
15610         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
15611         * to augment the event.
15612         * <p>
15613         * The default implementation behaves as
15614         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15615         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
15616         * the case of no accessibility delegate been set.
15617         * </p>
15618         *
15619         * @param host The View hosting the delegate.
15620         * @param child The child which requests sending the event.
15621         * @param event The event to be sent.
15622         * @return True if the event should be sent
15623         *
15624         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15625         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15626         */
15627        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
15628                AccessibilityEvent event) {
15629            return host.onRequestSendAccessibilityEventInternal(child, event);
15630        }
15631
15632        /**
15633         * Gets the provider for managing a virtual view hierarchy rooted at this View
15634         * and reported to {@link android.accessibilityservice.AccessibilityService}s
15635         * that explore the window content.
15636         * <p>
15637         * The default implementation behaves as
15638         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
15639         * the case of no accessibility delegate been set.
15640         * </p>
15641         *
15642         * @return The provider.
15643         *
15644         * @see AccessibilityNodeProvider
15645         */
15646        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
15647            return null;
15648        }
15649    }
15650}
15651