View.java revision d15ebf25c595b855f6978d0600218e3ea5f31e92
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Insets;
28import android.graphics.Interpolator;
29import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.Shader;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.hardware.display.DisplayManager;
43import android.hardware.display.DisplayManagerGlobal;
44import android.os.Bundle;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Parcel;
48import android.os.Parcelable;
49import android.os.RemoteException;
50import android.os.SystemClock;
51import android.os.SystemProperties;
52import android.util.AttributeSet;
53import android.util.FloatProperty;
54import android.util.LocaleUtil;
55import android.util.Log;
56import android.util.Pool;
57import android.util.Poolable;
58import android.util.PoolableManager;
59import android.util.Pools;
60import android.util.Property;
61import android.util.SparseArray;
62import android.util.TypedValue;
63import android.view.ContextMenu.ContextMenuInfo;
64import android.view.AccessibilityIterators.TextSegmentIterator;
65import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
66import android.view.AccessibilityIterators.WordTextSegmentIterator;
67import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
68import android.view.accessibility.AccessibilityEvent;
69import android.view.accessibility.AccessibilityEventSource;
70import android.view.accessibility.AccessibilityManager;
71import android.view.accessibility.AccessibilityNodeInfo;
72import android.view.accessibility.AccessibilityNodeProvider;
73import android.view.animation.Animation;
74import android.view.animation.AnimationUtils;
75import android.view.animation.Transformation;
76import android.view.inputmethod.EditorInfo;
77import android.view.inputmethod.InputConnection;
78import android.view.inputmethod.InputMethodManager;
79import android.widget.ScrollBarDrawable;
80
81import static android.os.Build.VERSION_CODES.*;
82import static java.lang.Math.max;
83
84import com.android.internal.R;
85import com.android.internal.util.Predicate;
86import com.android.internal.view.menu.MenuBuilder;
87
88import java.lang.ref.WeakReference;
89import java.lang.reflect.InvocationTargetException;
90import java.lang.reflect.Method;
91import java.util.ArrayList;
92import java.util.Arrays;
93import java.util.Locale;
94import java.util.concurrent.CopyOnWriteArrayList;
95import java.util.concurrent.atomic.AtomicInteger;
96
97/**
98 * <p>
99 * This class represents the basic building block for user interface components. A View
100 * occupies a rectangular area on the screen and is responsible for drawing and
101 * event handling. View is the base class for <em>widgets</em>, which are
102 * used to create interactive UI components (buttons, text fields, etc.). The
103 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
104 * are invisible containers that hold other Views (or other ViewGroups) and define
105 * their layout properties.
106 * </p>
107 *
108 * <div class="special reference">
109 * <h3>Developer Guides</h3>
110 * <p>For information about using this class to develop your application's user interface,
111 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
112 * </div>
113 *
114 * <a name="Using"></a>
115 * <h3>Using Views</h3>
116 * <p>
117 * All of the views in a window are arranged in a single tree. You can add views
118 * either from code or by specifying a tree of views in one or more XML layout
119 * files. There are many specialized subclasses of views that act as controls or
120 * are capable of displaying text, images, or other content.
121 * </p>
122 * <p>
123 * Once you have created a tree of views, there are typically a few types of
124 * common operations you may wish to perform:
125 * <ul>
126 * <li><strong>Set properties:</strong> for example setting the text of a
127 * {@link android.widget.TextView}. The available properties and the methods
128 * that set them will vary among the different subclasses of views. Note that
129 * properties that are known at build time can be set in the XML layout
130 * files.</li>
131 * <li><strong>Set focus:</strong> The framework will handled moving focus in
132 * response to user input. To force focus to a specific view, call
133 * {@link #requestFocus}.</li>
134 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
135 * that will be notified when something interesting happens to the view. For
136 * example, all views will let you set a listener to be notified when the view
137 * gains or loses focus. You can register such a listener using
138 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
139 * Other view subclasses offer more specialized listeners. For example, a Button
140 * exposes a listener to notify clients when the button is clicked.</li>
141 * <li><strong>Set visibility:</strong> You can hide or show views using
142 * {@link #setVisibility(int)}.</li>
143 * </ul>
144 * </p>
145 * <p><em>
146 * Note: The Android framework is responsible for measuring, laying out and
147 * drawing views. You should not call methods that perform these actions on
148 * views yourself unless you are actually implementing a
149 * {@link android.view.ViewGroup}.
150 * </em></p>
151 *
152 * <a name="Lifecycle"></a>
153 * <h3>Implementing a Custom View</h3>
154 *
155 * <p>
156 * To implement a custom view, you will usually begin by providing overrides for
157 * some of the standard methods that the framework calls on all views. You do
158 * not need to override all of these methods. In fact, you can start by just
159 * overriding {@link #onDraw(android.graphics.Canvas)}.
160 * <table border="2" width="85%" align="center" cellpadding="5">
161 *     <thead>
162 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
163 *     </thead>
164 *
165 *     <tbody>
166 *     <tr>
167 *         <td rowspan="2">Creation</td>
168 *         <td>Constructors</td>
169 *         <td>There is a form of the constructor that are called when the view
170 *         is created from code and a form that is called when the view is
171 *         inflated from a layout file. The second form should parse and apply
172 *         any attributes defined in the layout file.
173 *         </td>
174 *     </tr>
175 *     <tr>
176 *         <td><code>{@link #onFinishInflate()}</code></td>
177 *         <td>Called after a view and all of its children has been inflated
178 *         from XML.</td>
179 *     </tr>
180 *
181 *     <tr>
182 *         <td rowspan="3">Layout</td>
183 *         <td><code>{@link #onMeasure(int, int)}</code></td>
184 *         <td>Called to determine the size requirements for this view and all
185 *         of its children.
186 *         </td>
187 *     </tr>
188 *     <tr>
189 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
190 *         <td>Called when this view should assign a size and position to all
191 *         of its children.
192 *         </td>
193 *     </tr>
194 *     <tr>
195 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
196 *         <td>Called when the size of this view has changed.
197 *         </td>
198 *     </tr>
199 *
200 *     <tr>
201 *         <td>Drawing</td>
202 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
203 *         <td>Called when the view should render its content.
204 *         </td>
205 *     </tr>
206 *
207 *     <tr>
208 *         <td rowspan="4">Event processing</td>
209 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
210 *         <td>Called when a new hardware key event occurs.
211 *         </td>
212 *     </tr>
213 *     <tr>
214 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
215 *         <td>Called when a hardware key up event occurs.
216 *         </td>
217 *     </tr>
218 *     <tr>
219 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
220 *         <td>Called when a trackball motion event occurs.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
225 *         <td>Called when a touch screen motion event occurs.
226 *         </td>
227 *     </tr>
228 *
229 *     <tr>
230 *         <td rowspan="2">Focus</td>
231 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
232 *         <td>Called when the view gains or loses focus.
233 *         </td>
234 *     </tr>
235 *
236 *     <tr>
237 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
238 *         <td>Called when the window containing the view gains or loses focus.
239 *         </td>
240 *     </tr>
241 *
242 *     <tr>
243 *         <td rowspan="3">Attaching</td>
244 *         <td><code>{@link #onAttachedToWindow()}</code></td>
245 *         <td>Called when the view is attached to a window.
246 *         </td>
247 *     </tr>
248 *
249 *     <tr>
250 *         <td><code>{@link #onDetachedFromWindow}</code></td>
251 *         <td>Called when the view is detached from its window.
252 *         </td>
253 *     </tr>
254 *
255 *     <tr>
256 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
257 *         <td>Called when the visibility of the window containing the view
258 *         has changed.
259 *         </td>
260 *     </tr>
261 *     </tbody>
262 *
263 * </table>
264 * </p>
265 *
266 * <a name="IDs"></a>
267 * <h3>IDs</h3>
268 * Views may have an integer id associated with them. These ids are typically
269 * assigned in the layout XML files, and are used to find specific views within
270 * the view tree. A common pattern is to:
271 * <ul>
272 * <li>Define a Button in the layout file and assign it a unique ID.
273 * <pre>
274 * &lt;Button
275 *     android:id="@+id/my_button"
276 *     android:layout_width="wrap_content"
277 *     android:layout_height="wrap_content"
278 *     android:text="@string/my_button_text"/&gt;
279 * </pre></li>
280 * <li>From the onCreate method of an Activity, find the Button
281 * <pre class="prettyprint">
282 *      Button myButton = (Button) findViewById(R.id.my_button);
283 * </pre></li>
284 * </ul>
285 * <p>
286 * View IDs need not be unique throughout the tree, but it is good practice to
287 * ensure that they are at least unique within the part of the tree you are
288 * searching.
289 * </p>
290 *
291 * <a name="Position"></a>
292 * <h3>Position</h3>
293 * <p>
294 * The geometry of a view is that of a rectangle. A view has a location,
295 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
296 * two dimensions, expressed as a width and a height. The unit for location
297 * and dimensions is the pixel.
298 * </p>
299 *
300 * <p>
301 * It is possible to retrieve the location of a view by invoking the methods
302 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
303 * coordinate of the rectangle representing the view. The latter returns the
304 * top, or Y, coordinate of the rectangle representing the view. These methods
305 * both return the location of the view relative to its parent. For instance,
306 * when getLeft() returns 20, that means the view is located 20 pixels to the
307 * right of the left edge of its direct parent.
308 * </p>
309 *
310 * <p>
311 * In addition, several convenience methods are offered to avoid unnecessary
312 * computations, namely {@link #getRight()} and {@link #getBottom()}.
313 * These methods return the coordinates of the right and bottom edges of the
314 * rectangle representing the view. For instance, calling {@link #getRight()}
315 * is similar to the following computation: <code>getLeft() + getWidth()</code>
316 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
317 * </p>
318 *
319 * <a name="SizePaddingMargins"></a>
320 * <h3>Size, padding and margins</h3>
321 * <p>
322 * The size of a view is expressed with a width and a height. A view actually
323 * possess two pairs of width and height values.
324 * </p>
325 *
326 * <p>
327 * The first pair is known as <em>measured width</em> and
328 * <em>measured height</em>. These dimensions define how big a view wants to be
329 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
330 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
331 * and {@link #getMeasuredHeight()}.
332 * </p>
333 *
334 * <p>
335 * The second pair is simply known as <em>width</em> and <em>height</em>, or
336 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
337 * dimensions define the actual size of the view on screen, at drawing time and
338 * after layout. These values may, but do not have to, be different from the
339 * measured width and height. The width and height can be obtained by calling
340 * {@link #getWidth()} and {@link #getHeight()}.
341 * </p>
342 *
343 * <p>
344 * To measure its dimensions, a view takes into account its padding. The padding
345 * is expressed in pixels for the left, top, right and bottom parts of the view.
346 * Padding can be used to offset the content of the view by a specific amount of
347 * pixels. For instance, a left padding of 2 will push the view's content by
348 * 2 pixels to the right of the left edge. Padding can be set using the
349 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
350 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
351 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
352 * {@link #getPaddingEnd()}.
353 * </p>
354 *
355 * <p>
356 * Even though a view can define a padding, it does not provide any support for
357 * margins. However, view groups provide such a support. Refer to
358 * {@link android.view.ViewGroup} and
359 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
360 * </p>
361 *
362 * <a name="Layout"></a>
363 * <h3>Layout</h3>
364 * <p>
365 * Layout is a two pass process: a measure pass and a layout pass. The measuring
366 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
367 * of the view tree. Each view pushes dimension specifications down the tree
368 * during the recursion. At the end of the measure pass, every view has stored
369 * its measurements. The second pass happens in
370 * {@link #layout(int,int,int,int)} and is also top-down. During
371 * this pass each parent is responsible for positioning all of its children
372 * using the sizes computed in the measure pass.
373 * </p>
374 *
375 * <p>
376 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
377 * {@link #getMeasuredHeight()} values must be set, along with those for all of
378 * that view's descendants. A view's measured width and measured height values
379 * must respect the constraints imposed by the view's parents. This guarantees
380 * that at the end of the measure pass, all parents accept all of their
381 * children's measurements. A parent view may call measure() more than once on
382 * its children. For example, the parent may measure each child once with
383 * unspecified dimensions to find out how big they want to be, then call
384 * measure() on them again with actual numbers if the sum of all the children's
385 * unconstrained sizes is too big or too small.
386 * </p>
387 *
388 * <p>
389 * The measure pass uses two classes to communicate dimensions. The
390 * {@link MeasureSpec} class is used by views to tell their parents how they
391 * want to be measured and positioned. The base LayoutParams class just
392 * describes how big the view wants to be for both width and height. For each
393 * dimension, it can specify one of:
394 * <ul>
395 * <li> an exact number
396 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
397 * (minus padding)
398 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
399 * enclose its content (plus padding).
400 * </ul>
401 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
402 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
403 * an X and Y value.
404 * </p>
405 *
406 * <p>
407 * MeasureSpecs are used to push requirements down the tree from parent to
408 * child. A MeasureSpec can be in one of three modes:
409 * <ul>
410 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
411 * of a child view. For example, a LinearLayout may call measure() on its child
412 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
413 * tall the child view wants to be given a width of 240 pixels.
414 * <li>EXACTLY: This is used by the parent to impose an exact size on the
415 * child. The child must use this size, and guarantee that all of its
416 * descendants will fit within this size.
417 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
418 * child. The child must gurantee that it and all of its descendants will fit
419 * within this size.
420 * </ul>
421 * </p>
422 *
423 * <p>
424 * To intiate a layout, call {@link #requestLayout}. This method is typically
425 * called by a view on itself when it believes that is can no longer fit within
426 * its current bounds.
427 * </p>
428 *
429 * <a name="Drawing"></a>
430 * <h3>Drawing</h3>
431 * <p>
432 * Drawing is handled by walking the tree and rendering each view that
433 * intersects the invalid region. Because the tree is traversed in-order,
434 * this means that parents will draw before (i.e., behind) their children, with
435 * siblings drawn in the order they appear in the tree.
436 * If you set a background drawable for a View, then the View will draw it for you
437 * before calling back to its <code>onDraw()</code> method.
438 * </p>
439 *
440 * <p>
441 * Note that the framework will not draw views that are not in the invalid region.
442 * </p>
443 *
444 * <p>
445 * To force a view to draw, call {@link #invalidate()}.
446 * </p>
447 *
448 * <a name="EventHandlingThreading"></a>
449 * <h3>Event Handling and Threading</h3>
450 * <p>
451 * The basic cycle of a view is as follows:
452 * <ol>
453 * <li>An event comes in and is dispatched to the appropriate view. The view
454 * handles the event and notifies any listeners.</li>
455 * <li>If in the course of processing the event, the view's bounds may need
456 * to be changed, the view will call {@link #requestLayout()}.</li>
457 * <li>Similarly, if in the course of processing the event the view's appearance
458 * may need to be changed, the view will call {@link #invalidate()}.</li>
459 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
460 * the framework will take care of measuring, laying out, and drawing the tree
461 * as appropriate.</li>
462 * </ol>
463 * </p>
464 *
465 * <p><em>Note: The entire view tree is single threaded. You must always be on
466 * the UI thread when calling any method on any view.</em>
467 * If you are doing work on other threads and want to update the state of a view
468 * from that thread, you should use a {@link Handler}.
469 * </p>
470 *
471 * <a name="FocusHandling"></a>
472 * <h3>Focus Handling</h3>
473 * <p>
474 * The framework will handle routine focus movement in response to user input.
475 * This includes changing the focus as views are removed or hidden, or as new
476 * views become available. Views indicate their willingness to take focus
477 * through the {@link #isFocusable} method. To change whether a view can take
478 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
479 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
480 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
481 * </p>
482 * <p>
483 * Focus movement is based on an algorithm which finds the nearest neighbor in a
484 * given direction. In rare cases, the default algorithm may not match the
485 * intended behavior of the developer. In these situations, you can provide
486 * explicit overrides by using these XML attributes in the layout file:
487 * <pre>
488 * nextFocusDown
489 * nextFocusLeft
490 * nextFocusRight
491 * nextFocusUp
492 * </pre>
493 * </p>
494 *
495 *
496 * <p>
497 * To get a particular view to take focus, call {@link #requestFocus()}.
498 * </p>
499 *
500 * <a name="TouchMode"></a>
501 * <h3>Touch Mode</h3>
502 * <p>
503 * When a user is navigating a user interface via directional keys such as a D-pad, it is
504 * necessary to give focus to actionable items such as buttons so the user can see
505 * what will take input.  If the device has touch capabilities, however, and the user
506 * begins interacting with the interface by touching it, it is no longer necessary to
507 * always highlight, or give focus to, a particular view.  This motivates a mode
508 * for interaction named 'touch mode'.
509 * </p>
510 * <p>
511 * For a touch capable device, once the user touches the screen, the device
512 * will enter touch mode.  From this point onward, only views for which
513 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
514 * Other views that are touchable, like buttons, will not take focus when touched; they will
515 * only fire the on click listeners.
516 * </p>
517 * <p>
518 * Any time a user hits a directional key, such as a D-pad direction, the view device will
519 * exit touch mode, and find a view to take focus, so that the user may resume interacting
520 * with the user interface without touching the screen again.
521 * </p>
522 * <p>
523 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
524 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
525 * </p>
526 *
527 * <a name="Scrolling"></a>
528 * <h3>Scrolling</h3>
529 * <p>
530 * The framework provides basic support for views that wish to internally
531 * scroll their content. This includes keeping track of the X and Y scroll
532 * offset as well as mechanisms for drawing scrollbars. See
533 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
534 * {@link #awakenScrollBars()} for more details.
535 * </p>
536 *
537 * <a name="Tags"></a>
538 * <h3>Tags</h3>
539 * <p>
540 * Unlike IDs, tags are not used to identify views. Tags are essentially an
541 * extra piece of information that can be associated with a view. They are most
542 * often used as a convenience to store data related to views in the views
543 * themselves rather than by putting them in a separate structure.
544 * </p>
545 *
546 * <a name="Properties"></a>
547 * <h3>Properties</h3>
548 * <p>
549 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
550 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
551 * available both in the {@link Property} form as well as in similarly-named setter/getter
552 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
553 * be used to set persistent state associated with these rendering-related properties on the view.
554 * The properties and methods can also be used in conjunction with
555 * {@link android.animation.Animator Animator}-based animations, described more in the
556 * <a href="#Animation">Animation</a> section.
557 * </p>
558 *
559 * <a name="Animation"></a>
560 * <h3>Animation</h3>
561 * <p>
562 * Starting with Android 3.0, the preferred way of animating views is to use the
563 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
564 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
565 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
566 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
567 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
568 * makes animating these View properties particularly easy and efficient.
569 * </p>
570 * <p>
571 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
572 * You can attach an {@link Animation} object to a view using
573 * {@link #setAnimation(Animation)} or
574 * {@link #startAnimation(Animation)}. The animation can alter the scale,
575 * rotation, translation and alpha of a view over time. If the animation is
576 * attached to a view that has children, the animation will affect the entire
577 * subtree rooted by that node. When an animation is started, the framework will
578 * take care of redrawing the appropriate views until the animation completes.
579 * </p>
580 *
581 * <a name="Security"></a>
582 * <h3>Security</h3>
583 * <p>
584 * Sometimes it is essential that an application be able to verify that an action
585 * is being performed with the full knowledge and consent of the user, such as
586 * granting a permission request, making a purchase or clicking on an advertisement.
587 * Unfortunately, a malicious application could try to spoof the user into
588 * performing these actions, unaware, by concealing the intended purpose of the view.
589 * As a remedy, the framework offers a touch filtering mechanism that can be used to
590 * improve the security of views that provide access to sensitive functionality.
591 * </p><p>
592 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
593 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
594 * will discard touches that are received whenever the view's window is obscured by
595 * another visible window.  As a result, the view will not receive touches whenever a
596 * toast, dialog or other window appears above the view's window.
597 * </p><p>
598 * For more fine-grained control over security, consider overriding the
599 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
600 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
601 * </p>
602 *
603 * @attr ref android.R.styleable#View_alpha
604 * @attr ref android.R.styleable#View_background
605 * @attr ref android.R.styleable#View_clickable
606 * @attr ref android.R.styleable#View_contentDescription
607 * @attr ref android.R.styleable#View_drawingCacheQuality
608 * @attr ref android.R.styleable#View_duplicateParentState
609 * @attr ref android.R.styleable#View_id
610 * @attr ref android.R.styleable#View_requiresFadingEdge
611 * @attr ref android.R.styleable#View_fadeScrollbars
612 * @attr ref android.R.styleable#View_fadingEdgeLength
613 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
614 * @attr ref android.R.styleable#View_fitsSystemWindows
615 * @attr ref android.R.styleable#View_isScrollContainer
616 * @attr ref android.R.styleable#View_focusable
617 * @attr ref android.R.styleable#View_focusableInTouchMode
618 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
619 * @attr ref android.R.styleable#View_keepScreenOn
620 * @attr ref android.R.styleable#View_layerType
621 * @attr ref android.R.styleable#View_longClickable
622 * @attr ref android.R.styleable#View_minHeight
623 * @attr ref android.R.styleable#View_minWidth
624 * @attr ref android.R.styleable#View_nextFocusDown
625 * @attr ref android.R.styleable#View_nextFocusLeft
626 * @attr ref android.R.styleable#View_nextFocusRight
627 * @attr ref android.R.styleable#View_nextFocusUp
628 * @attr ref android.R.styleable#View_onClick
629 * @attr ref android.R.styleable#View_padding
630 * @attr ref android.R.styleable#View_paddingBottom
631 * @attr ref android.R.styleable#View_paddingLeft
632 * @attr ref android.R.styleable#View_paddingRight
633 * @attr ref android.R.styleable#View_paddingTop
634 * @attr ref android.R.styleable#View_paddingStart
635 * @attr ref android.R.styleable#View_paddingEnd
636 * @attr ref android.R.styleable#View_saveEnabled
637 * @attr ref android.R.styleable#View_rotation
638 * @attr ref android.R.styleable#View_rotationX
639 * @attr ref android.R.styleable#View_rotationY
640 * @attr ref android.R.styleable#View_scaleX
641 * @attr ref android.R.styleable#View_scaleY
642 * @attr ref android.R.styleable#View_scrollX
643 * @attr ref android.R.styleable#View_scrollY
644 * @attr ref android.R.styleable#View_scrollbarSize
645 * @attr ref android.R.styleable#View_scrollbarStyle
646 * @attr ref android.R.styleable#View_scrollbars
647 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
648 * @attr ref android.R.styleable#View_scrollbarFadeDuration
649 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
650 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
651 * @attr ref android.R.styleable#View_scrollbarThumbVertical
652 * @attr ref android.R.styleable#View_scrollbarTrackVertical
653 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
654 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
655 * @attr ref android.R.styleable#View_soundEffectsEnabled
656 * @attr ref android.R.styleable#View_tag
657 * @attr ref android.R.styleable#View_textAlignment
658 * @attr ref android.R.styleable#View_transformPivotX
659 * @attr ref android.R.styleable#View_transformPivotY
660 * @attr ref android.R.styleable#View_translationX
661 * @attr ref android.R.styleable#View_translationY
662 * @attr ref android.R.styleable#View_visibility
663 *
664 * @see android.view.ViewGroup
665 */
666public class View implements Drawable.Callback, KeyEvent.Callback,
667        AccessibilityEventSource {
668    private static final boolean DBG = false;
669
670    /**
671     * The logging tag used by this class with android.util.Log.
672     */
673    protected static final String VIEW_LOG_TAG = "View";
674
675    /**
676     * When set to true, apps will draw debugging information about their layouts.
677     *
678     * @hide
679     */
680    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
681
682    /**
683     * Used to mark a View that has no ID.
684     */
685    public static final int NO_ID = -1;
686
687    /**
688     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
689     * calling setFlags.
690     */
691    private static final int NOT_FOCUSABLE = 0x00000000;
692
693    /**
694     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
695     * setFlags.
696     */
697    private static final int FOCUSABLE = 0x00000001;
698
699    /**
700     * Mask for use with setFlags indicating bits used for focus.
701     */
702    private static final int FOCUSABLE_MASK = 0x00000001;
703
704    /**
705     * This view will adjust its padding to fit sytem windows (e.g. status bar)
706     */
707    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
708
709    /**
710     * This view is visible.
711     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
712     * android:visibility}.
713     */
714    public static final int VISIBLE = 0x00000000;
715
716    /**
717     * This view is invisible, but it still takes up space for layout purposes.
718     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
719     * android:visibility}.
720     */
721    public static final int INVISIBLE = 0x00000004;
722
723    /**
724     * This view is invisible, and it doesn't take any space for layout
725     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
726     * android:visibility}.
727     */
728    public static final int GONE = 0x00000008;
729
730    /**
731     * Mask for use with setFlags indicating bits used for visibility.
732     * {@hide}
733     */
734    static final int VISIBILITY_MASK = 0x0000000C;
735
736    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
737
738    /**
739     * This view is enabled. Interpretation varies by subclass.
740     * Use with ENABLED_MASK when calling setFlags.
741     * {@hide}
742     */
743    static final int ENABLED = 0x00000000;
744
745    /**
746     * This view is disabled. Interpretation varies by subclass.
747     * Use with ENABLED_MASK when calling setFlags.
748     * {@hide}
749     */
750    static final int DISABLED = 0x00000020;
751
752   /**
753    * Mask for use with setFlags indicating bits used for indicating whether
754    * this view is enabled
755    * {@hide}
756    */
757    static final int ENABLED_MASK = 0x00000020;
758
759    /**
760     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
761     * called and further optimizations will be performed. It is okay to have
762     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
763     * {@hide}
764     */
765    static final int WILL_NOT_DRAW = 0x00000080;
766
767    /**
768     * Mask for use with setFlags indicating bits used for indicating whether
769     * this view is will draw
770     * {@hide}
771     */
772    static final int DRAW_MASK = 0x00000080;
773
774    /**
775     * <p>This view doesn't show scrollbars.</p>
776     * {@hide}
777     */
778    static final int SCROLLBARS_NONE = 0x00000000;
779
780    /**
781     * <p>This view shows horizontal scrollbars.</p>
782     * {@hide}
783     */
784    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
785
786    /**
787     * <p>This view shows vertical scrollbars.</p>
788     * {@hide}
789     */
790    static final int SCROLLBARS_VERTICAL = 0x00000200;
791
792    /**
793     * <p>Mask for use with setFlags indicating bits used for indicating which
794     * scrollbars are enabled.</p>
795     * {@hide}
796     */
797    static final int SCROLLBARS_MASK = 0x00000300;
798
799    /**
800     * Indicates that the view should filter touches when its window is obscured.
801     * Refer to the class comments for more information about this security feature.
802     * {@hide}
803     */
804    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
805
806    /**
807     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
808     * that they are optional and should be skipped if the window has
809     * requested system UI flags that ignore those insets for layout.
810     */
811    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
812
813    /**
814     * <p>This view doesn't show fading edges.</p>
815     * {@hide}
816     */
817    static final int FADING_EDGE_NONE = 0x00000000;
818
819    /**
820     * <p>This view shows horizontal fading edges.</p>
821     * {@hide}
822     */
823    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
824
825    /**
826     * <p>This view shows vertical fading edges.</p>
827     * {@hide}
828     */
829    static final int FADING_EDGE_VERTICAL = 0x00002000;
830
831    /**
832     * <p>Mask for use with setFlags indicating bits used for indicating which
833     * fading edges are enabled.</p>
834     * {@hide}
835     */
836    static final int FADING_EDGE_MASK = 0x00003000;
837
838    /**
839     * <p>Indicates this view can be clicked. When clickable, a View reacts
840     * to clicks by notifying the OnClickListener.<p>
841     * {@hide}
842     */
843    static final int CLICKABLE = 0x00004000;
844
845    /**
846     * <p>Indicates this view is caching its drawing into a bitmap.</p>
847     * {@hide}
848     */
849    static final int DRAWING_CACHE_ENABLED = 0x00008000;
850
851    /**
852     * <p>Indicates that no icicle should be saved for this view.<p>
853     * {@hide}
854     */
855    static final int SAVE_DISABLED = 0x000010000;
856
857    /**
858     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
859     * property.</p>
860     * {@hide}
861     */
862    static final int SAVE_DISABLED_MASK = 0x000010000;
863
864    /**
865     * <p>Indicates that no drawing cache should ever be created for this view.<p>
866     * {@hide}
867     */
868    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
869
870    /**
871     * <p>Indicates this view can take / keep focus when int touch mode.</p>
872     * {@hide}
873     */
874    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
875
876    /**
877     * <p>Enables low quality mode for the drawing cache.</p>
878     */
879    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
880
881    /**
882     * <p>Enables high quality mode for the drawing cache.</p>
883     */
884    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
885
886    /**
887     * <p>Enables automatic quality mode for the drawing cache.</p>
888     */
889    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
890
891    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
892            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
893    };
894
895    /**
896     * <p>Mask for use with setFlags indicating bits used for the cache
897     * quality property.</p>
898     * {@hide}
899     */
900    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
901
902    /**
903     * <p>
904     * Indicates this view can be long clicked. When long clickable, a View
905     * reacts to long clicks by notifying the OnLongClickListener or showing a
906     * context menu.
907     * </p>
908     * {@hide}
909     */
910    static final int LONG_CLICKABLE = 0x00200000;
911
912    /**
913     * <p>Indicates that this view gets its drawable states from its direct parent
914     * and ignores its original internal states.</p>
915     *
916     * @hide
917     */
918    static final int DUPLICATE_PARENT_STATE = 0x00400000;
919
920    /**
921     * The scrollbar style to display the scrollbars inside the content area,
922     * without increasing the padding. The scrollbars will be overlaid with
923     * translucency on the view's content.
924     */
925    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
926
927    /**
928     * The scrollbar style to display the scrollbars inside the padded area,
929     * increasing the padding of the view. The scrollbars will not overlap the
930     * content area of the view.
931     */
932    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
933
934    /**
935     * The scrollbar style to display the scrollbars at the edge of the view,
936     * without increasing the padding. The scrollbars will be overlaid with
937     * translucency.
938     */
939    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
940
941    /**
942     * The scrollbar style to display the scrollbars at the edge of the view,
943     * increasing the padding of the view. The scrollbars will only overlap the
944     * background, if any.
945     */
946    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
947
948    /**
949     * Mask to check if the scrollbar style is overlay or inset.
950     * {@hide}
951     */
952    static final int SCROLLBARS_INSET_MASK = 0x01000000;
953
954    /**
955     * Mask to check if the scrollbar style is inside or outside.
956     * {@hide}
957     */
958    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
959
960    /**
961     * Mask for scrollbar style.
962     * {@hide}
963     */
964    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
965
966    /**
967     * View flag indicating that the screen should remain on while the
968     * window containing this view is visible to the user.  This effectively
969     * takes care of automatically setting the WindowManager's
970     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
971     */
972    public static final int KEEP_SCREEN_ON = 0x04000000;
973
974    /**
975     * View flag indicating whether this view should have sound effects enabled
976     * for events such as clicking and touching.
977     */
978    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
979
980    /**
981     * View flag indicating whether this view should have haptic feedback
982     * enabled for events such as long presses.
983     */
984    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
985
986    /**
987     * <p>Indicates that the view hierarchy should stop saving state when
988     * it reaches this view.  If state saving is initiated immediately at
989     * the view, it will be allowed.
990     * {@hide}
991     */
992    static final int PARENT_SAVE_DISABLED = 0x20000000;
993
994    /**
995     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
996     * {@hide}
997     */
998    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
999
1000    /**
1001     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1002     * should add all focusable Views regardless if they are focusable in touch mode.
1003     */
1004    public static final int FOCUSABLES_ALL = 0x00000000;
1005
1006    /**
1007     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1008     * should add only Views focusable in touch mode.
1009     */
1010    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1011
1012    /**
1013     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1014     * item.
1015     */
1016    public static final int FOCUS_BACKWARD = 0x00000001;
1017
1018    /**
1019     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1020     * item.
1021     */
1022    public static final int FOCUS_FORWARD = 0x00000002;
1023
1024    /**
1025     * Use with {@link #focusSearch(int)}. Move focus to the left.
1026     */
1027    public static final int FOCUS_LEFT = 0x00000011;
1028
1029    /**
1030     * Use with {@link #focusSearch(int)}. Move focus up.
1031     */
1032    public static final int FOCUS_UP = 0x00000021;
1033
1034    /**
1035     * Use with {@link #focusSearch(int)}. Move focus to the right.
1036     */
1037    public static final int FOCUS_RIGHT = 0x00000042;
1038
1039    /**
1040     * Use with {@link #focusSearch(int)}. Move focus down.
1041     */
1042    public static final int FOCUS_DOWN = 0x00000082;
1043
1044    /**
1045     * Bits of {@link #getMeasuredWidthAndState()} and
1046     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1047     */
1048    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1049
1050    /**
1051     * Bits of {@link #getMeasuredWidthAndState()} and
1052     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1053     */
1054    public static final int MEASURED_STATE_MASK = 0xff000000;
1055
1056    /**
1057     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1058     * for functions that combine both width and height into a single int,
1059     * such as {@link #getMeasuredState()} and the childState argument of
1060     * {@link #resolveSizeAndState(int, int, int)}.
1061     */
1062    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1063
1064    /**
1065     * Bit of {@link #getMeasuredWidthAndState()} and
1066     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1067     * is smaller that the space the view would like to have.
1068     */
1069    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1070
1071    /**
1072     * Base View state sets
1073     */
1074    // Singles
1075    /**
1076     * Indicates the view has no states set. States are used with
1077     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1078     * view depending on its state.
1079     *
1080     * @see android.graphics.drawable.Drawable
1081     * @see #getDrawableState()
1082     */
1083    protected static final int[] EMPTY_STATE_SET;
1084    /**
1085     * Indicates the view is enabled. States are used with
1086     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1087     * view depending on its state.
1088     *
1089     * @see android.graphics.drawable.Drawable
1090     * @see #getDrawableState()
1091     */
1092    protected static final int[] ENABLED_STATE_SET;
1093    /**
1094     * Indicates the view is focused. States are used with
1095     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1096     * view depending on its state.
1097     *
1098     * @see android.graphics.drawable.Drawable
1099     * @see #getDrawableState()
1100     */
1101    protected static final int[] FOCUSED_STATE_SET;
1102    /**
1103     * Indicates the view is selected. States are used with
1104     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1105     * view depending on its state.
1106     *
1107     * @see android.graphics.drawable.Drawable
1108     * @see #getDrawableState()
1109     */
1110    protected static final int[] SELECTED_STATE_SET;
1111    /**
1112     * Indicates the view is pressed. States are used with
1113     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1114     * view depending on its state.
1115     *
1116     * @see android.graphics.drawable.Drawable
1117     * @see #getDrawableState()
1118     * @hide
1119     */
1120    protected static final int[] PRESSED_STATE_SET;
1121    /**
1122     * Indicates the view's window has focus. States are used with
1123     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1124     * view depending on its state.
1125     *
1126     * @see android.graphics.drawable.Drawable
1127     * @see #getDrawableState()
1128     */
1129    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1130    // Doubles
1131    /**
1132     * Indicates the view is enabled and has the focus.
1133     *
1134     * @see #ENABLED_STATE_SET
1135     * @see #FOCUSED_STATE_SET
1136     */
1137    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1138    /**
1139     * Indicates the view is enabled and selected.
1140     *
1141     * @see #ENABLED_STATE_SET
1142     * @see #SELECTED_STATE_SET
1143     */
1144    protected static final int[] ENABLED_SELECTED_STATE_SET;
1145    /**
1146     * Indicates the view is enabled and that its window has focus.
1147     *
1148     * @see #ENABLED_STATE_SET
1149     * @see #WINDOW_FOCUSED_STATE_SET
1150     */
1151    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1152    /**
1153     * Indicates the view is focused and selected.
1154     *
1155     * @see #FOCUSED_STATE_SET
1156     * @see #SELECTED_STATE_SET
1157     */
1158    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1159    /**
1160     * Indicates the view has the focus and that its window has the focus.
1161     *
1162     * @see #FOCUSED_STATE_SET
1163     * @see #WINDOW_FOCUSED_STATE_SET
1164     */
1165    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1166    /**
1167     * Indicates the view is selected and that its window has the focus.
1168     *
1169     * @see #SELECTED_STATE_SET
1170     * @see #WINDOW_FOCUSED_STATE_SET
1171     */
1172    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1173    // Triples
1174    /**
1175     * Indicates the view is enabled, focused and selected.
1176     *
1177     * @see #ENABLED_STATE_SET
1178     * @see #FOCUSED_STATE_SET
1179     * @see #SELECTED_STATE_SET
1180     */
1181    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1182    /**
1183     * Indicates the view is enabled, focused and its window has the focus.
1184     *
1185     * @see #ENABLED_STATE_SET
1186     * @see #FOCUSED_STATE_SET
1187     * @see #WINDOW_FOCUSED_STATE_SET
1188     */
1189    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1190    /**
1191     * Indicates the view is enabled, selected and its window has the focus.
1192     *
1193     * @see #ENABLED_STATE_SET
1194     * @see #SELECTED_STATE_SET
1195     * @see #WINDOW_FOCUSED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is focused, selected and its window has the focus.
1200     *
1201     * @see #FOCUSED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is enabled, focused, selected and its window
1208     * has the focus.
1209     *
1210     * @see #ENABLED_STATE_SET
1211     * @see #FOCUSED_STATE_SET
1212     * @see #SELECTED_STATE_SET
1213     * @see #WINDOW_FOCUSED_STATE_SET
1214     */
1215    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1216    /**
1217     * Indicates the view is pressed and its window has the focus.
1218     *
1219     * @see #PRESSED_STATE_SET
1220     * @see #WINDOW_FOCUSED_STATE_SET
1221     */
1222    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1223    /**
1224     * Indicates the view is pressed and selected.
1225     *
1226     * @see #PRESSED_STATE_SET
1227     * @see #SELECTED_STATE_SET
1228     */
1229    protected static final int[] PRESSED_SELECTED_STATE_SET;
1230    /**
1231     * Indicates the view is pressed, selected and its window has the focus.
1232     *
1233     * @see #PRESSED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     * @see #WINDOW_FOCUSED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed and focused.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #FOCUSED_STATE_SET
1243     */
1244    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is pressed, focused and its window has the focus.
1247     *
1248     * @see #PRESSED_STATE_SET
1249     * @see #FOCUSED_STATE_SET
1250     * @see #WINDOW_FOCUSED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, focused and selected.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #SELECTED_STATE_SET
1258     * @see #FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed, focused, selected and its window has the focus.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     * @see #WINDOW_FOCUSED_STATE_SET
1268     */
1269    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1270    /**
1271     * Indicates the view is pressed and enabled.
1272     *
1273     * @see #PRESSED_STATE_SET
1274     * @see #ENABLED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_ENABLED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed, enabled and its window has the focus.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #ENABLED_STATE_SET
1282     * @see #WINDOW_FOCUSED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, enabled and selected.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #ENABLED_STATE_SET
1290     * @see #SELECTED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, enabled, selected and its window has the
1295     * focus.
1296     *
1297     * @see #PRESSED_STATE_SET
1298     * @see #ENABLED_STATE_SET
1299     * @see #SELECTED_STATE_SET
1300     * @see #WINDOW_FOCUSED_STATE_SET
1301     */
1302    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1303    /**
1304     * Indicates the view is pressed, enabled and focused.
1305     *
1306     * @see #PRESSED_STATE_SET
1307     * @see #ENABLED_STATE_SET
1308     * @see #FOCUSED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled, focused and its window has the
1313     * focus.
1314     *
1315     * @see #PRESSED_STATE_SET
1316     * @see #ENABLED_STATE_SET
1317     * @see #FOCUSED_STATE_SET
1318     * @see #WINDOW_FOCUSED_STATE_SET
1319     */
1320    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1321    /**
1322     * Indicates the view is pressed, enabled, focused and selected.
1323     *
1324     * @see #PRESSED_STATE_SET
1325     * @see #ENABLED_STATE_SET
1326     * @see #SELECTED_STATE_SET
1327     * @see #FOCUSED_STATE_SET
1328     */
1329    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1330    /**
1331     * Indicates the view is pressed, enabled, focused, selected and its window
1332     * has the focus.
1333     *
1334     * @see #PRESSED_STATE_SET
1335     * @see #ENABLED_STATE_SET
1336     * @see #SELECTED_STATE_SET
1337     * @see #FOCUSED_STATE_SET
1338     * @see #WINDOW_FOCUSED_STATE_SET
1339     */
1340    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1341
1342    /**
1343     * The order here is very important to {@link #getDrawableState()}
1344     */
1345    private static final int[][] VIEW_STATE_SETS;
1346
1347    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1348    static final int VIEW_STATE_SELECTED = 1 << 1;
1349    static final int VIEW_STATE_FOCUSED = 1 << 2;
1350    static final int VIEW_STATE_ENABLED = 1 << 3;
1351    static final int VIEW_STATE_PRESSED = 1 << 4;
1352    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1353    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1354    static final int VIEW_STATE_HOVERED = 1 << 7;
1355    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1356    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1357
1358    static final int[] VIEW_STATE_IDS = new int[] {
1359        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1360        R.attr.state_selected,          VIEW_STATE_SELECTED,
1361        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1362        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1363        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1364        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1365        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1366        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1367        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1368        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1369    };
1370
1371    static {
1372        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1373            throw new IllegalStateException(
1374                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1375        }
1376        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1377        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1378            int viewState = R.styleable.ViewDrawableStates[i];
1379            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1380                if (VIEW_STATE_IDS[j] == viewState) {
1381                    orderedIds[i * 2] = viewState;
1382                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1383                }
1384            }
1385        }
1386        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1387        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1388        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1389            int numBits = Integer.bitCount(i);
1390            int[] set = new int[numBits];
1391            int pos = 0;
1392            for (int j = 0; j < orderedIds.length; j += 2) {
1393                if ((i & orderedIds[j+1]) != 0) {
1394                    set[pos++] = orderedIds[j];
1395                }
1396            }
1397            VIEW_STATE_SETS[i] = set;
1398        }
1399
1400        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1401        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1402        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1403        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1404                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1405        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1406        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1408        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1409                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1410        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1412                | VIEW_STATE_FOCUSED];
1413        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1414        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1416        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1418        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420                | VIEW_STATE_ENABLED];
1421        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1423        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1425                | VIEW_STATE_ENABLED];
1426        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1431                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1432
1433        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1434        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1436        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1437                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1438        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1439                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1440                | VIEW_STATE_PRESSED];
1441        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1443        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1445                | VIEW_STATE_PRESSED];
1446        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1451                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1452        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1454        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1459                | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1462                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1463        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1465                | VIEW_STATE_PRESSED];
1466        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1468                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1469        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1471                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1472        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1474                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1475                | VIEW_STATE_PRESSED];
1476    }
1477
1478    /**
1479     * Accessibility event types that are dispatched for text population.
1480     */
1481    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1482            AccessibilityEvent.TYPE_VIEW_CLICKED
1483            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1484            | AccessibilityEvent.TYPE_VIEW_SELECTED
1485            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1486            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1487            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1488            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1489            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1490            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1491            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1492            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1493
1494    /**
1495     * Temporary Rect currently for use in setBackground().  This will probably
1496     * be extended in the future to hold our own class with more than just
1497     * a Rect. :)
1498     */
1499    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1500
1501    /**
1502     * Map used to store views' tags.
1503     */
1504    private SparseArray<Object> mKeyedTags;
1505
1506    /**
1507     * The next available accessiiblity id.
1508     */
1509    private static int sNextAccessibilityViewId;
1510
1511    /**
1512     * The animation currently associated with this view.
1513     * @hide
1514     */
1515    protected Animation mCurrentAnimation = null;
1516
1517    /**
1518     * Width as measured during measure pass.
1519     * {@hide}
1520     */
1521    @ViewDebug.ExportedProperty(category = "measurement")
1522    int mMeasuredWidth;
1523
1524    /**
1525     * Height as measured during measure pass.
1526     * {@hide}
1527     */
1528    @ViewDebug.ExportedProperty(category = "measurement")
1529    int mMeasuredHeight;
1530
1531    /**
1532     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1533     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1534     * its display list. This flag, used only when hw accelerated, allows us to clear the
1535     * flag while retaining this information until it's needed (at getDisplayList() time and
1536     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1537     *
1538     * {@hide}
1539     */
1540    boolean mRecreateDisplayList = false;
1541
1542    /**
1543     * The view's identifier.
1544     * {@hide}
1545     *
1546     * @see #setId(int)
1547     * @see #getId()
1548     */
1549    @ViewDebug.ExportedProperty(resolveId = true)
1550    int mID = NO_ID;
1551
1552    /**
1553     * The stable ID of this view for accessibility purposes.
1554     */
1555    int mAccessibilityViewId = NO_ID;
1556
1557    /**
1558     * @hide
1559     */
1560    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1561
1562    /**
1563     * The view's tag.
1564     * {@hide}
1565     *
1566     * @see #setTag(Object)
1567     * @see #getTag()
1568     */
1569    protected Object mTag;
1570
1571    // for mPrivateFlags:
1572    /** {@hide} */
1573    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1574    /** {@hide} */
1575    static final int PFLAG_FOCUSED                     = 0x00000002;
1576    /** {@hide} */
1577    static final int PFLAG_SELECTED                    = 0x00000004;
1578    /** {@hide} */
1579    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1580    /** {@hide} */
1581    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1582    /** {@hide} */
1583    static final int PFLAG_DRAWN                       = 0x00000020;
1584    /**
1585     * When this flag is set, this view is running an animation on behalf of its
1586     * children and should therefore not cancel invalidate requests, even if they
1587     * lie outside of this view's bounds.
1588     *
1589     * {@hide}
1590     */
1591    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1592    /** {@hide} */
1593    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1594    /** {@hide} */
1595    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1596    /** {@hide} */
1597    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1598    /** {@hide} */
1599    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1600    /** {@hide} */
1601    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1602    /** {@hide} */
1603    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1604    /** {@hide} */
1605    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1606
1607    private static final int PFLAG_PRESSED             = 0x00004000;
1608
1609    /** {@hide} */
1610    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1611    /**
1612     * Flag used to indicate that this view should be drawn once more (and only once
1613     * more) after its animation has completed.
1614     * {@hide}
1615     */
1616    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1617
1618    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1619
1620    /**
1621     * Indicates that the View returned true when onSetAlpha() was called and that
1622     * the alpha must be restored.
1623     * {@hide}
1624     */
1625    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1626
1627    /**
1628     * Set by {@link #setScrollContainer(boolean)}.
1629     */
1630    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1631
1632    /**
1633     * Set by {@link #setScrollContainer(boolean)}.
1634     */
1635    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1636
1637    /**
1638     * View flag indicating whether this view was invalidated (fully or partially.)
1639     *
1640     * @hide
1641     */
1642    static final int PFLAG_DIRTY                       = 0x00200000;
1643
1644    /**
1645     * View flag indicating whether this view was invalidated by an opaque
1646     * invalidate request.
1647     *
1648     * @hide
1649     */
1650    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1651
1652    /**
1653     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1654     *
1655     * @hide
1656     */
1657    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1658
1659    /**
1660     * Indicates whether the background is opaque.
1661     *
1662     * @hide
1663     */
1664    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1665
1666    /**
1667     * Indicates whether the scrollbars are opaque.
1668     *
1669     * @hide
1670     */
1671    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1672
1673    /**
1674     * Indicates whether the view is opaque.
1675     *
1676     * @hide
1677     */
1678    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1679
1680    /**
1681     * Indicates a prepressed state;
1682     * the short time between ACTION_DOWN and recognizing
1683     * a 'real' press. Prepressed is used to recognize quick taps
1684     * even when they are shorter than ViewConfiguration.getTapTimeout().
1685     *
1686     * @hide
1687     */
1688    private static final int PFLAG_PREPRESSED          = 0x02000000;
1689
1690    /**
1691     * Indicates whether the view is temporarily detached.
1692     *
1693     * @hide
1694     */
1695    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1696
1697    /**
1698     * Indicates that we should awaken scroll bars once attached
1699     *
1700     * @hide
1701     */
1702    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1703
1704    /**
1705     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1706     * @hide
1707     */
1708    private static final int PFLAG_HOVERED             = 0x10000000;
1709
1710    /**
1711     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1712     * for transform operations
1713     *
1714     * @hide
1715     */
1716    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1717
1718    /** {@hide} */
1719    static final int PFLAG_ACTIVATED                   = 0x40000000;
1720
1721    /**
1722     * Indicates that this view was specifically invalidated, not just dirtied because some
1723     * child view was invalidated. The flag is used to determine when we need to recreate
1724     * a view's display list (as opposed to just returning a reference to its existing
1725     * display list).
1726     *
1727     * @hide
1728     */
1729    static final int PFLAG_INVALIDATED                 = 0x80000000;
1730
1731    /* Masks for mPrivateFlags2 */
1732
1733    /**
1734     * Indicates that this view has reported that it can accept the current drag's content.
1735     * Cleared when the drag operation concludes.
1736     * @hide
1737     */
1738    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1739
1740    /**
1741     * Indicates that this view is currently directly under the drag location in a
1742     * drag-and-drop operation involving content that it can accept.  Cleared when
1743     * the drag exits the view, or when the drag operation concludes.
1744     * @hide
1745     */
1746    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1747
1748    /**
1749     * Horizontal layout direction of this view is from Left to Right.
1750     * Use with {@link #setLayoutDirection}.
1751     */
1752    public static final int LAYOUT_DIRECTION_LTR = 0;
1753
1754    /**
1755     * Horizontal layout direction of this view is from Right to Left.
1756     * Use with {@link #setLayoutDirection}.
1757     */
1758    public static final int LAYOUT_DIRECTION_RTL = 1;
1759
1760    /**
1761     * Horizontal layout direction of this view is inherited from its parent.
1762     * Use with {@link #setLayoutDirection}.
1763     */
1764    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1765
1766    /**
1767     * Horizontal layout direction of this view is from deduced from the default language
1768     * script for the locale. Use with {@link #setLayoutDirection}.
1769     */
1770    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1771
1772    /**
1773     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1774     * @hide
1775     */
1776    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1777
1778    /**
1779     * Mask for use with private flags indicating bits used for horizontal layout direction.
1780     * @hide
1781     */
1782    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1783
1784    /**
1785     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1786     * right-to-left direction.
1787     * @hide
1788     */
1789    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1790
1791    /**
1792     * Indicates whether the view horizontal layout direction has been resolved.
1793     * @hide
1794     */
1795    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1796
1797    /**
1798     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1799     * @hide
1800     */
1801    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1802            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1803
1804    /*
1805     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1806     * flag value.
1807     * @hide
1808     */
1809    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1810            LAYOUT_DIRECTION_LTR,
1811            LAYOUT_DIRECTION_RTL,
1812            LAYOUT_DIRECTION_INHERIT,
1813            LAYOUT_DIRECTION_LOCALE
1814    };
1815
1816    /**
1817     * Default horizontal layout direction.
1818     * @hide
1819     */
1820    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1821
1822    /**
1823     * Indicates that the view is tracking some sort of transient state
1824     * that the app should not need to be aware of, but that the framework
1825     * should take special care to preserve.
1826     *
1827     * @hide
1828     */
1829    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x00000100;
1830
1831
1832    /**
1833     * Text direction is inherited thru {@link ViewGroup}
1834     */
1835    public static final int TEXT_DIRECTION_INHERIT = 0;
1836
1837    /**
1838     * Text direction is using "first strong algorithm". The first strong directional character
1839     * determines the paragraph direction. If there is no strong directional character, the
1840     * paragraph direction is the view's resolved layout direction.
1841     */
1842    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1843
1844    /**
1845     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1846     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1847     * If there are neither, the paragraph direction is the view's resolved layout direction.
1848     */
1849    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1850
1851    /**
1852     * Text direction is forced to LTR.
1853     */
1854    public static final int TEXT_DIRECTION_LTR = 3;
1855
1856    /**
1857     * Text direction is forced to RTL.
1858     */
1859    public static final int TEXT_DIRECTION_RTL = 4;
1860
1861    /**
1862     * Text direction is coming from the system Locale.
1863     */
1864    public static final int TEXT_DIRECTION_LOCALE = 5;
1865
1866    /**
1867     * Default text direction is inherited
1868     */
1869    public static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1870
1871    /**
1872     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1873     * @hide
1874     */
1875    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1876
1877    /**
1878     * Mask for use with private flags indicating bits used for text direction.
1879     * @hide
1880     */
1881    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1882            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1883
1884    /**
1885     * Array of text direction flags for mapping attribute "textDirection" to correct
1886     * flag value.
1887     * @hide
1888     */
1889    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1890            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1891            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1892            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1893            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1894            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1895            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1896    };
1897
1898    /**
1899     * Indicates whether the view text direction has been resolved.
1900     * @hide
1901     */
1902    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1903            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1904
1905    /**
1906     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1907     * @hide
1908     */
1909    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1910
1911    /**
1912     * Mask for use with private flags indicating bits used for resolved text direction.
1913     * @hide
1914     */
1915    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1916            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1917
1918    /**
1919     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1920     * @hide
1921     */
1922    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1923            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1924
1925    /*
1926     * Default text alignment. The text alignment of this View is inherited from its parent.
1927     * Use with {@link #setTextAlignment(int)}
1928     */
1929    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1930
1931    /**
1932     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1933     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1934     *
1935     * Use with {@link #setTextAlignment(int)}
1936     */
1937    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1938
1939    /**
1940     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1941     *
1942     * Use with {@link #setTextAlignment(int)}
1943     */
1944    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1945
1946    /**
1947     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1948     *
1949     * Use with {@link #setTextAlignment(int)}
1950     */
1951    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1952
1953    /**
1954     * Center the paragraph, e.g. ALIGN_CENTER.
1955     *
1956     * Use with {@link #setTextAlignment(int)}
1957     */
1958    public static final int TEXT_ALIGNMENT_CENTER = 4;
1959
1960    /**
1961     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
1962     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
1963     *
1964     * Use with {@link #setTextAlignment(int)}
1965     */
1966    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
1967
1968    /**
1969     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
1970     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
1971     *
1972     * Use with {@link #setTextAlignment(int)}
1973     */
1974    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
1975
1976    /**
1977     * Default text alignment is inherited
1978     */
1979    public static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
1980
1981    /**
1982      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1983      * @hide
1984      */
1985    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
1986
1987    /**
1988      * Mask for use with private flags indicating bits used for text alignment.
1989      * @hide
1990      */
1991    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
1992
1993    /**
1994     * Array of text direction flags for mapping attribute "textAlignment" to correct
1995     * flag value.
1996     * @hide
1997     */
1998    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
1999            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2000            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2001            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2002            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2003            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2004            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2005            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2006    };
2007
2008    /**
2009     * Indicates whether the view text alignment has been resolved.
2010     * @hide
2011     */
2012    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2013
2014    /**
2015     * Bit shift to get the resolved text alignment.
2016     * @hide
2017     */
2018    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2019
2020    /**
2021     * Mask for use with private flags indicating bits used for text alignment.
2022     * @hide
2023     */
2024    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2025            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2026
2027    /**
2028     * Indicates whether if the view text alignment has been resolved to gravity
2029     */
2030    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2031            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2032
2033    // Accessiblity constants for mPrivateFlags2
2034
2035    /**
2036     * Shift for the bits in {@link #mPrivateFlags2} related to the
2037     * "importantForAccessibility" attribute.
2038     */
2039    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2040
2041    /**
2042     * Automatically determine whether a view is important for accessibility.
2043     */
2044    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2045
2046    /**
2047     * The view is important for accessibility.
2048     */
2049    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2050
2051    /**
2052     * The view is not important for accessibility.
2053     */
2054    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2055
2056    /**
2057     * The default whether the view is important for accessiblity.
2058     */
2059    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2060
2061    /**
2062     * Mask for obtainig the bits which specify how to determine
2063     * whether a view is important for accessibility.
2064     */
2065    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2066        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2067        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2068
2069    /**
2070     * Flag indicating whether a view has accessibility focus.
2071     */
2072    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2073
2074    /**
2075     * Flag indicating whether a view state for accessibility has changed.
2076     */
2077    static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080
2078            << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2079
2080    /**
2081     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2082     * is used to check whether later changes to the view's transform should invalidate the
2083     * view to force the quickReject test to run again.
2084     */
2085    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2086
2087    /**
2088     * Flag indicating that start/end padding has been resolved into left/right padding
2089     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2090     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2091     * during measurement. In some special cases this is required such as when an adapter-based
2092     * view measures prospective children without attaching them to a window.
2093     */
2094    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2095
2096    // There are a couple of flags left in mPrivateFlags2
2097
2098    /* End of masks for mPrivateFlags2 */
2099
2100    /* Masks for mPrivateFlags3 */
2101
2102    /**
2103     * Flag indicating that view has a transform animation set on it. This is used to track whether
2104     * an animation is cleared between successive frames, in order to tell the associated
2105     * DisplayList to clear its animation matrix.
2106     */
2107    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2108
2109    /**
2110     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2111     * animation is cleared between successive frames, in order to tell the associated
2112     * DisplayList to restore its alpha value.
2113     */
2114    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2115
2116
2117    /* End of masks for mPrivateFlags3 */
2118
2119    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2120
2121    /**
2122     * Always allow a user to over-scroll this view, provided it is a
2123     * view that can scroll.
2124     *
2125     * @see #getOverScrollMode()
2126     * @see #setOverScrollMode(int)
2127     */
2128    public static final int OVER_SCROLL_ALWAYS = 0;
2129
2130    /**
2131     * Allow a user to over-scroll this view only if the content is large
2132     * enough to meaningfully scroll, provided it is a view that can scroll.
2133     *
2134     * @see #getOverScrollMode()
2135     * @see #setOverScrollMode(int)
2136     */
2137    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2138
2139    /**
2140     * Never allow a user to over-scroll this view.
2141     *
2142     * @see #getOverScrollMode()
2143     * @see #setOverScrollMode(int)
2144     */
2145    public static final int OVER_SCROLL_NEVER = 2;
2146
2147    /**
2148     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2149     * requested the system UI (status bar) to be visible (the default).
2150     *
2151     * @see #setSystemUiVisibility(int)
2152     */
2153    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2154
2155    /**
2156     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2157     * system UI to enter an unobtrusive "low profile" mode.
2158     *
2159     * <p>This is for use in games, book readers, video players, or any other
2160     * "immersive" application where the usual system chrome is deemed too distracting.
2161     *
2162     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2163     *
2164     * @see #setSystemUiVisibility(int)
2165     */
2166    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2167
2168    /**
2169     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2170     * system navigation be temporarily hidden.
2171     *
2172     * <p>This is an even less obtrusive state than that called for by
2173     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2174     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2175     * those to disappear. This is useful (in conjunction with the
2176     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2177     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2178     * window flags) for displaying content using every last pixel on the display.
2179     *
2180     * <p>There is a limitation: because navigation controls are so important, the least user
2181     * interaction will cause them to reappear immediately.  When this happens, both
2182     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2183     * so that both elements reappear at the same time.
2184     *
2185     * @see #setSystemUiVisibility(int)
2186     */
2187    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2188
2189    /**
2190     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2191     * into the normal fullscreen mode so that its content can take over the screen
2192     * while still allowing the user to interact with the application.
2193     *
2194     * <p>This has the same visual effect as
2195     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2196     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2197     * meaning that non-critical screen decorations (such as the status bar) will be
2198     * hidden while the user is in the View's window, focusing the experience on
2199     * that content.  Unlike the window flag, if you are using ActionBar in
2200     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2201     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2202     * hide the action bar.
2203     *
2204     * <p>This approach to going fullscreen is best used over the window flag when
2205     * it is a transient state -- that is, the application does this at certain
2206     * points in its user interaction where it wants to allow the user to focus
2207     * on content, but not as a continuous state.  For situations where the application
2208     * would like to simply stay full screen the entire time (such as a game that
2209     * wants to take over the screen), the
2210     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2211     * is usually a better approach.  The state set here will be removed by the system
2212     * in various situations (such as the user moving to another application) like
2213     * the other system UI states.
2214     *
2215     * <p>When using this flag, the application should provide some easy facility
2216     * for the user to go out of it.  A common example would be in an e-book
2217     * reader, where tapping on the screen brings back whatever screen and UI
2218     * decorations that had been hidden while the user was immersed in reading
2219     * the book.
2220     *
2221     * @see #setSystemUiVisibility(int)
2222     */
2223    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2224
2225    /**
2226     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2227     * flags, we would like a stable view of the content insets given to
2228     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2229     * will always represent the worst case that the application can expect
2230     * as a continuous state.  In the stock Android UI this is the space for
2231     * the system bar, nav bar, and status bar, but not more transient elements
2232     * such as an input method.
2233     *
2234     * The stable layout your UI sees is based on the system UI modes you can
2235     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2236     * then you will get a stable layout for changes of the
2237     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2238     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2239     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2240     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2241     * with a stable layout.  (Note that you should avoid using
2242     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2243     *
2244     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2245     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2246     * then a hidden status bar will be considered a "stable" state for purposes
2247     * here.  This allows your UI to continually hide the status bar, while still
2248     * using the system UI flags to hide the action bar while still retaining
2249     * a stable layout.  Note that changing the window fullscreen flag will never
2250     * provide a stable layout for a clean transition.
2251     *
2252     * <p>If you are using ActionBar in
2253     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2254     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2255     * insets it adds to those given to the application.
2256     */
2257    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2258
2259    /**
2260     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2261     * to be layed out as if it has requested
2262     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2263     * allows it to avoid artifacts when switching in and out of that mode, at
2264     * the expense that some of its user interface may be covered by screen
2265     * decorations when they are shown.  You can perform layout of your inner
2266     * UI elements to account for the navagation system UI through the
2267     * {@link #fitSystemWindows(Rect)} method.
2268     */
2269    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2270
2271    /**
2272     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2273     * to be layed out as if it has requested
2274     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2275     * allows it to avoid artifacts when switching in and out of that mode, at
2276     * the expense that some of its user interface may be covered by screen
2277     * decorations when they are shown.  You can perform layout of your inner
2278     * UI elements to account for non-fullscreen system UI through the
2279     * {@link #fitSystemWindows(Rect)} method.
2280     */
2281    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2282
2283    /**
2284     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2285     */
2286    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2287
2288    /**
2289     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2290     */
2291    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2292
2293    /**
2294     * @hide
2295     *
2296     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2297     * out of the public fields to keep the undefined bits out of the developer's way.
2298     *
2299     * Flag to make the status bar not expandable.  Unless you also
2300     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2301     */
2302    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2303
2304    /**
2305     * @hide
2306     *
2307     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2308     * out of the public fields to keep the undefined bits out of the developer's way.
2309     *
2310     * Flag to hide notification icons and scrolling ticker text.
2311     */
2312    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2313
2314    /**
2315     * @hide
2316     *
2317     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2318     * out of the public fields to keep the undefined bits out of the developer's way.
2319     *
2320     * Flag to disable incoming notification alerts.  This will not block
2321     * icons, but it will block sound, vibrating and other visual or aural notifications.
2322     */
2323    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2324
2325    /**
2326     * @hide
2327     *
2328     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2329     * out of the public fields to keep the undefined bits out of the developer's way.
2330     *
2331     * Flag to hide only the scrolling ticker.  Note that
2332     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2333     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2334     */
2335    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2336
2337    /**
2338     * @hide
2339     *
2340     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2341     * out of the public fields to keep the undefined bits out of the developer's way.
2342     *
2343     * Flag to hide the center system info area.
2344     */
2345    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2346
2347    /**
2348     * @hide
2349     *
2350     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2351     * out of the public fields to keep the undefined bits out of the developer's way.
2352     *
2353     * Flag to hide only the home button.  Don't use this
2354     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2355     */
2356    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2357
2358    /**
2359     * @hide
2360     *
2361     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2362     * out of the public fields to keep the undefined bits out of the developer's way.
2363     *
2364     * Flag to hide only the back button. Don't use this
2365     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2366     */
2367    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2368
2369    /**
2370     * @hide
2371     *
2372     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2373     * out of the public fields to keep the undefined bits out of the developer's way.
2374     *
2375     * Flag to hide only the clock.  You might use this if your activity has
2376     * its own clock making the status bar's clock redundant.
2377     */
2378    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2379
2380    /**
2381     * @hide
2382     *
2383     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2384     * out of the public fields to keep the undefined bits out of the developer's way.
2385     *
2386     * Flag to hide only the recent apps button. Don't use this
2387     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2388     */
2389    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2390
2391    /**
2392     * @hide
2393     */
2394    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2395
2396    /**
2397     * These are the system UI flags that can be cleared by events outside
2398     * of an application.  Currently this is just the ability to tap on the
2399     * screen while hiding the navigation bar to have it return.
2400     * @hide
2401     */
2402    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2403            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2404            | SYSTEM_UI_FLAG_FULLSCREEN;
2405
2406    /**
2407     * Flags that can impact the layout in relation to system UI.
2408     */
2409    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2410            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2411            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2412
2413    /**
2414     * Find views that render the specified text.
2415     *
2416     * @see #findViewsWithText(ArrayList, CharSequence, int)
2417     */
2418    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2419
2420    /**
2421     * Find find views that contain the specified content description.
2422     *
2423     * @see #findViewsWithText(ArrayList, CharSequence, int)
2424     */
2425    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2426
2427    /**
2428     * Find views that contain {@link AccessibilityNodeProvider}. Such
2429     * a View is a root of virtual view hierarchy and may contain the searched
2430     * text. If this flag is set Views with providers are automatically
2431     * added and it is a responsibility of the client to call the APIs of
2432     * the provider to determine whether the virtual tree rooted at this View
2433     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2434     * represeting the virtual views with this text.
2435     *
2436     * @see #findViewsWithText(ArrayList, CharSequence, int)
2437     *
2438     * @hide
2439     */
2440    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2441
2442    /**
2443     * The undefined cursor position.
2444     */
2445    private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2446
2447    /**
2448     * Indicates that the screen has changed state and is now off.
2449     *
2450     * @see #onScreenStateChanged(int)
2451     */
2452    public static final int SCREEN_STATE_OFF = 0x0;
2453
2454    /**
2455     * Indicates that the screen has changed state and is now on.
2456     *
2457     * @see #onScreenStateChanged(int)
2458     */
2459    public static final int SCREEN_STATE_ON = 0x1;
2460
2461    /**
2462     * Controls the over-scroll mode for this view.
2463     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2464     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2465     * and {@link #OVER_SCROLL_NEVER}.
2466     */
2467    private int mOverScrollMode;
2468
2469    /**
2470     * The parent this view is attached to.
2471     * {@hide}
2472     *
2473     * @see #getParent()
2474     */
2475    protected ViewParent mParent;
2476
2477    /**
2478     * {@hide}
2479     */
2480    AttachInfo mAttachInfo;
2481
2482    /**
2483     * {@hide}
2484     */
2485    @ViewDebug.ExportedProperty(flagMapping = {
2486        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2487                name = "FORCE_LAYOUT"),
2488        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2489                name = "LAYOUT_REQUIRED"),
2490        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2491            name = "DRAWING_CACHE_INVALID", outputIf = false),
2492        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2493        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2494        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2495        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2496    })
2497    int mPrivateFlags;
2498    int mPrivateFlags2;
2499    int mPrivateFlags3;
2500
2501    /**
2502     * This view's request for the visibility of the status bar.
2503     * @hide
2504     */
2505    @ViewDebug.ExportedProperty(flagMapping = {
2506        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2507                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2508                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2509        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2510                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2511                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2512        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2513                                equals = SYSTEM_UI_FLAG_VISIBLE,
2514                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2515    })
2516    int mSystemUiVisibility;
2517
2518    /**
2519     * Reference count for transient state.
2520     * @see #setHasTransientState(boolean)
2521     */
2522    int mTransientStateCount = 0;
2523
2524    /**
2525     * Count of how many windows this view has been attached to.
2526     */
2527    int mWindowAttachCount;
2528
2529    /**
2530     * The layout parameters associated with this view and used by the parent
2531     * {@link android.view.ViewGroup} to determine how this view should be
2532     * laid out.
2533     * {@hide}
2534     */
2535    protected ViewGroup.LayoutParams mLayoutParams;
2536
2537    /**
2538     * The view flags hold various views states.
2539     * {@hide}
2540     */
2541    @ViewDebug.ExportedProperty
2542    int mViewFlags;
2543
2544    static class TransformationInfo {
2545        /**
2546         * The transform matrix for the View. This transform is calculated internally
2547         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2548         * is used by default. Do *not* use this variable directly; instead call
2549         * getMatrix(), which will automatically recalculate the matrix if necessary
2550         * to get the correct matrix based on the latest rotation and scale properties.
2551         */
2552        private final Matrix mMatrix = new Matrix();
2553
2554        /**
2555         * The transform matrix for the View. This transform is calculated internally
2556         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2557         * is used by default. Do *not* use this variable directly; instead call
2558         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2559         * to get the correct matrix based on the latest rotation and scale properties.
2560         */
2561        private Matrix mInverseMatrix;
2562
2563        /**
2564         * An internal variable that tracks whether we need to recalculate the
2565         * transform matrix, based on whether the rotation or scaleX/Y properties
2566         * have changed since the matrix was last calculated.
2567         */
2568        boolean mMatrixDirty = false;
2569
2570        /**
2571         * An internal variable that tracks whether we need to recalculate the
2572         * transform matrix, based on whether the rotation or scaleX/Y properties
2573         * have changed since the matrix was last calculated.
2574         */
2575        private boolean mInverseMatrixDirty = true;
2576
2577        /**
2578         * A variable that tracks whether we need to recalculate the
2579         * transform matrix, based on whether the rotation or scaleX/Y properties
2580         * have changed since the matrix was last calculated. This variable
2581         * is only valid after a call to updateMatrix() or to a function that
2582         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2583         */
2584        private boolean mMatrixIsIdentity = true;
2585
2586        /**
2587         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2588         */
2589        private Camera mCamera = null;
2590
2591        /**
2592         * This matrix is used when computing the matrix for 3D rotations.
2593         */
2594        private Matrix matrix3D = null;
2595
2596        /**
2597         * These prev values are used to recalculate a centered pivot point when necessary. The
2598         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2599         * set), so thes values are only used then as well.
2600         */
2601        private int mPrevWidth = -1;
2602        private int mPrevHeight = -1;
2603
2604        /**
2605         * The degrees rotation around the vertical axis through the pivot point.
2606         */
2607        @ViewDebug.ExportedProperty
2608        float mRotationY = 0f;
2609
2610        /**
2611         * The degrees rotation around the horizontal axis through the pivot point.
2612         */
2613        @ViewDebug.ExportedProperty
2614        float mRotationX = 0f;
2615
2616        /**
2617         * The degrees rotation around the pivot point.
2618         */
2619        @ViewDebug.ExportedProperty
2620        float mRotation = 0f;
2621
2622        /**
2623         * The amount of translation of the object away from its left property (post-layout).
2624         */
2625        @ViewDebug.ExportedProperty
2626        float mTranslationX = 0f;
2627
2628        /**
2629         * The amount of translation of the object away from its top property (post-layout).
2630         */
2631        @ViewDebug.ExportedProperty
2632        float mTranslationY = 0f;
2633
2634        /**
2635         * The amount of scale in the x direction around the pivot point. A
2636         * value of 1 means no scaling is applied.
2637         */
2638        @ViewDebug.ExportedProperty
2639        float mScaleX = 1f;
2640
2641        /**
2642         * The amount of scale in the y direction around the pivot point. A
2643         * value of 1 means no scaling is applied.
2644         */
2645        @ViewDebug.ExportedProperty
2646        float mScaleY = 1f;
2647
2648        /**
2649         * The x location of the point around which the view is rotated and scaled.
2650         */
2651        @ViewDebug.ExportedProperty
2652        float mPivotX = 0f;
2653
2654        /**
2655         * The y location of the point around which the view is rotated and scaled.
2656         */
2657        @ViewDebug.ExportedProperty
2658        float mPivotY = 0f;
2659
2660        /**
2661         * The opacity of the View. This is a value from 0 to 1, where 0 means
2662         * completely transparent and 1 means completely opaque.
2663         */
2664        @ViewDebug.ExportedProperty
2665        float mAlpha = 1f;
2666    }
2667
2668    TransformationInfo mTransformationInfo;
2669
2670    private boolean mLastIsOpaque;
2671
2672    /**
2673     * Convenience value to check for float values that are close enough to zero to be considered
2674     * zero.
2675     */
2676    private static final float NONZERO_EPSILON = .001f;
2677
2678    /**
2679     * The distance in pixels from the left edge of this view's parent
2680     * to the left edge of this view.
2681     * {@hide}
2682     */
2683    @ViewDebug.ExportedProperty(category = "layout")
2684    protected int mLeft;
2685    /**
2686     * The distance in pixels from the left edge of this view's parent
2687     * to the right edge of this view.
2688     * {@hide}
2689     */
2690    @ViewDebug.ExportedProperty(category = "layout")
2691    protected int mRight;
2692    /**
2693     * The distance in pixels from the top edge of this view's parent
2694     * to the top edge of this view.
2695     * {@hide}
2696     */
2697    @ViewDebug.ExportedProperty(category = "layout")
2698    protected int mTop;
2699    /**
2700     * The distance in pixels from the top edge of this view's parent
2701     * to the bottom edge of this view.
2702     * {@hide}
2703     */
2704    @ViewDebug.ExportedProperty(category = "layout")
2705    protected int mBottom;
2706
2707    /**
2708     * The offset, in pixels, by which the content of this view is scrolled
2709     * horizontally.
2710     * {@hide}
2711     */
2712    @ViewDebug.ExportedProperty(category = "scrolling")
2713    protected int mScrollX;
2714    /**
2715     * The offset, in pixels, by which the content of this view is scrolled
2716     * vertically.
2717     * {@hide}
2718     */
2719    @ViewDebug.ExportedProperty(category = "scrolling")
2720    protected int mScrollY;
2721
2722    /**
2723     * The left padding in pixels, that is the distance in pixels between the
2724     * left edge of this view and the left edge of its content.
2725     * {@hide}
2726     */
2727    @ViewDebug.ExportedProperty(category = "padding")
2728    protected int mPaddingLeft;
2729    /**
2730     * The right padding in pixels, that is the distance in pixels between the
2731     * right edge of this view and the right edge of its content.
2732     * {@hide}
2733     */
2734    @ViewDebug.ExportedProperty(category = "padding")
2735    protected int mPaddingRight;
2736    /**
2737     * The top padding in pixels, that is the distance in pixels between the
2738     * top edge of this view and the top edge of its content.
2739     * {@hide}
2740     */
2741    @ViewDebug.ExportedProperty(category = "padding")
2742    protected int mPaddingTop;
2743    /**
2744     * The bottom padding in pixels, that is the distance in pixels between the
2745     * bottom edge of this view and the bottom edge of its content.
2746     * {@hide}
2747     */
2748    @ViewDebug.ExportedProperty(category = "padding")
2749    protected int mPaddingBottom;
2750
2751    /**
2752     * The layout insets in pixels, that is the distance in pixels between the
2753     * visible edges of this view its bounds.
2754     */
2755    private Insets mLayoutInsets;
2756
2757    /**
2758     * Briefly describes the view and is primarily used for accessibility support.
2759     */
2760    private CharSequence mContentDescription;
2761
2762    /**
2763     * Cache the paddingRight set by the user to append to the scrollbar's size.
2764     *
2765     * @hide
2766     */
2767    @ViewDebug.ExportedProperty(category = "padding")
2768    protected int mUserPaddingRight;
2769
2770    /**
2771     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2772     *
2773     * @hide
2774     */
2775    @ViewDebug.ExportedProperty(category = "padding")
2776    protected int mUserPaddingBottom;
2777
2778    /**
2779     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2780     *
2781     * @hide
2782     */
2783    @ViewDebug.ExportedProperty(category = "padding")
2784    protected int mUserPaddingLeft;
2785
2786    /**
2787     * Cache the paddingStart set by the user to append to the scrollbar's size.
2788     *
2789     */
2790    @ViewDebug.ExportedProperty(category = "padding")
2791    int mUserPaddingStart;
2792
2793    /**
2794     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2795     *
2796     */
2797    @ViewDebug.ExportedProperty(category = "padding")
2798    int mUserPaddingEnd;
2799
2800    /**
2801     * Whether a left padding has been defined during layout inflation.
2802     *
2803     * @hide
2804     */
2805    boolean mUserPaddingLeftDefined = false;
2806
2807    /**
2808     * Whether a right padding has been defined during layout inflation.
2809     *
2810     * @hide
2811     */
2812    boolean mUserPaddingRightDefined = false;
2813
2814    /**
2815     * Default undefined padding
2816     */
2817    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2818
2819    /**
2820     * @hide
2821     */
2822    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2823    /**
2824     * @hide
2825     */
2826    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2827
2828    private Drawable mBackground;
2829
2830    private int mBackgroundResource;
2831    private boolean mBackgroundSizeChanged;
2832
2833    static class ListenerInfo {
2834        /**
2835         * Listener used to dispatch focus change events.
2836         * This field should be made private, so it is hidden from the SDK.
2837         * {@hide}
2838         */
2839        protected OnFocusChangeListener mOnFocusChangeListener;
2840
2841        /**
2842         * Listeners for layout change events.
2843         */
2844        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2845
2846        /**
2847         * Listeners for attach events.
2848         */
2849        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2850
2851        /**
2852         * Listener used to dispatch click events.
2853         * This field should be made private, so it is hidden from the SDK.
2854         * {@hide}
2855         */
2856        public OnClickListener mOnClickListener;
2857
2858        /**
2859         * Listener used to dispatch long click events.
2860         * This field should be made private, so it is hidden from the SDK.
2861         * {@hide}
2862         */
2863        protected OnLongClickListener mOnLongClickListener;
2864
2865        /**
2866         * Listener used to build the context menu.
2867         * This field should be made private, so it is hidden from the SDK.
2868         * {@hide}
2869         */
2870        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2871
2872        private OnKeyListener mOnKeyListener;
2873
2874        private OnTouchListener mOnTouchListener;
2875
2876        private OnHoverListener mOnHoverListener;
2877
2878        private OnGenericMotionListener mOnGenericMotionListener;
2879
2880        private OnDragListener mOnDragListener;
2881
2882        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2883    }
2884
2885    ListenerInfo mListenerInfo;
2886
2887    /**
2888     * The application environment this view lives in.
2889     * This field should be made private, so it is hidden from the SDK.
2890     * {@hide}
2891     */
2892    protected Context mContext;
2893
2894    private final Resources mResources;
2895
2896    private ScrollabilityCache mScrollCache;
2897
2898    private int[] mDrawableState = null;
2899
2900    /**
2901     * Set to true when drawing cache is enabled and cannot be created.
2902     *
2903     * @hide
2904     */
2905    public boolean mCachingFailed;
2906
2907    private Bitmap mDrawingCache;
2908    private Bitmap mUnscaledDrawingCache;
2909    private HardwareLayer mHardwareLayer;
2910    DisplayList mDisplayList;
2911
2912    /**
2913     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2914     * the user may specify which view to go to next.
2915     */
2916    private int mNextFocusLeftId = View.NO_ID;
2917
2918    /**
2919     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2920     * the user may specify which view to go to next.
2921     */
2922    private int mNextFocusRightId = View.NO_ID;
2923
2924    /**
2925     * When this view has focus and the next focus is {@link #FOCUS_UP},
2926     * the user may specify which view to go to next.
2927     */
2928    private int mNextFocusUpId = View.NO_ID;
2929
2930    /**
2931     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2932     * the user may specify which view to go to next.
2933     */
2934    private int mNextFocusDownId = View.NO_ID;
2935
2936    /**
2937     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2938     * the user may specify which view to go to next.
2939     */
2940    int mNextFocusForwardId = View.NO_ID;
2941
2942    private CheckForLongPress mPendingCheckForLongPress;
2943    private CheckForTap mPendingCheckForTap = null;
2944    private PerformClick mPerformClick;
2945    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2946
2947    private UnsetPressedState mUnsetPressedState;
2948
2949    /**
2950     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2951     * up event while a long press is invoked as soon as the long press duration is reached, so
2952     * a long press could be performed before the tap is checked, in which case the tap's action
2953     * should not be invoked.
2954     */
2955    private boolean mHasPerformedLongPress;
2956
2957    /**
2958     * The minimum height of the view. We'll try our best to have the height
2959     * of this view to at least this amount.
2960     */
2961    @ViewDebug.ExportedProperty(category = "measurement")
2962    private int mMinHeight;
2963
2964    /**
2965     * The minimum width of the view. We'll try our best to have the width
2966     * of this view to at least this amount.
2967     */
2968    @ViewDebug.ExportedProperty(category = "measurement")
2969    private int mMinWidth;
2970
2971    /**
2972     * The delegate to handle touch events that are physically in this view
2973     * but should be handled by another view.
2974     */
2975    private TouchDelegate mTouchDelegate = null;
2976
2977    /**
2978     * Solid color to use as a background when creating the drawing cache. Enables
2979     * the cache to use 16 bit bitmaps instead of 32 bit.
2980     */
2981    private int mDrawingCacheBackgroundColor = 0;
2982
2983    /**
2984     * Special tree observer used when mAttachInfo is null.
2985     */
2986    private ViewTreeObserver mFloatingTreeObserver;
2987
2988    /**
2989     * Cache the touch slop from the context that created the view.
2990     */
2991    private int mTouchSlop;
2992
2993    /**
2994     * Object that handles automatic animation of view properties.
2995     */
2996    private ViewPropertyAnimator mAnimator = null;
2997
2998    /**
2999     * Flag indicating that a drag can cross window boundaries.  When
3000     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3001     * with this flag set, all visible applications will be able to participate
3002     * in the drag operation and receive the dragged content.
3003     *
3004     * @hide
3005     */
3006    public static final int DRAG_FLAG_GLOBAL = 1;
3007
3008    /**
3009     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3010     */
3011    private float mVerticalScrollFactor;
3012
3013    /**
3014     * Position of the vertical scroll bar.
3015     */
3016    private int mVerticalScrollbarPosition;
3017
3018    /**
3019     * Position the scroll bar at the default position as determined by the system.
3020     */
3021    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3022
3023    /**
3024     * Position the scroll bar along the left edge.
3025     */
3026    public static final int SCROLLBAR_POSITION_LEFT = 1;
3027
3028    /**
3029     * Position the scroll bar along the right edge.
3030     */
3031    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3032
3033    /**
3034     * Indicates that the view does not have a layer.
3035     *
3036     * @see #getLayerType()
3037     * @see #setLayerType(int, android.graphics.Paint)
3038     * @see #LAYER_TYPE_SOFTWARE
3039     * @see #LAYER_TYPE_HARDWARE
3040     */
3041    public static final int LAYER_TYPE_NONE = 0;
3042
3043    /**
3044     * <p>Indicates that the view has a software layer. A software layer is backed
3045     * by a bitmap and causes the view to be rendered using Android's software
3046     * rendering pipeline, even if hardware acceleration is enabled.</p>
3047     *
3048     * <p>Software layers have various usages:</p>
3049     * <p>When the application is not using hardware acceleration, a software layer
3050     * is useful to apply a specific color filter and/or blending mode and/or
3051     * translucency to a view and all its children.</p>
3052     * <p>When the application is using hardware acceleration, a software layer
3053     * is useful to render drawing primitives not supported by the hardware
3054     * accelerated pipeline. It can also be used to cache a complex view tree
3055     * into a texture and reduce the complexity of drawing operations. For instance,
3056     * when animating a complex view tree with a translation, a software layer can
3057     * be used to render the view tree only once.</p>
3058     * <p>Software layers should be avoided when the affected view tree updates
3059     * often. Every update will require to re-render the software layer, which can
3060     * potentially be slow (particularly when hardware acceleration is turned on
3061     * since the layer will have to be uploaded into a hardware texture after every
3062     * update.)</p>
3063     *
3064     * @see #getLayerType()
3065     * @see #setLayerType(int, android.graphics.Paint)
3066     * @see #LAYER_TYPE_NONE
3067     * @see #LAYER_TYPE_HARDWARE
3068     */
3069    public static final int LAYER_TYPE_SOFTWARE = 1;
3070
3071    /**
3072     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3073     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3074     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3075     * rendering pipeline, but only if hardware acceleration is turned on for the
3076     * view hierarchy. When hardware acceleration is turned off, hardware layers
3077     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3078     *
3079     * <p>A hardware layer is useful to apply a specific color filter and/or
3080     * blending mode and/or translucency to a view and all its children.</p>
3081     * <p>A hardware layer can be used to cache a complex view tree into a
3082     * texture and reduce the complexity of drawing operations. For instance,
3083     * when animating a complex view tree with a translation, a hardware layer can
3084     * be used to render the view tree only once.</p>
3085     * <p>A hardware layer can also be used to increase the rendering quality when
3086     * rotation transformations are applied on a view. It can also be used to
3087     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3088     *
3089     * @see #getLayerType()
3090     * @see #setLayerType(int, android.graphics.Paint)
3091     * @see #LAYER_TYPE_NONE
3092     * @see #LAYER_TYPE_SOFTWARE
3093     */
3094    public static final int LAYER_TYPE_HARDWARE = 2;
3095
3096    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3097            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3098            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3099            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3100    })
3101    int mLayerType = LAYER_TYPE_NONE;
3102    Paint mLayerPaint;
3103    Rect mLocalDirtyRect;
3104
3105    /**
3106     * Set to true when the view is sending hover accessibility events because it
3107     * is the innermost hovered view.
3108     */
3109    private boolean mSendingHoverAccessibilityEvents;
3110
3111    /**
3112     * Delegate for injecting accessiblity functionality.
3113     */
3114    AccessibilityDelegate mAccessibilityDelegate;
3115
3116    /**
3117     * Consistency verifier for debugging purposes.
3118     * @hide
3119     */
3120    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3121            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3122                    new InputEventConsistencyVerifier(this, 0) : null;
3123
3124    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3125
3126    /**
3127     * Simple constructor to use when creating a view from code.
3128     *
3129     * @param context The Context the view is running in, through which it can
3130     *        access the current theme, resources, etc.
3131     */
3132    public View(Context context) {
3133        mContext = context;
3134        mResources = context != null ? context.getResources() : null;
3135        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3136        // Set layout and text direction defaults
3137        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3138                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3139                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3140                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3141        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3142        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3143        mUserPaddingStart = UNDEFINED_PADDING;
3144        mUserPaddingEnd = UNDEFINED_PADDING;
3145    }
3146
3147    /**
3148     * Constructor that is called when inflating a view from XML. This is called
3149     * when a view is being constructed from an XML file, supplying attributes
3150     * that were specified in the XML file. This version uses a default style of
3151     * 0, so the only attribute values applied are those in the Context's Theme
3152     * and the given AttributeSet.
3153     *
3154     * <p>
3155     * The method onFinishInflate() will be called after all children have been
3156     * added.
3157     *
3158     * @param context The Context the view is running in, through which it can
3159     *        access the current theme, resources, etc.
3160     * @param attrs The attributes of the XML tag that is inflating the view.
3161     * @see #View(Context, AttributeSet, int)
3162     */
3163    public View(Context context, AttributeSet attrs) {
3164        this(context, attrs, 0);
3165    }
3166
3167    /**
3168     * Perform inflation from XML and apply a class-specific base style. This
3169     * constructor of View allows subclasses to use their own base style when
3170     * they are inflating. For example, a Button class's constructor would call
3171     * this version of the super class constructor and supply
3172     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3173     * the theme's button style to modify all of the base view attributes (in
3174     * particular its background) as well as the Button class's attributes.
3175     *
3176     * @param context The Context the view is running in, through which it can
3177     *        access the current theme, resources, etc.
3178     * @param attrs The attributes of the XML tag that is inflating the view.
3179     * @param defStyle The default style to apply to this view. If 0, no style
3180     *        will be applied (beyond what is included in the theme). This may
3181     *        either be an attribute resource, whose value will be retrieved
3182     *        from the current theme, or an explicit style resource.
3183     * @see #View(Context, AttributeSet)
3184     */
3185    public View(Context context, AttributeSet attrs, int defStyle) {
3186        this(context);
3187
3188        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3189                defStyle, 0);
3190
3191        Drawable background = null;
3192
3193        int leftPadding = -1;
3194        int topPadding = -1;
3195        int rightPadding = -1;
3196        int bottomPadding = -1;
3197        int startPadding = UNDEFINED_PADDING;
3198        int endPadding = UNDEFINED_PADDING;
3199
3200        int padding = -1;
3201
3202        int viewFlagValues = 0;
3203        int viewFlagMasks = 0;
3204
3205        boolean setScrollContainer = false;
3206
3207        int x = 0;
3208        int y = 0;
3209
3210        float tx = 0;
3211        float ty = 0;
3212        float rotation = 0;
3213        float rotationX = 0;
3214        float rotationY = 0;
3215        float sx = 1f;
3216        float sy = 1f;
3217        boolean transformSet = false;
3218
3219        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3220        int overScrollMode = mOverScrollMode;
3221        boolean initializeScrollbars = false;
3222
3223        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3224
3225        final int N = a.getIndexCount();
3226        for (int i = 0; i < N; i++) {
3227            int attr = a.getIndex(i);
3228            switch (attr) {
3229                case com.android.internal.R.styleable.View_background:
3230                    background = a.getDrawable(attr);
3231                    break;
3232                case com.android.internal.R.styleable.View_padding:
3233                    padding = a.getDimensionPixelSize(attr, -1);
3234                    mUserPaddingLeftDefined = true;
3235                    mUserPaddingRightDefined = true;
3236                    break;
3237                 case com.android.internal.R.styleable.View_paddingLeft:
3238                    leftPadding = a.getDimensionPixelSize(attr, -1);
3239                    mUserPaddingLeftDefined = true;
3240                    break;
3241                case com.android.internal.R.styleable.View_paddingTop:
3242                    topPadding = a.getDimensionPixelSize(attr, -1);
3243                    break;
3244                case com.android.internal.R.styleable.View_paddingRight:
3245                    rightPadding = a.getDimensionPixelSize(attr, -1);
3246                    mUserPaddingRightDefined = true;
3247                    break;
3248                case com.android.internal.R.styleable.View_paddingBottom:
3249                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3250                    break;
3251                case com.android.internal.R.styleable.View_paddingStart:
3252                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3253                    break;
3254                case com.android.internal.R.styleable.View_paddingEnd:
3255                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3256                    break;
3257                case com.android.internal.R.styleable.View_scrollX:
3258                    x = a.getDimensionPixelOffset(attr, 0);
3259                    break;
3260                case com.android.internal.R.styleable.View_scrollY:
3261                    y = a.getDimensionPixelOffset(attr, 0);
3262                    break;
3263                case com.android.internal.R.styleable.View_alpha:
3264                    setAlpha(a.getFloat(attr, 1f));
3265                    break;
3266                case com.android.internal.R.styleable.View_transformPivotX:
3267                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3268                    break;
3269                case com.android.internal.R.styleable.View_transformPivotY:
3270                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3271                    break;
3272                case com.android.internal.R.styleable.View_translationX:
3273                    tx = a.getDimensionPixelOffset(attr, 0);
3274                    transformSet = true;
3275                    break;
3276                case com.android.internal.R.styleable.View_translationY:
3277                    ty = a.getDimensionPixelOffset(attr, 0);
3278                    transformSet = true;
3279                    break;
3280                case com.android.internal.R.styleable.View_rotation:
3281                    rotation = a.getFloat(attr, 0);
3282                    transformSet = true;
3283                    break;
3284                case com.android.internal.R.styleable.View_rotationX:
3285                    rotationX = a.getFloat(attr, 0);
3286                    transformSet = true;
3287                    break;
3288                case com.android.internal.R.styleable.View_rotationY:
3289                    rotationY = a.getFloat(attr, 0);
3290                    transformSet = true;
3291                    break;
3292                case com.android.internal.R.styleable.View_scaleX:
3293                    sx = a.getFloat(attr, 1f);
3294                    transformSet = true;
3295                    break;
3296                case com.android.internal.R.styleable.View_scaleY:
3297                    sy = a.getFloat(attr, 1f);
3298                    transformSet = true;
3299                    break;
3300                case com.android.internal.R.styleable.View_id:
3301                    mID = a.getResourceId(attr, NO_ID);
3302                    break;
3303                case com.android.internal.R.styleable.View_tag:
3304                    mTag = a.getText(attr);
3305                    break;
3306                case com.android.internal.R.styleable.View_fitsSystemWindows:
3307                    if (a.getBoolean(attr, false)) {
3308                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3309                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3310                    }
3311                    break;
3312                case com.android.internal.R.styleable.View_focusable:
3313                    if (a.getBoolean(attr, false)) {
3314                        viewFlagValues |= FOCUSABLE;
3315                        viewFlagMasks |= FOCUSABLE_MASK;
3316                    }
3317                    break;
3318                case com.android.internal.R.styleable.View_focusableInTouchMode:
3319                    if (a.getBoolean(attr, false)) {
3320                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3321                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3322                    }
3323                    break;
3324                case com.android.internal.R.styleable.View_clickable:
3325                    if (a.getBoolean(attr, false)) {
3326                        viewFlagValues |= CLICKABLE;
3327                        viewFlagMasks |= CLICKABLE;
3328                    }
3329                    break;
3330                case com.android.internal.R.styleable.View_longClickable:
3331                    if (a.getBoolean(attr, false)) {
3332                        viewFlagValues |= LONG_CLICKABLE;
3333                        viewFlagMasks |= LONG_CLICKABLE;
3334                    }
3335                    break;
3336                case com.android.internal.R.styleable.View_saveEnabled:
3337                    if (!a.getBoolean(attr, true)) {
3338                        viewFlagValues |= SAVE_DISABLED;
3339                        viewFlagMasks |= SAVE_DISABLED_MASK;
3340                    }
3341                    break;
3342                case com.android.internal.R.styleable.View_duplicateParentState:
3343                    if (a.getBoolean(attr, false)) {
3344                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3345                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3346                    }
3347                    break;
3348                case com.android.internal.R.styleable.View_visibility:
3349                    final int visibility = a.getInt(attr, 0);
3350                    if (visibility != 0) {
3351                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3352                        viewFlagMasks |= VISIBILITY_MASK;
3353                    }
3354                    break;
3355                case com.android.internal.R.styleable.View_layoutDirection:
3356                    // Clear any layout direction flags (included resolved bits) already set
3357                    mPrivateFlags2 &= ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3358                    // Set the layout direction flags depending on the value of the attribute
3359                    final int layoutDirection = a.getInt(attr, -1);
3360                    final int value = (layoutDirection != -1) ?
3361                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3362                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3363                    break;
3364                case com.android.internal.R.styleable.View_drawingCacheQuality:
3365                    final int cacheQuality = a.getInt(attr, 0);
3366                    if (cacheQuality != 0) {
3367                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3368                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3369                    }
3370                    break;
3371                case com.android.internal.R.styleable.View_contentDescription:
3372                    setContentDescription(a.getString(attr));
3373                    break;
3374                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3375                    if (!a.getBoolean(attr, true)) {
3376                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3377                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3378                    }
3379                    break;
3380                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3381                    if (!a.getBoolean(attr, true)) {
3382                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3383                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3384                    }
3385                    break;
3386                case R.styleable.View_scrollbars:
3387                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3388                    if (scrollbars != SCROLLBARS_NONE) {
3389                        viewFlagValues |= scrollbars;
3390                        viewFlagMasks |= SCROLLBARS_MASK;
3391                        initializeScrollbars = true;
3392                    }
3393                    break;
3394                //noinspection deprecation
3395                case R.styleable.View_fadingEdge:
3396                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3397                        // Ignore the attribute starting with ICS
3398                        break;
3399                    }
3400                    // With builds < ICS, fall through and apply fading edges
3401                case R.styleable.View_requiresFadingEdge:
3402                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3403                    if (fadingEdge != FADING_EDGE_NONE) {
3404                        viewFlagValues |= fadingEdge;
3405                        viewFlagMasks |= FADING_EDGE_MASK;
3406                        initializeFadingEdge(a);
3407                    }
3408                    break;
3409                case R.styleable.View_scrollbarStyle:
3410                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3411                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3412                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3413                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3414                    }
3415                    break;
3416                case R.styleable.View_isScrollContainer:
3417                    setScrollContainer = true;
3418                    if (a.getBoolean(attr, false)) {
3419                        setScrollContainer(true);
3420                    }
3421                    break;
3422                case com.android.internal.R.styleable.View_keepScreenOn:
3423                    if (a.getBoolean(attr, false)) {
3424                        viewFlagValues |= KEEP_SCREEN_ON;
3425                        viewFlagMasks |= KEEP_SCREEN_ON;
3426                    }
3427                    break;
3428                case R.styleable.View_filterTouchesWhenObscured:
3429                    if (a.getBoolean(attr, false)) {
3430                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3431                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3432                    }
3433                    break;
3434                case R.styleable.View_nextFocusLeft:
3435                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3436                    break;
3437                case R.styleable.View_nextFocusRight:
3438                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3439                    break;
3440                case R.styleable.View_nextFocusUp:
3441                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3442                    break;
3443                case R.styleable.View_nextFocusDown:
3444                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3445                    break;
3446                case R.styleable.View_nextFocusForward:
3447                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3448                    break;
3449                case R.styleable.View_minWidth:
3450                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3451                    break;
3452                case R.styleable.View_minHeight:
3453                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3454                    break;
3455                case R.styleable.View_onClick:
3456                    if (context.isRestricted()) {
3457                        throw new IllegalStateException("The android:onClick attribute cannot "
3458                                + "be used within a restricted context");
3459                    }
3460
3461                    final String handlerName = a.getString(attr);
3462                    if (handlerName != null) {
3463                        setOnClickListener(new OnClickListener() {
3464                            private Method mHandler;
3465
3466                            public void onClick(View v) {
3467                                if (mHandler == null) {
3468                                    try {
3469                                        mHandler = getContext().getClass().getMethod(handlerName,
3470                                                View.class);
3471                                    } catch (NoSuchMethodException e) {
3472                                        int id = getId();
3473                                        String idText = id == NO_ID ? "" : " with id '"
3474                                                + getContext().getResources().getResourceEntryName(
3475                                                    id) + "'";
3476                                        throw new IllegalStateException("Could not find a method " +
3477                                                handlerName + "(View) in the activity "
3478                                                + getContext().getClass() + " for onClick handler"
3479                                                + " on view " + View.this.getClass() + idText, e);
3480                                    }
3481                                }
3482
3483                                try {
3484                                    mHandler.invoke(getContext(), View.this);
3485                                } catch (IllegalAccessException e) {
3486                                    throw new IllegalStateException("Could not execute non "
3487                                            + "public method of the activity", e);
3488                                } catch (InvocationTargetException e) {
3489                                    throw new IllegalStateException("Could not execute "
3490                                            + "method of the activity", e);
3491                                }
3492                            }
3493                        });
3494                    }
3495                    break;
3496                case R.styleable.View_overScrollMode:
3497                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3498                    break;
3499                case R.styleable.View_verticalScrollbarPosition:
3500                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3501                    break;
3502                case R.styleable.View_layerType:
3503                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3504                    break;
3505                case R.styleable.View_textDirection:
3506                    // Clear any text direction flag already set
3507                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3508                    // Set the text direction flags depending on the value of the attribute
3509                    final int textDirection = a.getInt(attr, -1);
3510                    if (textDirection != -1) {
3511                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3512                    }
3513                    break;
3514                case R.styleable.View_textAlignment:
3515                    // Clear any text alignment flag already set
3516                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3517                    // Set the text alignment flag depending on the value of the attribute
3518                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3519                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3520                    break;
3521                case R.styleable.View_importantForAccessibility:
3522                    setImportantForAccessibility(a.getInt(attr,
3523                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3524                    break;
3525            }
3526        }
3527
3528        setOverScrollMode(overScrollMode);
3529
3530        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3531        // the resolved layout direction). Those cached values will be used later during padding
3532        // resolution.
3533        mUserPaddingStart = startPadding;
3534        mUserPaddingEnd = endPadding;
3535
3536        if (background != null) {
3537            setBackground(background);
3538        }
3539
3540        if (padding >= 0) {
3541            leftPadding = padding;
3542            topPadding = padding;
3543            rightPadding = padding;
3544            bottomPadding = padding;
3545        }
3546
3547        // If the user specified the padding (either with android:padding or
3548        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3549        // use the default padding or the padding from the background drawable
3550        // (stored at this point in mPadding*)
3551        internalSetPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3552                topPadding >= 0 ? topPadding : mPaddingTop,
3553                rightPadding >= 0 ? rightPadding : mPaddingRight,
3554                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3555
3556        if (viewFlagMasks != 0) {
3557            setFlags(viewFlagValues, viewFlagMasks);
3558        }
3559
3560        if (initializeScrollbars) {
3561            initializeScrollbars(a);
3562        }
3563
3564        a.recycle();
3565
3566        // Needs to be called after mViewFlags is set
3567        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3568            recomputePadding();
3569        }
3570
3571        if (x != 0 || y != 0) {
3572            scrollTo(x, y);
3573        }
3574
3575        if (transformSet) {
3576            setTranslationX(tx);
3577            setTranslationY(ty);
3578            setRotation(rotation);
3579            setRotationX(rotationX);
3580            setRotationY(rotationY);
3581            setScaleX(sx);
3582            setScaleY(sy);
3583        }
3584
3585        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3586            setScrollContainer(true);
3587        }
3588
3589        computeOpaqueFlags();
3590    }
3591
3592    /**
3593     * Non-public constructor for use in testing
3594     */
3595    View() {
3596        mResources = null;
3597    }
3598
3599    public String toString() {
3600        StringBuilder out = new StringBuilder(128);
3601        out.append(getClass().getName());
3602        out.append('{');
3603        out.append(Integer.toHexString(System.identityHashCode(this)));
3604        out.append(' ');
3605        switch (mViewFlags&VISIBILITY_MASK) {
3606            case VISIBLE: out.append('V'); break;
3607            case INVISIBLE: out.append('I'); break;
3608            case GONE: out.append('G'); break;
3609            default: out.append('.'); break;
3610        }
3611        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3612        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3613        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3614        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3615        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3616        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3617        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3618        out.append(' ');
3619        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3620        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3621        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3622        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3623            out.append('p');
3624        } else {
3625            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3626        }
3627        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3628        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3629        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3630        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3631        out.append(' ');
3632        out.append(mLeft);
3633        out.append(',');
3634        out.append(mTop);
3635        out.append('-');
3636        out.append(mRight);
3637        out.append(',');
3638        out.append(mBottom);
3639        final int id = getId();
3640        if (id != NO_ID) {
3641            out.append(" #");
3642            out.append(Integer.toHexString(id));
3643            final Resources r = mResources;
3644            if (id != 0 && r != null) {
3645                try {
3646                    String pkgname;
3647                    switch (id&0xff000000) {
3648                        case 0x7f000000:
3649                            pkgname="app";
3650                            break;
3651                        case 0x01000000:
3652                            pkgname="android";
3653                            break;
3654                        default:
3655                            pkgname = r.getResourcePackageName(id);
3656                            break;
3657                    }
3658                    String typename = r.getResourceTypeName(id);
3659                    String entryname = r.getResourceEntryName(id);
3660                    out.append(" ");
3661                    out.append(pkgname);
3662                    out.append(":");
3663                    out.append(typename);
3664                    out.append("/");
3665                    out.append(entryname);
3666                } catch (Resources.NotFoundException e) {
3667                }
3668            }
3669        }
3670        out.append("}");
3671        return out.toString();
3672    }
3673
3674    /**
3675     * <p>
3676     * Initializes the fading edges from a given set of styled attributes. This
3677     * method should be called by subclasses that need fading edges and when an
3678     * instance of these subclasses is created programmatically rather than
3679     * being inflated from XML. This method is automatically called when the XML
3680     * is inflated.
3681     * </p>
3682     *
3683     * @param a the styled attributes set to initialize the fading edges from
3684     */
3685    protected void initializeFadingEdge(TypedArray a) {
3686        initScrollCache();
3687
3688        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3689                R.styleable.View_fadingEdgeLength,
3690                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3691    }
3692
3693    /**
3694     * Returns the size of the vertical faded edges used to indicate that more
3695     * content in this view is visible.
3696     *
3697     * @return The size in pixels of the vertical faded edge or 0 if vertical
3698     *         faded edges are not enabled for this view.
3699     * @attr ref android.R.styleable#View_fadingEdgeLength
3700     */
3701    public int getVerticalFadingEdgeLength() {
3702        if (isVerticalFadingEdgeEnabled()) {
3703            ScrollabilityCache cache = mScrollCache;
3704            if (cache != null) {
3705                return cache.fadingEdgeLength;
3706            }
3707        }
3708        return 0;
3709    }
3710
3711    /**
3712     * Set the size of the faded edge used to indicate that more content in this
3713     * view is available.  Will not change whether the fading edge is enabled; use
3714     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3715     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3716     * for the vertical or horizontal fading edges.
3717     *
3718     * @param length The size in pixels of the faded edge used to indicate that more
3719     *        content in this view is visible.
3720     */
3721    public void setFadingEdgeLength(int length) {
3722        initScrollCache();
3723        mScrollCache.fadingEdgeLength = length;
3724    }
3725
3726    /**
3727     * Returns the size of the horizontal faded edges used to indicate that more
3728     * content in this view is visible.
3729     *
3730     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3731     *         faded edges are not enabled for this view.
3732     * @attr ref android.R.styleable#View_fadingEdgeLength
3733     */
3734    public int getHorizontalFadingEdgeLength() {
3735        if (isHorizontalFadingEdgeEnabled()) {
3736            ScrollabilityCache cache = mScrollCache;
3737            if (cache != null) {
3738                return cache.fadingEdgeLength;
3739            }
3740        }
3741        return 0;
3742    }
3743
3744    /**
3745     * Returns the width of the vertical scrollbar.
3746     *
3747     * @return The width in pixels of the vertical scrollbar or 0 if there
3748     *         is no vertical scrollbar.
3749     */
3750    public int getVerticalScrollbarWidth() {
3751        ScrollabilityCache cache = mScrollCache;
3752        if (cache != null) {
3753            ScrollBarDrawable scrollBar = cache.scrollBar;
3754            if (scrollBar != null) {
3755                int size = scrollBar.getSize(true);
3756                if (size <= 0) {
3757                    size = cache.scrollBarSize;
3758                }
3759                return size;
3760            }
3761            return 0;
3762        }
3763        return 0;
3764    }
3765
3766    /**
3767     * Returns the height of the horizontal scrollbar.
3768     *
3769     * @return The height in pixels of the horizontal scrollbar or 0 if
3770     *         there is no horizontal scrollbar.
3771     */
3772    protected int getHorizontalScrollbarHeight() {
3773        ScrollabilityCache cache = mScrollCache;
3774        if (cache != null) {
3775            ScrollBarDrawable scrollBar = cache.scrollBar;
3776            if (scrollBar != null) {
3777                int size = scrollBar.getSize(false);
3778                if (size <= 0) {
3779                    size = cache.scrollBarSize;
3780                }
3781                return size;
3782            }
3783            return 0;
3784        }
3785        return 0;
3786    }
3787
3788    /**
3789     * <p>
3790     * Initializes the scrollbars from a given set of styled attributes. This
3791     * method should be called by subclasses that need scrollbars and when an
3792     * instance of these subclasses is created programmatically rather than
3793     * being inflated from XML. This method is automatically called when the XML
3794     * is inflated.
3795     * </p>
3796     *
3797     * @param a the styled attributes set to initialize the scrollbars from
3798     */
3799    protected void initializeScrollbars(TypedArray a) {
3800        initScrollCache();
3801
3802        final ScrollabilityCache scrollabilityCache = mScrollCache;
3803
3804        if (scrollabilityCache.scrollBar == null) {
3805            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3806        }
3807
3808        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3809
3810        if (!fadeScrollbars) {
3811            scrollabilityCache.state = ScrollabilityCache.ON;
3812        }
3813        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3814
3815
3816        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3817                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3818                        .getScrollBarFadeDuration());
3819        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3820                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3821                ViewConfiguration.getScrollDefaultDelay());
3822
3823
3824        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3825                com.android.internal.R.styleable.View_scrollbarSize,
3826                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3827
3828        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3829        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3830
3831        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3832        if (thumb != null) {
3833            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3834        }
3835
3836        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3837                false);
3838        if (alwaysDraw) {
3839            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3840        }
3841
3842        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3843        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3844
3845        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3846        if (thumb != null) {
3847            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3848        }
3849
3850        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3851                false);
3852        if (alwaysDraw) {
3853            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3854        }
3855
3856        // Apply layout direction to the new Drawables if needed
3857        final int layoutDirection = getResolvedLayoutDirection();
3858        if (track != null) {
3859            track.setLayoutDirection(layoutDirection);
3860        }
3861        if (thumb != null) {
3862            thumb.setLayoutDirection(layoutDirection);
3863        }
3864
3865        // Re-apply user/background padding so that scrollbar(s) get added
3866        resolvePadding();
3867    }
3868
3869    /**
3870     * <p>
3871     * Initalizes the scrollability cache if necessary.
3872     * </p>
3873     */
3874    private void initScrollCache() {
3875        if (mScrollCache == null) {
3876            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3877        }
3878    }
3879
3880    private ScrollabilityCache getScrollCache() {
3881        initScrollCache();
3882        return mScrollCache;
3883    }
3884
3885    /**
3886     * Set the position of the vertical scroll bar. Should be one of
3887     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3888     * {@link #SCROLLBAR_POSITION_RIGHT}.
3889     *
3890     * @param position Where the vertical scroll bar should be positioned.
3891     */
3892    public void setVerticalScrollbarPosition(int position) {
3893        if (mVerticalScrollbarPosition != position) {
3894            mVerticalScrollbarPosition = position;
3895            computeOpaqueFlags();
3896            resolvePadding();
3897        }
3898    }
3899
3900    /**
3901     * @return The position where the vertical scroll bar will show, if applicable.
3902     * @see #setVerticalScrollbarPosition(int)
3903     */
3904    public int getVerticalScrollbarPosition() {
3905        return mVerticalScrollbarPosition;
3906    }
3907
3908    ListenerInfo getListenerInfo() {
3909        if (mListenerInfo != null) {
3910            return mListenerInfo;
3911        }
3912        mListenerInfo = new ListenerInfo();
3913        return mListenerInfo;
3914    }
3915
3916    /**
3917     * Register a callback to be invoked when focus of this view changed.
3918     *
3919     * @param l The callback that will run.
3920     */
3921    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3922        getListenerInfo().mOnFocusChangeListener = l;
3923    }
3924
3925    /**
3926     * Add a listener that will be called when the bounds of the view change due to
3927     * layout processing.
3928     *
3929     * @param listener The listener that will be called when layout bounds change.
3930     */
3931    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3932        ListenerInfo li = getListenerInfo();
3933        if (li.mOnLayoutChangeListeners == null) {
3934            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3935        }
3936        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3937            li.mOnLayoutChangeListeners.add(listener);
3938        }
3939    }
3940
3941    /**
3942     * Remove a listener for layout changes.
3943     *
3944     * @param listener The listener for layout bounds change.
3945     */
3946    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3947        ListenerInfo li = mListenerInfo;
3948        if (li == null || li.mOnLayoutChangeListeners == null) {
3949            return;
3950        }
3951        li.mOnLayoutChangeListeners.remove(listener);
3952    }
3953
3954    /**
3955     * Add a listener for attach state changes.
3956     *
3957     * This listener will be called whenever this view is attached or detached
3958     * from a window. Remove the listener using
3959     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3960     *
3961     * @param listener Listener to attach
3962     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3963     */
3964    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3965        ListenerInfo li = getListenerInfo();
3966        if (li.mOnAttachStateChangeListeners == null) {
3967            li.mOnAttachStateChangeListeners
3968                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3969        }
3970        li.mOnAttachStateChangeListeners.add(listener);
3971    }
3972
3973    /**
3974     * Remove a listener for attach state changes. The listener will receive no further
3975     * notification of window attach/detach events.
3976     *
3977     * @param listener Listener to remove
3978     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3979     */
3980    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3981        ListenerInfo li = mListenerInfo;
3982        if (li == null || li.mOnAttachStateChangeListeners == null) {
3983            return;
3984        }
3985        li.mOnAttachStateChangeListeners.remove(listener);
3986    }
3987
3988    /**
3989     * Returns the focus-change callback registered for this view.
3990     *
3991     * @return The callback, or null if one is not registered.
3992     */
3993    public OnFocusChangeListener getOnFocusChangeListener() {
3994        ListenerInfo li = mListenerInfo;
3995        return li != null ? li.mOnFocusChangeListener : null;
3996    }
3997
3998    /**
3999     * Register a callback to be invoked when this view is clicked. If this view is not
4000     * clickable, it becomes clickable.
4001     *
4002     * @param l The callback that will run
4003     *
4004     * @see #setClickable(boolean)
4005     */
4006    public void setOnClickListener(OnClickListener l) {
4007        if (!isClickable()) {
4008            setClickable(true);
4009        }
4010        getListenerInfo().mOnClickListener = l;
4011    }
4012
4013    /**
4014     * Return whether this view has an attached OnClickListener.  Returns
4015     * true if there is a listener, false if there is none.
4016     */
4017    public boolean hasOnClickListeners() {
4018        ListenerInfo li = mListenerInfo;
4019        return (li != null && li.mOnClickListener != null);
4020    }
4021
4022    /**
4023     * Register a callback to be invoked when this view is clicked and held. If this view is not
4024     * long clickable, it becomes long clickable.
4025     *
4026     * @param l The callback that will run
4027     *
4028     * @see #setLongClickable(boolean)
4029     */
4030    public void setOnLongClickListener(OnLongClickListener l) {
4031        if (!isLongClickable()) {
4032            setLongClickable(true);
4033        }
4034        getListenerInfo().mOnLongClickListener = l;
4035    }
4036
4037    /**
4038     * Register a callback to be invoked when the context menu for this view is
4039     * being built. If this view is not long clickable, it becomes long clickable.
4040     *
4041     * @param l The callback that will run
4042     *
4043     */
4044    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4045        if (!isLongClickable()) {
4046            setLongClickable(true);
4047        }
4048        getListenerInfo().mOnCreateContextMenuListener = l;
4049    }
4050
4051    /**
4052     * Call this view's OnClickListener, if it is defined.  Performs all normal
4053     * actions associated with clicking: reporting accessibility event, playing
4054     * a sound, etc.
4055     *
4056     * @return True there was an assigned OnClickListener that was called, false
4057     *         otherwise is returned.
4058     */
4059    public boolean performClick() {
4060        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4061
4062        ListenerInfo li = mListenerInfo;
4063        if (li != null && li.mOnClickListener != null) {
4064            playSoundEffect(SoundEffectConstants.CLICK);
4065            li.mOnClickListener.onClick(this);
4066            return true;
4067        }
4068
4069        return false;
4070    }
4071
4072    /**
4073     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4074     * this only calls the listener, and does not do any associated clicking
4075     * actions like reporting an accessibility event.
4076     *
4077     * @return True there was an assigned OnClickListener that was called, false
4078     *         otherwise is returned.
4079     */
4080    public boolean callOnClick() {
4081        ListenerInfo li = mListenerInfo;
4082        if (li != null && li.mOnClickListener != null) {
4083            li.mOnClickListener.onClick(this);
4084            return true;
4085        }
4086        return false;
4087    }
4088
4089    /**
4090     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4091     * OnLongClickListener did not consume the event.
4092     *
4093     * @return True if one of the above receivers consumed the event, false otherwise.
4094     */
4095    public boolean performLongClick() {
4096        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4097
4098        boolean handled = false;
4099        ListenerInfo li = mListenerInfo;
4100        if (li != null && li.mOnLongClickListener != null) {
4101            handled = li.mOnLongClickListener.onLongClick(View.this);
4102        }
4103        if (!handled) {
4104            handled = showContextMenu();
4105        }
4106        if (handled) {
4107            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4108        }
4109        return handled;
4110    }
4111
4112    /**
4113     * Performs button-related actions during a touch down event.
4114     *
4115     * @param event The event.
4116     * @return True if the down was consumed.
4117     *
4118     * @hide
4119     */
4120    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4121        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4122            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4123                return true;
4124            }
4125        }
4126        return false;
4127    }
4128
4129    /**
4130     * Bring up the context menu for this view.
4131     *
4132     * @return Whether a context menu was displayed.
4133     */
4134    public boolean showContextMenu() {
4135        return getParent().showContextMenuForChild(this);
4136    }
4137
4138    /**
4139     * Bring up the context menu for this view, referring to the item under the specified point.
4140     *
4141     * @param x The referenced x coordinate.
4142     * @param y The referenced y coordinate.
4143     * @param metaState The keyboard modifiers that were pressed.
4144     * @return Whether a context menu was displayed.
4145     *
4146     * @hide
4147     */
4148    public boolean showContextMenu(float x, float y, int metaState) {
4149        return showContextMenu();
4150    }
4151
4152    /**
4153     * Start an action mode.
4154     *
4155     * @param callback Callback that will control the lifecycle of the action mode
4156     * @return The new action mode if it is started, null otherwise
4157     *
4158     * @see ActionMode
4159     */
4160    public ActionMode startActionMode(ActionMode.Callback callback) {
4161        ViewParent parent = getParent();
4162        if (parent == null) return null;
4163        return parent.startActionModeForChild(this, callback);
4164    }
4165
4166    /**
4167     * Register a callback to be invoked when a hardware key is pressed in this view.
4168     * Key presses in software input methods will generally not trigger the methods of
4169     * this listener.
4170     * @param l the key listener to attach to this view
4171     */
4172    public void setOnKeyListener(OnKeyListener l) {
4173        getListenerInfo().mOnKeyListener = l;
4174    }
4175
4176    /**
4177     * Register a callback to be invoked when a touch event is sent to this view.
4178     * @param l the touch listener to attach to this view
4179     */
4180    public void setOnTouchListener(OnTouchListener l) {
4181        getListenerInfo().mOnTouchListener = l;
4182    }
4183
4184    /**
4185     * Register a callback to be invoked when a generic motion event is sent to this view.
4186     * @param l the generic motion listener to attach to this view
4187     */
4188    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4189        getListenerInfo().mOnGenericMotionListener = l;
4190    }
4191
4192    /**
4193     * Register a callback to be invoked when a hover event is sent to this view.
4194     * @param l the hover listener to attach to this view
4195     */
4196    public void setOnHoverListener(OnHoverListener l) {
4197        getListenerInfo().mOnHoverListener = l;
4198    }
4199
4200    /**
4201     * Register a drag event listener callback object for this View. The parameter is
4202     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4203     * View, the system calls the
4204     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4205     * @param l An implementation of {@link android.view.View.OnDragListener}.
4206     */
4207    public void setOnDragListener(OnDragListener l) {
4208        getListenerInfo().mOnDragListener = l;
4209    }
4210
4211    /**
4212     * Give this view focus. This will cause
4213     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4214     *
4215     * Note: this does not check whether this {@link View} should get focus, it just
4216     * gives it focus no matter what.  It should only be called internally by framework
4217     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4218     *
4219     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4220     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4221     *        focus moved when requestFocus() is called. It may not always
4222     *        apply, in which case use the default View.FOCUS_DOWN.
4223     * @param previouslyFocusedRect The rectangle of the view that had focus
4224     *        prior in this View's coordinate system.
4225     */
4226    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4227        if (DBG) {
4228            System.out.println(this + " requestFocus()");
4229        }
4230
4231        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4232            mPrivateFlags |= PFLAG_FOCUSED;
4233
4234            if (mParent != null) {
4235                mParent.requestChildFocus(this, this);
4236            }
4237
4238            onFocusChanged(true, direction, previouslyFocusedRect);
4239            refreshDrawableState();
4240
4241            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4242                notifyAccessibilityStateChanged();
4243            }
4244        }
4245    }
4246
4247    /**
4248     * Request that a rectangle of this view be visible on the screen,
4249     * scrolling if necessary just enough.
4250     *
4251     * <p>A View should call this if it maintains some notion of which part
4252     * of its content is interesting.  For example, a text editing view
4253     * should call this when its cursor moves.
4254     *
4255     * @param rectangle The rectangle.
4256     * @return Whether any parent scrolled.
4257     */
4258    public boolean requestRectangleOnScreen(Rect rectangle) {
4259        return requestRectangleOnScreen(rectangle, false);
4260    }
4261
4262    /**
4263     * Request that a rectangle of this view be visible on the screen,
4264     * scrolling if necessary just enough.
4265     *
4266     * <p>A View should call this if it maintains some notion of which part
4267     * of its content is interesting.  For example, a text editing view
4268     * should call this when its cursor moves.
4269     *
4270     * <p>When <code>immediate</code> is set to true, scrolling will not be
4271     * animated.
4272     *
4273     * @param rectangle The rectangle.
4274     * @param immediate True to forbid animated scrolling, false otherwise
4275     * @return Whether any parent scrolled.
4276     */
4277    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4278        View child = this;
4279        ViewParent parent = mParent;
4280        boolean scrolled = false;
4281        while (parent != null) {
4282            scrolled |= parent.requestChildRectangleOnScreen(child,
4283                    rectangle, immediate);
4284
4285            // offset rect so next call has the rectangle in the
4286            // coordinate system of its direct child.
4287            rectangle.offset(child.getLeft(), child.getTop());
4288            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4289
4290            if (!(parent instanceof View)) {
4291                break;
4292            }
4293
4294            child = (View) parent;
4295            parent = child.getParent();
4296        }
4297        return scrolled;
4298    }
4299
4300    /**
4301     * Called when this view wants to give up focus. If focus is cleared
4302     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4303     * <p>
4304     * <strong>Note:</strong> When a View clears focus the framework is trying
4305     * to give focus to the first focusable View from the top. Hence, if this
4306     * View is the first from the top that can take focus, then all callbacks
4307     * related to clearing focus will be invoked after wich the framework will
4308     * give focus to this view.
4309     * </p>
4310     */
4311    public void clearFocus() {
4312        if (DBG) {
4313            System.out.println(this + " clearFocus()");
4314        }
4315
4316        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4317            mPrivateFlags &= ~PFLAG_FOCUSED;
4318
4319            if (mParent != null) {
4320                mParent.clearChildFocus(this);
4321            }
4322
4323            onFocusChanged(false, 0, null);
4324
4325            refreshDrawableState();
4326
4327            ensureInputFocusOnFirstFocusable();
4328
4329            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4330                notifyAccessibilityStateChanged();
4331            }
4332        }
4333    }
4334
4335    void ensureInputFocusOnFirstFocusable() {
4336        View root = getRootView();
4337        if (root != null) {
4338            root.requestFocus();
4339        }
4340    }
4341
4342    /**
4343     * Called internally by the view system when a new view is getting focus.
4344     * This is what clears the old focus.
4345     */
4346    void unFocus() {
4347        if (DBG) {
4348            System.out.println(this + " unFocus()");
4349        }
4350
4351        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4352            mPrivateFlags &= ~PFLAG_FOCUSED;
4353
4354            onFocusChanged(false, 0, null);
4355            refreshDrawableState();
4356
4357            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4358                notifyAccessibilityStateChanged();
4359            }
4360        }
4361    }
4362
4363    /**
4364     * Returns true if this view has focus iteself, or is the ancestor of the
4365     * view that has focus.
4366     *
4367     * @return True if this view has or contains focus, false otherwise.
4368     */
4369    @ViewDebug.ExportedProperty(category = "focus")
4370    public boolean hasFocus() {
4371        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4372    }
4373
4374    /**
4375     * Returns true if this view is focusable or if it contains a reachable View
4376     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4377     * is a View whose parents do not block descendants focus.
4378     *
4379     * Only {@link #VISIBLE} views are considered focusable.
4380     *
4381     * @return True if the view is focusable or if the view contains a focusable
4382     *         View, false otherwise.
4383     *
4384     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4385     */
4386    public boolean hasFocusable() {
4387        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4388    }
4389
4390    /**
4391     * Called by the view system when the focus state of this view changes.
4392     * When the focus change event is caused by directional navigation, direction
4393     * and previouslyFocusedRect provide insight into where the focus is coming from.
4394     * When overriding, be sure to call up through to the super class so that
4395     * the standard focus handling will occur.
4396     *
4397     * @param gainFocus True if the View has focus; false otherwise.
4398     * @param direction The direction focus has moved when requestFocus()
4399     *                  is called to give this view focus. Values are
4400     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4401     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4402     *                  It may not always apply, in which case use the default.
4403     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4404     *        system, of the previously focused view.  If applicable, this will be
4405     *        passed in as finer grained information about where the focus is coming
4406     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4407     */
4408    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4409        if (gainFocus) {
4410            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4411                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4412            }
4413        }
4414
4415        InputMethodManager imm = InputMethodManager.peekInstance();
4416        if (!gainFocus) {
4417            if (isPressed()) {
4418                setPressed(false);
4419            }
4420            if (imm != null && mAttachInfo != null
4421                    && mAttachInfo.mHasWindowFocus) {
4422                imm.focusOut(this);
4423            }
4424            onFocusLost();
4425        } else if (imm != null && mAttachInfo != null
4426                && mAttachInfo.mHasWindowFocus) {
4427            imm.focusIn(this);
4428        }
4429
4430        invalidate(true);
4431        ListenerInfo li = mListenerInfo;
4432        if (li != null && li.mOnFocusChangeListener != null) {
4433            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4434        }
4435
4436        if (mAttachInfo != null) {
4437            mAttachInfo.mKeyDispatchState.reset(this);
4438        }
4439    }
4440
4441    /**
4442     * Sends an accessibility event of the given type. If accessiiblity is
4443     * not enabled this method has no effect. The default implementation calls
4444     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4445     * to populate information about the event source (this View), then calls
4446     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4447     * populate the text content of the event source including its descendants,
4448     * and last calls
4449     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4450     * on its parent to resuest sending of the event to interested parties.
4451     * <p>
4452     * If an {@link AccessibilityDelegate} has been specified via calling
4453     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4454     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4455     * responsible for handling this call.
4456     * </p>
4457     *
4458     * @param eventType The type of the event to send, as defined by several types from
4459     * {@link android.view.accessibility.AccessibilityEvent}, such as
4460     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4461     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4462     *
4463     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4464     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4465     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4466     * @see AccessibilityDelegate
4467     */
4468    public void sendAccessibilityEvent(int eventType) {
4469        if (mAccessibilityDelegate != null) {
4470            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4471        } else {
4472            sendAccessibilityEventInternal(eventType);
4473        }
4474    }
4475
4476    /**
4477     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4478     * {@link AccessibilityEvent} to make an announcement which is related to some
4479     * sort of a context change for which none of the events representing UI transitions
4480     * is a good fit. For example, announcing a new page in a book. If accessibility
4481     * is not enabled this method does nothing.
4482     *
4483     * @param text The announcement text.
4484     */
4485    public void announceForAccessibility(CharSequence text) {
4486        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4487            AccessibilityEvent event = AccessibilityEvent.obtain(
4488                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4489            onInitializeAccessibilityEvent(event);
4490            event.getText().add(text);
4491            event.setContentDescription(null);
4492            mParent.requestSendAccessibilityEvent(this, event);
4493        }
4494    }
4495
4496    /**
4497     * @see #sendAccessibilityEvent(int)
4498     *
4499     * Note: Called from the default {@link AccessibilityDelegate}.
4500     */
4501    void sendAccessibilityEventInternal(int eventType) {
4502        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4503            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4504        }
4505    }
4506
4507    /**
4508     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4509     * takes as an argument an empty {@link AccessibilityEvent} and does not
4510     * perform a check whether accessibility is enabled.
4511     * <p>
4512     * If an {@link AccessibilityDelegate} has been specified via calling
4513     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4514     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4515     * is responsible for handling this call.
4516     * </p>
4517     *
4518     * @param event The event to send.
4519     *
4520     * @see #sendAccessibilityEvent(int)
4521     */
4522    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4523        if (mAccessibilityDelegate != null) {
4524            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4525        } else {
4526            sendAccessibilityEventUncheckedInternal(event);
4527        }
4528    }
4529
4530    /**
4531     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4532     *
4533     * Note: Called from the default {@link AccessibilityDelegate}.
4534     */
4535    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4536        if (!isShown()) {
4537            return;
4538        }
4539        onInitializeAccessibilityEvent(event);
4540        // Only a subset of accessibility events populates text content.
4541        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4542            dispatchPopulateAccessibilityEvent(event);
4543        }
4544        // In the beginning we called #isShown(), so we know that getParent() is not null.
4545        getParent().requestSendAccessibilityEvent(this, event);
4546    }
4547
4548    /**
4549     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4550     * to its children for adding their text content to the event. Note that the
4551     * event text is populated in a separate dispatch path since we add to the
4552     * event not only the text of the source but also the text of all its descendants.
4553     * A typical implementation will call
4554     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4555     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4556     * on each child. Override this method if custom population of the event text
4557     * content is required.
4558     * <p>
4559     * If an {@link AccessibilityDelegate} has been specified via calling
4560     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4561     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4562     * is responsible for handling this call.
4563     * </p>
4564     * <p>
4565     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4566     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4567     * </p>
4568     *
4569     * @param event The event.
4570     *
4571     * @return True if the event population was completed.
4572     */
4573    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4574        if (mAccessibilityDelegate != null) {
4575            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4576        } else {
4577            return dispatchPopulateAccessibilityEventInternal(event);
4578        }
4579    }
4580
4581    /**
4582     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4583     *
4584     * Note: Called from the default {@link AccessibilityDelegate}.
4585     */
4586    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4587        onPopulateAccessibilityEvent(event);
4588        return false;
4589    }
4590
4591    /**
4592     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4593     * giving a chance to this View to populate the accessibility event with its
4594     * text content. While this method is free to modify event
4595     * attributes other than text content, doing so should normally be performed in
4596     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4597     * <p>
4598     * Example: Adding formatted date string to an accessibility event in addition
4599     *          to the text added by the super implementation:
4600     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4601     *     super.onPopulateAccessibilityEvent(event);
4602     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4603     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4604     *         mCurrentDate.getTimeInMillis(), flags);
4605     *     event.getText().add(selectedDateUtterance);
4606     * }</pre>
4607     * <p>
4608     * If an {@link AccessibilityDelegate} has been specified via calling
4609     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4610     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4611     * is responsible for handling this call.
4612     * </p>
4613     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4614     * information to the event, in case the default implementation has basic information to add.
4615     * </p>
4616     *
4617     * @param event The accessibility event which to populate.
4618     *
4619     * @see #sendAccessibilityEvent(int)
4620     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4621     */
4622    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4623        if (mAccessibilityDelegate != null) {
4624            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4625        } else {
4626            onPopulateAccessibilityEventInternal(event);
4627        }
4628    }
4629
4630    /**
4631     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4632     *
4633     * Note: Called from the default {@link AccessibilityDelegate}.
4634     */
4635    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4636
4637    }
4638
4639    /**
4640     * Initializes an {@link AccessibilityEvent} with information about
4641     * this View which is the event source. In other words, the source of
4642     * an accessibility event is the view whose state change triggered firing
4643     * the event.
4644     * <p>
4645     * Example: Setting the password property of an event in addition
4646     *          to properties set by the super implementation:
4647     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4648     *     super.onInitializeAccessibilityEvent(event);
4649     *     event.setPassword(true);
4650     * }</pre>
4651     * <p>
4652     * If an {@link AccessibilityDelegate} has been specified via calling
4653     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4654     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4655     * is responsible for handling this call.
4656     * </p>
4657     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4658     * information to the event, in case the default implementation has basic information to add.
4659     * </p>
4660     * @param event The event to initialize.
4661     *
4662     * @see #sendAccessibilityEvent(int)
4663     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4664     */
4665    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4666        if (mAccessibilityDelegate != null) {
4667            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4668        } else {
4669            onInitializeAccessibilityEventInternal(event);
4670        }
4671    }
4672
4673    /**
4674     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4675     *
4676     * Note: Called from the default {@link AccessibilityDelegate}.
4677     */
4678    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4679        event.setSource(this);
4680        event.setClassName(View.class.getName());
4681        event.setPackageName(getContext().getPackageName());
4682        event.setEnabled(isEnabled());
4683        event.setContentDescription(mContentDescription);
4684
4685        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4686            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4687            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4688                    FOCUSABLES_ALL);
4689            event.setItemCount(focusablesTempList.size());
4690            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4691            focusablesTempList.clear();
4692        }
4693    }
4694
4695    /**
4696     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4697     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4698     * This method is responsible for obtaining an accessibility node info from a
4699     * pool of reusable instances and calling
4700     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4701     * initialize the former.
4702     * <p>
4703     * Note: The client is responsible for recycling the obtained instance by calling
4704     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4705     * </p>
4706     *
4707     * @return A populated {@link AccessibilityNodeInfo}.
4708     *
4709     * @see AccessibilityNodeInfo
4710     */
4711    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4712        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4713        if (provider != null) {
4714            return provider.createAccessibilityNodeInfo(View.NO_ID);
4715        } else {
4716            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4717            onInitializeAccessibilityNodeInfo(info);
4718            return info;
4719        }
4720    }
4721
4722    /**
4723     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4724     * The base implementation sets:
4725     * <ul>
4726     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4727     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4728     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4729     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4730     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4731     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4732     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4733     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4734     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4735     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4736     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4737     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4738     * </ul>
4739     * <p>
4740     * Subclasses should override this method, call the super implementation,
4741     * and set additional attributes.
4742     * </p>
4743     * <p>
4744     * If an {@link AccessibilityDelegate} has been specified via calling
4745     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4746     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4747     * is responsible for handling this call.
4748     * </p>
4749     *
4750     * @param info The instance to initialize.
4751     */
4752    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4753        if (mAccessibilityDelegate != null) {
4754            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4755        } else {
4756            onInitializeAccessibilityNodeInfoInternal(info);
4757        }
4758    }
4759
4760    /**
4761     * Gets the location of this view in screen coordintates.
4762     *
4763     * @param outRect The output location
4764     */
4765    private void getBoundsOnScreen(Rect outRect) {
4766        if (mAttachInfo == null) {
4767            return;
4768        }
4769
4770        RectF position = mAttachInfo.mTmpTransformRect;
4771        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4772
4773        if (!hasIdentityMatrix()) {
4774            getMatrix().mapRect(position);
4775        }
4776
4777        position.offset(mLeft, mTop);
4778
4779        ViewParent parent = mParent;
4780        while (parent instanceof View) {
4781            View parentView = (View) parent;
4782
4783            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4784
4785            if (!parentView.hasIdentityMatrix()) {
4786                parentView.getMatrix().mapRect(position);
4787            }
4788
4789            position.offset(parentView.mLeft, parentView.mTop);
4790
4791            parent = parentView.mParent;
4792        }
4793
4794        if (parent instanceof ViewRootImpl) {
4795            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4796            position.offset(0, -viewRootImpl.mCurScrollY);
4797        }
4798
4799        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4800
4801        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4802                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4803    }
4804
4805    /**
4806     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4807     *
4808     * Note: Called from the default {@link AccessibilityDelegate}.
4809     */
4810    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4811        Rect bounds = mAttachInfo.mTmpInvalRect;
4812
4813        getDrawingRect(bounds);
4814        info.setBoundsInParent(bounds);
4815
4816        getBoundsOnScreen(bounds);
4817        info.setBoundsInScreen(bounds);
4818
4819        ViewParent parent = getParentForAccessibility();
4820        if (parent instanceof View) {
4821            info.setParent((View) parent);
4822        }
4823
4824        info.setVisibleToUser(isVisibleToUser());
4825
4826        info.setPackageName(mContext.getPackageName());
4827        info.setClassName(View.class.getName());
4828        info.setContentDescription(getContentDescription());
4829
4830        info.setEnabled(isEnabled());
4831        info.setClickable(isClickable());
4832        info.setFocusable(isFocusable());
4833        info.setFocused(isFocused());
4834        info.setAccessibilityFocused(isAccessibilityFocused());
4835        info.setSelected(isSelected());
4836        info.setLongClickable(isLongClickable());
4837
4838        // TODO: These make sense only if we are in an AdapterView but all
4839        // views can be selected. Maybe from accessiiblity perspective
4840        // we should report as selectable view in an AdapterView.
4841        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4842        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4843
4844        if (isFocusable()) {
4845            if (isFocused()) {
4846                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4847            } else {
4848                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4849            }
4850        }
4851
4852        if (!isAccessibilityFocused()) {
4853            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4854        } else {
4855            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4856        }
4857
4858        if (isClickable() && isEnabled()) {
4859            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4860        }
4861
4862        if (isLongClickable() && isEnabled()) {
4863            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4864        }
4865
4866        if (mContentDescription != null && mContentDescription.length() > 0) {
4867            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4868            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4869            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4870                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4871                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4872        }
4873    }
4874
4875    /**
4876     * Computes whether this view is visible to the user. Such a view is
4877     * attached, visible, all its predecessors are visible, it is not clipped
4878     * entirely by its predecessors, and has an alpha greater than zero.
4879     *
4880     * @return Whether the view is visible on the screen.
4881     *
4882     * @hide
4883     */
4884    protected boolean isVisibleToUser() {
4885        return isVisibleToUser(null);
4886    }
4887
4888    /**
4889     * Computes whether the given portion of this view is visible to the user.
4890     * Such a view is attached, visible, all its predecessors are visible,
4891     * has an alpha greater than zero, and the specified portion is not
4892     * clipped entirely by its predecessors.
4893     *
4894     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4895     *                    <code>null</code>, and the entire view will be tested in this case.
4896     *                    When <code>true</code> is returned by the function, the actual visible
4897     *                    region will be stored in this parameter; that is, if boundInView is fully
4898     *                    contained within the view, no modification will be made, otherwise regions
4899     *                    outside of the visible area of the view will be clipped.
4900     *
4901     * @return Whether the specified portion of the view is visible on the screen.
4902     *
4903     * @hide
4904     */
4905    protected boolean isVisibleToUser(Rect boundInView) {
4906        if (mAttachInfo != null) {
4907            Rect visibleRect = mAttachInfo.mTmpInvalRect;
4908            Point offset = mAttachInfo.mPoint;
4909            // The first two checks are made also made by isShown() which
4910            // however traverses the tree up to the parent to catch that.
4911            // Therefore, we do some fail fast check to minimize the up
4912            // tree traversal.
4913            boolean isVisible = mAttachInfo.mWindowVisibility == View.VISIBLE
4914                && getAlpha() > 0
4915                && isShown()
4916                && getGlobalVisibleRect(visibleRect, offset);
4917            if (isVisible && boundInView != null) {
4918                visibleRect.offset(-offset.x, -offset.y);
4919                // isVisible is always true here, use a simple assignment
4920                isVisible = boundInView.intersect(visibleRect);
4921            }
4922            return isVisible;
4923        }
4924
4925        return false;
4926    }
4927
4928    /**
4929     * Returns the delegate for implementing accessibility support via
4930     * composition. For more details see {@link AccessibilityDelegate}.
4931     *
4932     * @return The delegate, or null if none set.
4933     *
4934     * @hide
4935     */
4936    public AccessibilityDelegate getAccessibilityDelegate() {
4937        return mAccessibilityDelegate;
4938    }
4939
4940    /**
4941     * Sets a delegate for implementing accessibility support via compositon as
4942     * opposed to inheritance. The delegate's primary use is for implementing
4943     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4944     *
4945     * @param delegate The delegate instance.
4946     *
4947     * @see AccessibilityDelegate
4948     */
4949    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4950        mAccessibilityDelegate = delegate;
4951    }
4952
4953    /**
4954     * Gets the provider for managing a virtual view hierarchy rooted at this View
4955     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4956     * that explore the window content.
4957     * <p>
4958     * If this method returns an instance, this instance is responsible for managing
4959     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4960     * View including the one representing the View itself. Similarly the returned
4961     * instance is responsible for performing accessibility actions on any virtual
4962     * view or the root view itself.
4963     * </p>
4964     * <p>
4965     * If an {@link AccessibilityDelegate} has been specified via calling
4966     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4967     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4968     * is responsible for handling this call.
4969     * </p>
4970     *
4971     * @return The provider.
4972     *
4973     * @see AccessibilityNodeProvider
4974     */
4975    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4976        if (mAccessibilityDelegate != null) {
4977            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4978        } else {
4979            return null;
4980        }
4981    }
4982
4983    /**
4984     * Gets the unique identifier of this view on the screen for accessibility purposes.
4985     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4986     *
4987     * @return The view accessibility id.
4988     *
4989     * @hide
4990     */
4991    public int getAccessibilityViewId() {
4992        if (mAccessibilityViewId == NO_ID) {
4993            mAccessibilityViewId = sNextAccessibilityViewId++;
4994        }
4995        return mAccessibilityViewId;
4996    }
4997
4998    /**
4999     * Gets the unique identifier of the window in which this View reseides.
5000     *
5001     * @return The window accessibility id.
5002     *
5003     * @hide
5004     */
5005    public int getAccessibilityWindowId() {
5006        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5007    }
5008
5009    /**
5010     * Gets the {@link View} description. It briefly describes the view and is
5011     * primarily used for accessibility support. Set this property to enable
5012     * better accessibility support for your application. This is especially
5013     * true for views that do not have textual representation (For example,
5014     * ImageButton).
5015     *
5016     * @return The content description.
5017     *
5018     * @attr ref android.R.styleable#View_contentDescription
5019     */
5020    @ViewDebug.ExportedProperty(category = "accessibility")
5021    public CharSequence getContentDescription() {
5022        return mContentDescription;
5023    }
5024
5025    /**
5026     * Sets the {@link View} description. It briefly describes the view and is
5027     * primarily used for accessibility support. Set this property to enable
5028     * better accessibility support for your application. This is especially
5029     * true for views that do not have textual representation (For example,
5030     * ImageButton).
5031     *
5032     * @param contentDescription The content description.
5033     *
5034     * @attr ref android.R.styleable#View_contentDescription
5035     */
5036    @RemotableViewMethod
5037    public void setContentDescription(CharSequence contentDescription) {
5038        mContentDescription = contentDescription;
5039        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5040        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5041             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5042        }
5043    }
5044
5045    /**
5046     * Invoked whenever this view loses focus, either by losing window focus or by losing
5047     * focus within its window. This method can be used to clear any state tied to the
5048     * focus. For instance, if a button is held pressed with the trackball and the window
5049     * loses focus, this method can be used to cancel the press.
5050     *
5051     * Subclasses of View overriding this method should always call super.onFocusLost().
5052     *
5053     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5054     * @see #onWindowFocusChanged(boolean)
5055     *
5056     * @hide pending API council approval
5057     */
5058    protected void onFocusLost() {
5059        resetPressedState();
5060    }
5061
5062    private void resetPressedState() {
5063        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5064            return;
5065        }
5066
5067        if (isPressed()) {
5068            setPressed(false);
5069
5070            if (!mHasPerformedLongPress) {
5071                removeLongPressCallback();
5072            }
5073        }
5074    }
5075
5076    /**
5077     * Returns true if this view has focus
5078     *
5079     * @return True if this view has focus, false otherwise.
5080     */
5081    @ViewDebug.ExportedProperty(category = "focus")
5082    public boolean isFocused() {
5083        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5084    }
5085
5086    /**
5087     * Find the view in the hierarchy rooted at this view that currently has
5088     * focus.
5089     *
5090     * @return The view that currently has focus, or null if no focused view can
5091     *         be found.
5092     */
5093    public View findFocus() {
5094        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5095    }
5096
5097    /**
5098     * Indicates whether this view is one of the set of scrollable containers in
5099     * its window.
5100     *
5101     * @return whether this view is one of the set of scrollable containers in
5102     * its window
5103     *
5104     * @attr ref android.R.styleable#View_isScrollContainer
5105     */
5106    public boolean isScrollContainer() {
5107        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5108    }
5109
5110    /**
5111     * Change whether this view is one of the set of scrollable containers in
5112     * its window.  This will be used to determine whether the window can
5113     * resize or must pan when a soft input area is open -- scrollable
5114     * containers allow the window to use resize mode since the container
5115     * will appropriately shrink.
5116     *
5117     * @attr ref android.R.styleable#View_isScrollContainer
5118     */
5119    public void setScrollContainer(boolean isScrollContainer) {
5120        if (isScrollContainer) {
5121            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5122                mAttachInfo.mScrollContainers.add(this);
5123                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5124            }
5125            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5126        } else {
5127            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5128                mAttachInfo.mScrollContainers.remove(this);
5129            }
5130            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5131        }
5132    }
5133
5134    /**
5135     * Returns the quality of the drawing cache.
5136     *
5137     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5138     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5139     *
5140     * @see #setDrawingCacheQuality(int)
5141     * @see #setDrawingCacheEnabled(boolean)
5142     * @see #isDrawingCacheEnabled()
5143     *
5144     * @attr ref android.R.styleable#View_drawingCacheQuality
5145     */
5146    public int getDrawingCacheQuality() {
5147        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5148    }
5149
5150    /**
5151     * Set the drawing cache quality of this view. This value is used only when the
5152     * drawing cache is enabled
5153     *
5154     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5155     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5156     *
5157     * @see #getDrawingCacheQuality()
5158     * @see #setDrawingCacheEnabled(boolean)
5159     * @see #isDrawingCacheEnabled()
5160     *
5161     * @attr ref android.R.styleable#View_drawingCacheQuality
5162     */
5163    public void setDrawingCacheQuality(int quality) {
5164        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5165    }
5166
5167    /**
5168     * Returns whether the screen should remain on, corresponding to the current
5169     * value of {@link #KEEP_SCREEN_ON}.
5170     *
5171     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5172     *
5173     * @see #setKeepScreenOn(boolean)
5174     *
5175     * @attr ref android.R.styleable#View_keepScreenOn
5176     */
5177    public boolean getKeepScreenOn() {
5178        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5179    }
5180
5181    /**
5182     * Controls whether the screen should remain on, modifying the
5183     * value of {@link #KEEP_SCREEN_ON}.
5184     *
5185     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5186     *
5187     * @see #getKeepScreenOn()
5188     *
5189     * @attr ref android.R.styleable#View_keepScreenOn
5190     */
5191    public void setKeepScreenOn(boolean keepScreenOn) {
5192        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5193    }
5194
5195    /**
5196     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5197     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5198     *
5199     * @attr ref android.R.styleable#View_nextFocusLeft
5200     */
5201    public int getNextFocusLeftId() {
5202        return mNextFocusLeftId;
5203    }
5204
5205    /**
5206     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5207     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5208     * decide automatically.
5209     *
5210     * @attr ref android.R.styleable#View_nextFocusLeft
5211     */
5212    public void setNextFocusLeftId(int nextFocusLeftId) {
5213        mNextFocusLeftId = nextFocusLeftId;
5214    }
5215
5216    /**
5217     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5218     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5219     *
5220     * @attr ref android.R.styleable#View_nextFocusRight
5221     */
5222    public int getNextFocusRightId() {
5223        return mNextFocusRightId;
5224    }
5225
5226    /**
5227     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5228     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5229     * decide automatically.
5230     *
5231     * @attr ref android.R.styleable#View_nextFocusRight
5232     */
5233    public void setNextFocusRightId(int nextFocusRightId) {
5234        mNextFocusRightId = nextFocusRightId;
5235    }
5236
5237    /**
5238     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5239     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5240     *
5241     * @attr ref android.R.styleable#View_nextFocusUp
5242     */
5243    public int getNextFocusUpId() {
5244        return mNextFocusUpId;
5245    }
5246
5247    /**
5248     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5249     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5250     * decide automatically.
5251     *
5252     * @attr ref android.R.styleable#View_nextFocusUp
5253     */
5254    public void setNextFocusUpId(int nextFocusUpId) {
5255        mNextFocusUpId = nextFocusUpId;
5256    }
5257
5258    /**
5259     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5260     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5261     *
5262     * @attr ref android.R.styleable#View_nextFocusDown
5263     */
5264    public int getNextFocusDownId() {
5265        return mNextFocusDownId;
5266    }
5267
5268    /**
5269     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5270     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5271     * decide automatically.
5272     *
5273     * @attr ref android.R.styleable#View_nextFocusDown
5274     */
5275    public void setNextFocusDownId(int nextFocusDownId) {
5276        mNextFocusDownId = nextFocusDownId;
5277    }
5278
5279    /**
5280     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5281     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5282     *
5283     * @attr ref android.R.styleable#View_nextFocusForward
5284     */
5285    public int getNextFocusForwardId() {
5286        return mNextFocusForwardId;
5287    }
5288
5289    /**
5290     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5291     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5292     * decide automatically.
5293     *
5294     * @attr ref android.R.styleable#View_nextFocusForward
5295     */
5296    public void setNextFocusForwardId(int nextFocusForwardId) {
5297        mNextFocusForwardId = nextFocusForwardId;
5298    }
5299
5300    /**
5301     * Returns the visibility of this view and all of its ancestors
5302     *
5303     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5304     */
5305    public boolean isShown() {
5306        View current = this;
5307        //noinspection ConstantConditions
5308        do {
5309            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5310                return false;
5311            }
5312            ViewParent parent = current.mParent;
5313            if (parent == null) {
5314                return false; // We are not attached to the view root
5315            }
5316            if (!(parent instanceof View)) {
5317                return true;
5318            }
5319            current = (View) parent;
5320        } while (current != null);
5321
5322        return false;
5323    }
5324
5325    /**
5326     * Called by the view hierarchy when the content insets for a window have
5327     * changed, to allow it to adjust its content to fit within those windows.
5328     * The content insets tell you the space that the status bar, input method,
5329     * and other system windows infringe on the application's window.
5330     *
5331     * <p>You do not normally need to deal with this function, since the default
5332     * window decoration given to applications takes care of applying it to the
5333     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5334     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5335     * and your content can be placed under those system elements.  You can then
5336     * use this method within your view hierarchy if you have parts of your UI
5337     * which you would like to ensure are not being covered.
5338     *
5339     * <p>The default implementation of this method simply applies the content
5340     * inset's to the view's padding, consuming that content (modifying the
5341     * insets to be 0), and returning true.  This behavior is off by default, but can
5342     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5343     *
5344     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5345     * insets object is propagated down the hierarchy, so any changes made to it will
5346     * be seen by all following views (including potentially ones above in
5347     * the hierarchy since this is a depth-first traversal).  The first view
5348     * that returns true will abort the entire traversal.
5349     *
5350     * <p>The default implementation works well for a situation where it is
5351     * used with a container that covers the entire window, allowing it to
5352     * apply the appropriate insets to its content on all edges.  If you need
5353     * a more complicated layout (such as two different views fitting system
5354     * windows, one on the top of the window, and one on the bottom),
5355     * you can override the method and handle the insets however you would like.
5356     * Note that the insets provided by the framework are always relative to the
5357     * far edges of the window, not accounting for the location of the called view
5358     * within that window.  (In fact when this method is called you do not yet know
5359     * where the layout will place the view, as it is done before layout happens.)
5360     *
5361     * <p>Note: unlike many View methods, there is no dispatch phase to this
5362     * call.  If you are overriding it in a ViewGroup and want to allow the
5363     * call to continue to your children, you must be sure to call the super
5364     * implementation.
5365     *
5366     * <p>Here is a sample layout that makes use of fitting system windows
5367     * to have controls for a video view placed inside of the window decorations
5368     * that it hides and shows.  This can be used with code like the second
5369     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5370     *
5371     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5372     *
5373     * @param insets Current content insets of the window.  Prior to
5374     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5375     * the insets or else you and Android will be unhappy.
5376     *
5377     * @return Return true if this view applied the insets and it should not
5378     * continue propagating further down the hierarchy, false otherwise.
5379     * @see #getFitsSystemWindows()
5380     * @see #setFitsSystemWindows(boolean)
5381     * @see #setSystemUiVisibility(int)
5382     */
5383    protected boolean fitSystemWindows(Rect insets) {
5384        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5385            mUserPaddingStart = UNDEFINED_PADDING;
5386            mUserPaddingEnd = UNDEFINED_PADDING;
5387            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5388                    || mAttachInfo == null
5389                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5390                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5391                return true;
5392            } else {
5393                internalSetPadding(0, 0, 0, 0);
5394                return false;
5395            }
5396        }
5397        return false;
5398    }
5399
5400    /**
5401     * Sets whether or not this view should account for system screen decorations
5402     * such as the status bar and inset its content; that is, controlling whether
5403     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5404     * executed.  See that method for more details.
5405     *
5406     * <p>Note that if you are providing your own implementation of
5407     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5408     * flag to true -- your implementation will be overriding the default
5409     * implementation that checks this flag.
5410     *
5411     * @param fitSystemWindows If true, then the default implementation of
5412     * {@link #fitSystemWindows(Rect)} will be executed.
5413     *
5414     * @attr ref android.R.styleable#View_fitsSystemWindows
5415     * @see #getFitsSystemWindows()
5416     * @see #fitSystemWindows(Rect)
5417     * @see #setSystemUiVisibility(int)
5418     */
5419    public void setFitsSystemWindows(boolean fitSystemWindows) {
5420        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5421    }
5422
5423    /**
5424     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5425     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5426     * will be executed.
5427     *
5428     * @return Returns true if the default implementation of
5429     * {@link #fitSystemWindows(Rect)} will be executed.
5430     *
5431     * @attr ref android.R.styleable#View_fitsSystemWindows
5432     * @see #setFitsSystemWindows()
5433     * @see #fitSystemWindows(Rect)
5434     * @see #setSystemUiVisibility(int)
5435     */
5436    public boolean getFitsSystemWindows() {
5437        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5438    }
5439
5440    /** @hide */
5441    public boolean fitsSystemWindows() {
5442        return getFitsSystemWindows();
5443    }
5444
5445    /**
5446     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5447     */
5448    public void requestFitSystemWindows() {
5449        if (mParent != null) {
5450            mParent.requestFitSystemWindows();
5451        }
5452    }
5453
5454    /**
5455     * For use by PhoneWindow to make its own system window fitting optional.
5456     * @hide
5457     */
5458    public void makeOptionalFitsSystemWindows() {
5459        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5460    }
5461
5462    /**
5463     * Returns the visibility status for this view.
5464     *
5465     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5466     * @attr ref android.R.styleable#View_visibility
5467     */
5468    @ViewDebug.ExportedProperty(mapping = {
5469        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5470        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5471        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5472    })
5473    public int getVisibility() {
5474        return mViewFlags & VISIBILITY_MASK;
5475    }
5476
5477    /**
5478     * Set the enabled state of this view.
5479     *
5480     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5481     * @attr ref android.R.styleable#View_visibility
5482     */
5483    @RemotableViewMethod
5484    public void setVisibility(int visibility) {
5485        setFlags(visibility, VISIBILITY_MASK);
5486        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5487    }
5488
5489    /**
5490     * Returns the enabled status for this view. The interpretation of the
5491     * enabled state varies by subclass.
5492     *
5493     * @return True if this view is enabled, false otherwise.
5494     */
5495    @ViewDebug.ExportedProperty
5496    public boolean isEnabled() {
5497        return (mViewFlags & ENABLED_MASK) == ENABLED;
5498    }
5499
5500    /**
5501     * Set the enabled state of this view. The interpretation of the enabled
5502     * state varies by subclass.
5503     *
5504     * @param enabled True if this view is enabled, false otherwise.
5505     */
5506    @RemotableViewMethod
5507    public void setEnabled(boolean enabled) {
5508        if (enabled == isEnabled()) return;
5509
5510        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5511
5512        /*
5513         * The View most likely has to change its appearance, so refresh
5514         * the drawable state.
5515         */
5516        refreshDrawableState();
5517
5518        // Invalidate too, since the default behavior for views is to be
5519        // be drawn at 50% alpha rather than to change the drawable.
5520        invalidate(true);
5521    }
5522
5523    /**
5524     * Set whether this view can receive the focus.
5525     *
5526     * Setting this to false will also ensure that this view is not focusable
5527     * in touch mode.
5528     *
5529     * @param focusable If true, this view can receive the focus.
5530     *
5531     * @see #setFocusableInTouchMode(boolean)
5532     * @attr ref android.R.styleable#View_focusable
5533     */
5534    public void setFocusable(boolean focusable) {
5535        if (!focusable) {
5536            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5537        }
5538        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5539    }
5540
5541    /**
5542     * Set whether this view can receive focus while in touch mode.
5543     *
5544     * Setting this to true will also ensure that this view is focusable.
5545     *
5546     * @param focusableInTouchMode If true, this view can receive the focus while
5547     *   in touch mode.
5548     *
5549     * @see #setFocusable(boolean)
5550     * @attr ref android.R.styleable#View_focusableInTouchMode
5551     */
5552    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5553        // Focusable in touch mode should always be set before the focusable flag
5554        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5555        // which, in touch mode, will not successfully request focus on this view
5556        // because the focusable in touch mode flag is not set
5557        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5558        if (focusableInTouchMode) {
5559            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5560        }
5561    }
5562
5563    /**
5564     * Set whether this view should have sound effects enabled for events such as
5565     * clicking and touching.
5566     *
5567     * <p>You may wish to disable sound effects for a view if you already play sounds,
5568     * for instance, a dial key that plays dtmf tones.
5569     *
5570     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5571     * @see #isSoundEffectsEnabled()
5572     * @see #playSoundEffect(int)
5573     * @attr ref android.R.styleable#View_soundEffectsEnabled
5574     */
5575    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5576        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5577    }
5578
5579    /**
5580     * @return whether this view should have sound effects enabled for events such as
5581     *     clicking and touching.
5582     *
5583     * @see #setSoundEffectsEnabled(boolean)
5584     * @see #playSoundEffect(int)
5585     * @attr ref android.R.styleable#View_soundEffectsEnabled
5586     */
5587    @ViewDebug.ExportedProperty
5588    public boolean isSoundEffectsEnabled() {
5589        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5590    }
5591
5592    /**
5593     * Set whether this view should have haptic feedback for events such as
5594     * long presses.
5595     *
5596     * <p>You may wish to disable haptic feedback if your view already controls
5597     * its own haptic feedback.
5598     *
5599     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5600     * @see #isHapticFeedbackEnabled()
5601     * @see #performHapticFeedback(int)
5602     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5603     */
5604    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5605        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5606    }
5607
5608    /**
5609     * @return whether this view should have haptic feedback enabled for events
5610     * long presses.
5611     *
5612     * @see #setHapticFeedbackEnabled(boolean)
5613     * @see #performHapticFeedback(int)
5614     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5615     */
5616    @ViewDebug.ExportedProperty
5617    public boolean isHapticFeedbackEnabled() {
5618        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5619    }
5620
5621    /**
5622     * Returns the layout direction for this view.
5623     *
5624     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5625     *   {@link #LAYOUT_DIRECTION_RTL},
5626     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5627     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5628     * @attr ref android.R.styleable#View_layoutDirection
5629     */
5630    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5631        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5632        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5633        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5634        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5635    })
5636    public int getLayoutDirection() {
5637        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
5638    }
5639
5640    /**
5641     * Set the layout direction for this view. This will propagate a reset of layout direction
5642     * resolution to the view's children and resolve layout direction for this view.
5643     *
5644     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5645     *   {@link #LAYOUT_DIRECTION_RTL},
5646     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5647     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5648     *
5649     * @attr ref android.R.styleable#View_layoutDirection
5650     */
5651    @RemotableViewMethod
5652    public void setLayoutDirection(int layoutDirection) {
5653        if (getLayoutDirection() != layoutDirection) {
5654            // Reset the current layout direction and the resolved one
5655            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
5656            resetResolvedLayoutDirection();
5657            // Reset padding resolution
5658            mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
5659            // Set the new layout direction (filtered)
5660            mPrivateFlags2 |=
5661                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
5662            resolveRtlProperties();
5663            // ... and ask for a layout pass
5664            requestLayout();
5665        }
5666    }
5667
5668    /**
5669     * Returns the resolved layout direction for this view.
5670     *
5671     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5672     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5673     */
5674    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5675        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5676        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5677    })
5678    public int getResolvedLayoutDirection() {
5679        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
5680        if (targetSdkVersion < JELLY_BEAN_MR1) {
5681            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
5682            return LAYOUT_DIRECTION_LTR;
5683        }
5684        // The layout direction will be resolved only if needed
5685        if ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) != PFLAG2_LAYOUT_DIRECTION_RESOLVED) {
5686            resolveLayoutDirection();
5687        }
5688        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ?
5689                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5690    }
5691
5692    /**
5693     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5694     * layout attribute and/or the inherited value from the parent
5695     *
5696     * @return true if the layout is right-to-left.
5697     */
5698    @ViewDebug.ExportedProperty(category = "layout")
5699    public boolean isLayoutRtl() {
5700        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5701    }
5702
5703    /**
5704     * Indicates whether the view is currently tracking transient state that the
5705     * app should not need to concern itself with saving and restoring, but that
5706     * the framework should take special note to preserve when possible.
5707     *
5708     * <p>A view with transient state cannot be trivially rebound from an external
5709     * data source, such as an adapter binding item views in a list. This may be
5710     * because the view is performing an animation, tracking user selection
5711     * of content, or similar.</p>
5712     *
5713     * @return true if the view has transient state
5714     */
5715    @ViewDebug.ExportedProperty(category = "layout")
5716    public boolean hasTransientState() {
5717        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
5718    }
5719
5720    /**
5721     * Set whether this view is currently tracking transient state that the
5722     * framework should attempt to preserve when possible. This flag is reference counted,
5723     * so every call to setHasTransientState(true) should be paired with a later call
5724     * to setHasTransientState(false).
5725     *
5726     * <p>A view with transient state cannot be trivially rebound from an external
5727     * data source, such as an adapter binding item views in a list. This may be
5728     * because the view is performing an animation, tracking user selection
5729     * of content, or similar.</p>
5730     *
5731     * @param hasTransientState true if this view has transient state
5732     */
5733    public void setHasTransientState(boolean hasTransientState) {
5734        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5735                mTransientStateCount - 1;
5736        if (mTransientStateCount < 0) {
5737            mTransientStateCount = 0;
5738            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5739                    "unmatched pair of setHasTransientState calls");
5740        }
5741        if ((hasTransientState && mTransientStateCount == 1) ||
5742                (!hasTransientState && mTransientStateCount == 0)) {
5743            // update flag if we've just incremented up from 0 or decremented down to 0
5744            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
5745                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
5746            if (mParent != null) {
5747                try {
5748                    mParent.childHasTransientStateChanged(this, hasTransientState);
5749                } catch (AbstractMethodError e) {
5750                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5751                            " does not fully implement ViewParent", e);
5752                }
5753            }
5754        }
5755    }
5756
5757    /**
5758     * If this view doesn't do any drawing on its own, set this flag to
5759     * allow further optimizations. By default, this flag is not set on
5760     * View, but could be set on some View subclasses such as ViewGroup.
5761     *
5762     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5763     * you should clear this flag.
5764     *
5765     * @param willNotDraw whether or not this View draw on its own
5766     */
5767    public void setWillNotDraw(boolean willNotDraw) {
5768        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5769    }
5770
5771    /**
5772     * Returns whether or not this View draws on its own.
5773     *
5774     * @return true if this view has nothing to draw, false otherwise
5775     */
5776    @ViewDebug.ExportedProperty(category = "drawing")
5777    public boolean willNotDraw() {
5778        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5779    }
5780
5781    /**
5782     * When a View's drawing cache is enabled, drawing is redirected to an
5783     * offscreen bitmap. Some views, like an ImageView, must be able to
5784     * bypass this mechanism if they already draw a single bitmap, to avoid
5785     * unnecessary usage of the memory.
5786     *
5787     * @param willNotCacheDrawing true if this view does not cache its
5788     *        drawing, false otherwise
5789     */
5790    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5791        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5792    }
5793
5794    /**
5795     * Returns whether or not this View can cache its drawing or not.
5796     *
5797     * @return true if this view does not cache its drawing, false otherwise
5798     */
5799    @ViewDebug.ExportedProperty(category = "drawing")
5800    public boolean willNotCacheDrawing() {
5801        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5802    }
5803
5804    /**
5805     * Indicates whether this view reacts to click events or not.
5806     *
5807     * @return true if the view is clickable, false otherwise
5808     *
5809     * @see #setClickable(boolean)
5810     * @attr ref android.R.styleable#View_clickable
5811     */
5812    @ViewDebug.ExportedProperty
5813    public boolean isClickable() {
5814        return (mViewFlags & CLICKABLE) == CLICKABLE;
5815    }
5816
5817    /**
5818     * Enables or disables click events for this view. When a view
5819     * is clickable it will change its state to "pressed" on every click.
5820     * Subclasses should set the view clickable to visually react to
5821     * user's clicks.
5822     *
5823     * @param clickable true to make the view clickable, false otherwise
5824     *
5825     * @see #isClickable()
5826     * @attr ref android.R.styleable#View_clickable
5827     */
5828    public void setClickable(boolean clickable) {
5829        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5830    }
5831
5832    /**
5833     * Indicates whether this view reacts to long click events or not.
5834     *
5835     * @return true if the view is long clickable, false otherwise
5836     *
5837     * @see #setLongClickable(boolean)
5838     * @attr ref android.R.styleable#View_longClickable
5839     */
5840    public boolean isLongClickable() {
5841        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5842    }
5843
5844    /**
5845     * Enables or disables long click events for this view. When a view is long
5846     * clickable it reacts to the user holding down the button for a longer
5847     * duration than a tap. This event can either launch the listener or a
5848     * context menu.
5849     *
5850     * @param longClickable true to make the view long clickable, false otherwise
5851     * @see #isLongClickable()
5852     * @attr ref android.R.styleable#View_longClickable
5853     */
5854    public void setLongClickable(boolean longClickable) {
5855        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5856    }
5857
5858    /**
5859     * Sets the pressed state for this view.
5860     *
5861     * @see #isClickable()
5862     * @see #setClickable(boolean)
5863     *
5864     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5865     *        the View's internal state from a previously set "pressed" state.
5866     */
5867    public void setPressed(boolean pressed) {
5868        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
5869
5870        if (pressed) {
5871            mPrivateFlags |= PFLAG_PRESSED;
5872        } else {
5873            mPrivateFlags &= ~PFLAG_PRESSED;
5874        }
5875
5876        if (needsRefresh) {
5877            refreshDrawableState();
5878        }
5879        dispatchSetPressed(pressed);
5880    }
5881
5882    /**
5883     * Dispatch setPressed to all of this View's children.
5884     *
5885     * @see #setPressed(boolean)
5886     *
5887     * @param pressed The new pressed state
5888     */
5889    protected void dispatchSetPressed(boolean pressed) {
5890    }
5891
5892    /**
5893     * Indicates whether the view is currently in pressed state. Unless
5894     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5895     * the pressed state.
5896     *
5897     * @see #setPressed(boolean)
5898     * @see #isClickable()
5899     * @see #setClickable(boolean)
5900     *
5901     * @return true if the view is currently pressed, false otherwise
5902     */
5903    public boolean isPressed() {
5904        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
5905    }
5906
5907    /**
5908     * Indicates whether this view will save its state (that is,
5909     * whether its {@link #onSaveInstanceState} method will be called).
5910     *
5911     * @return Returns true if the view state saving is enabled, else false.
5912     *
5913     * @see #setSaveEnabled(boolean)
5914     * @attr ref android.R.styleable#View_saveEnabled
5915     */
5916    public boolean isSaveEnabled() {
5917        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5918    }
5919
5920    /**
5921     * Controls whether the saving of this view's state is
5922     * enabled (that is, whether its {@link #onSaveInstanceState} method
5923     * will be called).  Note that even if freezing is enabled, the
5924     * view still must have an id assigned to it (via {@link #setId(int)})
5925     * for its state to be saved.  This flag can only disable the
5926     * saving of this view; any child views may still have their state saved.
5927     *
5928     * @param enabled Set to false to <em>disable</em> state saving, or true
5929     * (the default) to allow it.
5930     *
5931     * @see #isSaveEnabled()
5932     * @see #setId(int)
5933     * @see #onSaveInstanceState()
5934     * @attr ref android.R.styleable#View_saveEnabled
5935     */
5936    public void setSaveEnabled(boolean enabled) {
5937        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5938    }
5939
5940    /**
5941     * Gets whether the framework should discard touches when the view's
5942     * window is obscured by another visible window.
5943     * Refer to the {@link View} security documentation for more details.
5944     *
5945     * @return True if touch filtering is enabled.
5946     *
5947     * @see #setFilterTouchesWhenObscured(boolean)
5948     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5949     */
5950    @ViewDebug.ExportedProperty
5951    public boolean getFilterTouchesWhenObscured() {
5952        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5953    }
5954
5955    /**
5956     * Sets whether the framework should discard touches when the view's
5957     * window is obscured by another visible window.
5958     * Refer to the {@link View} security documentation for more details.
5959     *
5960     * @param enabled True if touch filtering should be enabled.
5961     *
5962     * @see #getFilterTouchesWhenObscured
5963     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5964     */
5965    public void setFilterTouchesWhenObscured(boolean enabled) {
5966        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5967                FILTER_TOUCHES_WHEN_OBSCURED);
5968    }
5969
5970    /**
5971     * Indicates whether the entire hierarchy under this view will save its
5972     * state when a state saving traversal occurs from its parent.  The default
5973     * is true; if false, these views will not be saved unless
5974     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5975     *
5976     * @return Returns true if the view state saving from parent is enabled, else false.
5977     *
5978     * @see #setSaveFromParentEnabled(boolean)
5979     */
5980    public boolean isSaveFromParentEnabled() {
5981        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5982    }
5983
5984    /**
5985     * Controls whether the entire hierarchy under this view will save its
5986     * state when a state saving traversal occurs from its parent.  The default
5987     * is true; if false, these views will not be saved unless
5988     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5989     *
5990     * @param enabled Set to false to <em>disable</em> state saving, or true
5991     * (the default) to allow it.
5992     *
5993     * @see #isSaveFromParentEnabled()
5994     * @see #setId(int)
5995     * @see #onSaveInstanceState()
5996     */
5997    public void setSaveFromParentEnabled(boolean enabled) {
5998        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5999    }
6000
6001
6002    /**
6003     * Returns whether this View is able to take focus.
6004     *
6005     * @return True if this view can take focus, or false otherwise.
6006     * @attr ref android.R.styleable#View_focusable
6007     */
6008    @ViewDebug.ExportedProperty(category = "focus")
6009    public final boolean isFocusable() {
6010        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6011    }
6012
6013    /**
6014     * When a view is focusable, it may not want to take focus when in touch mode.
6015     * For example, a button would like focus when the user is navigating via a D-pad
6016     * so that the user can click on it, but once the user starts touching the screen,
6017     * the button shouldn't take focus
6018     * @return Whether the view is focusable in touch mode.
6019     * @attr ref android.R.styleable#View_focusableInTouchMode
6020     */
6021    @ViewDebug.ExportedProperty
6022    public final boolean isFocusableInTouchMode() {
6023        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6024    }
6025
6026    /**
6027     * Find the nearest view in the specified direction that can take focus.
6028     * This does not actually give focus to that view.
6029     *
6030     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6031     *
6032     * @return The nearest focusable in the specified direction, or null if none
6033     *         can be found.
6034     */
6035    public View focusSearch(int direction) {
6036        if (mParent != null) {
6037            return mParent.focusSearch(this, direction);
6038        } else {
6039            return null;
6040        }
6041    }
6042
6043    /**
6044     * This method is the last chance for the focused view and its ancestors to
6045     * respond to an arrow key. This is called when the focused view did not
6046     * consume the key internally, nor could the view system find a new view in
6047     * the requested direction to give focus to.
6048     *
6049     * @param focused The currently focused view.
6050     * @param direction The direction focus wants to move. One of FOCUS_UP,
6051     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6052     * @return True if the this view consumed this unhandled move.
6053     */
6054    public boolean dispatchUnhandledMove(View focused, int direction) {
6055        return false;
6056    }
6057
6058    /**
6059     * If a user manually specified the next view id for a particular direction,
6060     * use the root to look up the view.
6061     * @param root The root view of the hierarchy containing this view.
6062     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6063     * or FOCUS_BACKWARD.
6064     * @return The user specified next view, or null if there is none.
6065     */
6066    View findUserSetNextFocus(View root, int direction) {
6067        switch (direction) {
6068            case FOCUS_LEFT:
6069                if (mNextFocusLeftId == View.NO_ID) return null;
6070                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6071            case FOCUS_RIGHT:
6072                if (mNextFocusRightId == View.NO_ID) return null;
6073                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6074            case FOCUS_UP:
6075                if (mNextFocusUpId == View.NO_ID) return null;
6076                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6077            case FOCUS_DOWN:
6078                if (mNextFocusDownId == View.NO_ID) return null;
6079                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6080            case FOCUS_FORWARD:
6081                if (mNextFocusForwardId == View.NO_ID) return null;
6082                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6083            case FOCUS_BACKWARD: {
6084                if (mID == View.NO_ID) return null;
6085                final int id = mID;
6086                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6087                    @Override
6088                    public boolean apply(View t) {
6089                        return t.mNextFocusForwardId == id;
6090                    }
6091                });
6092            }
6093        }
6094        return null;
6095    }
6096
6097    private View findViewInsideOutShouldExist(View root, final int childViewId) {
6098        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6099            @Override
6100            public boolean apply(View t) {
6101                return t.mID == childViewId;
6102            }
6103        });
6104
6105        if (result == null) {
6106            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
6107                    + "by user for id " + childViewId);
6108        }
6109        return result;
6110    }
6111
6112    /**
6113     * Find and return all focusable views that are descendants of this view,
6114     * possibly including this view if it is focusable itself.
6115     *
6116     * @param direction The direction of the focus
6117     * @return A list of focusable views
6118     */
6119    public ArrayList<View> getFocusables(int direction) {
6120        ArrayList<View> result = new ArrayList<View>(24);
6121        addFocusables(result, direction);
6122        return result;
6123    }
6124
6125    /**
6126     * Add any focusable views that are descendants of this view (possibly
6127     * including this view if it is focusable itself) to views.  If we are in touch mode,
6128     * only add views that are also focusable in touch mode.
6129     *
6130     * @param views Focusable views found so far
6131     * @param direction The direction of the focus
6132     */
6133    public void addFocusables(ArrayList<View> views, int direction) {
6134        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6135    }
6136
6137    /**
6138     * Adds any focusable views that are descendants of this view (possibly
6139     * including this view if it is focusable itself) to views. This method
6140     * adds all focusable views regardless if we are in touch mode or
6141     * only views focusable in touch mode if we are in touch mode or
6142     * only views that can take accessibility focus if accessibility is enabeld
6143     * depending on the focusable mode paramater.
6144     *
6145     * @param views Focusable views found so far or null if all we are interested is
6146     *        the number of focusables.
6147     * @param direction The direction of the focus.
6148     * @param focusableMode The type of focusables to be added.
6149     *
6150     * @see #FOCUSABLES_ALL
6151     * @see #FOCUSABLES_TOUCH_MODE
6152     */
6153    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6154        if (views == null) {
6155            return;
6156        }
6157        if (!isFocusable()) {
6158            return;
6159        }
6160        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6161                && isInTouchMode() && !isFocusableInTouchMode()) {
6162            return;
6163        }
6164        views.add(this);
6165    }
6166
6167    /**
6168     * Finds the Views that contain given text. The containment is case insensitive.
6169     * The search is performed by either the text that the View renders or the content
6170     * description that describes the view for accessibility purposes and the view does
6171     * not render or both. Clients can specify how the search is to be performed via
6172     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6173     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6174     *
6175     * @param outViews The output list of matching Views.
6176     * @param searched The text to match against.
6177     *
6178     * @see #FIND_VIEWS_WITH_TEXT
6179     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6180     * @see #setContentDescription(CharSequence)
6181     */
6182    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6183        if (getAccessibilityNodeProvider() != null) {
6184            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6185                outViews.add(this);
6186            }
6187        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6188                && (searched != null && searched.length() > 0)
6189                && (mContentDescription != null && mContentDescription.length() > 0)) {
6190            String searchedLowerCase = searched.toString().toLowerCase();
6191            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6192            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6193                outViews.add(this);
6194            }
6195        }
6196    }
6197
6198    /**
6199     * Find and return all touchable views that are descendants of this view,
6200     * possibly including this view if it is touchable itself.
6201     *
6202     * @return A list of touchable views
6203     */
6204    public ArrayList<View> getTouchables() {
6205        ArrayList<View> result = new ArrayList<View>();
6206        addTouchables(result);
6207        return result;
6208    }
6209
6210    /**
6211     * Add any touchable views that are descendants of this view (possibly
6212     * including this view if it is touchable itself) to views.
6213     *
6214     * @param views Touchable views found so far
6215     */
6216    public void addTouchables(ArrayList<View> views) {
6217        final int viewFlags = mViewFlags;
6218
6219        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6220                && (viewFlags & ENABLED_MASK) == ENABLED) {
6221            views.add(this);
6222        }
6223    }
6224
6225    /**
6226     * Returns whether this View is accessibility focused.
6227     *
6228     * @return True if this View is accessibility focused.
6229     */
6230    boolean isAccessibilityFocused() {
6231        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6232    }
6233
6234    /**
6235     * Call this to try to give accessibility focus to this view.
6236     *
6237     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6238     * returns false or the view is no visible or the view already has accessibility
6239     * focus.
6240     *
6241     * See also {@link #focusSearch(int)}, which is what you call to say that you
6242     * have focus, and you want your parent to look for the next one.
6243     *
6244     * @return Whether this view actually took accessibility focus.
6245     *
6246     * @hide
6247     */
6248    public boolean requestAccessibilityFocus() {
6249        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6250        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6251            return false;
6252        }
6253        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6254            return false;
6255        }
6256        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6257            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6258            ViewRootImpl viewRootImpl = getViewRootImpl();
6259            if (viewRootImpl != null) {
6260                viewRootImpl.setAccessibilityFocus(this, null);
6261            }
6262            if (mAttachInfo != null) {
6263                Rect rectangle = mAttachInfo.mTmpInvalRect;
6264                getDrawingRect(rectangle);
6265                requestRectangleOnScreen(rectangle);
6266            }
6267            invalidate();
6268            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6269            notifyAccessibilityStateChanged();
6270            return true;
6271        }
6272        return false;
6273    }
6274
6275    /**
6276     * Call this to try to clear accessibility focus of this view.
6277     *
6278     * See also {@link #focusSearch(int)}, which is what you call to say that you
6279     * have focus, and you want your parent to look for the next one.
6280     *
6281     * @hide
6282     */
6283    public void clearAccessibilityFocus() {
6284        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6285            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6286            invalidate();
6287            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6288            notifyAccessibilityStateChanged();
6289        }
6290        // Clear the global reference of accessibility focus if this
6291        // view or any of its descendants had accessibility focus.
6292        ViewRootImpl viewRootImpl = getViewRootImpl();
6293        if (viewRootImpl != null) {
6294            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6295            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6296                viewRootImpl.setAccessibilityFocus(null, null);
6297            }
6298        }
6299    }
6300
6301    private void sendAccessibilityHoverEvent(int eventType) {
6302        // Since we are not delivering to a client accessibility events from not
6303        // important views (unless the clinet request that) we need to fire the
6304        // event from the deepest view exposed to the client. As a consequence if
6305        // the user crosses a not exposed view the client will see enter and exit
6306        // of the exposed predecessor followed by and enter and exit of that same
6307        // predecessor when entering and exiting the not exposed descendant. This
6308        // is fine since the client has a clear idea which view is hovered at the
6309        // price of a couple more events being sent. This is a simple and
6310        // working solution.
6311        View source = this;
6312        while (true) {
6313            if (source.includeForAccessibility()) {
6314                source.sendAccessibilityEvent(eventType);
6315                return;
6316            }
6317            ViewParent parent = source.getParent();
6318            if (parent instanceof View) {
6319                source = (View) parent;
6320            } else {
6321                return;
6322            }
6323        }
6324    }
6325
6326    /**
6327     * Clears accessibility focus without calling any callback methods
6328     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6329     * is used for clearing accessibility focus when giving this focus to
6330     * another view.
6331     */
6332    void clearAccessibilityFocusNoCallbacks() {
6333        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6334            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6335            invalidate();
6336        }
6337    }
6338
6339    /**
6340     * Call this to try to give focus to a specific view or to one of its
6341     * descendants.
6342     *
6343     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6344     * false), or if it is focusable and it is not focusable in touch mode
6345     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6346     *
6347     * See also {@link #focusSearch(int)}, which is what you call to say that you
6348     * have focus, and you want your parent to look for the next one.
6349     *
6350     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6351     * {@link #FOCUS_DOWN} and <code>null</code>.
6352     *
6353     * @return Whether this view or one of its descendants actually took focus.
6354     */
6355    public final boolean requestFocus() {
6356        return requestFocus(View.FOCUS_DOWN);
6357    }
6358
6359    /**
6360     * Call this to try to give focus to a specific view or to one of its
6361     * descendants and give it a hint about what direction focus is heading.
6362     *
6363     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6364     * false), or if it is focusable and it is not focusable in touch mode
6365     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6366     *
6367     * See also {@link #focusSearch(int)}, which is what you call to say that you
6368     * have focus, and you want your parent to look for the next one.
6369     *
6370     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6371     * <code>null</code> set for the previously focused rectangle.
6372     *
6373     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6374     * @return Whether this view or one of its descendants actually took focus.
6375     */
6376    public final boolean requestFocus(int direction) {
6377        return requestFocus(direction, null);
6378    }
6379
6380    /**
6381     * Call this to try to give focus to a specific view or to one of its descendants
6382     * and give it hints about the direction and a specific rectangle that the focus
6383     * is coming from.  The rectangle can help give larger views a finer grained hint
6384     * about where focus is coming from, and therefore, where to show selection, or
6385     * forward focus change internally.
6386     *
6387     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6388     * false), or if it is focusable and it is not focusable in touch mode
6389     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6390     *
6391     * A View will not take focus if it is not visible.
6392     *
6393     * A View will not take focus if one of its parents has
6394     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6395     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6396     *
6397     * See also {@link #focusSearch(int)}, which is what you call to say that you
6398     * have focus, and you want your parent to look for the next one.
6399     *
6400     * You may wish to override this method if your custom {@link View} has an internal
6401     * {@link View} that it wishes to forward the request to.
6402     *
6403     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6404     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6405     *        to give a finer grained hint about where focus is coming from.  May be null
6406     *        if there is no hint.
6407     * @return Whether this view or one of its descendants actually took focus.
6408     */
6409    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6410        return requestFocusNoSearch(direction, previouslyFocusedRect);
6411    }
6412
6413    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6414        // need to be focusable
6415        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6416                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6417            return false;
6418        }
6419
6420        // need to be focusable in touch mode if in touch mode
6421        if (isInTouchMode() &&
6422            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6423               return false;
6424        }
6425
6426        // need to not have any parents blocking us
6427        if (hasAncestorThatBlocksDescendantFocus()) {
6428            return false;
6429        }
6430
6431        handleFocusGainInternal(direction, previouslyFocusedRect);
6432        return true;
6433    }
6434
6435    /**
6436     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6437     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6438     * touch mode to request focus when they are touched.
6439     *
6440     * @return Whether this view or one of its descendants actually took focus.
6441     *
6442     * @see #isInTouchMode()
6443     *
6444     */
6445    public final boolean requestFocusFromTouch() {
6446        // Leave touch mode if we need to
6447        if (isInTouchMode()) {
6448            ViewRootImpl viewRoot = getViewRootImpl();
6449            if (viewRoot != null) {
6450                viewRoot.ensureTouchMode(false);
6451            }
6452        }
6453        return requestFocus(View.FOCUS_DOWN);
6454    }
6455
6456    /**
6457     * @return Whether any ancestor of this view blocks descendant focus.
6458     */
6459    private boolean hasAncestorThatBlocksDescendantFocus() {
6460        ViewParent ancestor = mParent;
6461        while (ancestor instanceof ViewGroup) {
6462            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6463            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6464                return true;
6465            } else {
6466                ancestor = vgAncestor.getParent();
6467            }
6468        }
6469        return false;
6470    }
6471
6472    /**
6473     * Gets the mode for determining whether this View is important for accessibility
6474     * which is if it fires accessibility events and if it is reported to
6475     * accessibility services that query the screen.
6476     *
6477     * @return The mode for determining whether a View is important for accessibility.
6478     *
6479     * @attr ref android.R.styleable#View_importantForAccessibility
6480     *
6481     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6482     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6483     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6484     */
6485    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6486            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6487            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6488            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6489        })
6490    public int getImportantForAccessibility() {
6491        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6492                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6493    }
6494
6495    /**
6496     * Sets how to determine whether this view is important for accessibility
6497     * which is if it fires accessibility events and if it is reported to
6498     * accessibility services that query the screen.
6499     *
6500     * @param mode How to determine whether this view is important for accessibility.
6501     *
6502     * @attr ref android.R.styleable#View_importantForAccessibility
6503     *
6504     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6505     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6506     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6507     */
6508    public void setImportantForAccessibility(int mode) {
6509        if (mode != getImportantForAccessibility()) {
6510            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6511            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6512                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6513            notifyAccessibilityStateChanged();
6514        }
6515    }
6516
6517    /**
6518     * Gets whether this view should be exposed for accessibility.
6519     *
6520     * @return Whether the view is exposed for accessibility.
6521     *
6522     * @hide
6523     */
6524    public boolean isImportantForAccessibility() {
6525        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6526                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6527        switch (mode) {
6528            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6529                return true;
6530            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6531                return false;
6532            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6533                return isActionableForAccessibility() || hasListenersForAccessibility()
6534                        || getAccessibilityNodeProvider() != null;
6535            default:
6536                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6537                        + mode);
6538        }
6539    }
6540
6541    /**
6542     * Gets the parent for accessibility purposes. Note that the parent for
6543     * accessibility is not necessary the immediate parent. It is the first
6544     * predecessor that is important for accessibility.
6545     *
6546     * @return The parent for accessibility purposes.
6547     */
6548    public ViewParent getParentForAccessibility() {
6549        if (mParent instanceof View) {
6550            View parentView = (View) mParent;
6551            if (parentView.includeForAccessibility()) {
6552                return mParent;
6553            } else {
6554                return mParent.getParentForAccessibility();
6555            }
6556        }
6557        return null;
6558    }
6559
6560    /**
6561     * Adds the children of a given View for accessibility. Since some Views are
6562     * not important for accessibility the children for accessibility are not
6563     * necessarily direct children of the riew, rather they are the first level of
6564     * descendants important for accessibility.
6565     *
6566     * @param children The list of children for accessibility.
6567     */
6568    public void addChildrenForAccessibility(ArrayList<View> children) {
6569        if (includeForAccessibility()) {
6570            children.add(this);
6571        }
6572    }
6573
6574    /**
6575     * Whether to regard this view for accessibility. A view is regarded for
6576     * accessibility if it is important for accessibility or the querying
6577     * accessibility service has explicitly requested that view not
6578     * important for accessibility are regarded.
6579     *
6580     * @return Whether to regard the view for accessibility.
6581     *
6582     * @hide
6583     */
6584    public boolean includeForAccessibility() {
6585        if (mAttachInfo != null) {
6586            return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility();
6587        }
6588        return false;
6589    }
6590
6591    /**
6592     * Returns whether the View is considered actionable from
6593     * accessibility perspective. Such view are important for
6594     * accessiiblity.
6595     *
6596     * @return True if the view is actionable for accessibility.
6597     *
6598     * @hide
6599     */
6600    public boolean isActionableForAccessibility() {
6601        return (isClickable() || isLongClickable() || isFocusable());
6602    }
6603
6604    /**
6605     * Returns whether the View has registered callbacks wich makes it
6606     * important for accessiiblity.
6607     *
6608     * @return True if the view is actionable for accessibility.
6609     */
6610    private boolean hasListenersForAccessibility() {
6611        ListenerInfo info = getListenerInfo();
6612        return mTouchDelegate != null || info.mOnKeyListener != null
6613                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6614                || info.mOnHoverListener != null || info.mOnDragListener != null;
6615    }
6616
6617    /**
6618     * Notifies accessibility services that some view's important for
6619     * accessibility state has changed. Note that such notifications
6620     * are made at most once every
6621     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6622     * to avoid unnecessary load to the system. Also once a view has
6623     * made a notifucation this method is a NOP until the notification has
6624     * been sent to clients.
6625     *
6626     * @hide
6627     *
6628     * TODO: Makse sure this method is called for any view state change
6629     *       that is interesting for accessilility purposes.
6630     */
6631    public void notifyAccessibilityStateChanged() {
6632        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6633            return;
6634        }
6635        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) {
6636            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6637            if (mParent != null) {
6638                mParent.childAccessibilityStateChanged(this);
6639            }
6640        }
6641    }
6642
6643    /**
6644     * Reset the state indicating the this view has requested clients
6645     * interested in its accessiblity state to be notified.
6646     *
6647     * @hide
6648     */
6649    public void resetAccessibilityStateChanged() {
6650        mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6651    }
6652
6653    /**
6654     * Performs the specified accessibility action on the view. For
6655     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6656    * <p>
6657    * If an {@link AccessibilityDelegate} has been specified via calling
6658    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6659    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6660    * is responsible for handling this call.
6661    * </p>
6662     *
6663     * @param action The action to perform.
6664     * @param arguments Optional action arguments.
6665     * @return Whether the action was performed.
6666     */
6667    public boolean performAccessibilityAction(int action, Bundle arguments) {
6668      if (mAccessibilityDelegate != null) {
6669          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6670      } else {
6671          return performAccessibilityActionInternal(action, arguments);
6672      }
6673    }
6674
6675   /**
6676    * @see #performAccessibilityAction(int, Bundle)
6677    *
6678    * Note: Called from the default {@link AccessibilityDelegate}.
6679    */
6680    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6681        switch (action) {
6682            case AccessibilityNodeInfo.ACTION_CLICK: {
6683                if (isClickable()) {
6684                    return performClick();
6685                }
6686            } break;
6687            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6688                if (isLongClickable()) {
6689                    return performLongClick();
6690                }
6691            } break;
6692            case AccessibilityNodeInfo.ACTION_FOCUS: {
6693                if (!hasFocus()) {
6694                    // Get out of touch mode since accessibility
6695                    // wants to move focus around.
6696                    getViewRootImpl().ensureTouchMode(false);
6697                    return requestFocus();
6698                }
6699            } break;
6700            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6701                if (hasFocus()) {
6702                    clearFocus();
6703                    return !isFocused();
6704                }
6705            } break;
6706            case AccessibilityNodeInfo.ACTION_SELECT: {
6707                if (!isSelected()) {
6708                    setSelected(true);
6709                    return isSelected();
6710                }
6711            } break;
6712            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6713                if (isSelected()) {
6714                    setSelected(false);
6715                    return !isSelected();
6716                }
6717            } break;
6718            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6719                if (!isAccessibilityFocused()) {
6720                    return requestAccessibilityFocus();
6721                }
6722            } break;
6723            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6724                if (isAccessibilityFocused()) {
6725                    clearAccessibilityFocus();
6726                    return true;
6727                }
6728            } break;
6729            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6730                if (arguments != null) {
6731                    final int granularity = arguments.getInt(
6732                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6733                    return nextAtGranularity(granularity);
6734                }
6735            } break;
6736            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6737                if (arguments != null) {
6738                    final int granularity = arguments.getInt(
6739                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6740                    return previousAtGranularity(granularity);
6741                }
6742            } break;
6743        }
6744        return false;
6745    }
6746
6747    private boolean nextAtGranularity(int granularity) {
6748        CharSequence text = getIterableTextForAccessibility();
6749        if (text == null || text.length() == 0) {
6750            return false;
6751        }
6752        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6753        if (iterator == null) {
6754            return false;
6755        }
6756        final int current = getAccessibilityCursorPosition();
6757        final int[] range = iterator.following(current);
6758        if (range == null) {
6759            return false;
6760        }
6761        final int start = range[0];
6762        final int end = range[1];
6763        setAccessibilityCursorPosition(end);
6764        sendViewTextTraversedAtGranularityEvent(
6765                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6766                granularity, start, end);
6767        return true;
6768    }
6769
6770    private boolean previousAtGranularity(int granularity) {
6771        CharSequence text = getIterableTextForAccessibility();
6772        if (text == null || text.length() == 0) {
6773            return false;
6774        }
6775        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6776        if (iterator == null) {
6777            return false;
6778        }
6779        int current = getAccessibilityCursorPosition();
6780        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
6781            current = text.length();
6782        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6783            // When traversing by character we always put the cursor after the character
6784            // to ease edit and have to compensate before asking the for previous segment.
6785            current--;
6786        }
6787        final int[] range = iterator.preceding(current);
6788        if (range == null) {
6789            return false;
6790        }
6791        final int start = range[0];
6792        final int end = range[1];
6793        // Always put the cursor after the character to ease edit.
6794        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6795            setAccessibilityCursorPosition(end);
6796        } else {
6797            setAccessibilityCursorPosition(start);
6798        }
6799        sendViewTextTraversedAtGranularityEvent(
6800                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6801                granularity, start, end);
6802        return true;
6803    }
6804
6805    /**
6806     * Gets the text reported for accessibility purposes.
6807     *
6808     * @return The accessibility text.
6809     *
6810     * @hide
6811     */
6812    public CharSequence getIterableTextForAccessibility() {
6813        return getContentDescription();
6814    }
6815
6816    /**
6817     * @hide
6818     */
6819    public int getAccessibilityCursorPosition() {
6820        return mAccessibilityCursorPosition;
6821    }
6822
6823    /**
6824     * @hide
6825     */
6826    public void setAccessibilityCursorPosition(int position) {
6827        mAccessibilityCursorPosition = position;
6828    }
6829
6830    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6831            int fromIndex, int toIndex) {
6832        if (mParent == null) {
6833            return;
6834        }
6835        AccessibilityEvent event = AccessibilityEvent.obtain(
6836                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6837        onInitializeAccessibilityEvent(event);
6838        onPopulateAccessibilityEvent(event);
6839        event.setFromIndex(fromIndex);
6840        event.setToIndex(toIndex);
6841        event.setAction(action);
6842        event.setMovementGranularity(granularity);
6843        mParent.requestSendAccessibilityEvent(this, event);
6844    }
6845
6846    /**
6847     * @hide
6848     */
6849    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6850        switch (granularity) {
6851            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6852                CharSequence text = getIterableTextForAccessibility();
6853                if (text != null && text.length() > 0) {
6854                    CharacterTextSegmentIterator iterator =
6855                        CharacterTextSegmentIterator.getInstance(
6856                                mContext.getResources().getConfiguration().locale);
6857                    iterator.initialize(text.toString());
6858                    return iterator;
6859                }
6860            } break;
6861            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6862                CharSequence text = getIterableTextForAccessibility();
6863                if (text != null && text.length() > 0) {
6864                    WordTextSegmentIterator iterator =
6865                        WordTextSegmentIterator.getInstance(
6866                                mContext.getResources().getConfiguration().locale);
6867                    iterator.initialize(text.toString());
6868                    return iterator;
6869                }
6870            } break;
6871            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6872                CharSequence text = getIterableTextForAccessibility();
6873                if (text != null && text.length() > 0) {
6874                    ParagraphTextSegmentIterator iterator =
6875                        ParagraphTextSegmentIterator.getInstance();
6876                    iterator.initialize(text.toString());
6877                    return iterator;
6878                }
6879            } break;
6880        }
6881        return null;
6882    }
6883
6884    /**
6885     * @hide
6886     */
6887    public void dispatchStartTemporaryDetach() {
6888        clearAccessibilityFocus();
6889        clearDisplayList();
6890
6891        onStartTemporaryDetach();
6892    }
6893
6894    /**
6895     * This is called when a container is going to temporarily detach a child, with
6896     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6897     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6898     * {@link #onDetachedFromWindow()} when the container is done.
6899     */
6900    public void onStartTemporaryDetach() {
6901        removeUnsetPressCallback();
6902        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
6903    }
6904
6905    /**
6906     * @hide
6907     */
6908    public void dispatchFinishTemporaryDetach() {
6909        onFinishTemporaryDetach();
6910    }
6911
6912    /**
6913     * Called after {@link #onStartTemporaryDetach} when the container is done
6914     * changing the view.
6915     */
6916    public void onFinishTemporaryDetach() {
6917    }
6918
6919    /**
6920     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6921     * for this view's window.  Returns null if the view is not currently attached
6922     * to the window.  Normally you will not need to use this directly, but
6923     * just use the standard high-level event callbacks like
6924     * {@link #onKeyDown(int, KeyEvent)}.
6925     */
6926    public KeyEvent.DispatcherState getKeyDispatcherState() {
6927        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6928    }
6929
6930    /**
6931     * Dispatch a key event before it is processed by any input method
6932     * associated with the view hierarchy.  This can be used to intercept
6933     * key events in special situations before the IME consumes them; a
6934     * typical example would be handling the BACK key to update the application's
6935     * UI instead of allowing the IME to see it and close itself.
6936     *
6937     * @param event The key event to be dispatched.
6938     * @return True if the event was handled, false otherwise.
6939     */
6940    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6941        return onKeyPreIme(event.getKeyCode(), event);
6942    }
6943
6944    /**
6945     * Dispatch a key event to the next view on the focus path. This path runs
6946     * from the top of the view tree down to the currently focused view. If this
6947     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6948     * the next node down the focus path. This method also fires any key
6949     * listeners.
6950     *
6951     * @param event The key event to be dispatched.
6952     * @return True if the event was handled, false otherwise.
6953     */
6954    public boolean dispatchKeyEvent(KeyEvent event) {
6955        if (mInputEventConsistencyVerifier != null) {
6956            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6957        }
6958
6959        // Give any attached key listener a first crack at the event.
6960        //noinspection SimplifiableIfStatement
6961        ListenerInfo li = mListenerInfo;
6962        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6963                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6964            return true;
6965        }
6966
6967        if (event.dispatch(this, mAttachInfo != null
6968                ? mAttachInfo.mKeyDispatchState : null, this)) {
6969            return true;
6970        }
6971
6972        if (mInputEventConsistencyVerifier != null) {
6973            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6974        }
6975        return false;
6976    }
6977
6978    /**
6979     * Dispatches a key shortcut event.
6980     *
6981     * @param event The key event to be dispatched.
6982     * @return True if the event was handled by the view, false otherwise.
6983     */
6984    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6985        return onKeyShortcut(event.getKeyCode(), event);
6986    }
6987
6988    /**
6989     * Pass the touch screen motion event down to the target view, or this
6990     * view if it is the target.
6991     *
6992     * @param event The motion event to be dispatched.
6993     * @return True if the event was handled by the view, false otherwise.
6994     */
6995    public boolean dispatchTouchEvent(MotionEvent event) {
6996        if (mInputEventConsistencyVerifier != null) {
6997            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6998        }
6999
7000        if (onFilterTouchEventForSecurity(event)) {
7001            //noinspection SimplifiableIfStatement
7002            ListenerInfo li = mListenerInfo;
7003            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7004                    && li.mOnTouchListener.onTouch(this, event)) {
7005                return true;
7006            }
7007
7008            if (onTouchEvent(event)) {
7009                return true;
7010            }
7011        }
7012
7013        if (mInputEventConsistencyVerifier != null) {
7014            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7015        }
7016        return false;
7017    }
7018
7019    /**
7020     * Filter the touch event to apply security policies.
7021     *
7022     * @param event The motion event to be filtered.
7023     * @return True if the event should be dispatched, false if the event should be dropped.
7024     *
7025     * @see #getFilterTouchesWhenObscured
7026     */
7027    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7028        //noinspection RedundantIfStatement
7029        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7030                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7031            // Window is obscured, drop this touch.
7032            return false;
7033        }
7034        return true;
7035    }
7036
7037    /**
7038     * Pass a trackball motion event down to the focused view.
7039     *
7040     * @param event The motion event to be dispatched.
7041     * @return True if the event was handled by the view, false otherwise.
7042     */
7043    public boolean dispatchTrackballEvent(MotionEvent event) {
7044        if (mInputEventConsistencyVerifier != null) {
7045            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7046        }
7047
7048        return onTrackballEvent(event);
7049    }
7050
7051    /**
7052     * Dispatch a generic motion event.
7053     * <p>
7054     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7055     * are delivered to the view under the pointer.  All other generic motion events are
7056     * delivered to the focused view.  Hover events are handled specially and are delivered
7057     * to {@link #onHoverEvent(MotionEvent)}.
7058     * </p>
7059     *
7060     * @param event The motion event to be dispatched.
7061     * @return True if the event was handled by the view, false otherwise.
7062     */
7063    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7064        if (mInputEventConsistencyVerifier != null) {
7065            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7066        }
7067
7068        final int source = event.getSource();
7069        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7070            final int action = event.getAction();
7071            if (action == MotionEvent.ACTION_HOVER_ENTER
7072                    || action == MotionEvent.ACTION_HOVER_MOVE
7073                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7074                if (dispatchHoverEvent(event)) {
7075                    return true;
7076                }
7077            } else if (dispatchGenericPointerEvent(event)) {
7078                return true;
7079            }
7080        } else if (dispatchGenericFocusedEvent(event)) {
7081            return true;
7082        }
7083
7084        if (dispatchGenericMotionEventInternal(event)) {
7085            return true;
7086        }
7087
7088        if (mInputEventConsistencyVerifier != null) {
7089            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7090        }
7091        return false;
7092    }
7093
7094    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7095        //noinspection SimplifiableIfStatement
7096        ListenerInfo li = mListenerInfo;
7097        if (li != null && li.mOnGenericMotionListener != null
7098                && (mViewFlags & ENABLED_MASK) == ENABLED
7099                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7100            return true;
7101        }
7102
7103        if (onGenericMotionEvent(event)) {
7104            return true;
7105        }
7106
7107        if (mInputEventConsistencyVerifier != null) {
7108            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7109        }
7110        return false;
7111    }
7112
7113    /**
7114     * Dispatch a hover event.
7115     * <p>
7116     * Do not call this method directly.
7117     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7118     * </p>
7119     *
7120     * @param event The motion event to be dispatched.
7121     * @return True if the event was handled by the view, false otherwise.
7122     */
7123    protected boolean dispatchHoverEvent(MotionEvent event) {
7124        //noinspection SimplifiableIfStatement
7125        ListenerInfo li = mListenerInfo;
7126        if (li != null && li.mOnHoverListener != null
7127                && (mViewFlags & ENABLED_MASK) == ENABLED
7128                && li.mOnHoverListener.onHover(this, event)) {
7129            return true;
7130        }
7131
7132        return onHoverEvent(event);
7133    }
7134
7135    /**
7136     * Returns true if the view has a child to which it has recently sent
7137     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7138     * it does not have a hovered child, then it must be the innermost hovered view.
7139     * @hide
7140     */
7141    protected boolean hasHoveredChild() {
7142        return false;
7143    }
7144
7145    /**
7146     * Dispatch a generic motion event to the view under the first pointer.
7147     * <p>
7148     * Do not call this method directly.
7149     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7150     * </p>
7151     *
7152     * @param event The motion event to be dispatched.
7153     * @return True if the event was handled by the view, false otherwise.
7154     */
7155    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7156        return false;
7157    }
7158
7159    /**
7160     * Dispatch a generic motion event to the currently focused view.
7161     * <p>
7162     * Do not call this method directly.
7163     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7164     * </p>
7165     *
7166     * @param event The motion event to be dispatched.
7167     * @return True if the event was handled by the view, false otherwise.
7168     */
7169    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7170        return false;
7171    }
7172
7173    /**
7174     * Dispatch a pointer event.
7175     * <p>
7176     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7177     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7178     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7179     * and should not be expected to handle other pointing device features.
7180     * </p>
7181     *
7182     * @param event The motion event to be dispatched.
7183     * @return True if the event was handled by the view, false otherwise.
7184     * @hide
7185     */
7186    public final boolean dispatchPointerEvent(MotionEvent event) {
7187        if (event.isTouchEvent()) {
7188            return dispatchTouchEvent(event);
7189        } else {
7190            return dispatchGenericMotionEvent(event);
7191        }
7192    }
7193
7194    /**
7195     * Called when the window containing this view gains or loses window focus.
7196     * ViewGroups should override to route to their children.
7197     *
7198     * @param hasFocus True if the window containing this view now has focus,
7199     *        false otherwise.
7200     */
7201    public void dispatchWindowFocusChanged(boolean hasFocus) {
7202        onWindowFocusChanged(hasFocus);
7203    }
7204
7205    /**
7206     * Called when the window containing this view gains or loses focus.  Note
7207     * that this is separate from view focus: to receive key events, both
7208     * your view and its window must have focus.  If a window is displayed
7209     * on top of yours that takes input focus, then your own window will lose
7210     * focus but the view focus will remain unchanged.
7211     *
7212     * @param hasWindowFocus True if the window containing this view now has
7213     *        focus, false otherwise.
7214     */
7215    public void onWindowFocusChanged(boolean hasWindowFocus) {
7216        InputMethodManager imm = InputMethodManager.peekInstance();
7217        if (!hasWindowFocus) {
7218            if (isPressed()) {
7219                setPressed(false);
7220            }
7221            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7222                imm.focusOut(this);
7223            }
7224            removeLongPressCallback();
7225            removeTapCallback();
7226            onFocusLost();
7227        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7228            imm.focusIn(this);
7229        }
7230        refreshDrawableState();
7231    }
7232
7233    /**
7234     * Returns true if this view is in a window that currently has window focus.
7235     * Note that this is not the same as the view itself having focus.
7236     *
7237     * @return True if this view is in a window that currently has window focus.
7238     */
7239    public boolean hasWindowFocus() {
7240        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7241    }
7242
7243    /**
7244     * Dispatch a view visibility change down the view hierarchy.
7245     * ViewGroups should override to route to their children.
7246     * @param changedView The view whose visibility changed. Could be 'this' or
7247     * an ancestor view.
7248     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7249     * {@link #INVISIBLE} or {@link #GONE}.
7250     */
7251    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7252        onVisibilityChanged(changedView, visibility);
7253    }
7254
7255    /**
7256     * Called when the visibility of the view or an ancestor of the view is changed.
7257     * @param changedView The view whose visibility changed. Could be 'this' or
7258     * an ancestor view.
7259     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7260     * {@link #INVISIBLE} or {@link #GONE}.
7261     */
7262    protected void onVisibilityChanged(View changedView, int visibility) {
7263        if (visibility == VISIBLE) {
7264            if (mAttachInfo != null) {
7265                initialAwakenScrollBars();
7266            } else {
7267                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7268            }
7269        }
7270    }
7271
7272    /**
7273     * Dispatch a hint about whether this view is displayed. For instance, when
7274     * a View moves out of the screen, it might receives a display hint indicating
7275     * the view is not displayed. Applications should not <em>rely</em> on this hint
7276     * as there is no guarantee that they will receive one.
7277     *
7278     * @param hint A hint about whether or not this view is displayed:
7279     * {@link #VISIBLE} or {@link #INVISIBLE}.
7280     */
7281    public void dispatchDisplayHint(int hint) {
7282        onDisplayHint(hint);
7283    }
7284
7285    /**
7286     * Gives this view a hint about whether is displayed or not. For instance, when
7287     * a View moves out of the screen, it might receives a display hint indicating
7288     * the view is not displayed. Applications should not <em>rely</em> on this hint
7289     * as there is no guarantee that they will receive one.
7290     *
7291     * @param hint A hint about whether or not this view is displayed:
7292     * {@link #VISIBLE} or {@link #INVISIBLE}.
7293     */
7294    protected void onDisplayHint(int hint) {
7295    }
7296
7297    /**
7298     * Dispatch a window visibility change down the view hierarchy.
7299     * ViewGroups should override to route to their children.
7300     *
7301     * @param visibility The new visibility of the window.
7302     *
7303     * @see #onWindowVisibilityChanged(int)
7304     */
7305    public void dispatchWindowVisibilityChanged(int visibility) {
7306        onWindowVisibilityChanged(visibility);
7307    }
7308
7309    /**
7310     * Called when the window containing has change its visibility
7311     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7312     * that this tells you whether or not your window is being made visible
7313     * to the window manager; this does <em>not</em> tell you whether or not
7314     * your window is obscured by other windows on the screen, even if it
7315     * is itself visible.
7316     *
7317     * @param visibility The new visibility of the window.
7318     */
7319    protected void onWindowVisibilityChanged(int visibility) {
7320        if (visibility == VISIBLE) {
7321            initialAwakenScrollBars();
7322        }
7323    }
7324
7325    /**
7326     * Returns the current visibility of the window this view is attached to
7327     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7328     *
7329     * @return Returns the current visibility of the view's window.
7330     */
7331    public int getWindowVisibility() {
7332        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7333    }
7334
7335    /**
7336     * Retrieve the overall visible display size in which the window this view is
7337     * attached to has been positioned in.  This takes into account screen
7338     * decorations above the window, for both cases where the window itself
7339     * is being position inside of them or the window is being placed under
7340     * then and covered insets are used for the window to position its content
7341     * inside.  In effect, this tells you the available area where content can
7342     * be placed and remain visible to users.
7343     *
7344     * <p>This function requires an IPC back to the window manager to retrieve
7345     * the requested information, so should not be used in performance critical
7346     * code like drawing.
7347     *
7348     * @param outRect Filled in with the visible display frame.  If the view
7349     * is not attached to a window, this is simply the raw display size.
7350     */
7351    public void getWindowVisibleDisplayFrame(Rect outRect) {
7352        if (mAttachInfo != null) {
7353            try {
7354                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7355            } catch (RemoteException e) {
7356                return;
7357            }
7358            // XXX This is really broken, and probably all needs to be done
7359            // in the window manager, and we need to know more about whether
7360            // we want the area behind or in front of the IME.
7361            final Rect insets = mAttachInfo.mVisibleInsets;
7362            outRect.left += insets.left;
7363            outRect.top += insets.top;
7364            outRect.right -= insets.right;
7365            outRect.bottom -= insets.bottom;
7366            return;
7367        }
7368        // The view is not attached to a display so we don't have a context.
7369        // Make a best guess about the display size.
7370        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7371        d.getRectSize(outRect);
7372    }
7373
7374    /**
7375     * Dispatch a notification about a resource configuration change down
7376     * the view hierarchy.
7377     * ViewGroups should override to route to their children.
7378     *
7379     * @param newConfig The new resource configuration.
7380     *
7381     * @see #onConfigurationChanged(android.content.res.Configuration)
7382     */
7383    public void dispatchConfigurationChanged(Configuration newConfig) {
7384        onConfigurationChanged(newConfig);
7385    }
7386
7387    /**
7388     * Called when the current configuration of the resources being used
7389     * by the application have changed.  You can use this to decide when
7390     * to reload resources that can changed based on orientation and other
7391     * configuration characterstics.  You only need to use this if you are
7392     * not relying on the normal {@link android.app.Activity} mechanism of
7393     * recreating the activity instance upon a configuration change.
7394     *
7395     * @param newConfig The new resource configuration.
7396     */
7397    protected void onConfigurationChanged(Configuration newConfig) {
7398    }
7399
7400    /**
7401     * Private function to aggregate all per-view attributes in to the view
7402     * root.
7403     */
7404    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7405        performCollectViewAttributes(attachInfo, visibility);
7406    }
7407
7408    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7409        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7410            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7411                attachInfo.mKeepScreenOn = true;
7412            }
7413            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7414            ListenerInfo li = mListenerInfo;
7415            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7416                attachInfo.mHasSystemUiListeners = true;
7417            }
7418        }
7419    }
7420
7421    void needGlobalAttributesUpdate(boolean force) {
7422        final AttachInfo ai = mAttachInfo;
7423        if (ai != null) {
7424            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7425                    || ai.mHasSystemUiListeners) {
7426                ai.mRecomputeGlobalAttributes = true;
7427            }
7428        }
7429    }
7430
7431    /**
7432     * Returns whether the device is currently in touch mode.  Touch mode is entered
7433     * once the user begins interacting with the device by touch, and affects various
7434     * things like whether focus is always visible to the user.
7435     *
7436     * @return Whether the device is in touch mode.
7437     */
7438    @ViewDebug.ExportedProperty
7439    public boolean isInTouchMode() {
7440        if (mAttachInfo != null) {
7441            return mAttachInfo.mInTouchMode;
7442        } else {
7443            return ViewRootImpl.isInTouchMode();
7444        }
7445    }
7446
7447    /**
7448     * Returns the context the view is running in, through which it can
7449     * access the current theme, resources, etc.
7450     *
7451     * @return The view's Context.
7452     */
7453    @ViewDebug.CapturedViewProperty
7454    public final Context getContext() {
7455        return mContext;
7456    }
7457
7458    /**
7459     * Handle a key event before it is processed by any input method
7460     * associated with the view hierarchy.  This can be used to intercept
7461     * key events in special situations before the IME consumes them; a
7462     * typical example would be handling the BACK key to update the application's
7463     * UI instead of allowing the IME to see it and close itself.
7464     *
7465     * @param keyCode The value in event.getKeyCode().
7466     * @param event Description of the key event.
7467     * @return If you handled the event, return true. If you want to allow the
7468     *         event to be handled by the next receiver, return false.
7469     */
7470    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7471        return false;
7472    }
7473
7474    /**
7475     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7476     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7477     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7478     * is released, if the view is enabled and clickable.
7479     *
7480     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7481     * although some may elect to do so in some situations. Do not rely on this to
7482     * catch software key presses.
7483     *
7484     * @param keyCode A key code that represents the button pressed, from
7485     *                {@link android.view.KeyEvent}.
7486     * @param event   The KeyEvent object that defines the button action.
7487     */
7488    public boolean onKeyDown(int keyCode, KeyEvent event) {
7489        boolean result = false;
7490
7491        switch (keyCode) {
7492            case KeyEvent.KEYCODE_DPAD_CENTER:
7493            case KeyEvent.KEYCODE_ENTER: {
7494                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7495                    return true;
7496                }
7497                // Long clickable items don't necessarily have to be clickable
7498                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7499                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7500                        (event.getRepeatCount() == 0)) {
7501                    setPressed(true);
7502                    checkForLongClick(0);
7503                    return true;
7504                }
7505                break;
7506            }
7507        }
7508        return result;
7509    }
7510
7511    /**
7512     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7513     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7514     * the event).
7515     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7516     * although some may elect to do so in some situations. Do not rely on this to
7517     * catch software key presses.
7518     */
7519    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7520        return false;
7521    }
7522
7523    /**
7524     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7525     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7526     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7527     * {@link KeyEvent#KEYCODE_ENTER} is released.
7528     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7529     * although some may elect to do so in some situations. Do not rely on this to
7530     * catch software key presses.
7531     *
7532     * @param keyCode A key code that represents the button pressed, from
7533     *                {@link android.view.KeyEvent}.
7534     * @param event   The KeyEvent object that defines the button action.
7535     */
7536    public boolean onKeyUp(int keyCode, KeyEvent event) {
7537        boolean result = false;
7538
7539        switch (keyCode) {
7540            case KeyEvent.KEYCODE_DPAD_CENTER:
7541            case KeyEvent.KEYCODE_ENTER: {
7542                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7543                    return true;
7544                }
7545                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7546                    setPressed(false);
7547
7548                    if (!mHasPerformedLongPress) {
7549                        // This is a tap, so remove the longpress check
7550                        removeLongPressCallback();
7551
7552                        result = performClick();
7553                    }
7554                }
7555                break;
7556            }
7557        }
7558        return result;
7559    }
7560
7561    /**
7562     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7563     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7564     * the event).
7565     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7566     * although some may elect to do so in some situations. Do not rely on this to
7567     * catch software key presses.
7568     *
7569     * @param keyCode     A key code that represents the button pressed, from
7570     *                    {@link android.view.KeyEvent}.
7571     * @param repeatCount The number of times the action was made.
7572     * @param event       The KeyEvent object that defines the button action.
7573     */
7574    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7575        return false;
7576    }
7577
7578    /**
7579     * Called on the focused view when a key shortcut event is not handled.
7580     * Override this method to implement local key shortcuts for the View.
7581     * Key shortcuts can also be implemented by setting the
7582     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7583     *
7584     * @param keyCode The value in event.getKeyCode().
7585     * @param event Description of the key event.
7586     * @return If you handled the event, return true. If you want to allow the
7587     *         event to be handled by the next receiver, return false.
7588     */
7589    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7590        return false;
7591    }
7592
7593    /**
7594     * Check whether the called view is a text editor, in which case it
7595     * would make sense to automatically display a soft input window for
7596     * it.  Subclasses should override this if they implement
7597     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7598     * a call on that method would return a non-null InputConnection, and
7599     * they are really a first-class editor that the user would normally
7600     * start typing on when the go into a window containing your view.
7601     *
7602     * <p>The default implementation always returns false.  This does
7603     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7604     * will not be called or the user can not otherwise perform edits on your
7605     * view; it is just a hint to the system that this is not the primary
7606     * purpose of this view.
7607     *
7608     * @return Returns true if this view is a text editor, else false.
7609     */
7610    public boolean onCheckIsTextEditor() {
7611        return false;
7612    }
7613
7614    /**
7615     * Create a new InputConnection for an InputMethod to interact
7616     * with the view.  The default implementation returns null, since it doesn't
7617     * support input methods.  You can override this to implement such support.
7618     * This is only needed for views that take focus and text input.
7619     *
7620     * <p>When implementing this, you probably also want to implement
7621     * {@link #onCheckIsTextEditor()} to indicate you will return a
7622     * non-null InputConnection.
7623     *
7624     * @param outAttrs Fill in with attribute information about the connection.
7625     */
7626    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7627        return null;
7628    }
7629
7630    /**
7631     * Called by the {@link android.view.inputmethod.InputMethodManager}
7632     * when a view who is not the current
7633     * input connection target is trying to make a call on the manager.  The
7634     * default implementation returns false; you can override this to return
7635     * true for certain views if you are performing InputConnection proxying
7636     * to them.
7637     * @param view The View that is making the InputMethodManager call.
7638     * @return Return true to allow the call, false to reject.
7639     */
7640    public boolean checkInputConnectionProxy(View view) {
7641        return false;
7642    }
7643
7644    /**
7645     * Show the context menu for this view. It is not safe to hold on to the
7646     * menu after returning from this method.
7647     *
7648     * You should normally not overload this method. Overload
7649     * {@link #onCreateContextMenu(ContextMenu)} or define an
7650     * {@link OnCreateContextMenuListener} to add items to the context menu.
7651     *
7652     * @param menu The context menu to populate
7653     */
7654    public void createContextMenu(ContextMenu menu) {
7655        ContextMenuInfo menuInfo = getContextMenuInfo();
7656
7657        // Sets the current menu info so all items added to menu will have
7658        // my extra info set.
7659        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7660
7661        onCreateContextMenu(menu);
7662        ListenerInfo li = mListenerInfo;
7663        if (li != null && li.mOnCreateContextMenuListener != null) {
7664            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7665        }
7666
7667        // Clear the extra information so subsequent items that aren't mine don't
7668        // have my extra info.
7669        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7670
7671        if (mParent != null) {
7672            mParent.createContextMenu(menu);
7673        }
7674    }
7675
7676    /**
7677     * Views should implement this if they have extra information to associate
7678     * with the context menu. The return result is supplied as a parameter to
7679     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7680     * callback.
7681     *
7682     * @return Extra information about the item for which the context menu
7683     *         should be shown. This information will vary across different
7684     *         subclasses of View.
7685     */
7686    protected ContextMenuInfo getContextMenuInfo() {
7687        return null;
7688    }
7689
7690    /**
7691     * Views should implement this if the view itself is going to add items to
7692     * the context menu.
7693     *
7694     * @param menu the context menu to populate
7695     */
7696    protected void onCreateContextMenu(ContextMenu menu) {
7697    }
7698
7699    /**
7700     * Implement this method to handle trackball motion events.  The
7701     * <em>relative</em> movement of the trackball since the last event
7702     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7703     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7704     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7705     * they will often be fractional values, representing the more fine-grained
7706     * movement information available from a trackball).
7707     *
7708     * @param event The motion event.
7709     * @return True if the event was handled, false otherwise.
7710     */
7711    public boolean onTrackballEvent(MotionEvent event) {
7712        return false;
7713    }
7714
7715    /**
7716     * Implement this method to handle generic motion events.
7717     * <p>
7718     * Generic motion events describe joystick movements, mouse hovers, track pad
7719     * touches, scroll wheel movements and other input events.  The
7720     * {@link MotionEvent#getSource() source} of the motion event specifies
7721     * the class of input that was received.  Implementations of this method
7722     * must examine the bits in the source before processing the event.
7723     * The following code example shows how this is done.
7724     * </p><p>
7725     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7726     * are delivered to the view under the pointer.  All other generic motion events are
7727     * delivered to the focused view.
7728     * </p>
7729     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7730     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7731     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7732     *             // process the joystick movement...
7733     *             return true;
7734     *         }
7735     *     }
7736     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7737     *         switch (event.getAction()) {
7738     *             case MotionEvent.ACTION_HOVER_MOVE:
7739     *                 // process the mouse hover movement...
7740     *                 return true;
7741     *             case MotionEvent.ACTION_SCROLL:
7742     *                 // process the scroll wheel movement...
7743     *                 return true;
7744     *         }
7745     *     }
7746     *     return super.onGenericMotionEvent(event);
7747     * }</pre>
7748     *
7749     * @param event The generic motion event being processed.
7750     * @return True if the event was handled, false otherwise.
7751     */
7752    public boolean onGenericMotionEvent(MotionEvent event) {
7753        return false;
7754    }
7755
7756    /**
7757     * Implement this method to handle hover events.
7758     * <p>
7759     * This method is called whenever a pointer is hovering into, over, or out of the
7760     * bounds of a view and the view is not currently being touched.
7761     * Hover events are represented as pointer events with action
7762     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7763     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7764     * </p>
7765     * <ul>
7766     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7767     * when the pointer enters the bounds of the view.</li>
7768     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7769     * when the pointer has already entered the bounds of the view and has moved.</li>
7770     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7771     * when the pointer has exited the bounds of the view or when the pointer is
7772     * about to go down due to a button click, tap, or similar user action that
7773     * causes the view to be touched.</li>
7774     * </ul>
7775     * <p>
7776     * The view should implement this method to return true to indicate that it is
7777     * handling the hover event, such as by changing its drawable state.
7778     * </p><p>
7779     * The default implementation calls {@link #setHovered} to update the hovered state
7780     * of the view when a hover enter or hover exit event is received, if the view
7781     * is enabled and is clickable.  The default implementation also sends hover
7782     * accessibility events.
7783     * </p>
7784     *
7785     * @param event The motion event that describes the hover.
7786     * @return True if the view handled the hover event.
7787     *
7788     * @see #isHovered
7789     * @see #setHovered
7790     * @see #onHoverChanged
7791     */
7792    public boolean onHoverEvent(MotionEvent event) {
7793        // The root view may receive hover (or touch) events that are outside the bounds of
7794        // the window.  This code ensures that we only send accessibility events for
7795        // hovers that are actually within the bounds of the root view.
7796        final int action = event.getActionMasked();
7797        if (!mSendingHoverAccessibilityEvents) {
7798            if ((action == MotionEvent.ACTION_HOVER_ENTER
7799                    || action == MotionEvent.ACTION_HOVER_MOVE)
7800                    && !hasHoveredChild()
7801                    && pointInView(event.getX(), event.getY())) {
7802                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7803                mSendingHoverAccessibilityEvents = true;
7804            }
7805        } else {
7806            if (action == MotionEvent.ACTION_HOVER_EXIT
7807                    || (action == MotionEvent.ACTION_MOVE
7808                            && !pointInView(event.getX(), event.getY()))) {
7809                mSendingHoverAccessibilityEvents = false;
7810                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7811                // If the window does not have input focus we take away accessibility
7812                // focus as soon as the user stop hovering over the view.
7813                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7814                    getViewRootImpl().setAccessibilityFocus(null, null);
7815                }
7816            }
7817        }
7818
7819        if (isHoverable()) {
7820            switch (action) {
7821                case MotionEvent.ACTION_HOVER_ENTER:
7822                    setHovered(true);
7823                    break;
7824                case MotionEvent.ACTION_HOVER_EXIT:
7825                    setHovered(false);
7826                    break;
7827            }
7828
7829            // Dispatch the event to onGenericMotionEvent before returning true.
7830            // This is to provide compatibility with existing applications that
7831            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7832            // break because of the new default handling for hoverable views
7833            // in onHoverEvent.
7834            // Note that onGenericMotionEvent will be called by default when
7835            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7836            dispatchGenericMotionEventInternal(event);
7837            return true;
7838        }
7839
7840        return false;
7841    }
7842
7843    /**
7844     * Returns true if the view should handle {@link #onHoverEvent}
7845     * by calling {@link #setHovered} to change its hovered state.
7846     *
7847     * @return True if the view is hoverable.
7848     */
7849    private boolean isHoverable() {
7850        final int viewFlags = mViewFlags;
7851        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7852            return false;
7853        }
7854
7855        return (viewFlags & CLICKABLE) == CLICKABLE
7856                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7857    }
7858
7859    /**
7860     * Returns true if the view is currently hovered.
7861     *
7862     * @return True if the view is currently hovered.
7863     *
7864     * @see #setHovered
7865     * @see #onHoverChanged
7866     */
7867    @ViewDebug.ExportedProperty
7868    public boolean isHovered() {
7869        return (mPrivateFlags & PFLAG_HOVERED) != 0;
7870    }
7871
7872    /**
7873     * Sets whether the view is currently hovered.
7874     * <p>
7875     * Calling this method also changes the drawable state of the view.  This
7876     * enables the view to react to hover by using different drawable resources
7877     * to change its appearance.
7878     * </p><p>
7879     * The {@link #onHoverChanged} method is called when the hovered state changes.
7880     * </p>
7881     *
7882     * @param hovered True if the view is hovered.
7883     *
7884     * @see #isHovered
7885     * @see #onHoverChanged
7886     */
7887    public void setHovered(boolean hovered) {
7888        if (hovered) {
7889            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
7890                mPrivateFlags |= PFLAG_HOVERED;
7891                refreshDrawableState();
7892                onHoverChanged(true);
7893            }
7894        } else {
7895            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
7896                mPrivateFlags &= ~PFLAG_HOVERED;
7897                refreshDrawableState();
7898                onHoverChanged(false);
7899            }
7900        }
7901    }
7902
7903    /**
7904     * Implement this method to handle hover state changes.
7905     * <p>
7906     * This method is called whenever the hover state changes as a result of a
7907     * call to {@link #setHovered}.
7908     * </p>
7909     *
7910     * @param hovered The current hover state, as returned by {@link #isHovered}.
7911     *
7912     * @see #isHovered
7913     * @see #setHovered
7914     */
7915    public void onHoverChanged(boolean hovered) {
7916    }
7917
7918    /**
7919     * Implement this method to handle touch screen motion events.
7920     *
7921     * @param event The motion event.
7922     * @return True if the event was handled, false otherwise.
7923     */
7924    public boolean onTouchEvent(MotionEvent event) {
7925        final int viewFlags = mViewFlags;
7926
7927        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7928            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
7929                setPressed(false);
7930            }
7931            // A disabled view that is clickable still consumes the touch
7932            // events, it just doesn't respond to them.
7933            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7934                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7935        }
7936
7937        if (mTouchDelegate != null) {
7938            if (mTouchDelegate.onTouchEvent(event)) {
7939                return true;
7940            }
7941        }
7942
7943        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7944                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7945            switch (event.getAction()) {
7946                case MotionEvent.ACTION_UP:
7947                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
7948                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
7949                        // take focus if we don't have it already and we should in
7950                        // touch mode.
7951                        boolean focusTaken = false;
7952                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7953                            focusTaken = requestFocus();
7954                        }
7955
7956                        if (prepressed) {
7957                            // The button is being released before we actually
7958                            // showed it as pressed.  Make it show the pressed
7959                            // state now (before scheduling the click) to ensure
7960                            // the user sees it.
7961                            setPressed(true);
7962                       }
7963
7964                        if (!mHasPerformedLongPress) {
7965                            // This is a tap, so remove the longpress check
7966                            removeLongPressCallback();
7967
7968                            // Only perform take click actions if we were in the pressed state
7969                            if (!focusTaken) {
7970                                // Use a Runnable and post this rather than calling
7971                                // performClick directly. This lets other visual state
7972                                // of the view update before click actions start.
7973                                if (mPerformClick == null) {
7974                                    mPerformClick = new PerformClick();
7975                                }
7976                                if (!post(mPerformClick)) {
7977                                    performClick();
7978                                }
7979                            }
7980                        }
7981
7982                        if (mUnsetPressedState == null) {
7983                            mUnsetPressedState = new UnsetPressedState();
7984                        }
7985
7986                        if (prepressed) {
7987                            postDelayed(mUnsetPressedState,
7988                                    ViewConfiguration.getPressedStateDuration());
7989                        } else if (!post(mUnsetPressedState)) {
7990                            // If the post failed, unpress right now
7991                            mUnsetPressedState.run();
7992                        }
7993                        removeTapCallback();
7994                    }
7995                    break;
7996
7997                case MotionEvent.ACTION_DOWN:
7998                    mHasPerformedLongPress = false;
7999
8000                    if (performButtonActionOnTouchDown(event)) {
8001                        break;
8002                    }
8003
8004                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8005                    boolean isInScrollingContainer = isInScrollingContainer();
8006
8007                    // For views inside a scrolling container, delay the pressed feedback for
8008                    // a short period in case this is a scroll.
8009                    if (isInScrollingContainer) {
8010                        mPrivateFlags |= PFLAG_PREPRESSED;
8011                        if (mPendingCheckForTap == null) {
8012                            mPendingCheckForTap = new CheckForTap();
8013                        }
8014                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8015                    } else {
8016                        // Not inside a scrolling container, so show the feedback right away
8017                        setPressed(true);
8018                        checkForLongClick(0);
8019                    }
8020                    break;
8021
8022                case MotionEvent.ACTION_CANCEL:
8023                    setPressed(false);
8024                    removeTapCallback();
8025                    break;
8026
8027                case MotionEvent.ACTION_MOVE:
8028                    final int x = (int) event.getX();
8029                    final int y = (int) event.getY();
8030
8031                    // Be lenient about moving outside of buttons
8032                    if (!pointInView(x, y, mTouchSlop)) {
8033                        // Outside button
8034                        removeTapCallback();
8035                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8036                            // Remove any future long press/tap checks
8037                            removeLongPressCallback();
8038
8039                            setPressed(false);
8040                        }
8041                    }
8042                    break;
8043            }
8044            return true;
8045        }
8046
8047        return false;
8048    }
8049
8050    /**
8051     * @hide
8052     */
8053    public boolean isInScrollingContainer() {
8054        ViewParent p = getParent();
8055        while (p != null && p instanceof ViewGroup) {
8056            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8057                return true;
8058            }
8059            p = p.getParent();
8060        }
8061        return false;
8062    }
8063
8064    /**
8065     * Remove the longpress detection timer.
8066     */
8067    private void removeLongPressCallback() {
8068        if (mPendingCheckForLongPress != null) {
8069          removeCallbacks(mPendingCheckForLongPress);
8070        }
8071    }
8072
8073    /**
8074     * Remove the pending click action
8075     */
8076    private void removePerformClickCallback() {
8077        if (mPerformClick != null) {
8078            removeCallbacks(mPerformClick);
8079        }
8080    }
8081
8082    /**
8083     * Remove the prepress detection timer.
8084     */
8085    private void removeUnsetPressCallback() {
8086        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8087            setPressed(false);
8088            removeCallbacks(mUnsetPressedState);
8089        }
8090    }
8091
8092    /**
8093     * Remove the tap detection timer.
8094     */
8095    private void removeTapCallback() {
8096        if (mPendingCheckForTap != null) {
8097            mPrivateFlags &= ~PFLAG_PREPRESSED;
8098            removeCallbacks(mPendingCheckForTap);
8099        }
8100    }
8101
8102    /**
8103     * Cancels a pending long press.  Your subclass can use this if you
8104     * want the context menu to come up if the user presses and holds
8105     * at the same place, but you don't want it to come up if they press
8106     * and then move around enough to cause scrolling.
8107     */
8108    public void cancelLongPress() {
8109        removeLongPressCallback();
8110
8111        /*
8112         * The prepressed state handled by the tap callback is a display
8113         * construct, but the tap callback will post a long press callback
8114         * less its own timeout. Remove it here.
8115         */
8116        removeTapCallback();
8117    }
8118
8119    /**
8120     * Remove the pending callback for sending a
8121     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8122     */
8123    private void removeSendViewScrolledAccessibilityEventCallback() {
8124        if (mSendViewScrolledAccessibilityEvent != null) {
8125            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8126            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8127        }
8128    }
8129
8130    /**
8131     * Sets the TouchDelegate for this View.
8132     */
8133    public void setTouchDelegate(TouchDelegate delegate) {
8134        mTouchDelegate = delegate;
8135    }
8136
8137    /**
8138     * Gets the TouchDelegate for this View.
8139     */
8140    public TouchDelegate getTouchDelegate() {
8141        return mTouchDelegate;
8142    }
8143
8144    /**
8145     * Set flags controlling behavior of this view.
8146     *
8147     * @param flags Constant indicating the value which should be set
8148     * @param mask Constant indicating the bit range that should be changed
8149     */
8150    void setFlags(int flags, int mask) {
8151        int old = mViewFlags;
8152        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8153
8154        int changed = mViewFlags ^ old;
8155        if (changed == 0) {
8156            return;
8157        }
8158        int privateFlags = mPrivateFlags;
8159
8160        /* Check if the FOCUSABLE bit has changed */
8161        if (((changed & FOCUSABLE_MASK) != 0) &&
8162                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8163            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8164                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8165                /* Give up focus if we are no longer focusable */
8166                clearFocus();
8167            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8168                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8169                /*
8170                 * Tell the view system that we are now available to take focus
8171                 * if no one else already has it.
8172                 */
8173                if (mParent != null) mParent.focusableViewAvailable(this);
8174            }
8175            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8176                notifyAccessibilityStateChanged();
8177            }
8178        }
8179
8180        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8181            if ((changed & VISIBILITY_MASK) != 0) {
8182                /*
8183                 * If this view is becoming visible, invalidate it in case it changed while
8184                 * it was not visible. Marking it drawn ensures that the invalidation will
8185                 * go through.
8186                 */
8187                mPrivateFlags |= PFLAG_DRAWN;
8188                invalidate(true);
8189
8190                needGlobalAttributesUpdate(true);
8191
8192                // a view becoming visible is worth notifying the parent
8193                // about in case nothing has focus.  even if this specific view
8194                // isn't focusable, it may contain something that is, so let
8195                // the root view try to give this focus if nothing else does.
8196                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8197                    mParent.focusableViewAvailable(this);
8198                }
8199            }
8200        }
8201
8202        /* Check if the GONE bit has changed */
8203        if ((changed & GONE) != 0) {
8204            needGlobalAttributesUpdate(false);
8205            requestLayout();
8206
8207            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8208                if (hasFocus()) clearFocus();
8209                clearAccessibilityFocus();
8210                destroyDrawingCache();
8211                if (mParent instanceof View) {
8212                    // GONE views noop invalidation, so invalidate the parent
8213                    ((View) mParent).invalidate(true);
8214                }
8215                // Mark the view drawn to ensure that it gets invalidated properly the next
8216                // time it is visible and gets invalidated
8217                mPrivateFlags |= PFLAG_DRAWN;
8218            }
8219            if (mAttachInfo != null) {
8220                mAttachInfo.mViewVisibilityChanged = true;
8221            }
8222        }
8223
8224        /* Check if the VISIBLE bit has changed */
8225        if ((changed & INVISIBLE) != 0) {
8226            needGlobalAttributesUpdate(false);
8227            /*
8228             * If this view is becoming invisible, set the DRAWN flag so that
8229             * the next invalidate() will not be skipped.
8230             */
8231            mPrivateFlags |= PFLAG_DRAWN;
8232
8233            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8234                // root view becoming invisible shouldn't clear focus and accessibility focus
8235                if (getRootView() != this) {
8236                    clearFocus();
8237                    clearAccessibilityFocus();
8238                }
8239            }
8240            if (mAttachInfo != null) {
8241                mAttachInfo.mViewVisibilityChanged = true;
8242            }
8243        }
8244
8245        if ((changed & VISIBILITY_MASK) != 0) {
8246            if (mParent instanceof ViewGroup) {
8247                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8248                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8249                ((View) mParent).invalidate(true);
8250            } else if (mParent != null) {
8251                mParent.invalidateChild(this, null);
8252            }
8253            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8254        }
8255
8256        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8257            destroyDrawingCache();
8258        }
8259
8260        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8261            destroyDrawingCache();
8262            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8263            invalidateParentCaches();
8264        }
8265
8266        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8267            destroyDrawingCache();
8268            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8269        }
8270
8271        if ((changed & DRAW_MASK) != 0) {
8272            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8273                if (mBackground != null) {
8274                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8275                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8276                } else {
8277                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8278                }
8279            } else {
8280                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8281            }
8282            requestLayout();
8283            invalidate(true);
8284        }
8285
8286        if ((changed & KEEP_SCREEN_ON) != 0) {
8287            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8288                mParent.recomputeViewAttributes(this);
8289            }
8290        }
8291
8292        if (AccessibilityManager.getInstance(mContext).isEnabled()
8293                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8294                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8295            notifyAccessibilityStateChanged();
8296        }
8297    }
8298
8299    /**
8300     * Change the view's z order in the tree, so it's on top of other sibling
8301     * views
8302     */
8303    public void bringToFront() {
8304        if (mParent != null) {
8305            mParent.bringChildToFront(this);
8306        }
8307    }
8308
8309    /**
8310     * This is called in response to an internal scroll in this view (i.e., the
8311     * view scrolled its own contents). This is typically as a result of
8312     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8313     * called.
8314     *
8315     * @param l Current horizontal scroll origin.
8316     * @param t Current vertical scroll origin.
8317     * @param oldl Previous horizontal scroll origin.
8318     * @param oldt Previous vertical scroll origin.
8319     */
8320    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8321        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8322            postSendViewScrolledAccessibilityEventCallback();
8323        }
8324
8325        mBackgroundSizeChanged = true;
8326
8327        final AttachInfo ai = mAttachInfo;
8328        if (ai != null) {
8329            ai.mViewScrollChanged = true;
8330        }
8331    }
8332
8333    /**
8334     * Interface definition for a callback to be invoked when the layout bounds of a view
8335     * changes due to layout processing.
8336     */
8337    public interface OnLayoutChangeListener {
8338        /**
8339         * Called when the focus state of a view has changed.
8340         *
8341         * @param v The view whose state has changed.
8342         * @param left The new value of the view's left property.
8343         * @param top The new value of the view's top property.
8344         * @param right The new value of the view's right property.
8345         * @param bottom The new value of the view's bottom property.
8346         * @param oldLeft The previous value of the view's left property.
8347         * @param oldTop The previous value of the view's top property.
8348         * @param oldRight The previous value of the view's right property.
8349         * @param oldBottom The previous value of the view's bottom property.
8350         */
8351        void onLayoutChange(View v, int left, int top, int right, int bottom,
8352            int oldLeft, int oldTop, int oldRight, int oldBottom);
8353    }
8354
8355    /**
8356     * This is called during layout when the size of this view has changed. If
8357     * you were just added to the view hierarchy, you're called with the old
8358     * values of 0.
8359     *
8360     * @param w Current width of this view.
8361     * @param h Current height of this view.
8362     * @param oldw Old width of this view.
8363     * @param oldh Old height of this view.
8364     */
8365    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8366    }
8367
8368    /**
8369     * Called by draw to draw the child views. This may be overridden
8370     * by derived classes to gain control just before its children are drawn
8371     * (but after its own view has been drawn).
8372     * @param canvas the canvas on which to draw the view
8373     */
8374    protected void dispatchDraw(Canvas canvas) {
8375
8376    }
8377
8378    /**
8379     * Gets the parent of this view. Note that the parent is a
8380     * ViewParent and not necessarily a View.
8381     *
8382     * @return Parent of this view.
8383     */
8384    public final ViewParent getParent() {
8385        return mParent;
8386    }
8387
8388    /**
8389     * Set the horizontal scrolled position of your view. This will cause a call to
8390     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8391     * invalidated.
8392     * @param value the x position to scroll to
8393     */
8394    public void setScrollX(int value) {
8395        scrollTo(value, mScrollY);
8396    }
8397
8398    /**
8399     * Set the vertical scrolled position of your view. This will cause a call to
8400     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8401     * invalidated.
8402     * @param value the y position to scroll to
8403     */
8404    public void setScrollY(int value) {
8405        scrollTo(mScrollX, value);
8406    }
8407
8408    /**
8409     * Return the scrolled left position of this view. This is the left edge of
8410     * the displayed part of your view. You do not need to draw any pixels
8411     * farther left, since those are outside of the frame of your view on
8412     * screen.
8413     *
8414     * @return The left edge of the displayed part of your view, in pixels.
8415     */
8416    public final int getScrollX() {
8417        return mScrollX;
8418    }
8419
8420    /**
8421     * Return the scrolled top position of this view. This is the top edge of
8422     * the displayed part of your view. You do not need to draw any pixels above
8423     * it, since those are outside of the frame of your view on screen.
8424     *
8425     * @return The top edge of the displayed part of your view, in pixels.
8426     */
8427    public final int getScrollY() {
8428        return mScrollY;
8429    }
8430
8431    /**
8432     * Return the width of the your view.
8433     *
8434     * @return The width of your view, in pixels.
8435     */
8436    @ViewDebug.ExportedProperty(category = "layout")
8437    public final int getWidth() {
8438        return mRight - mLeft;
8439    }
8440
8441    /**
8442     * Return the height of your view.
8443     *
8444     * @return The height of your view, in pixels.
8445     */
8446    @ViewDebug.ExportedProperty(category = "layout")
8447    public final int getHeight() {
8448        return mBottom - mTop;
8449    }
8450
8451    /**
8452     * Return the visible drawing bounds of your view. Fills in the output
8453     * rectangle with the values from getScrollX(), getScrollY(),
8454     * getWidth(), and getHeight().
8455     *
8456     * @param outRect The (scrolled) drawing bounds of the view.
8457     */
8458    public void getDrawingRect(Rect outRect) {
8459        outRect.left = mScrollX;
8460        outRect.top = mScrollY;
8461        outRect.right = mScrollX + (mRight - mLeft);
8462        outRect.bottom = mScrollY + (mBottom - mTop);
8463    }
8464
8465    /**
8466     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8467     * raw width component (that is the result is masked by
8468     * {@link #MEASURED_SIZE_MASK}).
8469     *
8470     * @return The raw measured width of this view.
8471     */
8472    public final int getMeasuredWidth() {
8473        return mMeasuredWidth & MEASURED_SIZE_MASK;
8474    }
8475
8476    /**
8477     * Return the full width measurement information for this view as computed
8478     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8479     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8480     * This should be used during measurement and layout calculations only. Use
8481     * {@link #getWidth()} to see how wide a view is after layout.
8482     *
8483     * @return The measured width of this view as a bit mask.
8484     */
8485    public final int getMeasuredWidthAndState() {
8486        return mMeasuredWidth;
8487    }
8488
8489    /**
8490     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8491     * raw width component (that is the result is masked by
8492     * {@link #MEASURED_SIZE_MASK}).
8493     *
8494     * @return The raw measured height of this view.
8495     */
8496    public final int getMeasuredHeight() {
8497        return mMeasuredHeight & MEASURED_SIZE_MASK;
8498    }
8499
8500    /**
8501     * Return the full height measurement information for this view as computed
8502     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8503     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8504     * This should be used during measurement and layout calculations only. Use
8505     * {@link #getHeight()} to see how wide a view is after layout.
8506     *
8507     * @return The measured width of this view as a bit mask.
8508     */
8509    public final int getMeasuredHeightAndState() {
8510        return mMeasuredHeight;
8511    }
8512
8513    /**
8514     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8515     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8516     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8517     * and the height component is at the shifted bits
8518     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8519     */
8520    public final int getMeasuredState() {
8521        return (mMeasuredWidth&MEASURED_STATE_MASK)
8522                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8523                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8524    }
8525
8526    /**
8527     * The transform matrix of this view, which is calculated based on the current
8528     * roation, scale, and pivot properties.
8529     *
8530     * @see #getRotation()
8531     * @see #getScaleX()
8532     * @see #getScaleY()
8533     * @see #getPivotX()
8534     * @see #getPivotY()
8535     * @return The current transform matrix for the view
8536     */
8537    public Matrix getMatrix() {
8538        if (mTransformationInfo != null) {
8539            updateMatrix();
8540            return mTransformationInfo.mMatrix;
8541        }
8542        return Matrix.IDENTITY_MATRIX;
8543    }
8544
8545    /**
8546     * Utility function to determine if the value is far enough away from zero to be
8547     * considered non-zero.
8548     * @param value A floating point value to check for zero-ness
8549     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8550     */
8551    private static boolean nonzero(float value) {
8552        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8553    }
8554
8555    /**
8556     * Returns true if the transform matrix is the identity matrix.
8557     * Recomputes the matrix if necessary.
8558     *
8559     * @return True if the transform matrix is the identity matrix, false otherwise.
8560     */
8561    final boolean hasIdentityMatrix() {
8562        if (mTransformationInfo != null) {
8563            updateMatrix();
8564            return mTransformationInfo.mMatrixIsIdentity;
8565        }
8566        return true;
8567    }
8568
8569    void ensureTransformationInfo() {
8570        if (mTransformationInfo == null) {
8571            mTransformationInfo = new TransformationInfo();
8572        }
8573    }
8574
8575    /**
8576     * Recomputes the transform matrix if necessary.
8577     */
8578    private void updateMatrix() {
8579        final TransformationInfo info = mTransformationInfo;
8580        if (info == null) {
8581            return;
8582        }
8583        if (info.mMatrixDirty) {
8584            // transform-related properties have changed since the last time someone
8585            // asked for the matrix; recalculate it with the current values
8586
8587            // Figure out if we need to update the pivot point
8588            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
8589                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8590                    info.mPrevWidth = mRight - mLeft;
8591                    info.mPrevHeight = mBottom - mTop;
8592                    info.mPivotX = info.mPrevWidth / 2f;
8593                    info.mPivotY = info.mPrevHeight / 2f;
8594                }
8595            }
8596            info.mMatrix.reset();
8597            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8598                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8599                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8600                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8601            } else {
8602                if (info.mCamera == null) {
8603                    info.mCamera = new Camera();
8604                    info.matrix3D = new Matrix();
8605                }
8606                info.mCamera.save();
8607                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8608                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8609                info.mCamera.getMatrix(info.matrix3D);
8610                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8611                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8612                        info.mPivotY + info.mTranslationY);
8613                info.mMatrix.postConcat(info.matrix3D);
8614                info.mCamera.restore();
8615            }
8616            info.mMatrixDirty = false;
8617            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8618            info.mInverseMatrixDirty = true;
8619        }
8620    }
8621
8622    /**
8623     * When searching for a view to focus this rectangle is used when considering if this view is
8624     * a good candidate for receiving focus.
8625     *
8626     * By default, the rectangle is the {@link #getDrawingRect}) of the view.
8627     *
8628     * @param r The rectangle to fill in, in this view's coordinates.
8629     */
8630    public void getFocusRect(Rect r) {
8631        getDrawingRect(r);
8632    }
8633
8634   /**
8635     * Utility method to retrieve the inverse of the current mMatrix property.
8636     * We cache the matrix to avoid recalculating it when transform properties
8637     * have not changed.
8638     *
8639     * @return The inverse of the current matrix of this view.
8640     */
8641    final Matrix getInverseMatrix() {
8642        final TransformationInfo info = mTransformationInfo;
8643        if (info != null) {
8644            updateMatrix();
8645            if (info.mInverseMatrixDirty) {
8646                if (info.mInverseMatrix == null) {
8647                    info.mInverseMatrix = new Matrix();
8648                }
8649                info.mMatrix.invert(info.mInverseMatrix);
8650                info.mInverseMatrixDirty = false;
8651            }
8652            return info.mInverseMatrix;
8653        }
8654        return Matrix.IDENTITY_MATRIX;
8655    }
8656
8657    /**
8658     * Gets the distance along the Z axis from the camera to this view.
8659     *
8660     * @see #setCameraDistance(float)
8661     *
8662     * @return The distance along the Z axis.
8663     */
8664    public float getCameraDistance() {
8665        ensureTransformationInfo();
8666        final float dpi = mResources.getDisplayMetrics().densityDpi;
8667        final TransformationInfo info = mTransformationInfo;
8668        if (info.mCamera == null) {
8669            info.mCamera = new Camera();
8670            info.matrix3D = new Matrix();
8671        }
8672        return -(info.mCamera.getLocationZ() * dpi);
8673    }
8674
8675    /**
8676     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8677     * views are drawn) from the camera to this view. The camera's distance
8678     * affects 3D transformations, for instance rotations around the X and Y
8679     * axis. If the rotationX or rotationY properties are changed and this view is
8680     * large (more than half the size of the screen), it is recommended to always
8681     * use a camera distance that's greater than the height (X axis rotation) or
8682     * the width (Y axis rotation) of this view.</p>
8683     *
8684     * <p>The distance of the camera from the view plane can have an affect on the
8685     * perspective distortion of the view when it is rotated around the x or y axis.
8686     * For example, a large distance will result in a large viewing angle, and there
8687     * will not be much perspective distortion of the view as it rotates. A short
8688     * distance may cause much more perspective distortion upon rotation, and can
8689     * also result in some drawing artifacts if the rotated view ends up partially
8690     * behind the camera (which is why the recommendation is to use a distance at
8691     * least as far as the size of the view, if the view is to be rotated.)</p>
8692     *
8693     * <p>The distance is expressed in "depth pixels." The default distance depends
8694     * on the screen density. For instance, on a medium density display, the
8695     * default distance is 1280. On a high density display, the default distance
8696     * is 1920.</p>
8697     *
8698     * <p>If you want to specify a distance that leads to visually consistent
8699     * results across various densities, use the following formula:</p>
8700     * <pre>
8701     * float scale = context.getResources().getDisplayMetrics().density;
8702     * view.setCameraDistance(distance * scale);
8703     * </pre>
8704     *
8705     * <p>The density scale factor of a high density display is 1.5,
8706     * and 1920 = 1280 * 1.5.</p>
8707     *
8708     * @param distance The distance in "depth pixels", if negative the opposite
8709     *        value is used
8710     *
8711     * @see #setRotationX(float)
8712     * @see #setRotationY(float)
8713     */
8714    public void setCameraDistance(float distance) {
8715        invalidateViewProperty(true, false);
8716
8717        ensureTransformationInfo();
8718        final float dpi = mResources.getDisplayMetrics().densityDpi;
8719        final TransformationInfo info = mTransformationInfo;
8720        if (info.mCamera == null) {
8721            info.mCamera = new Camera();
8722            info.matrix3D = new Matrix();
8723        }
8724
8725        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8726        info.mMatrixDirty = true;
8727
8728        invalidateViewProperty(false, false);
8729        if (mDisplayList != null) {
8730            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8731        }
8732        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8733            // View was rejected last time it was drawn by its parent; this may have changed
8734            invalidateParentIfNeeded();
8735        }
8736    }
8737
8738    /**
8739     * The degrees that the view is rotated around the pivot point.
8740     *
8741     * @see #setRotation(float)
8742     * @see #getPivotX()
8743     * @see #getPivotY()
8744     *
8745     * @return The degrees of rotation.
8746     */
8747    @ViewDebug.ExportedProperty(category = "drawing")
8748    public float getRotation() {
8749        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8750    }
8751
8752    /**
8753     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8754     * result in clockwise rotation.
8755     *
8756     * @param rotation The degrees of rotation.
8757     *
8758     * @see #getRotation()
8759     * @see #getPivotX()
8760     * @see #getPivotY()
8761     * @see #setRotationX(float)
8762     * @see #setRotationY(float)
8763     *
8764     * @attr ref android.R.styleable#View_rotation
8765     */
8766    public void setRotation(float rotation) {
8767        ensureTransformationInfo();
8768        final TransformationInfo info = mTransformationInfo;
8769        if (info.mRotation != rotation) {
8770            // Double-invalidation is necessary to capture view's old and new areas
8771            invalidateViewProperty(true, false);
8772            info.mRotation = rotation;
8773            info.mMatrixDirty = true;
8774            invalidateViewProperty(false, true);
8775            if (mDisplayList != null) {
8776                mDisplayList.setRotation(rotation);
8777            }
8778            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8779                // View was rejected last time it was drawn by its parent; this may have changed
8780                invalidateParentIfNeeded();
8781            }
8782        }
8783    }
8784
8785    /**
8786     * The degrees that the view is rotated around the vertical axis through the pivot point.
8787     *
8788     * @see #getPivotX()
8789     * @see #getPivotY()
8790     * @see #setRotationY(float)
8791     *
8792     * @return The degrees of Y rotation.
8793     */
8794    @ViewDebug.ExportedProperty(category = "drawing")
8795    public float getRotationY() {
8796        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8797    }
8798
8799    /**
8800     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8801     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8802     * down the y axis.
8803     *
8804     * When rotating large views, it is recommended to adjust the camera distance
8805     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8806     *
8807     * @param rotationY The degrees of Y rotation.
8808     *
8809     * @see #getRotationY()
8810     * @see #getPivotX()
8811     * @see #getPivotY()
8812     * @see #setRotation(float)
8813     * @see #setRotationX(float)
8814     * @see #setCameraDistance(float)
8815     *
8816     * @attr ref android.R.styleable#View_rotationY
8817     */
8818    public void setRotationY(float rotationY) {
8819        ensureTransformationInfo();
8820        final TransformationInfo info = mTransformationInfo;
8821        if (info.mRotationY != rotationY) {
8822            invalidateViewProperty(true, false);
8823            info.mRotationY = rotationY;
8824            info.mMatrixDirty = true;
8825            invalidateViewProperty(false, true);
8826            if (mDisplayList != null) {
8827                mDisplayList.setRotationY(rotationY);
8828            }
8829            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8830                // View was rejected last time it was drawn by its parent; this may have changed
8831                invalidateParentIfNeeded();
8832            }
8833        }
8834    }
8835
8836    /**
8837     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8838     *
8839     * @see #getPivotX()
8840     * @see #getPivotY()
8841     * @see #setRotationX(float)
8842     *
8843     * @return The degrees of X rotation.
8844     */
8845    @ViewDebug.ExportedProperty(category = "drawing")
8846    public float getRotationX() {
8847        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8848    }
8849
8850    /**
8851     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8852     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8853     * x axis.
8854     *
8855     * When rotating large views, it is recommended to adjust the camera distance
8856     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8857     *
8858     * @param rotationX The degrees of X rotation.
8859     *
8860     * @see #getRotationX()
8861     * @see #getPivotX()
8862     * @see #getPivotY()
8863     * @see #setRotation(float)
8864     * @see #setRotationY(float)
8865     * @see #setCameraDistance(float)
8866     *
8867     * @attr ref android.R.styleable#View_rotationX
8868     */
8869    public void setRotationX(float rotationX) {
8870        ensureTransformationInfo();
8871        final TransformationInfo info = mTransformationInfo;
8872        if (info.mRotationX != rotationX) {
8873            invalidateViewProperty(true, false);
8874            info.mRotationX = rotationX;
8875            info.mMatrixDirty = true;
8876            invalidateViewProperty(false, true);
8877            if (mDisplayList != null) {
8878                mDisplayList.setRotationX(rotationX);
8879            }
8880            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8881                // View was rejected last time it was drawn by its parent; this may have changed
8882                invalidateParentIfNeeded();
8883            }
8884        }
8885    }
8886
8887    /**
8888     * The amount that the view is scaled in x around the pivot point, as a proportion of
8889     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8890     *
8891     * <p>By default, this is 1.0f.
8892     *
8893     * @see #getPivotX()
8894     * @see #getPivotY()
8895     * @return The scaling factor.
8896     */
8897    @ViewDebug.ExportedProperty(category = "drawing")
8898    public float getScaleX() {
8899        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8900    }
8901
8902    /**
8903     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8904     * the view's unscaled width. A value of 1 means that no scaling is applied.
8905     *
8906     * @param scaleX The scaling factor.
8907     * @see #getPivotX()
8908     * @see #getPivotY()
8909     *
8910     * @attr ref android.R.styleable#View_scaleX
8911     */
8912    public void setScaleX(float scaleX) {
8913        ensureTransformationInfo();
8914        final TransformationInfo info = mTransformationInfo;
8915        if (info.mScaleX != scaleX) {
8916            invalidateViewProperty(true, false);
8917            info.mScaleX = scaleX;
8918            info.mMatrixDirty = true;
8919            invalidateViewProperty(false, true);
8920            if (mDisplayList != null) {
8921                mDisplayList.setScaleX(scaleX);
8922            }
8923            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8924                // View was rejected last time it was drawn by its parent; this may have changed
8925                invalidateParentIfNeeded();
8926            }
8927        }
8928    }
8929
8930    /**
8931     * The amount that the view is scaled in y around the pivot point, as a proportion of
8932     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8933     *
8934     * <p>By default, this is 1.0f.
8935     *
8936     * @see #getPivotX()
8937     * @see #getPivotY()
8938     * @return The scaling factor.
8939     */
8940    @ViewDebug.ExportedProperty(category = "drawing")
8941    public float getScaleY() {
8942        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8943    }
8944
8945    /**
8946     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8947     * the view's unscaled width. A value of 1 means that no scaling is applied.
8948     *
8949     * @param scaleY The scaling factor.
8950     * @see #getPivotX()
8951     * @see #getPivotY()
8952     *
8953     * @attr ref android.R.styleable#View_scaleY
8954     */
8955    public void setScaleY(float scaleY) {
8956        ensureTransformationInfo();
8957        final TransformationInfo info = mTransformationInfo;
8958        if (info.mScaleY != scaleY) {
8959            invalidateViewProperty(true, false);
8960            info.mScaleY = scaleY;
8961            info.mMatrixDirty = true;
8962            invalidateViewProperty(false, true);
8963            if (mDisplayList != null) {
8964                mDisplayList.setScaleY(scaleY);
8965            }
8966            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8967                // View was rejected last time it was drawn by its parent; this may have changed
8968                invalidateParentIfNeeded();
8969            }
8970        }
8971    }
8972
8973    /**
8974     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8975     * and {@link #setScaleX(float) scaled}.
8976     *
8977     * @see #getRotation()
8978     * @see #getScaleX()
8979     * @see #getScaleY()
8980     * @see #getPivotY()
8981     * @return The x location of the pivot point.
8982     *
8983     * @attr ref android.R.styleable#View_transformPivotX
8984     */
8985    @ViewDebug.ExportedProperty(category = "drawing")
8986    public float getPivotX() {
8987        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8988    }
8989
8990    /**
8991     * Sets the x location of the point around which the view is
8992     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8993     * By default, the pivot point is centered on the object.
8994     * Setting this property disables this behavior and causes the view to use only the
8995     * explicitly set pivotX and pivotY values.
8996     *
8997     * @param pivotX The x location of the pivot point.
8998     * @see #getRotation()
8999     * @see #getScaleX()
9000     * @see #getScaleY()
9001     * @see #getPivotY()
9002     *
9003     * @attr ref android.R.styleable#View_transformPivotX
9004     */
9005    public void setPivotX(float pivotX) {
9006        ensureTransformationInfo();
9007        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9008        final TransformationInfo info = mTransformationInfo;
9009        if (info.mPivotX != pivotX) {
9010            invalidateViewProperty(true, false);
9011            info.mPivotX = pivotX;
9012            info.mMatrixDirty = true;
9013            invalidateViewProperty(false, true);
9014            if (mDisplayList != null) {
9015                mDisplayList.setPivotX(pivotX);
9016            }
9017            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9018                // View was rejected last time it was drawn by its parent; this may have changed
9019                invalidateParentIfNeeded();
9020            }
9021        }
9022    }
9023
9024    /**
9025     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9026     * and {@link #setScaleY(float) scaled}.
9027     *
9028     * @see #getRotation()
9029     * @see #getScaleX()
9030     * @see #getScaleY()
9031     * @see #getPivotY()
9032     * @return The y location of the pivot point.
9033     *
9034     * @attr ref android.R.styleable#View_transformPivotY
9035     */
9036    @ViewDebug.ExportedProperty(category = "drawing")
9037    public float getPivotY() {
9038        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9039    }
9040
9041    /**
9042     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9043     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9044     * Setting this property disables this behavior and causes the view to use only the
9045     * explicitly set pivotX and pivotY values.
9046     *
9047     * @param pivotY The y location of the pivot point.
9048     * @see #getRotation()
9049     * @see #getScaleX()
9050     * @see #getScaleY()
9051     * @see #getPivotY()
9052     *
9053     * @attr ref android.R.styleable#View_transformPivotY
9054     */
9055    public void setPivotY(float pivotY) {
9056        ensureTransformationInfo();
9057        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9058        final TransformationInfo info = mTransformationInfo;
9059        if (info.mPivotY != pivotY) {
9060            invalidateViewProperty(true, false);
9061            info.mPivotY = pivotY;
9062            info.mMatrixDirty = true;
9063            invalidateViewProperty(false, true);
9064            if (mDisplayList != null) {
9065                mDisplayList.setPivotY(pivotY);
9066            }
9067            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9068                // View was rejected last time it was drawn by its parent; this may have changed
9069                invalidateParentIfNeeded();
9070            }
9071        }
9072    }
9073
9074    /**
9075     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9076     * completely transparent and 1 means the view is completely opaque.
9077     *
9078     * <p>By default this is 1.0f.
9079     * @return The opacity of the view.
9080     */
9081    @ViewDebug.ExportedProperty(category = "drawing")
9082    public float getAlpha() {
9083        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9084    }
9085
9086    /**
9087     * Returns whether this View has content which overlaps. This function, intended to be
9088     * overridden by specific View types, is an optimization when alpha is set on a view. If
9089     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9090     * and then composited it into place, which can be expensive. If the view has no overlapping
9091     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9092     * An example of overlapping rendering is a TextView with a background image, such as a
9093     * Button. An example of non-overlapping rendering is a TextView with no background, or
9094     * an ImageView with only the foreground image. The default implementation returns true;
9095     * subclasses should override if they have cases which can be optimized.
9096     *
9097     * @return true if the content in this view might overlap, false otherwise.
9098     */
9099    public boolean hasOverlappingRendering() {
9100        return true;
9101    }
9102
9103    /**
9104     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9105     * completely transparent and 1 means the view is completely opaque.</p>
9106     *
9107     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9108     * responsible for applying the opacity itself. Otherwise, calling this method is
9109     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
9110     * setting a hardware layer.</p>
9111     *
9112     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
9113     * performance implications. It is generally best to use the alpha property sparingly and
9114     * transiently, as in the case of fading animations.</p>
9115     *
9116     * @param alpha The opacity of the view.
9117     *
9118     * @see #setLayerType(int, android.graphics.Paint)
9119     *
9120     * @attr ref android.R.styleable#View_alpha
9121     */
9122    public void setAlpha(float alpha) {
9123        ensureTransformationInfo();
9124        if (mTransformationInfo.mAlpha != alpha) {
9125            mTransformationInfo.mAlpha = alpha;
9126            if (onSetAlpha((int) (alpha * 255))) {
9127                mPrivateFlags |= PFLAG_ALPHA_SET;
9128                // subclass is handling alpha - don't optimize rendering cache invalidation
9129                invalidateParentCaches();
9130                invalidate(true);
9131            } else {
9132                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9133                invalidateViewProperty(true, false);
9134                if (mDisplayList != null) {
9135                    mDisplayList.setAlpha(alpha);
9136                }
9137            }
9138        }
9139    }
9140
9141    /**
9142     * Faster version of setAlpha() which performs the same steps except there are
9143     * no calls to invalidate(). The caller of this function should perform proper invalidation
9144     * on the parent and this object. The return value indicates whether the subclass handles
9145     * alpha (the return value for onSetAlpha()).
9146     *
9147     * @param alpha The new value for the alpha property
9148     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9149     *         the new value for the alpha property is different from the old value
9150     */
9151    boolean setAlphaNoInvalidation(float alpha) {
9152        ensureTransformationInfo();
9153        if (mTransformationInfo.mAlpha != alpha) {
9154            mTransformationInfo.mAlpha = alpha;
9155            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9156            if (subclassHandlesAlpha) {
9157                mPrivateFlags |= PFLAG_ALPHA_SET;
9158                return true;
9159            } else {
9160                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9161                if (mDisplayList != null) {
9162                    mDisplayList.setAlpha(alpha);
9163                }
9164            }
9165        }
9166        return false;
9167    }
9168
9169    /**
9170     * Top position of this view relative to its parent.
9171     *
9172     * @return The top of this view, in pixels.
9173     */
9174    @ViewDebug.CapturedViewProperty
9175    public final int getTop() {
9176        return mTop;
9177    }
9178
9179    /**
9180     * Sets the top position of this view relative to its parent. This method is meant to be called
9181     * by the layout system and should not generally be called otherwise, because the property
9182     * may be changed at any time by the layout.
9183     *
9184     * @param top The top of this view, in pixels.
9185     */
9186    public final void setTop(int top) {
9187        if (top != mTop) {
9188            updateMatrix();
9189            final boolean matrixIsIdentity = mTransformationInfo == null
9190                    || mTransformationInfo.mMatrixIsIdentity;
9191            if (matrixIsIdentity) {
9192                if (mAttachInfo != null) {
9193                    int minTop;
9194                    int yLoc;
9195                    if (top < mTop) {
9196                        minTop = top;
9197                        yLoc = top - mTop;
9198                    } else {
9199                        minTop = mTop;
9200                        yLoc = 0;
9201                    }
9202                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9203                }
9204            } else {
9205                // Double-invalidation is necessary to capture view's old and new areas
9206                invalidate(true);
9207            }
9208
9209            int width = mRight - mLeft;
9210            int oldHeight = mBottom - mTop;
9211
9212            mTop = top;
9213            if (mDisplayList != null) {
9214                mDisplayList.setTop(mTop);
9215            }
9216
9217            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9218
9219            if (!matrixIsIdentity) {
9220                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9221                    // A change in dimension means an auto-centered pivot point changes, too
9222                    mTransformationInfo.mMatrixDirty = true;
9223                }
9224                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9225                invalidate(true);
9226            }
9227            mBackgroundSizeChanged = true;
9228            invalidateParentIfNeeded();
9229            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9230                // View was rejected last time it was drawn by its parent; this may have changed
9231                invalidateParentIfNeeded();
9232            }
9233        }
9234    }
9235
9236    /**
9237     * Bottom position of this view relative to its parent.
9238     *
9239     * @return The bottom of this view, in pixels.
9240     */
9241    @ViewDebug.CapturedViewProperty
9242    public final int getBottom() {
9243        return mBottom;
9244    }
9245
9246    /**
9247     * True if this view has changed since the last time being drawn.
9248     *
9249     * @return The dirty state of this view.
9250     */
9251    public boolean isDirty() {
9252        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9253    }
9254
9255    /**
9256     * Sets the bottom position of this view relative to its parent. This method is meant to be
9257     * called by the layout system and should not generally be called otherwise, because the
9258     * property may be changed at any time by the layout.
9259     *
9260     * @param bottom The bottom of this view, in pixels.
9261     */
9262    public final void setBottom(int bottom) {
9263        if (bottom != mBottom) {
9264            updateMatrix();
9265            final boolean matrixIsIdentity = mTransformationInfo == null
9266                    || mTransformationInfo.mMatrixIsIdentity;
9267            if (matrixIsIdentity) {
9268                if (mAttachInfo != null) {
9269                    int maxBottom;
9270                    if (bottom < mBottom) {
9271                        maxBottom = mBottom;
9272                    } else {
9273                        maxBottom = bottom;
9274                    }
9275                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9276                }
9277            } else {
9278                // Double-invalidation is necessary to capture view's old and new areas
9279                invalidate(true);
9280            }
9281
9282            int width = mRight - mLeft;
9283            int oldHeight = mBottom - mTop;
9284
9285            mBottom = bottom;
9286            if (mDisplayList != null) {
9287                mDisplayList.setBottom(mBottom);
9288            }
9289
9290            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9291
9292            if (!matrixIsIdentity) {
9293                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9294                    // A change in dimension means an auto-centered pivot point changes, too
9295                    mTransformationInfo.mMatrixDirty = true;
9296                }
9297                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9298                invalidate(true);
9299            }
9300            mBackgroundSizeChanged = true;
9301            invalidateParentIfNeeded();
9302            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9303                // View was rejected last time it was drawn by its parent; this may have changed
9304                invalidateParentIfNeeded();
9305            }
9306        }
9307    }
9308
9309    /**
9310     * Left position of this view relative to its parent.
9311     *
9312     * @return The left edge of this view, in pixels.
9313     */
9314    @ViewDebug.CapturedViewProperty
9315    public final int getLeft() {
9316        return mLeft;
9317    }
9318
9319    /**
9320     * Sets the left position of this view relative to its parent. This method is meant to be called
9321     * by the layout system and should not generally be called otherwise, because the property
9322     * may be changed at any time by the layout.
9323     *
9324     * @param left The bottom of this view, in pixels.
9325     */
9326    public final void setLeft(int left) {
9327        if (left != mLeft) {
9328            updateMatrix();
9329            final boolean matrixIsIdentity = mTransformationInfo == null
9330                    || mTransformationInfo.mMatrixIsIdentity;
9331            if (matrixIsIdentity) {
9332                if (mAttachInfo != null) {
9333                    int minLeft;
9334                    int xLoc;
9335                    if (left < mLeft) {
9336                        minLeft = left;
9337                        xLoc = left - mLeft;
9338                    } else {
9339                        minLeft = mLeft;
9340                        xLoc = 0;
9341                    }
9342                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9343                }
9344            } else {
9345                // Double-invalidation is necessary to capture view's old and new areas
9346                invalidate(true);
9347            }
9348
9349            int oldWidth = mRight - mLeft;
9350            int height = mBottom - mTop;
9351
9352            mLeft = left;
9353            if (mDisplayList != null) {
9354                mDisplayList.setLeft(left);
9355            }
9356
9357            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9358
9359            if (!matrixIsIdentity) {
9360                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9361                    // A change in dimension means an auto-centered pivot point changes, too
9362                    mTransformationInfo.mMatrixDirty = true;
9363                }
9364                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9365                invalidate(true);
9366            }
9367            mBackgroundSizeChanged = true;
9368            invalidateParentIfNeeded();
9369            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9370                // View was rejected last time it was drawn by its parent; this may have changed
9371                invalidateParentIfNeeded();
9372            }
9373        }
9374    }
9375
9376    /**
9377     * Right position of this view relative to its parent.
9378     *
9379     * @return The right edge of this view, in pixels.
9380     */
9381    @ViewDebug.CapturedViewProperty
9382    public final int getRight() {
9383        return mRight;
9384    }
9385
9386    /**
9387     * Sets the right position of this view relative to its parent. This method is meant to be called
9388     * by the layout system and should not generally be called otherwise, because the property
9389     * may be changed at any time by the layout.
9390     *
9391     * @param right The bottom of this view, in pixels.
9392     */
9393    public final void setRight(int right) {
9394        if (right != mRight) {
9395            updateMatrix();
9396            final boolean matrixIsIdentity = mTransformationInfo == null
9397                    || mTransformationInfo.mMatrixIsIdentity;
9398            if (matrixIsIdentity) {
9399                if (mAttachInfo != null) {
9400                    int maxRight;
9401                    if (right < mRight) {
9402                        maxRight = mRight;
9403                    } else {
9404                        maxRight = right;
9405                    }
9406                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9407                }
9408            } else {
9409                // Double-invalidation is necessary to capture view's old and new areas
9410                invalidate(true);
9411            }
9412
9413            int oldWidth = mRight - mLeft;
9414            int height = mBottom - mTop;
9415
9416            mRight = right;
9417            if (mDisplayList != null) {
9418                mDisplayList.setRight(mRight);
9419            }
9420
9421            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9422
9423            if (!matrixIsIdentity) {
9424                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9425                    // A change in dimension means an auto-centered pivot point changes, too
9426                    mTransformationInfo.mMatrixDirty = true;
9427                }
9428                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9429                invalidate(true);
9430            }
9431            mBackgroundSizeChanged = true;
9432            invalidateParentIfNeeded();
9433            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9434                // View was rejected last time it was drawn by its parent; this may have changed
9435                invalidateParentIfNeeded();
9436            }
9437        }
9438    }
9439
9440    /**
9441     * The visual x position of this view, in pixels. This is equivalent to the
9442     * {@link #setTranslationX(float) translationX} property plus the current
9443     * {@link #getLeft() left} property.
9444     *
9445     * @return The visual x position of this view, in pixels.
9446     */
9447    @ViewDebug.ExportedProperty(category = "drawing")
9448    public float getX() {
9449        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9450    }
9451
9452    /**
9453     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9454     * {@link #setTranslationX(float) translationX} property to be the difference between
9455     * the x value passed in and the current {@link #getLeft() left} property.
9456     *
9457     * @param x The visual x position of this view, in pixels.
9458     */
9459    public void setX(float x) {
9460        setTranslationX(x - mLeft);
9461    }
9462
9463    /**
9464     * The visual y position of this view, in pixels. This is equivalent to the
9465     * {@link #setTranslationY(float) translationY} property plus the current
9466     * {@link #getTop() top} property.
9467     *
9468     * @return The visual y position of this view, in pixels.
9469     */
9470    @ViewDebug.ExportedProperty(category = "drawing")
9471    public float getY() {
9472        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9473    }
9474
9475    /**
9476     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9477     * {@link #setTranslationY(float) translationY} property to be the difference between
9478     * the y value passed in and the current {@link #getTop() top} property.
9479     *
9480     * @param y The visual y position of this view, in pixels.
9481     */
9482    public void setY(float y) {
9483        setTranslationY(y - mTop);
9484    }
9485
9486
9487    /**
9488     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9489     * This position is post-layout, in addition to wherever the object's
9490     * layout placed it.
9491     *
9492     * @return The horizontal position of this view relative to its left position, in pixels.
9493     */
9494    @ViewDebug.ExportedProperty(category = "drawing")
9495    public float getTranslationX() {
9496        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9497    }
9498
9499    /**
9500     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9501     * This effectively positions the object post-layout, in addition to wherever the object's
9502     * layout placed it.
9503     *
9504     * @param translationX The horizontal position of this view relative to its left position,
9505     * in pixels.
9506     *
9507     * @attr ref android.R.styleable#View_translationX
9508     */
9509    public void setTranslationX(float translationX) {
9510        ensureTransformationInfo();
9511        final TransformationInfo info = mTransformationInfo;
9512        if (info.mTranslationX != translationX) {
9513            // Double-invalidation is necessary to capture view's old and new areas
9514            invalidateViewProperty(true, false);
9515            info.mTranslationX = translationX;
9516            info.mMatrixDirty = true;
9517            invalidateViewProperty(false, true);
9518            if (mDisplayList != null) {
9519                mDisplayList.setTranslationX(translationX);
9520            }
9521            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9522                // View was rejected last time it was drawn by its parent; this may have changed
9523                invalidateParentIfNeeded();
9524            }
9525        }
9526    }
9527
9528    /**
9529     * The horizontal location of this view relative to its {@link #getTop() top} position.
9530     * This position is post-layout, in addition to wherever the object's
9531     * layout placed it.
9532     *
9533     * @return The vertical position of this view relative to its top position,
9534     * in pixels.
9535     */
9536    @ViewDebug.ExportedProperty(category = "drawing")
9537    public float getTranslationY() {
9538        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9539    }
9540
9541    /**
9542     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9543     * This effectively positions the object post-layout, in addition to wherever the object's
9544     * layout placed it.
9545     *
9546     * @param translationY The vertical position of this view relative to its top position,
9547     * in pixels.
9548     *
9549     * @attr ref android.R.styleable#View_translationY
9550     */
9551    public void setTranslationY(float translationY) {
9552        ensureTransformationInfo();
9553        final TransformationInfo info = mTransformationInfo;
9554        if (info.mTranslationY != translationY) {
9555            invalidateViewProperty(true, false);
9556            info.mTranslationY = translationY;
9557            info.mMatrixDirty = true;
9558            invalidateViewProperty(false, true);
9559            if (mDisplayList != null) {
9560                mDisplayList.setTranslationY(translationY);
9561            }
9562            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9563                // View was rejected last time it was drawn by its parent; this may have changed
9564                invalidateParentIfNeeded();
9565            }
9566        }
9567    }
9568
9569    /**
9570     * Hit rectangle in parent's coordinates
9571     *
9572     * @param outRect The hit rectangle of the view.
9573     */
9574    public void getHitRect(Rect outRect) {
9575        updateMatrix();
9576        final TransformationInfo info = mTransformationInfo;
9577        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9578            outRect.set(mLeft, mTop, mRight, mBottom);
9579        } else {
9580            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9581            tmpRect.set(-info.mPivotX, -info.mPivotY,
9582                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9583            info.mMatrix.mapRect(tmpRect);
9584            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9585                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9586        }
9587    }
9588
9589    /**
9590     * Determines whether the given point, in local coordinates is inside the view.
9591     */
9592    /*package*/ final boolean pointInView(float localX, float localY) {
9593        return localX >= 0 && localX < (mRight - mLeft)
9594                && localY >= 0 && localY < (mBottom - mTop);
9595    }
9596
9597    /**
9598     * Utility method to determine whether the given point, in local coordinates,
9599     * is inside the view, where the area of the view is expanded by the slop factor.
9600     * This method is called while processing touch-move events to determine if the event
9601     * is still within the view.
9602     */
9603    private boolean pointInView(float localX, float localY, float slop) {
9604        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9605                localY < ((mBottom - mTop) + slop);
9606    }
9607
9608    /**
9609     * When a view has focus and the user navigates away from it, the next view is searched for
9610     * starting from the rectangle filled in by this method.
9611     *
9612     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9613     * of the view.  However, if your view maintains some idea of internal selection,
9614     * such as a cursor, or a selected row or column, you should override this method and
9615     * fill in a more specific rectangle.
9616     *
9617     * @param r The rectangle to fill in, in this view's coordinates.
9618     */
9619    public void getFocusedRect(Rect r) {
9620        getDrawingRect(r);
9621    }
9622
9623    /**
9624     * If some part of this view is not clipped by any of its parents, then
9625     * return that area in r in global (root) coordinates. To convert r to local
9626     * coordinates (without taking possible View rotations into account), offset
9627     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9628     * If the view is completely clipped or translated out, return false.
9629     *
9630     * @param r If true is returned, r holds the global coordinates of the
9631     *        visible portion of this view.
9632     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9633     *        between this view and its root. globalOffet may be null.
9634     * @return true if r is non-empty (i.e. part of the view is visible at the
9635     *         root level.
9636     */
9637    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9638        int width = mRight - mLeft;
9639        int height = mBottom - mTop;
9640        if (width > 0 && height > 0) {
9641            r.set(0, 0, width, height);
9642            if (globalOffset != null) {
9643                globalOffset.set(-mScrollX, -mScrollY);
9644            }
9645            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9646        }
9647        return false;
9648    }
9649
9650    public final boolean getGlobalVisibleRect(Rect r) {
9651        return getGlobalVisibleRect(r, null);
9652    }
9653
9654    public final boolean getLocalVisibleRect(Rect r) {
9655        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9656        if (getGlobalVisibleRect(r, offset)) {
9657            r.offset(-offset.x, -offset.y); // make r local
9658            return true;
9659        }
9660        return false;
9661    }
9662
9663    /**
9664     * Offset this view's vertical location by the specified number of pixels.
9665     *
9666     * @param offset the number of pixels to offset the view by
9667     */
9668    public void offsetTopAndBottom(int offset) {
9669        if (offset != 0) {
9670            updateMatrix();
9671            final boolean matrixIsIdentity = mTransformationInfo == null
9672                    || mTransformationInfo.mMatrixIsIdentity;
9673            if (matrixIsIdentity) {
9674                if (mDisplayList != null) {
9675                    invalidateViewProperty(false, false);
9676                } else {
9677                    final ViewParent p = mParent;
9678                    if (p != null && mAttachInfo != null) {
9679                        final Rect r = mAttachInfo.mTmpInvalRect;
9680                        int minTop;
9681                        int maxBottom;
9682                        int yLoc;
9683                        if (offset < 0) {
9684                            minTop = mTop + offset;
9685                            maxBottom = mBottom;
9686                            yLoc = offset;
9687                        } else {
9688                            minTop = mTop;
9689                            maxBottom = mBottom + offset;
9690                            yLoc = 0;
9691                        }
9692                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9693                        p.invalidateChild(this, r);
9694                    }
9695                }
9696            } else {
9697                invalidateViewProperty(false, false);
9698            }
9699
9700            mTop += offset;
9701            mBottom += offset;
9702            if (mDisplayList != null) {
9703                mDisplayList.offsetTopBottom(offset);
9704                invalidateViewProperty(false, false);
9705            } else {
9706                if (!matrixIsIdentity) {
9707                    invalidateViewProperty(false, true);
9708                }
9709                invalidateParentIfNeeded();
9710            }
9711        }
9712    }
9713
9714    /**
9715     * Offset this view's horizontal location by the specified amount of pixels.
9716     *
9717     * @param offset the numer of pixels to offset the view by
9718     */
9719    public void offsetLeftAndRight(int offset) {
9720        if (offset != 0) {
9721            updateMatrix();
9722            final boolean matrixIsIdentity = mTransformationInfo == null
9723                    || mTransformationInfo.mMatrixIsIdentity;
9724            if (matrixIsIdentity) {
9725                if (mDisplayList != null) {
9726                    invalidateViewProperty(false, false);
9727                } else {
9728                    final ViewParent p = mParent;
9729                    if (p != null && mAttachInfo != null) {
9730                        final Rect r = mAttachInfo.mTmpInvalRect;
9731                        int minLeft;
9732                        int maxRight;
9733                        if (offset < 0) {
9734                            minLeft = mLeft + offset;
9735                            maxRight = mRight;
9736                        } else {
9737                            minLeft = mLeft;
9738                            maxRight = mRight + offset;
9739                        }
9740                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9741                        p.invalidateChild(this, r);
9742                    }
9743                }
9744            } else {
9745                invalidateViewProperty(false, false);
9746            }
9747
9748            mLeft += offset;
9749            mRight += offset;
9750            if (mDisplayList != null) {
9751                mDisplayList.offsetLeftRight(offset);
9752                invalidateViewProperty(false, false);
9753            } else {
9754                if (!matrixIsIdentity) {
9755                    invalidateViewProperty(false, true);
9756                }
9757                invalidateParentIfNeeded();
9758            }
9759        }
9760    }
9761
9762    /**
9763     * Get the LayoutParams associated with this view. All views should have
9764     * layout parameters. These supply parameters to the <i>parent</i> of this
9765     * view specifying how it should be arranged. There are many subclasses of
9766     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9767     * of ViewGroup that are responsible for arranging their children.
9768     *
9769     * This method may return null if this View is not attached to a parent
9770     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9771     * was not invoked successfully. When a View is attached to a parent
9772     * ViewGroup, this method must not return null.
9773     *
9774     * @return The LayoutParams associated with this view, or null if no
9775     *         parameters have been set yet
9776     */
9777    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9778    public ViewGroup.LayoutParams getLayoutParams() {
9779        return mLayoutParams;
9780    }
9781
9782    /**
9783     * Set the layout parameters associated with this view. These supply
9784     * parameters to the <i>parent</i> of this view specifying how it should be
9785     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9786     * correspond to the different subclasses of ViewGroup that are responsible
9787     * for arranging their children.
9788     *
9789     * @param params The layout parameters for this view, cannot be null
9790     */
9791    public void setLayoutParams(ViewGroup.LayoutParams params) {
9792        if (params == null) {
9793            throw new NullPointerException("Layout parameters cannot be null");
9794        }
9795        mLayoutParams = params;
9796        resolveLayoutParams();
9797        if (mParent instanceof ViewGroup) {
9798            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9799        }
9800        requestLayout();
9801    }
9802
9803    /**
9804     * Resolve the layout parameters depending on the resolved layout direction
9805     */
9806    private void resolveLayoutParams() {
9807        if (mLayoutParams != null) {
9808            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
9809        }
9810    }
9811
9812    /**
9813     * Set the scrolled position of your view. This will cause a call to
9814     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9815     * invalidated.
9816     * @param x the x position to scroll to
9817     * @param y the y position to scroll to
9818     */
9819    public void scrollTo(int x, int y) {
9820        if (mScrollX != x || mScrollY != y) {
9821            int oldX = mScrollX;
9822            int oldY = mScrollY;
9823            mScrollX = x;
9824            mScrollY = y;
9825            invalidateParentCaches();
9826            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9827            if (!awakenScrollBars()) {
9828                postInvalidateOnAnimation();
9829            }
9830        }
9831    }
9832
9833    /**
9834     * Move the scrolled position of your view. This will cause a call to
9835     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9836     * invalidated.
9837     * @param x the amount of pixels to scroll by horizontally
9838     * @param y the amount of pixels to scroll by vertically
9839     */
9840    public void scrollBy(int x, int y) {
9841        scrollTo(mScrollX + x, mScrollY + y);
9842    }
9843
9844    /**
9845     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9846     * animation to fade the scrollbars out after a default delay. If a subclass
9847     * provides animated scrolling, the start delay should equal the duration
9848     * of the scrolling animation.</p>
9849     *
9850     * <p>The animation starts only if at least one of the scrollbars is
9851     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9852     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9853     * this method returns true, and false otherwise. If the animation is
9854     * started, this method calls {@link #invalidate()}; in that case the
9855     * caller should not call {@link #invalidate()}.</p>
9856     *
9857     * <p>This method should be invoked every time a subclass directly updates
9858     * the scroll parameters.</p>
9859     *
9860     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9861     * and {@link #scrollTo(int, int)}.</p>
9862     *
9863     * @return true if the animation is played, false otherwise
9864     *
9865     * @see #awakenScrollBars(int)
9866     * @see #scrollBy(int, int)
9867     * @see #scrollTo(int, int)
9868     * @see #isHorizontalScrollBarEnabled()
9869     * @see #isVerticalScrollBarEnabled()
9870     * @see #setHorizontalScrollBarEnabled(boolean)
9871     * @see #setVerticalScrollBarEnabled(boolean)
9872     */
9873    protected boolean awakenScrollBars() {
9874        return mScrollCache != null &&
9875                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9876    }
9877
9878    /**
9879     * Trigger the scrollbars to draw.
9880     * This method differs from awakenScrollBars() only in its default duration.
9881     * initialAwakenScrollBars() will show the scroll bars for longer than
9882     * usual to give the user more of a chance to notice them.
9883     *
9884     * @return true if the animation is played, false otherwise.
9885     */
9886    private boolean initialAwakenScrollBars() {
9887        return mScrollCache != null &&
9888                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9889    }
9890
9891    /**
9892     * <p>
9893     * Trigger the scrollbars to draw. When invoked this method starts an
9894     * animation to fade the scrollbars out after a fixed delay. If a subclass
9895     * provides animated scrolling, the start delay should equal the duration of
9896     * the scrolling animation.
9897     * </p>
9898     *
9899     * <p>
9900     * The animation starts only if at least one of the scrollbars is enabled,
9901     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9902     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9903     * this method returns true, and false otherwise. If the animation is
9904     * started, this method calls {@link #invalidate()}; in that case the caller
9905     * should not call {@link #invalidate()}.
9906     * </p>
9907     *
9908     * <p>
9909     * This method should be invoked everytime a subclass directly updates the
9910     * scroll parameters.
9911     * </p>
9912     *
9913     * @param startDelay the delay, in milliseconds, after which the animation
9914     *        should start; when the delay is 0, the animation starts
9915     *        immediately
9916     * @return true if the animation is played, false otherwise
9917     *
9918     * @see #scrollBy(int, int)
9919     * @see #scrollTo(int, int)
9920     * @see #isHorizontalScrollBarEnabled()
9921     * @see #isVerticalScrollBarEnabled()
9922     * @see #setHorizontalScrollBarEnabled(boolean)
9923     * @see #setVerticalScrollBarEnabled(boolean)
9924     */
9925    protected boolean awakenScrollBars(int startDelay) {
9926        return awakenScrollBars(startDelay, true);
9927    }
9928
9929    /**
9930     * <p>
9931     * Trigger the scrollbars to draw. When invoked this method starts an
9932     * animation to fade the scrollbars out after a fixed delay. If a subclass
9933     * provides animated scrolling, the start delay should equal the duration of
9934     * the scrolling animation.
9935     * </p>
9936     *
9937     * <p>
9938     * The animation starts only if at least one of the scrollbars is enabled,
9939     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9940     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9941     * this method returns true, and false otherwise. If the animation is
9942     * started, this method calls {@link #invalidate()} if the invalidate parameter
9943     * is set to true; in that case the caller
9944     * should not call {@link #invalidate()}.
9945     * </p>
9946     *
9947     * <p>
9948     * This method should be invoked everytime a subclass directly updates the
9949     * scroll parameters.
9950     * </p>
9951     *
9952     * @param startDelay the delay, in milliseconds, after which the animation
9953     *        should start; when the delay is 0, the animation starts
9954     *        immediately
9955     *
9956     * @param invalidate Wheter this method should call invalidate
9957     *
9958     * @return true if the animation is played, false otherwise
9959     *
9960     * @see #scrollBy(int, int)
9961     * @see #scrollTo(int, int)
9962     * @see #isHorizontalScrollBarEnabled()
9963     * @see #isVerticalScrollBarEnabled()
9964     * @see #setHorizontalScrollBarEnabled(boolean)
9965     * @see #setVerticalScrollBarEnabled(boolean)
9966     */
9967    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9968        final ScrollabilityCache scrollCache = mScrollCache;
9969
9970        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9971            return false;
9972        }
9973
9974        if (scrollCache.scrollBar == null) {
9975            scrollCache.scrollBar = new ScrollBarDrawable();
9976        }
9977
9978        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9979
9980            if (invalidate) {
9981                // Invalidate to show the scrollbars
9982                postInvalidateOnAnimation();
9983            }
9984
9985            if (scrollCache.state == ScrollabilityCache.OFF) {
9986                // FIXME: this is copied from WindowManagerService.
9987                // We should get this value from the system when it
9988                // is possible to do so.
9989                final int KEY_REPEAT_FIRST_DELAY = 750;
9990                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9991            }
9992
9993            // Tell mScrollCache when we should start fading. This may
9994            // extend the fade start time if one was already scheduled
9995            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9996            scrollCache.fadeStartTime = fadeStartTime;
9997            scrollCache.state = ScrollabilityCache.ON;
9998
9999            // Schedule our fader to run, unscheduling any old ones first
10000            if (mAttachInfo != null) {
10001                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10002                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10003            }
10004
10005            return true;
10006        }
10007
10008        return false;
10009    }
10010
10011    /**
10012     * Do not invalidate views which are not visible and which are not running an animation. They
10013     * will not get drawn and they should not set dirty flags as if they will be drawn
10014     */
10015    private boolean skipInvalidate() {
10016        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10017                (!(mParent instanceof ViewGroup) ||
10018                        !((ViewGroup) mParent).isViewTransitioning(this));
10019    }
10020    /**
10021     * Mark the area defined by dirty as needing to be drawn. If the view is
10022     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10023     * in the future. This must be called from a UI thread. To call from a non-UI
10024     * thread, call {@link #postInvalidate()}.
10025     *
10026     * WARNING: This method is destructive to dirty.
10027     * @param dirty the rectangle representing the bounds of the dirty region
10028     */
10029    public void invalidate(Rect dirty) {
10030        if (skipInvalidate()) {
10031            return;
10032        }
10033        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10034                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10035                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10036            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10037            mPrivateFlags |= PFLAG_INVALIDATED;
10038            mPrivateFlags |= PFLAG_DIRTY;
10039            final ViewParent p = mParent;
10040            final AttachInfo ai = mAttachInfo;
10041            //noinspection PointlessBooleanExpression,ConstantConditions
10042            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10043                if (p != null && ai != null && ai.mHardwareAccelerated) {
10044                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10045                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10046                    p.invalidateChild(this, null);
10047                    return;
10048                }
10049            }
10050            if (p != null && ai != null) {
10051                final int scrollX = mScrollX;
10052                final int scrollY = mScrollY;
10053                final Rect r = ai.mTmpInvalRect;
10054                r.set(dirty.left - scrollX, dirty.top - scrollY,
10055                        dirty.right - scrollX, dirty.bottom - scrollY);
10056                mParent.invalidateChild(this, r);
10057            }
10058        }
10059    }
10060
10061    /**
10062     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10063     * The coordinates of the dirty rect are relative to the view.
10064     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10065     * will be called at some point in the future. This must be called from
10066     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10067     * @param l the left position of the dirty region
10068     * @param t the top position of the dirty region
10069     * @param r the right position of the dirty region
10070     * @param b the bottom position of the dirty region
10071     */
10072    public void invalidate(int l, int t, int r, int b) {
10073        if (skipInvalidate()) {
10074            return;
10075        }
10076        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10077                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10078                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10079            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10080            mPrivateFlags |= PFLAG_INVALIDATED;
10081            mPrivateFlags |= PFLAG_DIRTY;
10082            final ViewParent p = mParent;
10083            final AttachInfo ai = mAttachInfo;
10084            //noinspection PointlessBooleanExpression,ConstantConditions
10085            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10086                if (p != null && ai != null && ai.mHardwareAccelerated) {
10087                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10088                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10089                    p.invalidateChild(this, null);
10090                    return;
10091                }
10092            }
10093            if (p != null && ai != null && l < r && t < b) {
10094                final int scrollX = mScrollX;
10095                final int scrollY = mScrollY;
10096                final Rect tmpr = ai.mTmpInvalRect;
10097                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10098                p.invalidateChild(this, tmpr);
10099            }
10100        }
10101    }
10102
10103    /**
10104     * Invalidate the whole view. If the view is visible,
10105     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10106     * the future. This must be called from a UI thread. To call from a non-UI thread,
10107     * call {@link #postInvalidate()}.
10108     */
10109    public void invalidate() {
10110        invalidate(true);
10111    }
10112
10113    /**
10114     * This is where the invalidate() work actually happens. A full invalidate()
10115     * causes the drawing cache to be invalidated, but this function can be called with
10116     * invalidateCache set to false to skip that invalidation step for cases that do not
10117     * need it (for example, a component that remains at the same dimensions with the same
10118     * content).
10119     *
10120     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10121     * well. This is usually true for a full invalidate, but may be set to false if the
10122     * View's contents or dimensions have not changed.
10123     */
10124    void invalidate(boolean invalidateCache) {
10125        if (skipInvalidate()) {
10126            return;
10127        }
10128        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10129                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10130                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10131            mLastIsOpaque = isOpaque();
10132            mPrivateFlags &= ~PFLAG_DRAWN;
10133            mPrivateFlags |= PFLAG_DIRTY;
10134            if (invalidateCache) {
10135                mPrivateFlags |= PFLAG_INVALIDATED;
10136                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10137            }
10138            final AttachInfo ai = mAttachInfo;
10139            final ViewParent p = mParent;
10140            //noinspection PointlessBooleanExpression,ConstantConditions
10141            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10142                if (p != null && ai != null && ai.mHardwareAccelerated) {
10143                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10144                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10145                    p.invalidateChild(this, null);
10146                    return;
10147                }
10148            }
10149
10150            if (p != null && ai != null) {
10151                final Rect r = ai.mTmpInvalRect;
10152                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10153                // Don't call invalidate -- we don't want to internally scroll
10154                // our own bounds
10155                p.invalidateChild(this, r);
10156            }
10157        }
10158    }
10159
10160    /**
10161     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10162     * set any flags or handle all of the cases handled by the default invalidation methods.
10163     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10164     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10165     * walk up the hierarchy, transforming the dirty rect as necessary.
10166     *
10167     * The method also handles normal invalidation logic if display list properties are not
10168     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10169     * backup approach, to handle these cases used in the various property-setting methods.
10170     *
10171     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10172     * are not being used in this view
10173     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10174     * list properties are not being used in this view
10175     */
10176    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10177        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10178            if (invalidateParent) {
10179                invalidateParentCaches();
10180            }
10181            if (forceRedraw) {
10182                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10183            }
10184            invalidate(false);
10185        } else {
10186            final AttachInfo ai = mAttachInfo;
10187            final ViewParent p = mParent;
10188            if (p != null && ai != null) {
10189                final Rect r = ai.mTmpInvalRect;
10190                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10191                if (mParent instanceof ViewGroup) {
10192                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10193                } else {
10194                    mParent.invalidateChild(this, r);
10195                }
10196            }
10197        }
10198    }
10199
10200    /**
10201     * Utility method to transform a given Rect by the current matrix of this view.
10202     */
10203    void transformRect(final Rect rect) {
10204        if (!getMatrix().isIdentity()) {
10205            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10206            boundingRect.set(rect);
10207            getMatrix().mapRect(boundingRect);
10208            rect.set((int) (boundingRect.left - 0.5f),
10209                    (int) (boundingRect.top - 0.5f),
10210                    (int) (boundingRect.right + 0.5f),
10211                    (int) (boundingRect.bottom + 0.5f));
10212        }
10213    }
10214
10215    /**
10216     * Used to indicate that the parent of this view should clear its caches. This functionality
10217     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10218     * which is necessary when various parent-managed properties of the view change, such as
10219     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10220     * clears the parent caches and does not causes an invalidate event.
10221     *
10222     * @hide
10223     */
10224    protected void invalidateParentCaches() {
10225        if (mParent instanceof View) {
10226            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10227        }
10228    }
10229
10230    /**
10231     * Used to indicate that the parent of this view should be invalidated. This functionality
10232     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10233     * which is necessary when various parent-managed properties of the view change, such as
10234     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10235     * an invalidation event to the parent.
10236     *
10237     * @hide
10238     */
10239    protected void invalidateParentIfNeeded() {
10240        if (isHardwareAccelerated() && mParent instanceof View) {
10241            ((View) mParent).invalidate(true);
10242        }
10243    }
10244
10245    /**
10246     * Indicates whether this View is opaque. An opaque View guarantees that it will
10247     * draw all the pixels overlapping its bounds using a fully opaque color.
10248     *
10249     * Subclasses of View should override this method whenever possible to indicate
10250     * whether an instance is opaque. Opaque Views are treated in a special way by
10251     * the View hierarchy, possibly allowing it to perform optimizations during
10252     * invalidate/draw passes.
10253     *
10254     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10255     */
10256    @ViewDebug.ExportedProperty(category = "drawing")
10257    public boolean isOpaque() {
10258        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10259                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10260    }
10261
10262    /**
10263     * @hide
10264     */
10265    protected void computeOpaqueFlags() {
10266        // Opaque if:
10267        //   - Has a background
10268        //   - Background is opaque
10269        //   - Doesn't have scrollbars or scrollbars are inside overlay
10270
10271        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10272            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10273        } else {
10274            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10275        }
10276
10277        final int flags = mViewFlags;
10278        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10279                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10280            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10281        } else {
10282            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10283        }
10284    }
10285
10286    /**
10287     * @hide
10288     */
10289    protected boolean hasOpaqueScrollbars() {
10290        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10291    }
10292
10293    /**
10294     * @return A handler associated with the thread running the View. This
10295     * handler can be used to pump events in the UI events queue.
10296     */
10297    public Handler getHandler() {
10298        if (mAttachInfo != null) {
10299            return mAttachInfo.mHandler;
10300        }
10301        return null;
10302    }
10303
10304    /**
10305     * Gets the view root associated with the View.
10306     * @return The view root, or null if none.
10307     * @hide
10308     */
10309    public ViewRootImpl getViewRootImpl() {
10310        if (mAttachInfo != null) {
10311            return mAttachInfo.mViewRootImpl;
10312        }
10313        return null;
10314    }
10315
10316    /**
10317     * <p>Causes the Runnable to be added to the message queue.
10318     * The runnable will be run on the user interface thread.</p>
10319     *
10320     * <p>This method can be invoked from outside of the UI thread
10321     * only when this View is attached to a window.</p>
10322     *
10323     * @param action The Runnable that will be executed.
10324     *
10325     * @return Returns true if the Runnable was successfully placed in to the
10326     *         message queue.  Returns false on failure, usually because the
10327     *         looper processing the message queue is exiting.
10328     *
10329     * @see #postDelayed
10330     * @see #removeCallbacks
10331     */
10332    public boolean post(Runnable action) {
10333        final AttachInfo attachInfo = mAttachInfo;
10334        if (attachInfo != null) {
10335            return attachInfo.mHandler.post(action);
10336        }
10337        // Assume that post will succeed later
10338        ViewRootImpl.getRunQueue().post(action);
10339        return true;
10340    }
10341
10342    /**
10343     * <p>Causes the Runnable to be added to the message queue, to be run
10344     * after the specified amount of time elapses.
10345     * The runnable will be run on the user interface thread.</p>
10346     *
10347     * <p>This method can be invoked from outside of the UI thread
10348     * only when this View is attached to a window.</p>
10349     *
10350     * @param action The Runnable that will be executed.
10351     * @param delayMillis The delay (in milliseconds) until the Runnable
10352     *        will be executed.
10353     *
10354     * @return true if the Runnable was successfully placed in to the
10355     *         message queue.  Returns false on failure, usually because the
10356     *         looper processing the message queue is exiting.  Note that a
10357     *         result of true does not mean the Runnable will be processed --
10358     *         if the looper is quit before the delivery time of the message
10359     *         occurs then the message will be dropped.
10360     *
10361     * @see #post
10362     * @see #removeCallbacks
10363     */
10364    public boolean postDelayed(Runnable action, long delayMillis) {
10365        final AttachInfo attachInfo = mAttachInfo;
10366        if (attachInfo != null) {
10367            return attachInfo.mHandler.postDelayed(action, delayMillis);
10368        }
10369        // Assume that post will succeed later
10370        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10371        return true;
10372    }
10373
10374    /**
10375     * <p>Causes the Runnable to execute on the next animation time step.
10376     * The runnable will be run on the user interface thread.</p>
10377     *
10378     * <p>This method can be invoked from outside of the UI thread
10379     * only when this View is attached to a window.</p>
10380     *
10381     * @param action The Runnable that will be executed.
10382     *
10383     * @see #postOnAnimationDelayed
10384     * @see #removeCallbacks
10385     */
10386    public void postOnAnimation(Runnable action) {
10387        final AttachInfo attachInfo = mAttachInfo;
10388        if (attachInfo != null) {
10389            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10390                    Choreographer.CALLBACK_ANIMATION, action, null);
10391        } else {
10392            // Assume that post will succeed later
10393            ViewRootImpl.getRunQueue().post(action);
10394        }
10395    }
10396
10397    /**
10398     * <p>Causes the Runnable to execute on the next animation time step,
10399     * after the specified amount of time elapses.
10400     * The runnable will be run on the user interface thread.</p>
10401     *
10402     * <p>This method can be invoked from outside of the UI thread
10403     * only when this View is attached to a window.</p>
10404     *
10405     * @param action The Runnable that will be executed.
10406     * @param delayMillis The delay (in milliseconds) until the Runnable
10407     *        will be executed.
10408     *
10409     * @see #postOnAnimation
10410     * @see #removeCallbacks
10411     */
10412    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10413        final AttachInfo attachInfo = mAttachInfo;
10414        if (attachInfo != null) {
10415            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10416                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10417        } else {
10418            // Assume that post will succeed later
10419            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10420        }
10421    }
10422
10423    /**
10424     * <p>Removes the specified Runnable from the message queue.</p>
10425     *
10426     * <p>This method can be invoked from outside of the UI thread
10427     * only when this View is attached to a window.</p>
10428     *
10429     * @param action The Runnable to remove from the message handling queue
10430     *
10431     * @return true if this view could ask the Handler to remove the Runnable,
10432     *         false otherwise. When the returned value is true, the Runnable
10433     *         may or may not have been actually removed from the message queue
10434     *         (for instance, if the Runnable was not in the queue already.)
10435     *
10436     * @see #post
10437     * @see #postDelayed
10438     * @see #postOnAnimation
10439     * @see #postOnAnimationDelayed
10440     */
10441    public boolean removeCallbacks(Runnable action) {
10442        if (action != null) {
10443            final AttachInfo attachInfo = mAttachInfo;
10444            if (attachInfo != null) {
10445                attachInfo.mHandler.removeCallbacks(action);
10446                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10447                        Choreographer.CALLBACK_ANIMATION, action, null);
10448            } else {
10449                // Assume that post will succeed later
10450                ViewRootImpl.getRunQueue().removeCallbacks(action);
10451            }
10452        }
10453        return true;
10454    }
10455
10456    /**
10457     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10458     * Use this to invalidate the View from a non-UI thread.</p>
10459     *
10460     * <p>This method can be invoked from outside of the UI thread
10461     * only when this View is attached to a window.</p>
10462     *
10463     * @see #invalidate()
10464     * @see #postInvalidateDelayed(long)
10465     */
10466    public void postInvalidate() {
10467        postInvalidateDelayed(0);
10468    }
10469
10470    /**
10471     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10472     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10473     *
10474     * <p>This method can be invoked from outside of the UI thread
10475     * only when this View is attached to a window.</p>
10476     *
10477     * @param left The left coordinate of the rectangle to invalidate.
10478     * @param top The top coordinate of the rectangle to invalidate.
10479     * @param right The right coordinate of the rectangle to invalidate.
10480     * @param bottom The bottom coordinate of the rectangle to invalidate.
10481     *
10482     * @see #invalidate(int, int, int, int)
10483     * @see #invalidate(Rect)
10484     * @see #postInvalidateDelayed(long, int, int, int, int)
10485     */
10486    public void postInvalidate(int left, int top, int right, int bottom) {
10487        postInvalidateDelayed(0, left, top, right, bottom);
10488    }
10489
10490    /**
10491     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10492     * loop. Waits for the specified amount of time.</p>
10493     *
10494     * <p>This method can be invoked from outside of the UI thread
10495     * only when this View is attached to a window.</p>
10496     *
10497     * @param delayMilliseconds the duration in milliseconds to delay the
10498     *         invalidation by
10499     *
10500     * @see #invalidate()
10501     * @see #postInvalidate()
10502     */
10503    public void postInvalidateDelayed(long delayMilliseconds) {
10504        // We try only with the AttachInfo because there's no point in invalidating
10505        // if we are not attached to our window
10506        final AttachInfo attachInfo = mAttachInfo;
10507        if (attachInfo != null) {
10508            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10509        }
10510    }
10511
10512    /**
10513     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10514     * through the event loop. Waits for the specified amount of time.</p>
10515     *
10516     * <p>This method can be invoked from outside of the UI thread
10517     * only when this View is attached to a window.</p>
10518     *
10519     * @param delayMilliseconds the duration in milliseconds to delay the
10520     *         invalidation by
10521     * @param left The left coordinate of the rectangle to invalidate.
10522     * @param top The top coordinate of the rectangle to invalidate.
10523     * @param right The right coordinate of the rectangle to invalidate.
10524     * @param bottom The bottom coordinate of the rectangle to invalidate.
10525     *
10526     * @see #invalidate(int, int, int, int)
10527     * @see #invalidate(Rect)
10528     * @see #postInvalidate(int, int, int, int)
10529     */
10530    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10531            int right, int bottom) {
10532
10533        // We try only with the AttachInfo because there's no point in invalidating
10534        // if we are not attached to our window
10535        final AttachInfo attachInfo = mAttachInfo;
10536        if (attachInfo != null) {
10537            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10538            info.target = this;
10539            info.left = left;
10540            info.top = top;
10541            info.right = right;
10542            info.bottom = bottom;
10543
10544            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10545        }
10546    }
10547
10548    /**
10549     * <p>Cause an invalidate to happen on the next animation time step, typically the
10550     * next display frame.</p>
10551     *
10552     * <p>This method can be invoked from outside of the UI thread
10553     * only when this View is attached to a window.</p>
10554     *
10555     * @see #invalidate()
10556     */
10557    public void postInvalidateOnAnimation() {
10558        // We try only with the AttachInfo because there's no point in invalidating
10559        // if we are not attached to our window
10560        final AttachInfo attachInfo = mAttachInfo;
10561        if (attachInfo != null) {
10562            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10563        }
10564    }
10565
10566    /**
10567     * <p>Cause an invalidate of the specified area to happen on the next animation
10568     * time step, typically the next display frame.</p>
10569     *
10570     * <p>This method can be invoked from outside of the UI thread
10571     * only when this View is attached to a window.</p>
10572     *
10573     * @param left The left coordinate of the rectangle to invalidate.
10574     * @param top The top coordinate of the rectangle to invalidate.
10575     * @param right The right coordinate of the rectangle to invalidate.
10576     * @param bottom The bottom coordinate of the rectangle to invalidate.
10577     *
10578     * @see #invalidate(int, int, int, int)
10579     * @see #invalidate(Rect)
10580     */
10581    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10582        // We try only with the AttachInfo because there's no point in invalidating
10583        // if we are not attached to our window
10584        final AttachInfo attachInfo = mAttachInfo;
10585        if (attachInfo != null) {
10586            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10587            info.target = this;
10588            info.left = left;
10589            info.top = top;
10590            info.right = right;
10591            info.bottom = bottom;
10592
10593            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10594        }
10595    }
10596
10597    /**
10598     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10599     * This event is sent at most once every
10600     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10601     */
10602    private void postSendViewScrolledAccessibilityEventCallback() {
10603        if (mSendViewScrolledAccessibilityEvent == null) {
10604            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10605        }
10606        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10607            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10608            postDelayed(mSendViewScrolledAccessibilityEvent,
10609                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10610        }
10611    }
10612
10613    /**
10614     * Called by a parent to request that a child update its values for mScrollX
10615     * and mScrollY if necessary. This will typically be done if the child is
10616     * animating a scroll using a {@link android.widget.Scroller Scroller}
10617     * object.
10618     */
10619    public void computeScroll() {
10620    }
10621
10622    /**
10623     * <p>Indicate whether the horizontal edges are faded when the view is
10624     * scrolled horizontally.</p>
10625     *
10626     * @return true if the horizontal edges should are faded on scroll, false
10627     *         otherwise
10628     *
10629     * @see #setHorizontalFadingEdgeEnabled(boolean)
10630     *
10631     * @attr ref android.R.styleable#View_requiresFadingEdge
10632     */
10633    public boolean isHorizontalFadingEdgeEnabled() {
10634        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10635    }
10636
10637    /**
10638     * <p>Define whether the horizontal edges should be faded when this view
10639     * is scrolled horizontally.</p>
10640     *
10641     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10642     *                                    be faded when the view is scrolled
10643     *                                    horizontally
10644     *
10645     * @see #isHorizontalFadingEdgeEnabled()
10646     *
10647     * @attr ref android.R.styleable#View_requiresFadingEdge
10648     */
10649    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10650        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10651            if (horizontalFadingEdgeEnabled) {
10652                initScrollCache();
10653            }
10654
10655            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10656        }
10657    }
10658
10659    /**
10660     * <p>Indicate whether the vertical edges are faded when the view is
10661     * scrolled horizontally.</p>
10662     *
10663     * @return true if the vertical edges should are faded on scroll, false
10664     *         otherwise
10665     *
10666     * @see #setVerticalFadingEdgeEnabled(boolean)
10667     *
10668     * @attr ref android.R.styleable#View_requiresFadingEdge
10669     */
10670    public boolean isVerticalFadingEdgeEnabled() {
10671        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10672    }
10673
10674    /**
10675     * <p>Define whether the vertical edges should be faded when this view
10676     * is scrolled vertically.</p>
10677     *
10678     * @param verticalFadingEdgeEnabled true if the vertical edges should
10679     *                                  be faded when the view is scrolled
10680     *                                  vertically
10681     *
10682     * @see #isVerticalFadingEdgeEnabled()
10683     *
10684     * @attr ref android.R.styleable#View_requiresFadingEdge
10685     */
10686    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10687        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10688            if (verticalFadingEdgeEnabled) {
10689                initScrollCache();
10690            }
10691
10692            mViewFlags ^= FADING_EDGE_VERTICAL;
10693        }
10694    }
10695
10696    /**
10697     * Returns the strength, or intensity, of the top faded edge. The strength is
10698     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10699     * returns 0.0 or 1.0 but no value in between.
10700     *
10701     * Subclasses should override this method to provide a smoother fade transition
10702     * when scrolling occurs.
10703     *
10704     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10705     */
10706    protected float getTopFadingEdgeStrength() {
10707        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10708    }
10709
10710    /**
10711     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10712     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10713     * returns 0.0 or 1.0 but no value in between.
10714     *
10715     * Subclasses should override this method to provide a smoother fade transition
10716     * when scrolling occurs.
10717     *
10718     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10719     */
10720    protected float getBottomFadingEdgeStrength() {
10721        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10722                computeVerticalScrollRange() ? 1.0f : 0.0f;
10723    }
10724
10725    /**
10726     * Returns the strength, or intensity, of the left faded edge. The strength is
10727     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10728     * returns 0.0 or 1.0 but no value in between.
10729     *
10730     * Subclasses should override this method to provide a smoother fade transition
10731     * when scrolling occurs.
10732     *
10733     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10734     */
10735    protected float getLeftFadingEdgeStrength() {
10736        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10737    }
10738
10739    /**
10740     * Returns the strength, or intensity, of the right faded edge. The strength is
10741     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10742     * returns 0.0 or 1.0 but no value in between.
10743     *
10744     * Subclasses should override this method to provide a smoother fade transition
10745     * when scrolling occurs.
10746     *
10747     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10748     */
10749    protected float getRightFadingEdgeStrength() {
10750        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10751                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10752    }
10753
10754    /**
10755     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10756     * scrollbar is not drawn by default.</p>
10757     *
10758     * @return true if the horizontal scrollbar should be painted, false
10759     *         otherwise
10760     *
10761     * @see #setHorizontalScrollBarEnabled(boolean)
10762     */
10763    public boolean isHorizontalScrollBarEnabled() {
10764        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10765    }
10766
10767    /**
10768     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10769     * scrollbar is not drawn by default.</p>
10770     *
10771     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10772     *                                   be painted
10773     *
10774     * @see #isHorizontalScrollBarEnabled()
10775     */
10776    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10777        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10778            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10779            computeOpaqueFlags();
10780            resolvePadding();
10781        }
10782    }
10783
10784    /**
10785     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10786     * scrollbar is not drawn by default.</p>
10787     *
10788     * @return true if the vertical scrollbar should be painted, false
10789     *         otherwise
10790     *
10791     * @see #setVerticalScrollBarEnabled(boolean)
10792     */
10793    public boolean isVerticalScrollBarEnabled() {
10794        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10795    }
10796
10797    /**
10798     * <p>Define whether the vertical scrollbar should be drawn or not. The
10799     * scrollbar is not drawn by default.</p>
10800     *
10801     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10802     *                                 be painted
10803     *
10804     * @see #isVerticalScrollBarEnabled()
10805     */
10806    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10807        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10808            mViewFlags ^= SCROLLBARS_VERTICAL;
10809            computeOpaqueFlags();
10810            resolvePadding();
10811        }
10812    }
10813
10814    /**
10815     * @hide
10816     */
10817    protected void recomputePadding() {
10818        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10819    }
10820
10821    /**
10822     * Define whether scrollbars will fade when the view is not scrolling.
10823     *
10824     * @param fadeScrollbars wheter to enable fading
10825     *
10826     * @attr ref android.R.styleable#View_fadeScrollbars
10827     */
10828    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10829        initScrollCache();
10830        final ScrollabilityCache scrollabilityCache = mScrollCache;
10831        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10832        if (fadeScrollbars) {
10833            scrollabilityCache.state = ScrollabilityCache.OFF;
10834        } else {
10835            scrollabilityCache.state = ScrollabilityCache.ON;
10836        }
10837    }
10838
10839    /**
10840     *
10841     * Returns true if scrollbars will fade when this view is not scrolling
10842     *
10843     * @return true if scrollbar fading is enabled
10844     *
10845     * @attr ref android.R.styleable#View_fadeScrollbars
10846     */
10847    public boolean isScrollbarFadingEnabled() {
10848        return mScrollCache != null && mScrollCache.fadeScrollBars;
10849    }
10850
10851    /**
10852     *
10853     * Returns the delay before scrollbars fade.
10854     *
10855     * @return the delay before scrollbars fade
10856     *
10857     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10858     */
10859    public int getScrollBarDefaultDelayBeforeFade() {
10860        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10861                mScrollCache.scrollBarDefaultDelayBeforeFade;
10862    }
10863
10864    /**
10865     * Define the delay before scrollbars fade.
10866     *
10867     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10868     *
10869     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10870     */
10871    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10872        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10873    }
10874
10875    /**
10876     *
10877     * Returns the scrollbar fade duration.
10878     *
10879     * @return the scrollbar fade duration
10880     *
10881     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10882     */
10883    public int getScrollBarFadeDuration() {
10884        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10885                mScrollCache.scrollBarFadeDuration;
10886    }
10887
10888    /**
10889     * Define the scrollbar fade duration.
10890     *
10891     * @param scrollBarFadeDuration - the scrollbar fade duration
10892     *
10893     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10894     */
10895    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10896        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10897    }
10898
10899    /**
10900     *
10901     * Returns the scrollbar size.
10902     *
10903     * @return the scrollbar size
10904     *
10905     * @attr ref android.R.styleable#View_scrollbarSize
10906     */
10907    public int getScrollBarSize() {
10908        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10909                mScrollCache.scrollBarSize;
10910    }
10911
10912    /**
10913     * Define the scrollbar size.
10914     *
10915     * @param scrollBarSize - the scrollbar size
10916     *
10917     * @attr ref android.R.styleable#View_scrollbarSize
10918     */
10919    public void setScrollBarSize(int scrollBarSize) {
10920        getScrollCache().scrollBarSize = scrollBarSize;
10921    }
10922
10923    /**
10924     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10925     * inset. When inset, they add to the padding of the view. And the scrollbars
10926     * can be drawn inside the padding area or on the edge of the view. For example,
10927     * if a view has a background drawable and you want to draw the scrollbars
10928     * inside the padding specified by the drawable, you can use
10929     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10930     * appear at the edge of the view, ignoring the padding, then you can use
10931     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10932     * @param style the style of the scrollbars. Should be one of
10933     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10934     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10935     * @see #SCROLLBARS_INSIDE_OVERLAY
10936     * @see #SCROLLBARS_INSIDE_INSET
10937     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10938     * @see #SCROLLBARS_OUTSIDE_INSET
10939     *
10940     * @attr ref android.R.styleable#View_scrollbarStyle
10941     */
10942    public void setScrollBarStyle(int style) {
10943        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10944            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10945            computeOpaqueFlags();
10946            resolvePadding();
10947        }
10948    }
10949
10950    /**
10951     * <p>Returns the current scrollbar style.</p>
10952     * @return the current scrollbar style
10953     * @see #SCROLLBARS_INSIDE_OVERLAY
10954     * @see #SCROLLBARS_INSIDE_INSET
10955     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10956     * @see #SCROLLBARS_OUTSIDE_INSET
10957     *
10958     * @attr ref android.R.styleable#View_scrollbarStyle
10959     */
10960    @ViewDebug.ExportedProperty(mapping = {
10961            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10962            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10963            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10964            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10965    })
10966    public int getScrollBarStyle() {
10967        return mViewFlags & SCROLLBARS_STYLE_MASK;
10968    }
10969
10970    /**
10971     * <p>Compute the horizontal range that the horizontal scrollbar
10972     * represents.</p>
10973     *
10974     * <p>The range is expressed in arbitrary units that must be the same as the
10975     * units used by {@link #computeHorizontalScrollExtent()} and
10976     * {@link #computeHorizontalScrollOffset()}.</p>
10977     *
10978     * <p>The default range is the drawing width of this view.</p>
10979     *
10980     * @return the total horizontal range represented by the horizontal
10981     *         scrollbar
10982     *
10983     * @see #computeHorizontalScrollExtent()
10984     * @see #computeHorizontalScrollOffset()
10985     * @see android.widget.ScrollBarDrawable
10986     */
10987    protected int computeHorizontalScrollRange() {
10988        return getWidth();
10989    }
10990
10991    /**
10992     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10993     * within the horizontal range. This value is used to compute the position
10994     * of the thumb within the scrollbar's track.</p>
10995     *
10996     * <p>The range is expressed in arbitrary units that must be the same as the
10997     * units used by {@link #computeHorizontalScrollRange()} and
10998     * {@link #computeHorizontalScrollExtent()}.</p>
10999     *
11000     * <p>The default offset is the scroll offset of this view.</p>
11001     *
11002     * @return the horizontal offset of the scrollbar's thumb
11003     *
11004     * @see #computeHorizontalScrollRange()
11005     * @see #computeHorizontalScrollExtent()
11006     * @see android.widget.ScrollBarDrawable
11007     */
11008    protected int computeHorizontalScrollOffset() {
11009        return mScrollX;
11010    }
11011
11012    /**
11013     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11014     * within the horizontal range. This value is used to compute the length
11015     * of the thumb within the scrollbar's track.</p>
11016     *
11017     * <p>The range is expressed in arbitrary units that must be the same as the
11018     * units used by {@link #computeHorizontalScrollRange()} and
11019     * {@link #computeHorizontalScrollOffset()}.</p>
11020     *
11021     * <p>The default extent is the drawing width of this view.</p>
11022     *
11023     * @return the horizontal extent of the scrollbar's thumb
11024     *
11025     * @see #computeHorizontalScrollRange()
11026     * @see #computeHorizontalScrollOffset()
11027     * @see android.widget.ScrollBarDrawable
11028     */
11029    protected int computeHorizontalScrollExtent() {
11030        return getWidth();
11031    }
11032
11033    /**
11034     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11035     *
11036     * <p>The range is expressed in arbitrary units that must be the same as the
11037     * units used by {@link #computeVerticalScrollExtent()} and
11038     * {@link #computeVerticalScrollOffset()}.</p>
11039     *
11040     * @return the total vertical range represented by the vertical scrollbar
11041     *
11042     * <p>The default range is the drawing height of this view.</p>
11043     *
11044     * @see #computeVerticalScrollExtent()
11045     * @see #computeVerticalScrollOffset()
11046     * @see android.widget.ScrollBarDrawable
11047     */
11048    protected int computeVerticalScrollRange() {
11049        return getHeight();
11050    }
11051
11052    /**
11053     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11054     * within the horizontal range. This value is used to compute the position
11055     * of the thumb within the scrollbar's track.</p>
11056     *
11057     * <p>The range is expressed in arbitrary units that must be the same as the
11058     * units used by {@link #computeVerticalScrollRange()} and
11059     * {@link #computeVerticalScrollExtent()}.</p>
11060     *
11061     * <p>The default offset is the scroll offset of this view.</p>
11062     *
11063     * @return the vertical offset of the scrollbar's thumb
11064     *
11065     * @see #computeVerticalScrollRange()
11066     * @see #computeVerticalScrollExtent()
11067     * @see android.widget.ScrollBarDrawable
11068     */
11069    protected int computeVerticalScrollOffset() {
11070        return mScrollY;
11071    }
11072
11073    /**
11074     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11075     * within the vertical range. This value is used to compute the length
11076     * of the thumb within the scrollbar's track.</p>
11077     *
11078     * <p>The range is expressed in arbitrary units that must be the same as the
11079     * units used by {@link #computeVerticalScrollRange()} and
11080     * {@link #computeVerticalScrollOffset()}.</p>
11081     *
11082     * <p>The default extent is the drawing height of this view.</p>
11083     *
11084     * @return the vertical extent of the scrollbar's thumb
11085     *
11086     * @see #computeVerticalScrollRange()
11087     * @see #computeVerticalScrollOffset()
11088     * @see android.widget.ScrollBarDrawable
11089     */
11090    protected int computeVerticalScrollExtent() {
11091        return getHeight();
11092    }
11093
11094    /**
11095     * Check if this view can be scrolled horizontally in a certain direction.
11096     *
11097     * @param direction Negative to check scrolling left, positive to check scrolling right.
11098     * @return true if this view can be scrolled in the specified direction, false otherwise.
11099     */
11100    public boolean canScrollHorizontally(int direction) {
11101        final int offset = computeHorizontalScrollOffset();
11102        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11103        if (range == 0) return false;
11104        if (direction < 0) {
11105            return offset > 0;
11106        } else {
11107            return offset < range - 1;
11108        }
11109    }
11110
11111    /**
11112     * Check if this view can be scrolled vertically in a certain direction.
11113     *
11114     * @param direction Negative to check scrolling up, positive to check scrolling down.
11115     * @return true if this view can be scrolled in the specified direction, false otherwise.
11116     */
11117    public boolean canScrollVertically(int direction) {
11118        final int offset = computeVerticalScrollOffset();
11119        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11120        if (range == 0) return false;
11121        if (direction < 0) {
11122            return offset > 0;
11123        } else {
11124            return offset < range - 1;
11125        }
11126    }
11127
11128    /**
11129     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11130     * scrollbars are painted only if they have been awakened first.</p>
11131     *
11132     * @param canvas the canvas on which to draw the scrollbars
11133     *
11134     * @see #awakenScrollBars(int)
11135     */
11136    protected final void onDrawScrollBars(Canvas canvas) {
11137        // scrollbars are drawn only when the animation is running
11138        final ScrollabilityCache cache = mScrollCache;
11139        if (cache != null) {
11140
11141            int state = cache.state;
11142
11143            if (state == ScrollabilityCache.OFF) {
11144                return;
11145            }
11146
11147            boolean invalidate = false;
11148
11149            if (state == ScrollabilityCache.FADING) {
11150                // We're fading -- get our fade interpolation
11151                if (cache.interpolatorValues == null) {
11152                    cache.interpolatorValues = new float[1];
11153                }
11154
11155                float[] values = cache.interpolatorValues;
11156
11157                // Stops the animation if we're done
11158                if (cache.scrollBarInterpolator.timeToValues(values) ==
11159                        Interpolator.Result.FREEZE_END) {
11160                    cache.state = ScrollabilityCache.OFF;
11161                } else {
11162                    cache.scrollBar.setAlpha(Math.round(values[0]));
11163                }
11164
11165                // This will make the scroll bars inval themselves after
11166                // drawing. We only want this when we're fading so that
11167                // we prevent excessive redraws
11168                invalidate = true;
11169            } else {
11170                // We're just on -- but we may have been fading before so
11171                // reset alpha
11172                cache.scrollBar.setAlpha(255);
11173            }
11174
11175
11176            final int viewFlags = mViewFlags;
11177
11178            final boolean drawHorizontalScrollBar =
11179                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11180            final boolean drawVerticalScrollBar =
11181                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11182                && !isVerticalScrollBarHidden();
11183
11184            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11185                final int width = mRight - mLeft;
11186                final int height = mBottom - mTop;
11187
11188                final ScrollBarDrawable scrollBar = cache.scrollBar;
11189
11190                final int scrollX = mScrollX;
11191                final int scrollY = mScrollY;
11192                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11193
11194                int left, top, right, bottom;
11195
11196                if (drawHorizontalScrollBar) {
11197                    int size = scrollBar.getSize(false);
11198                    if (size <= 0) {
11199                        size = cache.scrollBarSize;
11200                    }
11201
11202                    scrollBar.setParameters(computeHorizontalScrollRange(),
11203                                            computeHorizontalScrollOffset(),
11204                                            computeHorizontalScrollExtent(), false);
11205                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11206                            getVerticalScrollbarWidth() : 0;
11207                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11208                    left = scrollX + (mPaddingLeft & inside);
11209                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11210                    bottom = top + size;
11211                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11212                    if (invalidate) {
11213                        invalidate(left, top, right, bottom);
11214                    }
11215                }
11216
11217                if (drawVerticalScrollBar) {
11218                    int size = scrollBar.getSize(true);
11219                    if (size <= 0) {
11220                        size = cache.scrollBarSize;
11221                    }
11222
11223                    scrollBar.setParameters(computeVerticalScrollRange(),
11224                                            computeVerticalScrollOffset(),
11225                                            computeVerticalScrollExtent(), true);
11226                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11227                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11228                        verticalScrollbarPosition = isLayoutRtl() ?
11229                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11230                    }
11231                    switch (verticalScrollbarPosition) {
11232                        default:
11233                        case SCROLLBAR_POSITION_RIGHT:
11234                            left = scrollX + width - size - (mUserPaddingRight & inside);
11235                            break;
11236                        case SCROLLBAR_POSITION_LEFT:
11237                            left = scrollX + (mUserPaddingLeft & inside);
11238                            break;
11239                    }
11240                    top = scrollY + (mPaddingTop & inside);
11241                    right = left + size;
11242                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11243                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11244                    if (invalidate) {
11245                        invalidate(left, top, right, bottom);
11246                    }
11247                }
11248            }
11249        }
11250    }
11251
11252    /**
11253     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11254     * FastScroller is visible.
11255     * @return whether to temporarily hide the vertical scrollbar
11256     * @hide
11257     */
11258    protected boolean isVerticalScrollBarHidden() {
11259        return false;
11260    }
11261
11262    /**
11263     * <p>Draw the horizontal scrollbar if
11264     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11265     *
11266     * @param canvas the canvas on which to draw the scrollbar
11267     * @param scrollBar the scrollbar's drawable
11268     *
11269     * @see #isHorizontalScrollBarEnabled()
11270     * @see #computeHorizontalScrollRange()
11271     * @see #computeHorizontalScrollExtent()
11272     * @see #computeHorizontalScrollOffset()
11273     * @see android.widget.ScrollBarDrawable
11274     * @hide
11275     */
11276    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11277            int l, int t, int r, int b) {
11278        scrollBar.setBounds(l, t, r, b);
11279        scrollBar.draw(canvas);
11280    }
11281
11282    /**
11283     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11284     * returns true.</p>
11285     *
11286     * @param canvas the canvas on which to draw the scrollbar
11287     * @param scrollBar the scrollbar's drawable
11288     *
11289     * @see #isVerticalScrollBarEnabled()
11290     * @see #computeVerticalScrollRange()
11291     * @see #computeVerticalScrollExtent()
11292     * @see #computeVerticalScrollOffset()
11293     * @see android.widget.ScrollBarDrawable
11294     * @hide
11295     */
11296    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11297            int l, int t, int r, int b) {
11298        scrollBar.setBounds(l, t, r, b);
11299        scrollBar.draw(canvas);
11300    }
11301
11302    /**
11303     * Implement this to do your drawing.
11304     *
11305     * @param canvas the canvas on which the background will be drawn
11306     */
11307    protected void onDraw(Canvas canvas) {
11308    }
11309
11310    /*
11311     * Caller is responsible for calling requestLayout if necessary.
11312     * (This allows addViewInLayout to not request a new layout.)
11313     */
11314    void assignParent(ViewParent parent) {
11315        if (mParent == null) {
11316            mParent = parent;
11317        } else if (parent == null) {
11318            mParent = null;
11319        } else {
11320            throw new RuntimeException("view " + this + " being added, but"
11321                    + " it already has a parent");
11322        }
11323    }
11324
11325    /**
11326     * This is called when the view is attached to a window.  At this point it
11327     * has a Surface and will start drawing.  Note that this function is
11328     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11329     * however it may be called any time before the first onDraw -- including
11330     * before or after {@link #onMeasure(int, int)}.
11331     *
11332     * @see #onDetachedFromWindow()
11333     */
11334    protected void onAttachedToWindow() {
11335        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11336            mParent.requestTransparentRegion(this);
11337        }
11338
11339        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11340            initialAwakenScrollBars();
11341            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11342        }
11343
11344        jumpDrawablesToCurrentState();
11345
11346        resolveRtlProperties();
11347
11348        clearAccessibilityFocus();
11349        if (isFocused()) {
11350            InputMethodManager imm = InputMethodManager.peekInstance();
11351            imm.focusIn(this);
11352        }
11353
11354        if (mAttachInfo != null && mDisplayList != null) {
11355            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11356        }
11357    }
11358
11359    void resolveRtlProperties() {
11360        // Order is important here: LayoutDirection MUST be resolved first...
11361        resolveLayoutDirection();
11362        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11363        resolvePadding();
11364        resolveLayoutParams();
11365        resolveTextDirection();
11366        resolveTextAlignment();
11367        resolveDrawables();
11368    }
11369
11370    /**
11371     * @see #onScreenStateChanged(int)
11372     */
11373    void dispatchScreenStateChanged(int screenState) {
11374        onScreenStateChanged(screenState);
11375    }
11376
11377    /**
11378     * This method is called whenever the state of the screen this view is
11379     * attached to changes. A state change will usually occurs when the screen
11380     * turns on or off (whether it happens automatically or the user does it
11381     * manually.)
11382     *
11383     * @param screenState The new state of the screen. Can be either
11384     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11385     */
11386    public void onScreenStateChanged(int screenState) {
11387    }
11388
11389    /**
11390     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11391     */
11392    private boolean hasRtlSupport() {
11393        return mContext.getApplicationInfo().hasRtlSupport();
11394    }
11395
11396    /**
11397     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11398     * that the parent directionality can and will be resolved before its children.
11399     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11400     */
11401    public void resolveLayoutDirection() {
11402        // Clear any previous layout direction resolution
11403        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11404
11405        if (hasRtlSupport()) {
11406            // Set resolved depending on layout direction
11407            switch (getLayoutDirection()) {
11408                case LAYOUT_DIRECTION_INHERIT:
11409                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11410                    // later to get the correct resolved value
11411                    if (!canResolveLayoutDirection()) return;
11412
11413                    ViewGroup viewGroup = ((ViewGroup) mParent);
11414
11415                    // We cannot resolve yet on the parent too. LTR is by default and let the
11416                    // resolution happen again later
11417                    if (!viewGroup.canResolveLayoutDirection()) return;
11418
11419                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11420                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11421                    }
11422                    break;
11423                case LAYOUT_DIRECTION_RTL:
11424                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11425                    break;
11426                case LAYOUT_DIRECTION_LOCALE:
11427                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11428                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11429                    }
11430                    break;
11431                default:
11432                    // Nothing to do, LTR by default
11433            }
11434        }
11435
11436        // Set to resolved
11437        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11438        onResolvedLayoutDirectionChanged();
11439    }
11440
11441    /**
11442     * Called when layout direction has been resolved.
11443     *
11444     * The default implementation does nothing.
11445     */
11446    public void onResolvedLayoutDirectionChanged() {
11447    }
11448
11449    /**
11450     * Return if padding has been resolved
11451     */
11452    boolean isPaddingResolved() {
11453        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) != 0;
11454    }
11455
11456    /**
11457     * Resolve padding depending on layout direction.
11458     */
11459    public void resolvePadding() {
11460        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11461        if (targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport()) {
11462            // Pre Jelly Bean MR1 case (compatibility mode) OR no RTL support case:
11463            // left / right padding are used if defined. If they are not defined and start / end
11464            // padding are defined (e.g. in Frameworks resources), then we use start / end and
11465            // resolve them as left / right (layout direction is not taken into account).
11466            if (!mUserPaddingLeftDefined && mUserPaddingStart != UNDEFINED_PADDING) {
11467                mUserPaddingLeft = mUserPaddingStart;
11468            }
11469            if (!mUserPaddingRightDefined && mUserPaddingEnd != UNDEFINED_PADDING) {
11470                mUserPaddingRight = mUserPaddingEnd;
11471            }
11472
11473            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11474
11475            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11476                    mUserPaddingBottom);
11477        } else {
11478            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
11479            // If start / end padding are defined, they will be resolved (hence overriding) to
11480            // left / right or right / left depending on the resolved layout direction.
11481            // If start / end padding are not defined, use the left / right ones.
11482            int resolvedLayoutDirection = getResolvedLayoutDirection();
11483            switch (resolvedLayoutDirection) {
11484                case LAYOUT_DIRECTION_RTL:
11485                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11486                        mUserPaddingRight = mUserPaddingStart;
11487                    }
11488                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11489                        mUserPaddingLeft = mUserPaddingEnd;
11490                    }
11491                    break;
11492                case LAYOUT_DIRECTION_LTR:
11493                default:
11494                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11495                        mUserPaddingLeft = mUserPaddingStart;
11496                    }
11497                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11498                        mUserPaddingRight = mUserPaddingEnd;
11499                    }
11500            }
11501
11502            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11503
11504            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11505                    mUserPaddingBottom);
11506            onPaddingChanged(resolvedLayoutDirection);
11507        }
11508
11509        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
11510    }
11511
11512    /**
11513     * Resolve padding depending on the layout direction. Subclasses that care about
11514     * padding resolution should override this method. The default implementation does
11515     * nothing.
11516     *
11517     * @param layoutDirection the direction of the layout
11518     *
11519     * @see {@link #LAYOUT_DIRECTION_LTR}
11520     * @see {@link #LAYOUT_DIRECTION_RTL}
11521     */
11522    public void onPaddingChanged(int layoutDirection) {
11523    }
11524
11525    /**
11526     * Check if layout direction resolution can be done.
11527     *
11528     * @return true if layout direction resolution can be done otherwise return false.
11529     */
11530    public boolean canResolveLayoutDirection() {
11531        switch (getLayoutDirection()) {
11532            case LAYOUT_DIRECTION_INHERIT:
11533                return (mParent != null) && (mParent instanceof ViewGroup);
11534            default:
11535                return true;
11536        }
11537    }
11538
11539    /**
11540     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11541     * when reset is done.
11542     */
11543    public void resetResolvedLayoutDirection() {
11544        // Reset the current resolved bits
11545        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11546        onResolvedLayoutDirectionReset();
11547        // Reset also the text direction
11548        resetResolvedTextDirection();
11549    }
11550
11551    /**
11552     * Called during reset of resolved layout direction.
11553     *
11554     * Subclasses need to override this method to clear cached information that depends on the
11555     * resolved layout direction, or to inform child views that inherit their layout direction.
11556     *
11557     * The default implementation does nothing.
11558     */
11559    public void onResolvedLayoutDirectionReset() {
11560    }
11561
11562    /**
11563     * Check if a Locale uses an RTL script.
11564     *
11565     * @param locale Locale to check
11566     * @return true if the Locale uses an RTL script.
11567     */
11568    protected static boolean isLayoutDirectionRtl(Locale locale) {
11569        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11570    }
11571
11572    /**
11573     * This is called when the view is detached from a window.  At this point it
11574     * no longer has a surface for drawing.
11575     *
11576     * @see #onAttachedToWindow()
11577     */
11578    protected void onDetachedFromWindow() {
11579        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
11580
11581        removeUnsetPressCallback();
11582        removeLongPressCallback();
11583        removePerformClickCallback();
11584        removeSendViewScrolledAccessibilityEventCallback();
11585
11586        destroyDrawingCache();
11587
11588        destroyLayer(false);
11589
11590        if (mAttachInfo != null) {
11591            if (mDisplayList != null) {
11592                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11593            }
11594            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11595        } else {
11596            // Should never happen
11597            clearDisplayList();
11598        }
11599
11600        mCurrentAnimation = null;
11601
11602        resetResolvedLayoutDirection();
11603        resetResolvedTextAlignment();
11604        resetAccessibilityStateChanged();
11605        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
11606    }
11607
11608    /**
11609     * @return The number of times this view has been attached to a window
11610     */
11611    protected int getWindowAttachCount() {
11612        return mWindowAttachCount;
11613    }
11614
11615    /**
11616     * Retrieve a unique token identifying the window this view is attached to.
11617     * @return Return the window's token for use in
11618     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11619     */
11620    public IBinder getWindowToken() {
11621        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11622    }
11623
11624    /**
11625     * Retrieve a unique token identifying the top-level "real" window of
11626     * the window that this view is attached to.  That is, this is like
11627     * {@link #getWindowToken}, except if the window this view in is a panel
11628     * window (attached to another containing window), then the token of
11629     * the containing window is returned instead.
11630     *
11631     * @return Returns the associated window token, either
11632     * {@link #getWindowToken()} or the containing window's token.
11633     */
11634    public IBinder getApplicationWindowToken() {
11635        AttachInfo ai = mAttachInfo;
11636        if (ai != null) {
11637            IBinder appWindowToken = ai.mPanelParentWindowToken;
11638            if (appWindowToken == null) {
11639                appWindowToken = ai.mWindowToken;
11640            }
11641            return appWindowToken;
11642        }
11643        return null;
11644    }
11645
11646    /**
11647     * Gets the logical display to which the view's window has been attached.
11648     *
11649     * @return The logical display, or null if the view is not currently attached to a window.
11650     */
11651    public Display getDisplay() {
11652        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
11653    }
11654
11655    /**
11656     * Retrieve private session object this view hierarchy is using to
11657     * communicate with the window manager.
11658     * @return the session object to communicate with the window manager
11659     */
11660    /*package*/ IWindowSession getWindowSession() {
11661        return mAttachInfo != null ? mAttachInfo.mSession : null;
11662    }
11663
11664    /**
11665     * @param info the {@link android.view.View.AttachInfo} to associated with
11666     *        this view
11667     */
11668    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11669        //System.out.println("Attached! " + this);
11670        mAttachInfo = info;
11671        mWindowAttachCount++;
11672        // We will need to evaluate the drawable state at least once.
11673        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
11674        if (mFloatingTreeObserver != null) {
11675            info.mTreeObserver.merge(mFloatingTreeObserver);
11676            mFloatingTreeObserver = null;
11677        }
11678        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
11679            mAttachInfo.mScrollContainers.add(this);
11680            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
11681        }
11682        performCollectViewAttributes(mAttachInfo, visibility);
11683        onAttachedToWindow();
11684
11685        ListenerInfo li = mListenerInfo;
11686        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11687                li != null ? li.mOnAttachStateChangeListeners : null;
11688        if (listeners != null && listeners.size() > 0) {
11689            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11690            // perform the dispatching. The iterator is a safe guard against listeners that
11691            // could mutate the list by calling the various add/remove methods. This prevents
11692            // the array from being modified while we iterate it.
11693            for (OnAttachStateChangeListener listener : listeners) {
11694                listener.onViewAttachedToWindow(this);
11695            }
11696        }
11697
11698        int vis = info.mWindowVisibility;
11699        if (vis != GONE) {
11700            onWindowVisibilityChanged(vis);
11701        }
11702        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
11703            // If nobody has evaluated the drawable state yet, then do it now.
11704            refreshDrawableState();
11705        }
11706    }
11707
11708    void dispatchDetachedFromWindow() {
11709        AttachInfo info = mAttachInfo;
11710        if (info != null) {
11711            int vis = info.mWindowVisibility;
11712            if (vis != GONE) {
11713                onWindowVisibilityChanged(GONE);
11714            }
11715        }
11716
11717        onDetachedFromWindow();
11718
11719        ListenerInfo li = mListenerInfo;
11720        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11721                li != null ? li.mOnAttachStateChangeListeners : null;
11722        if (listeners != null && listeners.size() > 0) {
11723            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11724            // perform the dispatching. The iterator is a safe guard against listeners that
11725            // could mutate the list by calling the various add/remove methods. This prevents
11726            // the array from being modified while we iterate it.
11727            for (OnAttachStateChangeListener listener : listeners) {
11728                listener.onViewDetachedFromWindow(this);
11729            }
11730        }
11731
11732        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
11733            mAttachInfo.mScrollContainers.remove(this);
11734            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
11735        }
11736
11737        mAttachInfo = null;
11738    }
11739
11740    /**
11741     * Store this view hierarchy's frozen state into the given container.
11742     *
11743     * @param container The SparseArray in which to save the view's state.
11744     *
11745     * @see #restoreHierarchyState(android.util.SparseArray)
11746     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11747     * @see #onSaveInstanceState()
11748     */
11749    public void saveHierarchyState(SparseArray<Parcelable> container) {
11750        dispatchSaveInstanceState(container);
11751    }
11752
11753    /**
11754     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11755     * this view and its children. May be overridden to modify how freezing happens to a
11756     * view's children; for example, some views may want to not store state for their children.
11757     *
11758     * @param container The SparseArray in which to save the view's state.
11759     *
11760     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11761     * @see #saveHierarchyState(android.util.SparseArray)
11762     * @see #onSaveInstanceState()
11763     */
11764    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11765        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11766            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
11767            Parcelable state = onSaveInstanceState();
11768            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
11769                throw new IllegalStateException(
11770                        "Derived class did not call super.onSaveInstanceState()");
11771            }
11772            if (state != null) {
11773                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11774                // + ": " + state);
11775                container.put(mID, state);
11776            }
11777        }
11778    }
11779
11780    /**
11781     * Hook allowing a view to generate a representation of its internal state
11782     * that can later be used to create a new instance with that same state.
11783     * This state should only contain information that is not persistent or can
11784     * not be reconstructed later. For example, you will never store your
11785     * current position on screen because that will be computed again when a
11786     * new instance of the view is placed in its view hierarchy.
11787     * <p>
11788     * Some examples of things you may store here: the current cursor position
11789     * in a text view (but usually not the text itself since that is stored in a
11790     * content provider or other persistent storage), the currently selected
11791     * item in a list view.
11792     *
11793     * @return Returns a Parcelable object containing the view's current dynamic
11794     *         state, or null if there is nothing interesting to save. The
11795     *         default implementation returns null.
11796     * @see #onRestoreInstanceState(android.os.Parcelable)
11797     * @see #saveHierarchyState(android.util.SparseArray)
11798     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11799     * @see #setSaveEnabled(boolean)
11800     */
11801    protected Parcelable onSaveInstanceState() {
11802        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
11803        return BaseSavedState.EMPTY_STATE;
11804    }
11805
11806    /**
11807     * Restore this view hierarchy's frozen state from the given container.
11808     *
11809     * @param container The SparseArray which holds previously frozen states.
11810     *
11811     * @see #saveHierarchyState(android.util.SparseArray)
11812     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11813     * @see #onRestoreInstanceState(android.os.Parcelable)
11814     */
11815    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11816        dispatchRestoreInstanceState(container);
11817    }
11818
11819    /**
11820     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11821     * state for this view and its children. May be overridden to modify how restoring
11822     * happens to a view's children; for example, some views may want to not store state
11823     * for their children.
11824     *
11825     * @param container The SparseArray which holds previously saved state.
11826     *
11827     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11828     * @see #restoreHierarchyState(android.util.SparseArray)
11829     * @see #onRestoreInstanceState(android.os.Parcelable)
11830     */
11831    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11832        if (mID != NO_ID) {
11833            Parcelable state = container.get(mID);
11834            if (state != null) {
11835                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11836                // + ": " + state);
11837                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
11838                onRestoreInstanceState(state);
11839                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
11840                    throw new IllegalStateException(
11841                            "Derived class did not call super.onRestoreInstanceState()");
11842                }
11843            }
11844        }
11845    }
11846
11847    /**
11848     * Hook allowing a view to re-apply a representation of its internal state that had previously
11849     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11850     * null state.
11851     *
11852     * @param state The frozen state that had previously been returned by
11853     *        {@link #onSaveInstanceState}.
11854     *
11855     * @see #onSaveInstanceState()
11856     * @see #restoreHierarchyState(android.util.SparseArray)
11857     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11858     */
11859    protected void onRestoreInstanceState(Parcelable state) {
11860        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
11861        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11862            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11863                    + "received " + state.getClass().toString() + " instead. This usually happens "
11864                    + "when two views of different type have the same id in the same hierarchy. "
11865                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11866                    + "other views do not use the same id.");
11867        }
11868    }
11869
11870    /**
11871     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11872     *
11873     * @return the drawing start time in milliseconds
11874     */
11875    public long getDrawingTime() {
11876        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11877    }
11878
11879    /**
11880     * <p>Enables or disables the duplication of the parent's state into this view. When
11881     * duplication is enabled, this view gets its drawable state from its parent rather
11882     * than from its own internal properties.</p>
11883     *
11884     * <p>Note: in the current implementation, setting this property to true after the
11885     * view was added to a ViewGroup might have no effect at all. This property should
11886     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11887     *
11888     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11889     * property is enabled, an exception will be thrown.</p>
11890     *
11891     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11892     * parent, these states should not be affected by this method.</p>
11893     *
11894     * @param enabled True to enable duplication of the parent's drawable state, false
11895     *                to disable it.
11896     *
11897     * @see #getDrawableState()
11898     * @see #isDuplicateParentStateEnabled()
11899     */
11900    public void setDuplicateParentStateEnabled(boolean enabled) {
11901        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11902    }
11903
11904    /**
11905     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11906     *
11907     * @return True if this view's drawable state is duplicated from the parent,
11908     *         false otherwise
11909     *
11910     * @see #getDrawableState()
11911     * @see #setDuplicateParentStateEnabled(boolean)
11912     */
11913    public boolean isDuplicateParentStateEnabled() {
11914        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11915    }
11916
11917    /**
11918     * <p>Specifies the type of layer backing this view. The layer can be
11919     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11920     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11921     *
11922     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11923     * instance that controls how the layer is composed on screen. The following
11924     * properties of the paint are taken into account when composing the layer:</p>
11925     * <ul>
11926     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11927     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11928     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11929     * </ul>
11930     *
11931     * <p>If this view has an alpha value set to < 1.0 by calling
11932     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11933     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11934     * equivalent to setting a hardware layer on this view and providing a paint with
11935     * the desired alpha value.</p>
11936     *
11937     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11938     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11939     * for more information on when and how to use layers.</p>
11940     *
11941     * @param layerType The type of layer to use with this view, must be one of
11942     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11943     *        {@link #LAYER_TYPE_HARDWARE}
11944     * @param paint The paint used to compose the layer. This argument is optional
11945     *        and can be null. It is ignored when the layer type is
11946     *        {@link #LAYER_TYPE_NONE}
11947     *
11948     * @see #getLayerType()
11949     * @see #LAYER_TYPE_NONE
11950     * @see #LAYER_TYPE_SOFTWARE
11951     * @see #LAYER_TYPE_HARDWARE
11952     * @see #setAlpha(float)
11953     *
11954     * @attr ref android.R.styleable#View_layerType
11955     */
11956    public void setLayerType(int layerType, Paint paint) {
11957        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11958            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11959                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11960        }
11961
11962        if (layerType == mLayerType) {
11963            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11964                mLayerPaint = paint == null ? new Paint() : paint;
11965                invalidateParentCaches();
11966                invalidate(true);
11967            }
11968            return;
11969        }
11970
11971        // Destroy any previous software drawing cache if needed
11972        switch (mLayerType) {
11973            case LAYER_TYPE_HARDWARE:
11974                destroyLayer(false);
11975                // fall through - non-accelerated views may use software layer mechanism instead
11976            case LAYER_TYPE_SOFTWARE:
11977                destroyDrawingCache();
11978                break;
11979            default:
11980                break;
11981        }
11982
11983        mLayerType = layerType;
11984        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11985        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11986        mLocalDirtyRect = layerDisabled ? null : new Rect();
11987
11988        invalidateParentCaches();
11989        invalidate(true);
11990    }
11991
11992    /**
11993     * Updates the {@link Paint} object used with the current layer (used only if the current
11994     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
11995     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
11996     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
11997     * ensure that the view gets redrawn immediately.
11998     *
11999     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12000     * instance that controls how the layer is composed on screen. The following
12001     * properties of the paint are taken into account when composing the layer:</p>
12002     * <ul>
12003     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12004     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12005     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12006     * </ul>
12007     *
12008     * <p>If this view has an alpha value set to < 1.0 by calling
12009     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12010     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12011     * equivalent to setting a hardware layer on this view and providing a paint with
12012     * the desired alpha value.</p>
12013     *
12014     * @param paint The paint used to compose the layer. This argument is optional
12015     *        and can be null. It is ignored when the layer type is
12016     *        {@link #LAYER_TYPE_NONE}
12017     *
12018     * @see #setLayerType(int, android.graphics.Paint)
12019     */
12020    public void setLayerPaint(Paint paint) {
12021        int layerType = getLayerType();
12022        if (layerType != LAYER_TYPE_NONE) {
12023            mLayerPaint = paint == null ? new Paint() : paint;
12024            if (layerType == LAYER_TYPE_HARDWARE) {
12025                HardwareLayer layer = getHardwareLayer();
12026                if (layer != null) {
12027                    layer.setLayerPaint(paint);
12028                }
12029                invalidateViewProperty(false, false);
12030            } else {
12031                invalidate();
12032            }
12033        }
12034    }
12035
12036    /**
12037     * Indicates whether this view has a static layer. A view with layer type
12038     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12039     * dynamic.
12040     */
12041    boolean hasStaticLayer() {
12042        return true;
12043    }
12044
12045    /**
12046     * Indicates what type of layer is currently associated with this view. By default
12047     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12048     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12049     * for more information on the different types of layers.
12050     *
12051     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12052     *         {@link #LAYER_TYPE_HARDWARE}
12053     *
12054     * @see #setLayerType(int, android.graphics.Paint)
12055     * @see #buildLayer()
12056     * @see #LAYER_TYPE_NONE
12057     * @see #LAYER_TYPE_SOFTWARE
12058     * @see #LAYER_TYPE_HARDWARE
12059     */
12060    public int getLayerType() {
12061        return mLayerType;
12062    }
12063
12064    /**
12065     * Forces this view's layer to be created and this view to be rendered
12066     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12067     * invoking this method will have no effect.
12068     *
12069     * This method can for instance be used to render a view into its layer before
12070     * starting an animation. If this view is complex, rendering into the layer
12071     * before starting the animation will avoid skipping frames.
12072     *
12073     * @throws IllegalStateException If this view is not attached to a window
12074     *
12075     * @see #setLayerType(int, android.graphics.Paint)
12076     */
12077    public void buildLayer() {
12078        if (mLayerType == LAYER_TYPE_NONE) return;
12079
12080        if (mAttachInfo == null) {
12081            throw new IllegalStateException("This view must be attached to a window first");
12082        }
12083
12084        switch (mLayerType) {
12085            case LAYER_TYPE_HARDWARE:
12086                if (mAttachInfo.mHardwareRenderer != null &&
12087                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12088                        mAttachInfo.mHardwareRenderer.validate()) {
12089                    getHardwareLayer();
12090                }
12091                break;
12092            case LAYER_TYPE_SOFTWARE:
12093                buildDrawingCache(true);
12094                break;
12095        }
12096    }
12097
12098    /**
12099     * <p>Returns a hardware layer that can be used to draw this view again
12100     * without executing its draw method.</p>
12101     *
12102     * @return A HardwareLayer ready to render, or null if an error occurred.
12103     */
12104    HardwareLayer getHardwareLayer() {
12105        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12106                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12107            return null;
12108        }
12109
12110        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12111
12112        final int width = mRight - mLeft;
12113        final int height = mBottom - mTop;
12114
12115        if (width == 0 || height == 0) {
12116            return null;
12117        }
12118
12119        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12120            if (mHardwareLayer == null) {
12121                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12122                        width, height, isOpaque());
12123                mLocalDirtyRect.set(0, 0, width, height);
12124            } else {
12125                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12126                    mHardwareLayer.resize(width, height);
12127                    mLocalDirtyRect.set(0, 0, width, height);
12128                }
12129
12130                // This should not be necessary but applications that change
12131                // the parameters of their background drawable without calling
12132                // this.setBackground(Drawable) can leave the view in a bad state
12133                // (for instance isOpaque() returns true, but the background is
12134                // not opaque.)
12135                computeOpaqueFlags();
12136
12137                final boolean opaque = isOpaque();
12138                if (mHardwareLayer.isOpaque() != opaque) {
12139                    mHardwareLayer.setOpaque(opaque);
12140                    mLocalDirtyRect.set(0, 0, width, height);
12141                }
12142            }
12143
12144            // The layer is not valid if the underlying GPU resources cannot be allocated
12145            if (!mHardwareLayer.isValid()) {
12146                return null;
12147            }
12148            mHardwareLayer.setLayerPaint(mLayerPaint);
12149
12150            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12151            mLocalDirtyRect.setEmpty();
12152        }
12153
12154        return mHardwareLayer;
12155    }
12156
12157    /**
12158     * Destroys this View's hardware layer if possible.
12159     *
12160     * @return True if the layer was destroyed, false otherwise.
12161     *
12162     * @see #setLayerType(int, android.graphics.Paint)
12163     * @see #LAYER_TYPE_HARDWARE
12164     */
12165    boolean destroyLayer(boolean valid) {
12166        if (mHardwareLayer != null) {
12167            AttachInfo info = mAttachInfo;
12168            if (info != null && info.mHardwareRenderer != null &&
12169                    info.mHardwareRenderer.isEnabled() &&
12170                    (valid || info.mHardwareRenderer.validate())) {
12171                mHardwareLayer.destroy();
12172                mHardwareLayer = null;
12173
12174                invalidate(true);
12175                invalidateParentCaches();
12176            }
12177            return true;
12178        }
12179        return false;
12180    }
12181
12182    /**
12183     * Destroys all hardware rendering resources. This method is invoked
12184     * when the system needs to reclaim resources. Upon execution of this
12185     * method, you should free any OpenGL resources created by the view.
12186     *
12187     * Note: you <strong>must</strong> call
12188     * <code>super.destroyHardwareResources()</code> when overriding
12189     * this method.
12190     *
12191     * @hide
12192     */
12193    protected void destroyHardwareResources() {
12194        destroyLayer(true);
12195    }
12196
12197    /**
12198     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12199     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12200     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12201     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12202     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12203     * null.</p>
12204     *
12205     * <p>Enabling the drawing cache is similar to
12206     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12207     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12208     * drawing cache has no effect on rendering because the system uses a different mechanism
12209     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12210     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12211     * for information on how to enable software and hardware layers.</p>
12212     *
12213     * <p>This API can be used to manually generate
12214     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12215     * {@link #getDrawingCache()}.</p>
12216     *
12217     * @param enabled true to enable the drawing cache, false otherwise
12218     *
12219     * @see #isDrawingCacheEnabled()
12220     * @see #getDrawingCache()
12221     * @see #buildDrawingCache()
12222     * @see #setLayerType(int, android.graphics.Paint)
12223     */
12224    public void setDrawingCacheEnabled(boolean enabled) {
12225        mCachingFailed = false;
12226        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12227    }
12228
12229    /**
12230     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12231     *
12232     * @return true if the drawing cache is enabled
12233     *
12234     * @see #setDrawingCacheEnabled(boolean)
12235     * @see #getDrawingCache()
12236     */
12237    @ViewDebug.ExportedProperty(category = "drawing")
12238    public boolean isDrawingCacheEnabled() {
12239        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12240    }
12241
12242    /**
12243     * Debugging utility which recursively outputs the dirty state of a view and its
12244     * descendants.
12245     *
12246     * @hide
12247     */
12248    @SuppressWarnings({"UnusedDeclaration"})
12249    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12250        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12251                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12252                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12253                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12254        if (clear) {
12255            mPrivateFlags &= clearMask;
12256        }
12257        if (this instanceof ViewGroup) {
12258            ViewGroup parent = (ViewGroup) this;
12259            final int count = parent.getChildCount();
12260            for (int i = 0; i < count; i++) {
12261                final View child = parent.getChildAt(i);
12262                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12263            }
12264        }
12265    }
12266
12267    /**
12268     * This method is used by ViewGroup to cause its children to restore or recreate their
12269     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12270     * to recreate its own display list, which would happen if it went through the normal
12271     * draw/dispatchDraw mechanisms.
12272     *
12273     * @hide
12274     */
12275    protected void dispatchGetDisplayList() {}
12276
12277    /**
12278     * A view that is not attached or hardware accelerated cannot create a display list.
12279     * This method checks these conditions and returns the appropriate result.
12280     *
12281     * @return true if view has the ability to create a display list, false otherwise.
12282     *
12283     * @hide
12284     */
12285    public boolean canHaveDisplayList() {
12286        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12287    }
12288
12289    /**
12290     * @return The HardwareRenderer associated with that view or null if hardware rendering
12291     * is not supported or this this has not been attached to a window.
12292     *
12293     * @hide
12294     */
12295    public HardwareRenderer getHardwareRenderer() {
12296        if (mAttachInfo != null) {
12297            return mAttachInfo.mHardwareRenderer;
12298        }
12299        return null;
12300    }
12301
12302    /**
12303     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12304     * Otherwise, the same display list will be returned (after having been rendered into
12305     * along the way, depending on the invalidation state of the view).
12306     *
12307     * @param displayList The previous version of this displayList, could be null.
12308     * @param isLayer Whether the requester of the display list is a layer. If so,
12309     * the view will avoid creating a layer inside the resulting display list.
12310     * @return A new or reused DisplayList object.
12311     */
12312    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12313        if (!canHaveDisplayList()) {
12314            return null;
12315        }
12316
12317        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12318                displayList == null || !displayList.isValid() ||
12319                (!isLayer && mRecreateDisplayList))) {
12320            // Don't need to recreate the display list, just need to tell our
12321            // children to restore/recreate theirs
12322            if (displayList != null && displayList.isValid() &&
12323                    !isLayer && !mRecreateDisplayList) {
12324                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12325                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12326                dispatchGetDisplayList();
12327
12328                return displayList;
12329            }
12330
12331            if (!isLayer) {
12332                // If we got here, we're recreating it. Mark it as such to ensure that
12333                // we copy in child display lists into ours in drawChild()
12334                mRecreateDisplayList = true;
12335            }
12336            if (displayList == null) {
12337                final String name = getClass().getSimpleName();
12338                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12339                // If we're creating a new display list, make sure our parent gets invalidated
12340                // since they will need to recreate their display list to account for this
12341                // new child display list.
12342                invalidateParentCaches();
12343            }
12344
12345            boolean caching = false;
12346            final HardwareCanvas canvas = displayList.start();
12347            int width = mRight - mLeft;
12348            int height = mBottom - mTop;
12349
12350            try {
12351                canvas.setViewport(width, height);
12352                // The dirty rect should always be null for a display list
12353                canvas.onPreDraw(null);
12354                int layerType = getLayerType();
12355                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12356                    if (layerType == LAYER_TYPE_HARDWARE) {
12357                        final HardwareLayer layer = getHardwareLayer();
12358                        if (layer != null && layer.isValid()) {
12359                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12360                        } else {
12361                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12362                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12363                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12364                        }
12365                        caching = true;
12366                    } else {
12367                        buildDrawingCache(true);
12368                        Bitmap cache = getDrawingCache(true);
12369                        if (cache != null) {
12370                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12371                            caching = true;
12372                        }
12373                    }
12374                } else {
12375
12376                    computeScroll();
12377
12378                    canvas.translate(-mScrollX, -mScrollY);
12379                    if (!isLayer) {
12380                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12381                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12382                    }
12383
12384                    // Fast path for layouts with no backgrounds
12385                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12386                        dispatchDraw(canvas);
12387                    } else {
12388                        draw(canvas);
12389                    }
12390                }
12391            } finally {
12392                canvas.onPostDraw();
12393
12394                displayList.end();
12395                displayList.setCaching(caching);
12396                if (isLayer) {
12397                    displayList.setLeftTopRightBottom(0, 0, width, height);
12398                } else {
12399                    setDisplayListProperties(displayList);
12400                }
12401            }
12402        } else if (!isLayer) {
12403            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12404            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12405        }
12406
12407        return displayList;
12408    }
12409
12410    /**
12411     * Get the DisplayList for the HardwareLayer
12412     *
12413     * @param layer The HardwareLayer whose DisplayList we want
12414     * @return A DisplayList fopr the specified HardwareLayer
12415     */
12416    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12417        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12418        layer.setDisplayList(displayList);
12419        return displayList;
12420    }
12421
12422
12423    /**
12424     * <p>Returns a display list that can be used to draw this view again
12425     * without executing its draw method.</p>
12426     *
12427     * @return A DisplayList ready to replay, or null if caching is not enabled.
12428     *
12429     * @hide
12430     */
12431    public DisplayList getDisplayList() {
12432        mDisplayList = getDisplayList(mDisplayList, false);
12433        return mDisplayList;
12434    }
12435
12436    private void clearDisplayList() {
12437        if (mDisplayList != null) {
12438            mDisplayList.invalidate();
12439            mDisplayList.clear();
12440        }
12441    }
12442
12443    /**
12444     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12445     *
12446     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12447     *
12448     * @see #getDrawingCache(boolean)
12449     */
12450    public Bitmap getDrawingCache() {
12451        return getDrawingCache(false);
12452    }
12453
12454    /**
12455     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12456     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12457     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12458     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12459     * request the drawing cache by calling this method and draw it on screen if the
12460     * returned bitmap is not null.</p>
12461     *
12462     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12463     * this method will create a bitmap of the same size as this view. Because this bitmap
12464     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12465     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12466     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12467     * size than the view. This implies that your application must be able to handle this
12468     * size.</p>
12469     *
12470     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12471     *        the current density of the screen when the application is in compatibility
12472     *        mode.
12473     *
12474     * @return A bitmap representing this view or null if cache is disabled.
12475     *
12476     * @see #setDrawingCacheEnabled(boolean)
12477     * @see #isDrawingCacheEnabled()
12478     * @see #buildDrawingCache(boolean)
12479     * @see #destroyDrawingCache()
12480     */
12481    public Bitmap getDrawingCache(boolean autoScale) {
12482        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12483            return null;
12484        }
12485        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12486            buildDrawingCache(autoScale);
12487        }
12488        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12489    }
12490
12491    /**
12492     * <p>Frees the resources used by the drawing cache. If you call
12493     * {@link #buildDrawingCache()} manually without calling
12494     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12495     * should cleanup the cache with this method afterwards.</p>
12496     *
12497     * @see #setDrawingCacheEnabled(boolean)
12498     * @see #buildDrawingCache()
12499     * @see #getDrawingCache()
12500     */
12501    public void destroyDrawingCache() {
12502        if (mDrawingCache != null) {
12503            mDrawingCache.recycle();
12504            mDrawingCache = null;
12505        }
12506        if (mUnscaledDrawingCache != null) {
12507            mUnscaledDrawingCache.recycle();
12508            mUnscaledDrawingCache = null;
12509        }
12510    }
12511
12512    /**
12513     * Setting a solid background color for the drawing cache's bitmaps will improve
12514     * performance and memory usage. Note, though that this should only be used if this
12515     * view will always be drawn on top of a solid color.
12516     *
12517     * @param color The background color to use for the drawing cache's bitmap
12518     *
12519     * @see #setDrawingCacheEnabled(boolean)
12520     * @see #buildDrawingCache()
12521     * @see #getDrawingCache()
12522     */
12523    public void setDrawingCacheBackgroundColor(int color) {
12524        if (color != mDrawingCacheBackgroundColor) {
12525            mDrawingCacheBackgroundColor = color;
12526            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12527        }
12528    }
12529
12530    /**
12531     * @see #setDrawingCacheBackgroundColor(int)
12532     *
12533     * @return The background color to used for the drawing cache's bitmap
12534     */
12535    public int getDrawingCacheBackgroundColor() {
12536        return mDrawingCacheBackgroundColor;
12537    }
12538
12539    /**
12540     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12541     *
12542     * @see #buildDrawingCache(boolean)
12543     */
12544    public void buildDrawingCache() {
12545        buildDrawingCache(false);
12546    }
12547
12548    /**
12549     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12550     *
12551     * <p>If you call {@link #buildDrawingCache()} manually without calling
12552     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12553     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12554     *
12555     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12556     * this method will create a bitmap of the same size as this view. Because this bitmap
12557     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12558     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12559     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12560     * size than the view. This implies that your application must be able to handle this
12561     * size.</p>
12562     *
12563     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12564     * you do not need the drawing cache bitmap, calling this method will increase memory
12565     * usage and cause the view to be rendered in software once, thus negatively impacting
12566     * performance.</p>
12567     *
12568     * @see #getDrawingCache()
12569     * @see #destroyDrawingCache()
12570     */
12571    public void buildDrawingCache(boolean autoScale) {
12572        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
12573                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12574            mCachingFailed = false;
12575
12576            int width = mRight - mLeft;
12577            int height = mBottom - mTop;
12578
12579            final AttachInfo attachInfo = mAttachInfo;
12580            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12581
12582            if (autoScale && scalingRequired) {
12583                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12584                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12585            }
12586
12587            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12588            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12589            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12590
12591            final int projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
12592            final int drawingCacheSize =
12593                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
12594            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
12595                if (width > 0 && height > 0) {
12596                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
12597                            + projectedBitmapSize + " bytes, only "
12598                            + drawingCacheSize + " available");
12599                }
12600                destroyDrawingCache();
12601                mCachingFailed = true;
12602                return;
12603            }
12604
12605            boolean clear = true;
12606            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12607
12608            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12609                Bitmap.Config quality;
12610                if (!opaque) {
12611                    // Never pick ARGB_4444 because it looks awful
12612                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12613                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12614                        case DRAWING_CACHE_QUALITY_AUTO:
12615                            quality = Bitmap.Config.ARGB_8888;
12616                            break;
12617                        case DRAWING_CACHE_QUALITY_LOW:
12618                            quality = Bitmap.Config.ARGB_8888;
12619                            break;
12620                        case DRAWING_CACHE_QUALITY_HIGH:
12621                            quality = Bitmap.Config.ARGB_8888;
12622                            break;
12623                        default:
12624                            quality = Bitmap.Config.ARGB_8888;
12625                            break;
12626                    }
12627                } else {
12628                    // Optimization for translucent windows
12629                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12630                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12631                }
12632
12633                // Try to cleanup memory
12634                if (bitmap != null) bitmap.recycle();
12635
12636                try {
12637                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
12638                            width, height, quality);
12639                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12640                    if (autoScale) {
12641                        mDrawingCache = bitmap;
12642                    } else {
12643                        mUnscaledDrawingCache = bitmap;
12644                    }
12645                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12646                } catch (OutOfMemoryError e) {
12647                    // If there is not enough memory to create the bitmap cache, just
12648                    // ignore the issue as bitmap caches are not required to draw the
12649                    // view hierarchy
12650                    if (autoScale) {
12651                        mDrawingCache = null;
12652                    } else {
12653                        mUnscaledDrawingCache = null;
12654                    }
12655                    mCachingFailed = true;
12656                    return;
12657                }
12658
12659                clear = drawingCacheBackgroundColor != 0;
12660            }
12661
12662            Canvas canvas;
12663            if (attachInfo != null) {
12664                canvas = attachInfo.mCanvas;
12665                if (canvas == null) {
12666                    canvas = new Canvas();
12667                }
12668                canvas.setBitmap(bitmap);
12669                // Temporarily clobber the cached Canvas in case one of our children
12670                // is also using a drawing cache. Without this, the children would
12671                // steal the canvas by attaching their own bitmap to it and bad, bad
12672                // thing would happen (invisible views, corrupted drawings, etc.)
12673                attachInfo.mCanvas = null;
12674            } else {
12675                // This case should hopefully never or seldom happen
12676                canvas = new Canvas(bitmap);
12677            }
12678
12679            if (clear) {
12680                bitmap.eraseColor(drawingCacheBackgroundColor);
12681            }
12682
12683            computeScroll();
12684            final int restoreCount = canvas.save();
12685
12686            if (autoScale && scalingRequired) {
12687                final float scale = attachInfo.mApplicationScale;
12688                canvas.scale(scale, scale);
12689            }
12690
12691            canvas.translate(-mScrollX, -mScrollY);
12692
12693            mPrivateFlags |= PFLAG_DRAWN;
12694            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12695                    mLayerType != LAYER_TYPE_NONE) {
12696                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
12697            }
12698
12699            // Fast path for layouts with no backgrounds
12700            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12701                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12702                dispatchDraw(canvas);
12703            } else {
12704                draw(canvas);
12705            }
12706
12707            canvas.restoreToCount(restoreCount);
12708            canvas.setBitmap(null);
12709
12710            if (attachInfo != null) {
12711                // Restore the cached Canvas for our siblings
12712                attachInfo.mCanvas = canvas;
12713            }
12714        }
12715    }
12716
12717    /**
12718     * Create a snapshot of the view into a bitmap.  We should probably make
12719     * some form of this public, but should think about the API.
12720     */
12721    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12722        int width = mRight - mLeft;
12723        int height = mBottom - mTop;
12724
12725        final AttachInfo attachInfo = mAttachInfo;
12726        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12727        width = (int) ((width * scale) + 0.5f);
12728        height = (int) ((height * scale) + 0.5f);
12729
12730        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
12731                width > 0 ? width : 1, height > 0 ? height : 1, quality);
12732        if (bitmap == null) {
12733            throw new OutOfMemoryError();
12734        }
12735
12736        Resources resources = getResources();
12737        if (resources != null) {
12738            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12739        }
12740
12741        Canvas canvas;
12742        if (attachInfo != null) {
12743            canvas = attachInfo.mCanvas;
12744            if (canvas == null) {
12745                canvas = new Canvas();
12746            }
12747            canvas.setBitmap(bitmap);
12748            // Temporarily clobber the cached Canvas in case one of our children
12749            // is also using a drawing cache. Without this, the children would
12750            // steal the canvas by attaching their own bitmap to it and bad, bad
12751            // things would happen (invisible views, corrupted drawings, etc.)
12752            attachInfo.mCanvas = null;
12753        } else {
12754            // This case should hopefully never or seldom happen
12755            canvas = new Canvas(bitmap);
12756        }
12757
12758        if ((backgroundColor & 0xff000000) != 0) {
12759            bitmap.eraseColor(backgroundColor);
12760        }
12761
12762        computeScroll();
12763        final int restoreCount = canvas.save();
12764        canvas.scale(scale, scale);
12765        canvas.translate(-mScrollX, -mScrollY);
12766
12767        // Temporarily remove the dirty mask
12768        int flags = mPrivateFlags;
12769        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12770
12771        // Fast path for layouts with no backgrounds
12772        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12773            dispatchDraw(canvas);
12774        } else {
12775            draw(canvas);
12776        }
12777
12778        mPrivateFlags = flags;
12779
12780        canvas.restoreToCount(restoreCount);
12781        canvas.setBitmap(null);
12782
12783        if (attachInfo != null) {
12784            // Restore the cached Canvas for our siblings
12785            attachInfo.mCanvas = canvas;
12786        }
12787
12788        return bitmap;
12789    }
12790
12791    /**
12792     * Indicates whether this View is currently in edit mode. A View is usually
12793     * in edit mode when displayed within a developer tool. For instance, if
12794     * this View is being drawn by a visual user interface builder, this method
12795     * should return true.
12796     *
12797     * Subclasses should check the return value of this method to provide
12798     * different behaviors if their normal behavior might interfere with the
12799     * host environment. For instance: the class spawns a thread in its
12800     * constructor, the drawing code relies on device-specific features, etc.
12801     *
12802     * This method is usually checked in the drawing code of custom widgets.
12803     *
12804     * @return True if this View is in edit mode, false otherwise.
12805     */
12806    public boolean isInEditMode() {
12807        return false;
12808    }
12809
12810    /**
12811     * If the View draws content inside its padding and enables fading edges,
12812     * it needs to support padding offsets. Padding offsets are added to the
12813     * fading edges to extend the length of the fade so that it covers pixels
12814     * drawn inside the padding.
12815     *
12816     * Subclasses of this class should override this method if they need
12817     * to draw content inside the padding.
12818     *
12819     * @return True if padding offset must be applied, false otherwise.
12820     *
12821     * @see #getLeftPaddingOffset()
12822     * @see #getRightPaddingOffset()
12823     * @see #getTopPaddingOffset()
12824     * @see #getBottomPaddingOffset()
12825     *
12826     * @since CURRENT
12827     */
12828    protected boolean isPaddingOffsetRequired() {
12829        return false;
12830    }
12831
12832    /**
12833     * Amount by which to extend the left fading region. Called only when
12834     * {@link #isPaddingOffsetRequired()} returns true.
12835     *
12836     * @return The left padding offset in pixels.
12837     *
12838     * @see #isPaddingOffsetRequired()
12839     *
12840     * @since CURRENT
12841     */
12842    protected int getLeftPaddingOffset() {
12843        return 0;
12844    }
12845
12846    /**
12847     * Amount by which to extend the right fading region. Called only when
12848     * {@link #isPaddingOffsetRequired()} returns true.
12849     *
12850     * @return The right padding offset in pixels.
12851     *
12852     * @see #isPaddingOffsetRequired()
12853     *
12854     * @since CURRENT
12855     */
12856    protected int getRightPaddingOffset() {
12857        return 0;
12858    }
12859
12860    /**
12861     * Amount by which to extend the top fading region. Called only when
12862     * {@link #isPaddingOffsetRequired()} returns true.
12863     *
12864     * @return The top padding offset in pixels.
12865     *
12866     * @see #isPaddingOffsetRequired()
12867     *
12868     * @since CURRENT
12869     */
12870    protected int getTopPaddingOffset() {
12871        return 0;
12872    }
12873
12874    /**
12875     * Amount by which to extend the bottom fading region. Called only when
12876     * {@link #isPaddingOffsetRequired()} returns true.
12877     *
12878     * @return The bottom padding offset in pixels.
12879     *
12880     * @see #isPaddingOffsetRequired()
12881     *
12882     * @since CURRENT
12883     */
12884    protected int getBottomPaddingOffset() {
12885        return 0;
12886    }
12887
12888    /**
12889     * @hide
12890     * @param offsetRequired
12891     */
12892    protected int getFadeTop(boolean offsetRequired) {
12893        int top = mPaddingTop;
12894        if (offsetRequired) top += getTopPaddingOffset();
12895        return top;
12896    }
12897
12898    /**
12899     * @hide
12900     * @param offsetRequired
12901     */
12902    protected int getFadeHeight(boolean offsetRequired) {
12903        int padding = mPaddingTop;
12904        if (offsetRequired) padding += getTopPaddingOffset();
12905        return mBottom - mTop - mPaddingBottom - padding;
12906    }
12907
12908    /**
12909     * <p>Indicates whether this view is attached to a hardware accelerated
12910     * window or not.</p>
12911     *
12912     * <p>Even if this method returns true, it does not mean that every call
12913     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12914     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12915     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12916     * window is hardware accelerated,
12917     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12918     * return false, and this method will return true.</p>
12919     *
12920     * @return True if the view is attached to a window and the window is
12921     *         hardware accelerated; false in any other case.
12922     */
12923    public boolean isHardwareAccelerated() {
12924        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12925    }
12926
12927    /**
12928     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12929     * case of an active Animation being run on the view.
12930     */
12931    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12932            Animation a, boolean scalingRequired) {
12933        Transformation invalidationTransform;
12934        final int flags = parent.mGroupFlags;
12935        final boolean initialized = a.isInitialized();
12936        if (!initialized) {
12937            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12938            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12939            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
12940            onAnimationStart();
12941        }
12942
12943        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12944        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12945            if (parent.mInvalidationTransformation == null) {
12946                parent.mInvalidationTransformation = new Transformation();
12947            }
12948            invalidationTransform = parent.mInvalidationTransformation;
12949            a.getTransformation(drawingTime, invalidationTransform, 1f);
12950        } else {
12951            invalidationTransform = parent.mChildTransformation;
12952        }
12953
12954        if (more) {
12955            if (!a.willChangeBounds()) {
12956                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
12957                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
12958                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
12959                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
12960                    // The child need to draw an animation, potentially offscreen, so
12961                    // make sure we do not cancel invalidate requests
12962                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
12963                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12964                }
12965            } else {
12966                if (parent.mInvalidateRegion == null) {
12967                    parent.mInvalidateRegion = new RectF();
12968                }
12969                final RectF region = parent.mInvalidateRegion;
12970                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12971                        invalidationTransform);
12972
12973                // The child need to draw an animation, potentially offscreen, so
12974                // make sure we do not cancel invalidate requests
12975                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
12976
12977                final int left = mLeft + (int) region.left;
12978                final int top = mTop + (int) region.top;
12979                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12980                        top + (int) (region.height() + .5f));
12981            }
12982        }
12983        return more;
12984    }
12985
12986    /**
12987     * This method is called by getDisplayList() when a display list is created or re-rendered.
12988     * It sets or resets the current value of all properties on that display list (resetting is
12989     * necessary when a display list is being re-created, because we need to make sure that
12990     * previously-set transform values
12991     */
12992    void setDisplayListProperties(DisplayList displayList) {
12993        if (displayList != null) {
12994            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12995            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12996            if (mParent instanceof ViewGroup) {
12997                displayList.setClipChildren(
12998                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12999            }
13000            float alpha = 1;
13001            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13002                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13003                ViewGroup parentVG = (ViewGroup) mParent;
13004                final boolean hasTransform =
13005                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13006                if (hasTransform) {
13007                    Transformation transform = parentVG.mChildTransformation;
13008                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13009                    if (transformType != Transformation.TYPE_IDENTITY) {
13010                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13011                            alpha = transform.getAlpha();
13012                        }
13013                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13014                            displayList.setStaticMatrix(transform.getMatrix());
13015                        }
13016                    }
13017                }
13018            }
13019            if (mTransformationInfo != null) {
13020                alpha *= mTransformationInfo.mAlpha;
13021                if (alpha < 1) {
13022                    final int multipliedAlpha = (int) (255 * alpha);
13023                    if (onSetAlpha(multipliedAlpha)) {
13024                        alpha = 1;
13025                    }
13026                }
13027                displayList.setTransformationInfo(alpha,
13028                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13029                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13030                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13031                        mTransformationInfo.mScaleY);
13032                if (mTransformationInfo.mCamera == null) {
13033                    mTransformationInfo.mCamera = new Camera();
13034                    mTransformationInfo.matrix3D = new Matrix();
13035                }
13036                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13037                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13038                    displayList.setPivotX(getPivotX());
13039                    displayList.setPivotY(getPivotY());
13040                }
13041            } else if (alpha < 1) {
13042                displayList.setAlpha(alpha);
13043            }
13044        }
13045    }
13046
13047    /**
13048     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13049     * This draw() method is an implementation detail and is not intended to be overridden or
13050     * to be called from anywhere else other than ViewGroup.drawChild().
13051     */
13052    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13053        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13054        boolean more = false;
13055        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13056        final int flags = parent.mGroupFlags;
13057
13058        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13059            parent.mChildTransformation.clear();
13060            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13061        }
13062
13063        Transformation transformToApply = null;
13064        boolean concatMatrix = false;
13065
13066        boolean scalingRequired = false;
13067        boolean caching;
13068        int layerType = getLayerType();
13069
13070        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13071        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13072                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13073            caching = true;
13074            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13075            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13076        } else {
13077            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13078        }
13079
13080        final Animation a = getAnimation();
13081        if (a != null) {
13082            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13083            concatMatrix = a.willChangeTransformationMatrix();
13084            if (concatMatrix) {
13085                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13086            }
13087            transformToApply = parent.mChildTransformation;
13088        } else {
13089            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == PFLAG3_VIEW_IS_ANIMATING_TRANSFORM &&
13090                    mDisplayList != null) {
13091                // No longer animating: clear out old animation matrix
13092                mDisplayList.setAnimationMatrix(null);
13093                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13094            }
13095            if (!useDisplayListProperties &&
13096                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13097                final boolean hasTransform =
13098                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13099                if (hasTransform) {
13100                    final int transformType = parent.mChildTransformation.getTransformationType();
13101                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13102                            parent.mChildTransformation : null;
13103                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13104                }
13105            }
13106        }
13107
13108        concatMatrix |= !childHasIdentityMatrix;
13109
13110        // Sets the flag as early as possible to allow draw() implementations
13111        // to call invalidate() successfully when doing animations
13112        mPrivateFlags |= PFLAG_DRAWN;
13113
13114        if (!concatMatrix &&
13115                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13116                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13117                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13118                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13119            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13120            return more;
13121        }
13122        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13123
13124        if (hardwareAccelerated) {
13125            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13126            // retain the flag's value temporarily in the mRecreateDisplayList flag
13127            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13128            mPrivateFlags &= ~PFLAG_INVALIDATED;
13129        }
13130
13131        DisplayList displayList = null;
13132        Bitmap cache = null;
13133        boolean hasDisplayList = false;
13134        if (caching) {
13135            if (!hardwareAccelerated) {
13136                if (layerType != LAYER_TYPE_NONE) {
13137                    layerType = LAYER_TYPE_SOFTWARE;
13138                    buildDrawingCache(true);
13139                }
13140                cache = getDrawingCache(true);
13141            } else {
13142                switch (layerType) {
13143                    case LAYER_TYPE_SOFTWARE:
13144                        if (useDisplayListProperties) {
13145                            hasDisplayList = canHaveDisplayList();
13146                        } else {
13147                            buildDrawingCache(true);
13148                            cache = getDrawingCache(true);
13149                        }
13150                        break;
13151                    case LAYER_TYPE_HARDWARE:
13152                        if (useDisplayListProperties) {
13153                            hasDisplayList = canHaveDisplayList();
13154                        }
13155                        break;
13156                    case LAYER_TYPE_NONE:
13157                        // Delay getting the display list until animation-driven alpha values are
13158                        // set up and possibly passed on to the view
13159                        hasDisplayList = canHaveDisplayList();
13160                        break;
13161                }
13162            }
13163        }
13164        useDisplayListProperties &= hasDisplayList;
13165        if (useDisplayListProperties) {
13166            displayList = getDisplayList();
13167            if (!displayList.isValid()) {
13168                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13169                // to getDisplayList(), the display list will be marked invalid and we should not
13170                // try to use it again.
13171                displayList = null;
13172                hasDisplayList = false;
13173                useDisplayListProperties = false;
13174            }
13175        }
13176
13177        int sx = 0;
13178        int sy = 0;
13179        if (!hasDisplayList) {
13180            computeScroll();
13181            sx = mScrollX;
13182            sy = mScrollY;
13183        }
13184
13185        final boolean hasNoCache = cache == null || hasDisplayList;
13186        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13187                layerType != LAYER_TYPE_HARDWARE;
13188
13189        int restoreTo = -1;
13190        if (!useDisplayListProperties || transformToApply != null) {
13191            restoreTo = canvas.save();
13192        }
13193        if (offsetForScroll) {
13194            canvas.translate(mLeft - sx, mTop - sy);
13195        } else {
13196            if (!useDisplayListProperties) {
13197                canvas.translate(mLeft, mTop);
13198            }
13199            if (scalingRequired) {
13200                if (useDisplayListProperties) {
13201                    // TODO: Might not need this if we put everything inside the DL
13202                    restoreTo = canvas.save();
13203                }
13204                // mAttachInfo cannot be null, otherwise scalingRequired == false
13205                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13206                canvas.scale(scale, scale);
13207            }
13208        }
13209
13210        float alpha = useDisplayListProperties ? 1 : getAlpha();
13211        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13212                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13213            if (transformToApply != null || !childHasIdentityMatrix) {
13214                int transX = 0;
13215                int transY = 0;
13216
13217                if (offsetForScroll) {
13218                    transX = -sx;
13219                    transY = -sy;
13220                }
13221
13222                if (transformToApply != null) {
13223                    if (concatMatrix) {
13224                        if (useDisplayListProperties) {
13225                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13226                        } else {
13227                            // Undo the scroll translation, apply the transformation matrix,
13228                            // then redo the scroll translate to get the correct result.
13229                            canvas.translate(-transX, -transY);
13230                            canvas.concat(transformToApply.getMatrix());
13231                            canvas.translate(transX, transY);
13232                        }
13233                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13234                    }
13235
13236                    float transformAlpha = transformToApply.getAlpha();
13237                    if (transformAlpha < 1) {
13238                        alpha *= transformAlpha;
13239                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13240                    }
13241                }
13242
13243                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13244                    canvas.translate(-transX, -transY);
13245                    canvas.concat(getMatrix());
13246                    canvas.translate(transX, transY);
13247                }
13248            }
13249
13250            // Deal with alpha if it is or used to be <1
13251            if (alpha < 1 ||
13252                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13253                if (alpha < 1) {
13254                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13255                } else {
13256                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13257                }
13258                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13259                if (hasNoCache) {
13260                    final int multipliedAlpha = (int) (255 * alpha);
13261                    if (!onSetAlpha(multipliedAlpha)) {
13262                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13263                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13264                                layerType != LAYER_TYPE_NONE) {
13265                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13266                        }
13267                        if (useDisplayListProperties) {
13268                            displayList.setAlpha(alpha * getAlpha());
13269                        } else  if (layerType == LAYER_TYPE_NONE) {
13270                            final int scrollX = hasDisplayList ? 0 : sx;
13271                            final int scrollY = hasDisplayList ? 0 : sy;
13272                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13273                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13274                        }
13275                    } else {
13276                        // Alpha is handled by the child directly, clobber the layer's alpha
13277                        mPrivateFlags |= PFLAG_ALPHA_SET;
13278                    }
13279                }
13280            }
13281        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13282            onSetAlpha(255);
13283            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13284        }
13285
13286        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13287                !useDisplayListProperties) {
13288            if (offsetForScroll) {
13289                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13290            } else {
13291                if (!scalingRequired || cache == null) {
13292                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13293                } else {
13294                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13295                }
13296            }
13297        }
13298
13299        if (!useDisplayListProperties && hasDisplayList) {
13300            displayList = getDisplayList();
13301            if (!displayList.isValid()) {
13302                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13303                // to getDisplayList(), the display list will be marked invalid and we should not
13304                // try to use it again.
13305                displayList = null;
13306                hasDisplayList = false;
13307            }
13308        }
13309
13310        if (hasNoCache) {
13311            boolean layerRendered = false;
13312            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13313                final HardwareLayer layer = getHardwareLayer();
13314                if (layer != null && layer.isValid()) {
13315                    mLayerPaint.setAlpha((int) (alpha * 255));
13316                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13317                    layerRendered = true;
13318                } else {
13319                    final int scrollX = hasDisplayList ? 0 : sx;
13320                    final int scrollY = hasDisplayList ? 0 : sy;
13321                    canvas.saveLayer(scrollX, scrollY,
13322                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13323                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13324                }
13325            }
13326
13327            if (!layerRendered) {
13328                if (!hasDisplayList) {
13329                    // Fast path for layouts with no backgrounds
13330                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13331                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13332                        dispatchDraw(canvas);
13333                    } else {
13334                        draw(canvas);
13335                    }
13336                } else {
13337                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13338                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13339                }
13340            }
13341        } else if (cache != null) {
13342            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13343            Paint cachePaint;
13344
13345            if (layerType == LAYER_TYPE_NONE) {
13346                cachePaint = parent.mCachePaint;
13347                if (cachePaint == null) {
13348                    cachePaint = new Paint();
13349                    cachePaint.setDither(false);
13350                    parent.mCachePaint = cachePaint;
13351                }
13352                if (alpha < 1) {
13353                    cachePaint.setAlpha((int) (alpha * 255));
13354                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13355                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13356                    cachePaint.setAlpha(255);
13357                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13358                }
13359            } else {
13360                cachePaint = mLayerPaint;
13361                cachePaint.setAlpha((int) (alpha * 255));
13362            }
13363            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13364        }
13365
13366        if (restoreTo >= 0) {
13367            canvas.restoreToCount(restoreTo);
13368        }
13369
13370        if (a != null && !more) {
13371            if (!hardwareAccelerated && !a.getFillAfter()) {
13372                onSetAlpha(255);
13373            }
13374            parent.finishAnimatingView(this, a);
13375        }
13376
13377        if (more && hardwareAccelerated) {
13378            // invalidation is the trigger to recreate display lists, so if we're using
13379            // display lists to render, force an invalidate to allow the animation to
13380            // continue drawing another frame
13381            parent.invalidate(true);
13382            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13383                // alpha animations should cause the child to recreate its display list
13384                invalidate(true);
13385            }
13386        }
13387
13388        mRecreateDisplayList = false;
13389
13390        return more;
13391    }
13392
13393    /**
13394     * Manually render this view (and all of its children) to the given Canvas.
13395     * The view must have already done a full layout before this function is
13396     * called.  When implementing a view, implement
13397     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13398     * If you do need to override this method, call the superclass version.
13399     *
13400     * @param canvas The Canvas to which the View is rendered.
13401     */
13402    public void draw(Canvas canvas) {
13403        final int privateFlags = mPrivateFlags;
13404        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13405                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13406        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13407
13408        /*
13409         * Draw traversal performs several drawing steps which must be executed
13410         * in the appropriate order:
13411         *
13412         *      1. Draw the background
13413         *      2. If necessary, save the canvas' layers to prepare for fading
13414         *      3. Draw view's content
13415         *      4. Draw children
13416         *      5. If necessary, draw the fading edges and restore layers
13417         *      6. Draw decorations (scrollbars for instance)
13418         */
13419
13420        // Step 1, draw the background, if needed
13421        int saveCount;
13422
13423        if (!dirtyOpaque) {
13424            final Drawable background = mBackground;
13425            if (background != null) {
13426                final int scrollX = mScrollX;
13427                final int scrollY = mScrollY;
13428
13429                if (mBackgroundSizeChanged) {
13430                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13431                    mBackgroundSizeChanged = false;
13432                }
13433
13434                if ((scrollX | scrollY) == 0) {
13435                    background.draw(canvas);
13436                } else {
13437                    canvas.translate(scrollX, scrollY);
13438                    background.draw(canvas);
13439                    canvas.translate(-scrollX, -scrollY);
13440                }
13441            }
13442        }
13443
13444        // skip step 2 & 5 if possible (common case)
13445        final int viewFlags = mViewFlags;
13446        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13447        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13448        if (!verticalEdges && !horizontalEdges) {
13449            // Step 3, draw the content
13450            if (!dirtyOpaque) onDraw(canvas);
13451
13452            // Step 4, draw the children
13453            dispatchDraw(canvas);
13454
13455            // Step 6, draw decorations (scrollbars)
13456            onDrawScrollBars(canvas);
13457
13458            // we're done...
13459            return;
13460        }
13461
13462        /*
13463         * Here we do the full fledged routine...
13464         * (this is an uncommon case where speed matters less,
13465         * this is why we repeat some of the tests that have been
13466         * done above)
13467         */
13468
13469        boolean drawTop = false;
13470        boolean drawBottom = false;
13471        boolean drawLeft = false;
13472        boolean drawRight = false;
13473
13474        float topFadeStrength = 0.0f;
13475        float bottomFadeStrength = 0.0f;
13476        float leftFadeStrength = 0.0f;
13477        float rightFadeStrength = 0.0f;
13478
13479        // Step 2, save the canvas' layers
13480        int paddingLeft = mPaddingLeft;
13481
13482        final boolean offsetRequired = isPaddingOffsetRequired();
13483        if (offsetRequired) {
13484            paddingLeft += getLeftPaddingOffset();
13485        }
13486
13487        int left = mScrollX + paddingLeft;
13488        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13489        int top = mScrollY + getFadeTop(offsetRequired);
13490        int bottom = top + getFadeHeight(offsetRequired);
13491
13492        if (offsetRequired) {
13493            right += getRightPaddingOffset();
13494            bottom += getBottomPaddingOffset();
13495        }
13496
13497        final ScrollabilityCache scrollabilityCache = mScrollCache;
13498        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13499        int length = (int) fadeHeight;
13500
13501        // clip the fade length if top and bottom fades overlap
13502        // overlapping fades produce odd-looking artifacts
13503        if (verticalEdges && (top + length > bottom - length)) {
13504            length = (bottom - top) / 2;
13505        }
13506
13507        // also clip horizontal fades if necessary
13508        if (horizontalEdges && (left + length > right - length)) {
13509            length = (right - left) / 2;
13510        }
13511
13512        if (verticalEdges) {
13513            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13514            drawTop = topFadeStrength * fadeHeight > 1.0f;
13515            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13516            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13517        }
13518
13519        if (horizontalEdges) {
13520            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13521            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13522            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13523            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13524        }
13525
13526        saveCount = canvas.getSaveCount();
13527
13528        int solidColor = getSolidColor();
13529        if (solidColor == 0) {
13530            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13531
13532            if (drawTop) {
13533                canvas.saveLayer(left, top, right, top + length, null, flags);
13534            }
13535
13536            if (drawBottom) {
13537                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13538            }
13539
13540            if (drawLeft) {
13541                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13542            }
13543
13544            if (drawRight) {
13545                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13546            }
13547        } else {
13548            scrollabilityCache.setFadeColor(solidColor);
13549        }
13550
13551        // Step 3, draw the content
13552        if (!dirtyOpaque) onDraw(canvas);
13553
13554        // Step 4, draw the children
13555        dispatchDraw(canvas);
13556
13557        // Step 5, draw the fade effect and restore layers
13558        final Paint p = scrollabilityCache.paint;
13559        final Matrix matrix = scrollabilityCache.matrix;
13560        final Shader fade = scrollabilityCache.shader;
13561
13562        if (drawTop) {
13563            matrix.setScale(1, fadeHeight * topFadeStrength);
13564            matrix.postTranslate(left, top);
13565            fade.setLocalMatrix(matrix);
13566            canvas.drawRect(left, top, right, top + length, p);
13567        }
13568
13569        if (drawBottom) {
13570            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13571            matrix.postRotate(180);
13572            matrix.postTranslate(left, bottom);
13573            fade.setLocalMatrix(matrix);
13574            canvas.drawRect(left, bottom - length, right, bottom, p);
13575        }
13576
13577        if (drawLeft) {
13578            matrix.setScale(1, fadeHeight * leftFadeStrength);
13579            matrix.postRotate(-90);
13580            matrix.postTranslate(left, top);
13581            fade.setLocalMatrix(matrix);
13582            canvas.drawRect(left, top, left + length, bottom, p);
13583        }
13584
13585        if (drawRight) {
13586            matrix.setScale(1, fadeHeight * rightFadeStrength);
13587            matrix.postRotate(90);
13588            matrix.postTranslate(right, top);
13589            fade.setLocalMatrix(matrix);
13590            canvas.drawRect(right - length, top, right, bottom, p);
13591        }
13592
13593        canvas.restoreToCount(saveCount);
13594
13595        // Step 6, draw decorations (scrollbars)
13596        onDrawScrollBars(canvas);
13597    }
13598
13599    /**
13600     * Override this if your view is known to always be drawn on top of a solid color background,
13601     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13602     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13603     * should be set to 0xFF.
13604     *
13605     * @see #setVerticalFadingEdgeEnabled(boolean)
13606     * @see #setHorizontalFadingEdgeEnabled(boolean)
13607     *
13608     * @return The known solid color background for this view, or 0 if the color may vary
13609     */
13610    @ViewDebug.ExportedProperty(category = "drawing")
13611    public int getSolidColor() {
13612        return 0;
13613    }
13614
13615    /**
13616     * Build a human readable string representation of the specified view flags.
13617     *
13618     * @param flags the view flags to convert to a string
13619     * @return a String representing the supplied flags
13620     */
13621    private static String printFlags(int flags) {
13622        String output = "";
13623        int numFlags = 0;
13624        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13625            output += "TAKES_FOCUS";
13626            numFlags++;
13627        }
13628
13629        switch (flags & VISIBILITY_MASK) {
13630        case INVISIBLE:
13631            if (numFlags > 0) {
13632                output += " ";
13633            }
13634            output += "INVISIBLE";
13635            // USELESS HERE numFlags++;
13636            break;
13637        case GONE:
13638            if (numFlags > 0) {
13639                output += " ";
13640            }
13641            output += "GONE";
13642            // USELESS HERE numFlags++;
13643            break;
13644        default:
13645            break;
13646        }
13647        return output;
13648    }
13649
13650    /**
13651     * Build a human readable string representation of the specified private
13652     * view flags.
13653     *
13654     * @param privateFlags the private view flags to convert to a string
13655     * @return a String representing the supplied flags
13656     */
13657    private static String printPrivateFlags(int privateFlags) {
13658        String output = "";
13659        int numFlags = 0;
13660
13661        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
13662            output += "WANTS_FOCUS";
13663            numFlags++;
13664        }
13665
13666        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
13667            if (numFlags > 0) {
13668                output += " ";
13669            }
13670            output += "FOCUSED";
13671            numFlags++;
13672        }
13673
13674        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
13675            if (numFlags > 0) {
13676                output += " ";
13677            }
13678            output += "SELECTED";
13679            numFlags++;
13680        }
13681
13682        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
13683            if (numFlags > 0) {
13684                output += " ";
13685            }
13686            output += "IS_ROOT_NAMESPACE";
13687            numFlags++;
13688        }
13689
13690        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
13691            if (numFlags > 0) {
13692                output += " ";
13693            }
13694            output += "HAS_BOUNDS";
13695            numFlags++;
13696        }
13697
13698        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
13699            if (numFlags > 0) {
13700                output += " ";
13701            }
13702            output += "DRAWN";
13703            // USELESS HERE numFlags++;
13704        }
13705        return output;
13706    }
13707
13708    /**
13709     * <p>Indicates whether or not this view's layout will be requested during
13710     * the next hierarchy layout pass.</p>
13711     *
13712     * @return true if the layout will be forced during next layout pass
13713     */
13714    public boolean isLayoutRequested() {
13715        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
13716    }
13717
13718    /**
13719     * Assign a size and position to a view and all of its
13720     * descendants
13721     *
13722     * <p>This is the second phase of the layout mechanism.
13723     * (The first is measuring). In this phase, each parent calls
13724     * layout on all of its children to position them.
13725     * This is typically done using the child measurements
13726     * that were stored in the measure pass().</p>
13727     *
13728     * <p>Derived classes should not override this method.
13729     * Derived classes with children should override
13730     * onLayout. In that method, they should
13731     * call layout on each of their children.</p>
13732     *
13733     * @param l Left position, relative to parent
13734     * @param t Top position, relative to parent
13735     * @param r Right position, relative to parent
13736     * @param b Bottom position, relative to parent
13737     */
13738    @SuppressWarnings({"unchecked"})
13739    public void layout(int l, int t, int r, int b) {
13740        int oldL = mLeft;
13741        int oldT = mTop;
13742        int oldB = mBottom;
13743        int oldR = mRight;
13744        boolean changed = setFrame(l, t, r, b);
13745        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
13746            onLayout(changed, l, t, r, b);
13747            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
13748
13749            ListenerInfo li = mListenerInfo;
13750            if (li != null && li.mOnLayoutChangeListeners != null) {
13751                ArrayList<OnLayoutChangeListener> listenersCopy =
13752                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13753                int numListeners = listenersCopy.size();
13754                for (int i = 0; i < numListeners; ++i) {
13755                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13756                }
13757            }
13758        }
13759        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
13760    }
13761
13762    /**
13763     * Called from layout when this view should
13764     * assign a size and position to each of its children.
13765     *
13766     * Derived classes with children should override
13767     * this method and call layout on each of
13768     * their children.
13769     * @param changed This is a new size or position for this view
13770     * @param left Left position, relative to parent
13771     * @param top Top position, relative to parent
13772     * @param right Right position, relative to parent
13773     * @param bottom Bottom position, relative to parent
13774     */
13775    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13776    }
13777
13778    /**
13779     * Assign a size and position to this view.
13780     *
13781     * This is called from layout.
13782     *
13783     * @param left Left position, relative to parent
13784     * @param top Top position, relative to parent
13785     * @param right Right position, relative to parent
13786     * @param bottom Bottom position, relative to parent
13787     * @return true if the new size and position are different than the
13788     *         previous ones
13789     * {@hide}
13790     */
13791    protected boolean setFrame(int left, int top, int right, int bottom) {
13792        boolean changed = false;
13793
13794        if (DBG) {
13795            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13796                    + right + "," + bottom + ")");
13797        }
13798
13799        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13800            changed = true;
13801
13802            // Remember our drawn bit
13803            int drawn = mPrivateFlags & PFLAG_DRAWN;
13804
13805            int oldWidth = mRight - mLeft;
13806            int oldHeight = mBottom - mTop;
13807            int newWidth = right - left;
13808            int newHeight = bottom - top;
13809            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13810
13811            // Invalidate our old position
13812            invalidate(sizeChanged);
13813
13814            mLeft = left;
13815            mTop = top;
13816            mRight = right;
13817            mBottom = bottom;
13818            if (mDisplayList != null) {
13819                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13820            }
13821
13822            mPrivateFlags |= PFLAG_HAS_BOUNDS;
13823
13824
13825            if (sizeChanged) {
13826                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
13827                    // A change in dimension means an auto-centered pivot point changes, too
13828                    if (mTransformationInfo != null) {
13829                        mTransformationInfo.mMatrixDirty = true;
13830                    }
13831                }
13832                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13833            }
13834
13835            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13836                // If we are visible, force the DRAWN bit to on so that
13837                // this invalidate will go through (at least to our parent).
13838                // This is because someone may have invalidated this view
13839                // before this call to setFrame came in, thereby clearing
13840                // the DRAWN bit.
13841                mPrivateFlags |= PFLAG_DRAWN;
13842                invalidate(sizeChanged);
13843                // parent display list may need to be recreated based on a change in the bounds
13844                // of any child
13845                invalidateParentCaches();
13846            }
13847
13848            // Reset drawn bit to original value (invalidate turns it off)
13849            mPrivateFlags |= drawn;
13850
13851            mBackgroundSizeChanged = true;
13852        }
13853        return changed;
13854    }
13855
13856    /**
13857     * Finalize inflating a view from XML.  This is called as the last phase
13858     * of inflation, after all child views have been added.
13859     *
13860     * <p>Even if the subclass overrides onFinishInflate, they should always be
13861     * sure to call the super method, so that we get called.
13862     */
13863    protected void onFinishInflate() {
13864    }
13865
13866    /**
13867     * Returns the resources associated with this view.
13868     *
13869     * @return Resources object.
13870     */
13871    public Resources getResources() {
13872        return mResources;
13873    }
13874
13875    /**
13876     * Invalidates the specified Drawable.
13877     *
13878     * @param drawable the drawable to invalidate
13879     */
13880    public void invalidateDrawable(Drawable drawable) {
13881        if (verifyDrawable(drawable)) {
13882            final Rect dirty = drawable.getBounds();
13883            final int scrollX = mScrollX;
13884            final int scrollY = mScrollY;
13885
13886            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13887                    dirty.right + scrollX, dirty.bottom + scrollY);
13888        }
13889    }
13890
13891    /**
13892     * Schedules an action on a drawable to occur at a specified time.
13893     *
13894     * @param who the recipient of the action
13895     * @param what the action to run on the drawable
13896     * @param when the time at which the action must occur. Uses the
13897     *        {@link SystemClock#uptimeMillis} timebase.
13898     */
13899    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13900        if (verifyDrawable(who) && what != null) {
13901            final long delay = when - SystemClock.uptimeMillis();
13902            if (mAttachInfo != null) {
13903                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13904                        Choreographer.CALLBACK_ANIMATION, what, who,
13905                        Choreographer.subtractFrameDelay(delay));
13906            } else {
13907                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13908            }
13909        }
13910    }
13911
13912    /**
13913     * Cancels a scheduled action on a drawable.
13914     *
13915     * @param who the recipient of the action
13916     * @param what the action to cancel
13917     */
13918    public void unscheduleDrawable(Drawable who, Runnable what) {
13919        if (verifyDrawable(who) && what != null) {
13920            if (mAttachInfo != null) {
13921                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13922                        Choreographer.CALLBACK_ANIMATION, what, who);
13923            } else {
13924                ViewRootImpl.getRunQueue().removeCallbacks(what);
13925            }
13926        }
13927    }
13928
13929    /**
13930     * Unschedule any events associated with the given Drawable.  This can be
13931     * used when selecting a new Drawable into a view, so that the previous
13932     * one is completely unscheduled.
13933     *
13934     * @param who The Drawable to unschedule.
13935     *
13936     * @see #drawableStateChanged
13937     */
13938    public void unscheduleDrawable(Drawable who) {
13939        if (mAttachInfo != null && who != null) {
13940            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13941                    Choreographer.CALLBACK_ANIMATION, null, who);
13942        }
13943    }
13944
13945    /**
13946     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
13947     * that the View directionality can and will be resolved before its Drawables.
13948     *
13949     * Will call {@link View#onResolveDrawables} when resolution is done.
13950     */
13951    public void resolveDrawables() {
13952        if (mBackground != null) {
13953            mBackground.setLayoutDirection(getResolvedLayoutDirection());
13954        }
13955        onResolveDrawables(getResolvedLayoutDirection());
13956    }
13957
13958    /**
13959     * Called when layout direction has been resolved.
13960     *
13961     * The default implementation does nothing.
13962     *
13963     * @param layoutDirection The resolved layout direction.
13964     *
13965     * @see {@link #LAYOUT_DIRECTION_LTR}
13966     * @see {@link #LAYOUT_DIRECTION_RTL}
13967     */
13968    public void onResolveDrawables(int layoutDirection) {
13969    }
13970
13971    /**
13972     * If your view subclass is displaying its own Drawable objects, it should
13973     * override this function and return true for any Drawable it is
13974     * displaying.  This allows animations for those drawables to be
13975     * scheduled.
13976     *
13977     * <p>Be sure to call through to the super class when overriding this
13978     * function.
13979     *
13980     * @param who The Drawable to verify.  Return true if it is one you are
13981     *            displaying, else return the result of calling through to the
13982     *            super class.
13983     *
13984     * @return boolean If true than the Drawable is being displayed in the
13985     *         view; else false and it is not allowed to animate.
13986     *
13987     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13988     * @see #drawableStateChanged()
13989     */
13990    protected boolean verifyDrawable(Drawable who) {
13991        return who == mBackground;
13992    }
13993
13994    /**
13995     * This function is called whenever the state of the view changes in such
13996     * a way that it impacts the state of drawables being shown.
13997     *
13998     * <p>Be sure to call through to the superclass when overriding this
13999     * function.
14000     *
14001     * @see Drawable#setState(int[])
14002     */
14003    protected void drawableStateChanged() {
14004        Drawable d = mBackground;
14005        if (d != null && d.isStateful()) {
14006            d.setState(getDrawableState());
14007        }
14008    }
14009
14010    /**
14011     * Call this to force a view to update its drawable state. This will cause
14012     * drawableStateChanged to be called on this view. Views that are interested
14013     * in the new state should call getDrawableState.
14014     *
14015     * @see #drawableStateChanged
14016     * @see #getDrawableState
14017     */
14018    public void refreshDrawableState() {
14019        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14020        drawableStateChanged();
14021
14022        ViewParent parent = mParent;
14023        if (parent != null) {
14024            parent.childDrawableStateChanged(this);
14025        }
14026    }
14027
14028    /**
14029     * Return an array of resource IDs of the drawable states representing the
14030     * current state of the view.
14031     *
14032     * @return The current drawable state
14033     *
14034     * @see Drawable#setState(int[])
14035     * @see #drawableStateChanged()
14036     * @see #onCreateDrawableState(int)
14037     */
14038    public final int[] getDrawableState() {
14039        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14040            return mDrawableState;
14041        } else {
14042            mDrawableState = onCreateDrawableState(0);
14043            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14044            return mDrawableState;
14045        }
14046    }
14047
14048    /**
14049     * Generate the new {@link android.graphics.drawable.Drawable} state for
14050     * this view. This is called by the view
14051     * system when the cached Drawable state is determined to be invalid.  To
14052     * retrieve the current state, you should use {@link #getDrawableState}.
14053     *
14054     * @param extraSpace if non-zero, this is the number of extra entries you
14055     * would like in the returned array in which you can place your own
14056     * states.
14057     *
14058     * @return Returns an array holding the current {@link Drawable} state of
14059     * the view.
14060     *
14061     * @see #mergeDrawableStates(int[], int[])
14062     */
14063    protected int[] onCreateDrawableState(int extraSpace) {
14064        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14065                mParent instanceof View) {
14066            return ((View) mParent).onCreateDrawableState(extraSpace);
14067        }
14068
14069        int[] drawableState;
14070
14071        int privateFlags = mPrivateFlags;
14072
14073        int viewStateIndex = 0;
14074        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14075        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14076        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14077        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14078        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14079        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14080        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14081                HardwareRenderer.isAvailable()) {
14082            // This is set if HW acceleration is requested, even if the current
14083            // process doesn't allow it.  This is just to allow app preview
14084            // windows to better match their app.
14085            viewStateIndex |= VIEW_STATE_ACCELERATED;
14086        }
14087        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14088
14089        final int privateFlags2 = mPrivateFlags2;
14090        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14091        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14092
14093        drawableState = VIEW_STATE_SETS[viewStateIndex];
14094
14095        //noinspection ConstantIfStatement
14096        if (false) {
14097            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14098            Log.i("View", toString()
14099                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14100                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14101                    + " fo=" + hasFocus()
14102                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14103                    + " wf=" + hasWindowFocus()
14104                    + ": " + Arrays.toString(drawableState));
14105        }
14106
14107        if (extraSpace == 0) {
14108            return drawableState;
14109        }
14110
14111        final int[] fullState;
14112        if (drawableState != null) {
14113            fullState = new int[drawableState.length + extraSpace];
14114            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14115        } else {
14116            fullState = new int[extraSpace];
14117        }
14118
14119        return fullState;
14120    }
14121
14122    /**
14123     * Merge your own state values in <var>additionalState</var> into the base
14124     * state values <var>baseState</var> that were returned by
14125     * {@link #onCreateDrawableState(int)}.
14126     *
14127     * @param baseState The base state values returned by
14128     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14129     * own additional state values.
14130     *
14131     * @param additionalState The additional state values you would like
14132     * added to <var>baseState</var>; this array is not modified.
14133     *
14134     * @return As a convenience, the <var>baseState</var> array you originally
14135     * passed into the function is returned.
14136     *
14137     * @see #onCreateDrawableState(int)
14138     */
14139    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14140        final int N = baseState.length;
14141        int i = N - 1;
14142        while (i >= 0 && baseState[i] == 0) {
14143            i--;
14144        }
14145        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14146        return baseState;
14147    }
14148
14149    /**
14150     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14151     * on all Drawable objects associated with this view.
14152     */
14153    public void jumpDrawablesToCurrentState() {
14154        if (mBackground != null) {
14155            mBackground.jumpToCurrentState();
14156        }
14157    }
14158
14159    /**
14160     * Sets the background color for this view.
14161     * @param color the color of the background
14162     */
14163    @RemotableViewMethod
14164    public void setBackgroundColor(int color) {
14165        if (mBackground instanceof ColorDrawable) {
14166            ((ColorDrawable) mBackground.mutate()).setColor(color);
14167            computeOpaqueFlags();
14168        } else {
14169            setBackground(new ColorDrawable(color));
14170        }
14171    }
14172
14173    /**
14174     * Set the background to a given resource. The resource should refer to
14175     * a Drawable object or 0 to remove the background.
14176     * @param resid The identifier of the resource.
14177     *
14178     * @attr ref android.R.styleable#View_background
14179     */
14180    @RemotableViewMethod
14181    public void setBackgroundResource(int resid) {
14182        if (resid != 0 && resid == mBackgroundResource) {
14183            return;
14184        }
14185
14186        Drawable d= null;
14187        if (resid != 0) {
14188            d = mResources.getDrawable(resid);
14189        }
14190        setBackground(d);
14191
14192        mBackgroundResource = resid;
14193    }
14194
14195    /**
14196     * Set the background to a given Drawable, or remove the background. If the
14197     * background has padding, this View's padding is set to the background's
14198     * padding. However, when a background is removed, this View's padding isn't
14199     * touched. If setting the padding is desired, please use
14200     * {@link #setPadding(int, int, int, int)}.
14201     *
14202     * @param background The Drawable to use as the background, or null to remove the
14203     *        background
14204     */
14205    public void setBackground(Drawable background) {
14206        //noinspection deprecation
14207        setBackgroundDrawable(background);
14208    }
14209
14210    /**
14211     * @deprecated use {@link #setBackground(Drawable)} instead
14212     */
14213    @Deprecated
14214    public void setBackgroundDrawable(Drawable background) {
14215        computeOpaqueFlags();
14216
14217        if (background == mBackground) {
14218            return;
14219        }
14220
14221        boolean requestLayout = false;
14222
14223        mBackgroundResource = 0;
14224
14225        /*
14226         * Regardless of whether we're setting a new background or not, we want
14227         * to clear the previous drawable.
14228         */
14229        if (mBackground != null) {
14230            mBackground.setCallback(null);
14231            unscheduleDrawable(mBackground);
14232        }
14233
14234        if (background != null) {
14235            Rect padding = sThreadLocal.get();
14236            if (padding == null) {
14237                padding = new Rect();
14238                sThreadLocal.set(padding);
14239            }
14240            background.setLayoutDirection(getResolvedLayoutDirection());
14241            if (background.getPadding(padding)) {
14242                // Reset padding resolution
14243                mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
14244                switch (background.getLayoutDirection()) {
14245                    case LAYOUT_DIRECTION_RTL:
14246                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14247                        break;
14248                    case LAYOUT_DIRECTION_LTR:
14249                    default:
14250                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14251                }
14252            }
14253
14254            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14255            // if it has a different minimum size, we should layout again
14256            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14257                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14258                requestLayout = true;
14259            }
14260
14261            background.setCallback(this);
14262            if (background.isStateful()) {
14263                background.setState(getDrawableState());
14264            }
14265            background.setVisible(getVisibility() == VISIBLE, false);
14266            mBackground = background;
14267
14268            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14269                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14270                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14271                requestLayout = true;
14272            }
14273        } else {
14274            /* Remove the background */
14275            mBackground = null;
14276
14277            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14278                /*
14279                 * This view ONLY drew the background before and we're removing
14280                 * the background, so now it won't draw anything
14281                 * (hence we SKIP_DRAW)
14282                 */
14283                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14284                mPrivateFlags |= PFLAG_SKIP_DRAW;
14285            }
14286
14287            /*
14288             * When the background is set, we try to apply its padding to this
14289             * View. When the background is removed, we don't touch this View's
14290             * padding. This is noted in the Javadocs. Hence, we don't need to
14291             * requestLayout(), the invalidate() below is sufficient.
14292             */
14293
14294            // The old background's minimum size could have affected this
14295            // View's layout, so let's requestLayout
14296            requestLayout = true;
14297        }
14298
14299        computeOpaqueFlags();
14300
14301        if (requestLayout) {
14302            requestLayout();
14303        }
14304
14305        mBackgroundSizeChanged = true;
14306        invalidate(true);
14307    }
14308
14309    /**
14310     * Gets the background drawable
14311     *
14312     * @return The drawable used as the background for this view, if any.
14313     *
14314     * @see #setBackground(Drawable)
14315     *
14316     * @attr ref android.R.styleable#View_background
14317     */
14318    public Drawable getBackground() {
14319        return mBackground;
14320    }
14321
14322    /**
14323     * Sets the padding. The view may add on the space required to display
14324     * the scrollbars, depending on the style and visibility of the scrollbars.
14325     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14326     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14327     * from the values set in this call.
14328     *
14329     * @attr ref android.R.styleable#View_padding
14330     * @attr ref android.R.styleable#View_paddingBottom
14331     * @attr ref android.R.styleable#View_paddingLeft
14332     * @attr ref android.R.styleable#View_paddingRight
14333     * @attr ref android.R.styleable#View_paddingTop
14334     * @param left the left padding in pixels
14335     * @param top the top padding in pixels
14336     * @param right the right padding in pixels
14337     * @param bottom the bottom padding in pixels
14338     */
14339    public void setPadding(int left, int top, int right, int bottom) {
14340        // Reset padding resolution
14341        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
14342
14343        mUserPaddingStart = UNDEFINED_PADDING;
14344        mUserPaddingEnd = UNDEFINED_PADDING;
14345
14346        internalSetPadding(left, top, right, bottom);
14347    }
14348
14349    /**
14350     * @hide
14351     */
14352    protected void internalSetPadding(int left, int top, int right, int bottom) {
14353        mUserPaddingLeft = left;
14354        mUserPaddingRight = right;
14355        mUserPaddingBottom = bottom;
14356
14357        final int viewFlags = mViewFlags;
14358        boolean changed = false;
14359
14360        // Common case is there are no scroll bars.
14361        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14362            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14363                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14364                        ? 0 : getVerticalScrollbarWidth();
14365                switch (mVerticalScrollbarPosition) {
14366                    case SCROLLBAR_POSITION_DEFAULT:
14367                        if (isLayoutRtl()) {
14368                            left += offset;
14369                        } else {
14370                            right += offset;
14371                        }
14372                        break;
14373                    case SCROLLBAR_POSITION_RIGHT:
14374                        right += offset;
14375                        break;
14376                    case SCROLLBAR_POSITION_LEFT:
14377                        left += offset;
14378                        break;
14379                }
14380            }
14381            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14382                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14383                        ? 0 : getHorizontalScrollbarHeight();
14384            }
14385        }
14386
14387        if (mPaddingLeft != left) {
14388            changed = true;
14389            mPaddingLeft = left;
14390        }
14391        if (mPaddingTop != top) {
14392            changed = true;
14393            mPaddingTop = top;
14394        }
14395        if (mPaddingRight != right) {
14396            changed = true;
14397            mPaddingRight = right;
14398        }
14399        if (mPaddingBottom != bottom) {
14400            changed = true;
14401            mPaddingBottom = bottom;
14402        }
14403
14404        if (changed) {
14405            requestLayout();
14406        }
14407    }
14408
14409    /**
14410     * Sets the relative padding. The view may add on the space required to display
14411     * the scrollbars, depending on the style and visibility of the scrollbars.
14412     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14413     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14414     * from the values set in this call.
14415     *
14416     * @attr ref android.R.styleable#View_padding
14417     * @attr ref android.R.styleable#View_paddingBottom
14418     * @attr ref android.R.styleable#View_paddingStart
14419     * @attr ref android.R.styleable#View_paddingEnd
14420     * @attr ref android.R.styleable#View_paddingTop
14421     * @param start the start padding in pixels
14422     * @param top the top padding in pixels
14423     * @param end the end padding in pixels
14424     * @param bottom the bottom padding in pixels
14425     */
14426    public void setPaddingRelative(int start, int top, int end, int bottom) {
14427        // Reset padding resolution
14428        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
14429
14430        mUserPaddingStart = start;
14431        mUserPaddingEnd = end;
14432
14433        switch(getResolvedLayoutDirection()) {
14434            case LAYOUT_DIRECTION_RTL:
14435                internalSetPadding(end, top, start, bottom);
14436                break;
14437            case LAYOUT_DIRECTION_LTR:
14438            default:
14439                internalSetPadding(start, top, end, bottom);
14440        }
14441    }
14442
14443    /**
14444     * Returns the top padding of this view.
14445     *
14446     * @return the top padding in pixels
14447     */
14448    public int getPaddingTop() {
14449        return mPaddingTop;
14450    }
14451
14452    /**
14453     * Returns the bottom padding of this view. If there are inset and enabled
14454     * scrollbars, this value may include the space required to display the
14455     * scrollbars as well.
14456     *
14457     * @return the bottom padding in pixels
14458     */
14459    public int getPaddingBottom() {
14460        return mPaddingBottom;
14461    }
14462
14463    /**
14464     * Returns the left padding of this view. If there are inset and enabled
14465     * scrollbars, this value may include the space required to display the
14466     * scrollbars as well.
14467     *
14468     * @return the left padding in pixels
14469     */
14470    public int getPaddingLeft() {
14471        if (!isPaddingResolved()) {
14472            resolvePadding();
14473        }
14474        return mPaddingLeft;
14475    }
14476
14477    /**
14478     * Returns the start padding of this view depending on its resolved layout direction.
14479     * If there are inset and enabled scrollbars, this value may include the space
14480     * required to display the scrollbars as well.
14481     *
14482     * @return the start padding in pixels
14483     */
14484    public int getPaddingStart() {
14485        if (!isPaddingResolved()) {
14486            resolvePadding();
14487        }
14488        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14489                mPaddingRight : mPaddingLeft;
14490    }
14491
14492    /**
14493     * Returns the right padding of this view. If there are inset and enabled
14494     * scrollbars, this value may include the space required to display the
14495     * scrollbars as well.
14496     *
14497     * @return the right padding in pixels
14498     */
14499    public int getPaddingRight() {
14500        if (!isPaddingResolved()) {
14501            resolvePadding();
14502        }
14503        return mPaddingRight;
14504    }
14505
14506    /**
14507     * Returns the end padding of this view depending on its resolved layout direction.
14508     * If there are inset and enabled scrollbars, this value may include the space
14509     * required to display the scrollbars as well.
14510     *
14511     * @return the end padding in pixels
14512     */
14513    public int getPaddingEnd() {
14514        if (!isPaddingResolved()) {
14515            resolvePadding();
14516        }
14517        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14518                mPaddingLeft : mPaddingRight;
14519    }
14520
14521    /**
14522     * Return if the padding as been set thru relative values
14523     * {@link #setPaddingRelative(int, int, int, int)} or thru
14524     * @attr ref android.R.styleable#View_paddingStart or
14525     * @attr ref android.R.styleable#View_paddingEnd
14526     *
14527     * @return true if the padding is relative or false if it is not.
14528     */
14529    public boolean isPaddingRelative() {
14530        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
14531    }
14532
14533    /**
14534     * @hide
14535     */
14536    public Insets getOpticalInsets() {
14537        if (mLayoutInsets == null) {
14538            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14539        }
14540        return mLayoutInsets;
14541    }
14542
14543    /**
14544     * @hide
14545     */
14546    public void setLayoutInsets(Insets layoutInsets) {
14547        mLayoutInsets = layoutInsets;
14548    }
14549
14550    /**
14551     * Changes the selection state of this view. A view can be selected or not.
14552     * Note that selection is not the same as focus. Views are typically
14553     * selected in the context of an AdapterView like ListView or GridView;
14554     * the selected view is the view that is highlighted.
14555     *
14556     * @param selected true if the view must be selected, false otherwise
14557     */
14558    public void setSelected(boolean selected) {
14559        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
14560            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
14561            if (!selected) resetPressedState();
14562            invalidate(true);
14563            refreshDrawableState();
14564            dispatchSetSelected(selected);
14565            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14566                notifyAccessibilityStateChanged();
14567            }
14568        }
14569    }
14570
14571    /**
14572     * Dispatch setSelected to all of this View's children.
14573     *
14574     * @see #setSelected(boolean)
14575     *
14576     * @param selected The new selected state
14577     */
14578    protected void dispatchSetSelected(boolean selected) {
14579    }
14580
14581    /**
14582     * Indicates the selection state of this view.
14583     *
14584     * @return true if the view is selected, false otherwise
14585     */
14586    @ViewDebug.ExportedProperty
14587    public boolean isSelected() {
14588        return (mPrivateFlags & PFLAG_SELECTED) != 0;
14589    }
14590
14591    /**
14592     * Changes the activated state of this view. A view can be activated or not.
14593     * Note that activation is not the same as selection.  Selection is
14594     * a transient property, representing the view (hierarchy) the user is
14595     * currently interacting with.  Activation is a longer-term state that the
14596     * user can move views in and out of.  For example, in a list view with
14597     * single or multiple selection enabled, the views in the current selection
14598     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14599     * here.)  The activated state is propagated down to children of the view it
14600     * is set on.
14601     *
14602     * @param activated true if the view must be activated, false otherwise
14603     */
14604    public void setActivated(boolean activated) {
14605        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
14606            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
14607            invalidate(true);
14608            refreshDrawableState();
14609            dispatchSetActivated(activated);
14610        }
14611    }
14612
14613    /**
14614     * Dispatch setActivated to all of this View's children.
14615     *
14616     * @see #setActivated(boolean)
14617     *
14618     * @param activated The new activated state
14619     */
14620    protected void dispatchSetActivated(boolean activated) {
14621    }
14622
14623    /**
14624     * Indicates the activation state of this view.
14625     *
14626     * @return true if the view is activated, false otherwise
14627     */
14628    @ViewDebug.ExportedProperty
14629    public boolean isActivated() {
14630        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
14631    }
14632
14633    /**
14634     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14635     * observer can be used to get notifications when global events, like
14636     * layout, happen.
14637     *
14638     * The returned ViewTreeObserver observer is not guaranteed to remain
14639     * valid for the lifetime of this View. If the caller of this method keeps
14640     * a long-lived reference to ViewTreeObserver, it should always check for
14641     * the return value of {@link ViewTreeObserver#isAlive()}.
14642     *
14643     * @return The ViewTreeObserver for this view's hierarchy.
14644     */
14645    public ViewTreeObserver getViewTreeObserver() {
14646        if (mAttachInfo != null) {
14647            return mAttachInfo.mTreeObserver;
14648        }
14649        if (mFloatingTreeObserver == null) {
14650            mFloatingTreeObserver = new ViewTreeObserver();
14651        }
14652        return mFloatingTreeObserver;
14653    }
14654
14655    /**
14656     * <p>Finds the topmost view in the current view hierarchy.</p>
14657     *
14658     * @return the topmost view containing this view
14659     */
14660    public View getRootView() {
14661        if (mAttachInfo != null) {
14662            final View v = mAttachInfo.mRootView;
14663            if (v != null) {
14664                return v;
14665            }
14666        }
14667
14668        View parent = this;
14669
14670        while (parent.mParent != null && parent.mParent instanceof View) {
14671            parent = (View) parent.mParent;
14672        }
14673
14674        return parent;
14675    }
14676
14677    /**
14678     * <p>Computes the coordinates of this view on the screen. The argument
14679     * must be an array of two integers. After the method returns, the array
14680     * contains the x and y location in that order.</p>
14681     *
14682     * @param location an array of two integers in which to hold the coordinates
14683     */
14684    public void getLocationOnScreen(int[] location) {
14685        getLocationInWindow(location);
14686
14687        final AttachInfo info = mAttachInfo;
14688        if (info != null) {
14689            location[0] += info.mWindowLeft;
14690            location[1] += info.mWindowTop;
14691        }
14692    }
14693
14694    /**
14695     * <p>Computes the coordinates of this view in its window. The argument
14696     * must be an array of two integers. After the method returns, the array
14697     * contains the x and y location in that order.</p>
14698     *
14699     * @param location an array of two integers in which to hold the coordinates
14700     */
14701    public void getLocationInWindow(int[] location) {
14702        if (location == null || location.length < 2) {
14703            throw new IllegalArgumentException("location must be an array of two integers");
14704        }
14705
14706        if (mAttachInfo == null) {
14707            // When the view is not attached to a window, this method does not make sense
14708            location[0] = location[1] = 0;
14709            return;
14710        }
14711
14712        float[] position = mAttachInfo.mTmpTransformLocation;
14713        position[0] = position[1] = 0.0f;
14714
14715        if (!hasIdentityMatrix()) {
14716            getMatrix().mapPoints(position);
14717        }
14718
14719        position[0] += mLeft;
14720        position[1] += mTop;
14721
14722        ViewParent viewParent = mParent;
14723        while (viewParent instanceof View) {
14724            final View view = (View) viewParent;
14725
14726            position[0] -= view.mScrollX;
14727            position[1] -= view.mScrollY;
14728
14729            if (!view.hasIdentityMatrix()) {
14730                view.getMatrix().mapPoints(position);
14731            }
14732
14733            position[0] += view.mLeft;
14734            position[1] += view.mTop;
14735
14736            viewParent = view.mParent;
14737         }
14738
14739        if (viewParent instanceof ViewRootImpl) {
14740            // *cough*
14741            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14742            position[1] -= vr.mCurScrollY;
14743        }
14744
14745        location[0] = (int) (position[0] + 0.5f);
14746        location[1] = (int) (position[1] + 0.5f);
14747    }
14748
14749    /**
14750     * {@hide}
14751     * @param id the id of the view to be found
14752     * @return the view of the specified id, null if cannot be found
14753     */
14754    protected View findViewTraversal(int id) {
14755        if (id == mID) {
14756            return this;
14757        }
14758        return null;
14759    }
14760
14761    /**
14762     * {@hide}
14763     * @param tag the tag of the view to be found
14764     * @return the view of specified tag, null if cannot be found
14765     */
14766    protected View findViewWithTagTraversal(Object tag) {
14767        if (tag != null && tag.equals(mTag)) {
14768            return this;
14769        }
14770        return null;
14771    }
14772
14773    /**
14774     * {@hide}
14775     * @param predicate The predicate to evaluate.
14776     * @param childToSkip If not null, ignores this child during the recursive traversal.
14777     * @return The first view that matches the predicate or null.
14778     */
14779    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14780        if (predicate.apply(this)) {
14781            return this;
14782        }
14783        return null;
14784    }
14785
14786    /**
14787     * Look for a child view with the given id.  If this view has the given
14788     * id, return this view.
14789     *
14790     * @param id The id to search for.
14791     * @return The view that has the given id in the hierarchy or null
14792     */
14793    public final View findViewById(int id) {
14794        if (id < 0) {
14795            return null;
14796        }
14797        return findViewTraversal(id);
14798    }
14799
14800    /**
14801     * Finds a view by its unuque and stable accessibility id.
14802     *
14803     * @param accessibilityId The searched accessibility id.
14804     * @return The found view.
14805     */
14806    final View findViewByAccessibilityId(int accessibilityId) {
14807        if (accessibilityId < 0) {
14808            return null;
14809        }
14810        return findViewByAccessibilityIdTraversal(accessibilityId);
14811    }
14812
14813    /**
14814     * Performs the traversal to find a view by its unuque and stable accessibility id.
14815     *
14816     * <strong>Note:</strong>This method does not stop at the root namespace
14817     * boundary since the user can touch the screen at an arbitrary location
14818     * potentially crossing the root namespace bounday which will send an
14819     * accessibility event to accessibility services and they should be able
14820     * to obtain the event source. Also accessibility ids are guaranteed to be
14821     * unique in the window.
14822     *
14823     * @param accessibilityId The accessibility id.
14824     * @return The found view.
14825     */
14826    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14827        if (getAccessibilityViewId() == accessibilityId) {
14828            return this;
14829        }
14830        return null;
14831    }
14832
14833    /**
14834     * Look for a child view with the given tag.  If this view has the given
14835     * tag, return this view.
14836     *
14837     * @param tag The tag to search for, using "tag.equals(getTag())".
14838     * @return The View that has the given tag in the hierarchy or null
14839     */
14840    public final View findViewWithTag(Object tag) {
14841        if (tag == null) {
14842            return null;
14843        }
14844        return findViewWithTagTraversal(tag);
14845    }
14846
14847    /**
14848     * {@hide}
14849     * Look for a child view that matches the specified predicate.
14850     * If this view matches the predicate, return this view.
14851     *
14852     * @param predicate The predicate to evaluate.
14853     * @return The first view that matches the predicate or null.
14854     */
14855    public final View findViewByPredicate(Predicate<View> predicate) {
14856        return findViewByPredicateTraversal(predicate, null);
14857    }
14858
14859    /**
14860     * {@hide}
14861     * Look for a child view that matches the specified predicate,
14862     * starting with the specified view and its descendents and then
14863     * recusively searching the ancestors and siblings of that view
14864     * until this view is reached.
14865     *
14866     * This method is useful in cases where the predicate does not match
14867     * a single unique view (perhaps multiple views use the same id)
14868     * and we are trying to find the view that is "closest" in scope to the
14869     * starting view.
14870     *
14871     * @param start The view to start from.
14872     * @param predicate The predicate to evaluate.
14873     * @return The first view that matches the predicate or null.
14874     */
14875    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14876        View childToSkip = null;
14877        for (;;) {
14878            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14879            if (view != null || start == this) {
14880                return view;
14881            }
14882
14883            ViewParent parent = start.getParent();
14884            if (parent == null || !(parent instanceof View)) {
14885                return null;
14886            }
14887
14888            childToSkip = start;
14889            start = (View) parent;
14890        }
14891    }
14892
14893    /**
14894     * Sets the identifier for this view. The identifier does not have to be
14895     * unique in this view's hierarchy. The identifier should be a positive
14896     * number.
14897     *
14898     * @see #NO_ID
14899     * @see #getId()
14900     * @see #findViewById(int)
14901     *
14902     * @param id a number used to identify the view
14903     *
14904     * @attr ref android.R.styleable#View_id
14905     */
14906    public void setId(int id) {
14907        mID = id;
14908    }
14909
14910    /**
14911     * {@hide}
14912     *
14913     * @param isRoot true if the view belongs to the root namespace, false
14914     *        otherwise
14915     */
14916    public void setIsRootNamespace(boolean isRoot) {
14917        if (isRoot) {
14918            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
14919        } else {
14920            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
14921        }
14922    }
14923
14924    /**
14925     * {@hide}
14926     *
14927     * @return true if the view belongs to the root namespace, false otherwise
14928     */
14929    public boolean isRootNamespace() {
14930        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
14931    }
14932
14933    /**
14934     * Returns this view's identifier.
14935     *
14936     * @return a positive integer used to identify the view or {@link #NO_ID}
14937     *         if the view has no ID
14938     *
14939     * @see #setId(int)
14940     * @see #findViewById(int)
14941     * @attr ref android.R.styleable#View_id
14942     */
14943    @ViewDebug.CapturedViewProperty
14944    public int getId() {
14945        return mID;
14946    }
14947
14948    /**
14949     * Returns this view's tag.
14950     *
14951     * @return the Object stored in this view as a tag
14952     *
14953     * @see #setTag(Object)
14954     * @see #getTag(int)
14955     */
14956    @ViewDebug.ExportedProperty
14957    public Object getTag() {
14958        return mTag;
14959    }
14960
14961    /**
14962     * Sets the tag associated with this view. A tag can be used to mark
14963     * a view in its hierarchy and does not have to be unique within the
14964     * hierarchy. Tags can also be used to store data within a view without
14965     * resorting to another data structure.
14966     *
14967     * @param tag an Object to tag the view with
14968     *
14969     * @see #getTag()
14970     * @see #setTag(int, Object)
14971     */
14972    public void setTag(final Object tag) {
14973        mTag = tag;
14974    }
14975
14976    /**
14977     * Returns the tag associated with this view and the specified key.
14978     *
14979     * @param key The key identifying the tag
14980     *
14981     * @return the Object stored in this view as a tag
14982     *
14983     * @see #setTag(int, Object)
14984     * @see #getTag()
14985     */
14986    public Object getTag(int key) {
14987        if (mKeyedTags != null) return mKeyedTags.get(key);
14988        return null;
14989    }
14990
14991    /**
14992     * Sets a tag associated with this view and a key. A tag can be used
14993     * to mark a view in its hierarchy and does not have to be unique within
14994     * the hierarchy. Tags can also be used to store data within a view
14995     * without resorting to another data structure.
14996     *
14997     * The specified key should be an id declared in the resources of the
14998     * application to ensure it is unique (see the <a
14999     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15000     * Keys identified as belonging to
15001     * the Android framework or not associated with any package will cause
15002     * an {@link IllegalArgumentException} to be thrown.
15003     *
15004     * @param key The key identifying the tag
15005     * @param tag An Object to tag the view with
15006     *
15007     * @throws IllegalArgumentException If they specified key is not valid
15008     *
15009     * @see #setTag(Object)
15010     * @see #getTag(int)
15011     */
15012    public void setTag(int key, final Object tag) {
15013        // If the package id is 0x00 or 0x01, it's either an undefined package
15014        // or a framework id
15015        if ((key >>> 24) < 2) {
15016            throw new IllegalArgumentException("The key must be an application-specific "
15017                    + "resource id.");
15018        }
15019
15020        setKeyedTag(key, tag);
15021    }
15022
15023    /**
15024     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15025     * framework id.
15026     *
15027     * @hide
15028     */
15029    public void setTagInternal(int key, Object tag) {
15030        if ((key >>> 24) != 0x1) {
15031            throw new IllegalArgumentException("The key must be a framework-specific "
15032                    + "resource id.");
15033        }
15034
15035        setKeyedTag(key, tag);
15036    }
15037
15038    private void setKeyedTag(int key, Object tag) {
15039        if (mKeyedTags == null) {
15040            mKeyedTags = new SparseArray<Object>();
15041        }
15042
15043        mKeyedTags.put(key, tag);
15044    }
15045
15046    /**
15047     * Prints information about this view in the log output, with the tag
15048     * {@link #VIEW_LOG_TAG}.
15049     *
15050     * @hide
15051     */
15052    public void debug() {
15053        debug(0);
15054    }
15055
15056    /**
15057     * Prints information about this view in the log output, with the tag
15058     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15059     * indentation defined by the <code>depth</code>.
15060     *
15061     * @param depth the indentation level
15062     *
15063     * @hide
15064     */
15065    protected void debug(int depth) {
15066        String output = debugIndent(depth - 1);
15067
15068        output += "+ " + this;
15069        int id = getId();
15070        if (id != -1) {
15071            output += " (id=" + id + ")";
15072        }
15073        Object tag = getTag();
15074        if (tag != null) {
15075            output += " (tag=" + tag + ")";
15076        }
15077        Log.d(VIEW_LOG_TAG, output);
15078
15079        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15080            output = debugIndent(depth) + " FOCUSED";
15081            Log.d(VIEW_LOG_TAG, output);
15082        }
15083
15084        output = debugIndent(depth);
15085        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15086                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15087                + "} ";
15088        Log.d(VIEW_LOG_TAG, output);
15089
15090        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15091                || mPaddingBottom != 0) {
15092            output = debugIndent(depth);
15093            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15094                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15095            Log.d(VIEW_LOG_TAG, output);
15096        }
15097
15098        output = debugIndent(depth);
15099        output += "mMeasureWidth=" + mMeasuredWidth +
15100                " mMeasureHeight=" + mMeasuredHeight;
15101        Log.d(VIEW_LOG_TAG, output);
15102
15103        output = debugIndent(depth);
15104        if (mLayoutParams == null) {
15105            output += "BAD! no layout params";
15106        } else {
15107            output = mLayoutParams.debug(output);
15108        }
15109        Log.d(VIEW_LOG_TAG, output);
15110
15111        output = debugIndent(depth);
15112        output += "flags={";
15113        output += View.printFlags(mViewFlags);
15114        output += "}";
15115        Log.d(VIEW_LOG_TAG, output);
15116
15117        output = debugIndent(depth);
15118        output += "privateFlags={";
15119        output += View.printPrivateFlags(mPrivateFlags);
15120        output += "}";
15121        Log.d(VIEW_LOG_TAG, output);
15122    }
15123
15124    /**
15125     * Creates a string of whitespaces used for indentation.
15126     *
15127     * @param depth the indentation level
15128     * @return a String containing (depth * 2 + 3) * 2 white spaces
15129     *
15130     * @hide
15131     */
15132    protected static String debugIndent(int depth) {
15133        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15134        for (int i = 0; i < (depth * 2) + 3; i++) {
15135            spaces.append(' ').append(' ');
15136        }
15137        return spaces.toString();
15138    }
15139
15140    /**
15141     * <p>Return the offset of the widget's text baseline from the widget's top
15142     * boundary. If this widget does not support baseline alignment, this
15143     * method returns -1. </p>
15144     *
15145     * @return the offset of the baseline within the widget's bounds or -1
15146     *         if baseline alignment is not supported
15147     */
15148    @ViewDebug.ExportedProperty(category = "layout")
15149    public int getBaseline() {
15150        return -1;
15151    }
15152
15153    /**
15154     * Call this when something has changed which has invalidated the
15155     * layout of this view. This will schedule a layout pass of the view
15156     * tree.
15157     */
15158    public void requestLayout() {
15159        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15160        mPrivateFlags |= PFLAG_INVALIDATED;
15161
15162        if (mParent != null && !mParent.isLayoutRequested()) {
15163            mParent.requestLayout();
15164        }
15165    }
15166
15167    /**
15168     * Forces this view to be laid out during the next layout pass.
15169     * This method does not call requestLayout() or forceLayout()
15170     * on the parent.
15171     */
15172    public void forceLayout() {
15173        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15174        mPrivateFlags |= PFLAG_INVALIDATED;
15175    }
15176
15177    /**
15178     * <p>
15179     * This is called to find out how big a view should be. The parent
15180     * supplies constraint information in the width and height parameters.
15181     * </p>
15182     *
15183     * <p>
15184     * The actual measurement work of a view is performed in
15185     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15186     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15187     * </p>
15188     *
15189     *
15190     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15191     *        parent
15192     * @param heightMeasureSpec Vertical space requirements as imposed by the
15193     *        parent
15194     *
15195     * @see #onMeasure(int, int)
15196     */
15197    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15198        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15199                widthMeasureSpec != mOldWidthMeasureSpec ||
15200                heightMeasureSpec != mOldHeightMeasureSpec) {
15201
15202            // first clears the measured dimension flag
15203            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15204
15205            if (!isPaddingResolved()) {
15206                resolvePadding();
15207            }
15208
15209            // measure ourselves, this should set the measured dimension flag back
15210            onMeasure(widthMeasureSpec, heightMeasureSpec);
15211
15212            // flag not set, setMeasuredDimension() was not invoked, we raise
15213            // an exception to warn the developer
15214            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15215                throw new IllegalStateException("onMeasure() did not set the"
15216                        + " measured dimension by calling"
15217                        + " setMeasuredDimension()");
15218            }
15219
15220            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15221        }
15222
15223        mOldWidthMeasureSpec = widthMeasureSpec;
15224        mOldHeightMeasureSpec = heightMeasureSpec;
15225    }
15226
15227    /**
15228     * <p>
15229     * Measure the view and its content to determine the measured width and the
15230     * measured height. This method is invoked by {@link #measure(int, int)} and
15231     * should be overriden by subclasses to provide accurate and efficient
15232     * measurement of their contents.
15233     * </p>
15234     *
15235     * <p>
15236     * <strong>CONTRACT:</strong> When overriding this method, you
15237     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15238     * measured width and height of this view. Failure to do so will trigger an
15239     * <code>IllegalStateException</code>, thrown by
15240     * {@link #measure(int, int)}. Calling the superclass'
15241     * {@link #onMeasure(int, int)} is a valid use.
15242     * </p>
15243     *
15244     * <p>
15245     * The base class implementation of measure defaults to the background size,
15246     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15247     * override {@link #onMeasure(int, int)} to provide better measurements of
15248     * their content.
15249     * </p>
15250     *
15251     * <p>
15252     * If this method is overridden, it is the subclass's responsibility to make
15253     * sure the measured height and width are at least the view's minimum height
15254     * and width ({@link #getSuggestedMinimumHeight()} and
15255     * {@link #getSuggestedMinimumWidth()}).
15256     * </p>
15257     *
15258     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15259     *                         The requirements are encoded with
15260     *                         {@link android.view.View.MeasureSpec}.
15261     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15262     *                         The requirements are encoded with
15263     *                         {@link android.view.View.MeasureSpec}.
15264     *
15265     * @see #getMeasuredWidth()
15266     * @see #getMeasuredHeight()
15267     * @see #setMeasuredDimension(int, int)
15268     * @see #getSuggestedMinimumHeight()
15269     * @see #getSuggestedMinimumWidth()
15270     * @see android.view.View.MeasureSpec#getMode(int)
15271     * @see android.view.View.MeasureSpec#getSize(int)
15272     */
15273    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15274        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15275                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15276    }
15277
15278    /**
15279     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15280     * measured width and measured height. Failing to do so will trigger an
15281     * exception at measurement time.</p>
15282     *
15283     * @param measuredWidth The measured width of this view.  May be a complex
15284     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15285     * {@link #MEASURED_STATE_TOO_SMALL}.
15286     * @param measuredHeight The measured height of this view.  May be a complex
15287     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15288     * {@link #MEASURED_STATE_TOO_SMALL}.
15289     */
15290    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15291        mMeasuredWidth = measuredWidth;
15292        mMeasuredHeight = measuredHeight;
15293
15294        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
15295    }
15296
15297    /**
15298     * Merge two states as returned by {@link #getMeasuredState()}.
15299     * @param curState The current state as returned from a view or the result
15300     * of combining multiple views.
15301     * @param newState The new view state to combine.
15302     * @return Returns a new integer reflecting the combination of the two
15303     * states.
15304     */
15305    public static int combineMeasuredStates(int curState, int newState) {
15306        return curState | newState;
15307    }
15308
15309    /**
15310     * Version of {@link #resolveSizeAndState(int, int, int)}
15311     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15312     */
15313    public static int resolveSize(int size, int measureSpec) {
15314        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15315    }
15316
15317    /**
15318     * Utility to reconcile a desired size and state, with constraints imposed
15319     * by a MeasureSpec.  Will take the desired size, unless a different size
15320     * is imposed by the constraints.  The returned value is a compound integer,
15321     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15322     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15323     * size is smaller than the size the view wants to be.
15324     *
15325     * @param size How big the view wants to be
15326     * @param measureSpec Constraints imposed by the parent
15327     * @return Size information bit mask as defined by
15328     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15329     */
15330    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15331        int result = size;
15332        int specMode = MeasureSpec.getMode(measureSpec);
15333        int specSize =  MeasureSpec.getSize(measureSpec);
15334        switch (specMode) {
15335        case MeasureSpec.UNSPECIFIED:
15336            result = size;
15337            break;
15338        case MeasureSpec.AT_MOST:
15339            if (specSize < size) {
15340                result = specSize | MEASURED_STATE_TOO_SMALL;
15341            } else {
15342                result = size;
15343            }
15344            break;
15345        case MeasureSpec.EXACTLY:
15346            result = specSize;
15347            break;
15348        }
15349        return result | (childMeasuredState&MEASURED_STATE_MASK);
15350    }
15351
15352    /**
15353     * Utility to return a default size. Uses the supplied size if the
15354     * MeasureSpec imposed no constraints. Will get larger if allowed
15355     * by the MeasureSpec.
15356     *
15357     * @param size Default size for this view
15358     * @param measureSpec Constraints imposed by the parent
15359     * @return The size this view should be.
15360     */
15361    public static int getDefaultSize(int size, int measureSpec) {
15362        int result = size;
15363        int specMode = MeasureSpec.getMode(measureSpec);
15364        int specSize = MeasureSpec.getSize(measureSpec);
15365
15366        switch (specMode) {
15367        case MeasureSpec.UNSPECIFIED:
15368            result = size;
15369            break;
15370        case MeasureSpec.AT_MOST:
15371        case MeasureSpec.EXACTLY:
15372            result = specSize;
15373            break;
15374        }
15375        return result;
15376    }
15377
15378    /**
15379     * Returns the suggested minimum height that the view should use. This
15380     * returns the maximum of the view's minimum height
15381     * and the background's minimum height
15382     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15383     * <p>
15384     * When being used in {@link #onMeasure(int, int)}, the caller should still
15385     * ensure the returned height is within the requirements of the parent.
15386     *
15387     * @return The suggested minimum height of the view.
15388     */
15389    protected int getSuggestedMinimumHeight() {
15390        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15391
15392    }
15393
15394    /**
15395     * Returns the suggested minimum width that the view should use. This
15396     * returns the maximum of the view's minimum width)
15397     * and the background's minimum width
15398     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15399     * <p>
15400     * When being used in {@link #onMeasure(int, int)}, the caller should still
15401     * ensure the returned width is within the requirements of the parent.
15402     *
15403     * @return The suggested minimum width of the view.
15404     */
15405    protected int getSuggestedMinimumWidth() {
15406        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15407    }
15408
15409    /**
15410     * Returns the minimum height of the view.
15411     *
15412     * @return the minimum height the view will try to be.
15413     *
15414     * @see #setMinimumHeight(int)
15415     *
15416     * @attr ref android.R.styleable#View_minHeight
15417     */
15418    public int getMinimumHeight() {
15419        return mMinHeight;
15420    }
15421
15422    /**
15423     * Sets the minimum height of the view. It is not guaranteed the view will
15424     * be able to achieve this minimum height (for example, if its parent layout
15425     * constrains it with less available height).
15426     *
15427     * @param minHeight The minimum height the view will try to be.
15428     *
15429     * @see #getMinimumHeight()
15430     *
15431     * @attr ref android.R.styleable#View_minHeight
15432     */
15433    public void setMinimumHeight(int minHeight) {
15434        mMinHeight = minHeight;
15435        requestLayout();
15436    }
15437
15438    /**
15439     * Returns the minimum width of the view.
15440     *
15441     * @return the minimum width the view will try to be.
15442     *
15443     * @see #setMinimumWidth(int)
15444     *
15445     * @attr ref android.R.styleable#View_minWidth
15446     */
15447    public int getMinimumWidth() {
15448        return mMinWidth;
15449    }
15450
15451    /**
15452     * Sets the minimum width of the view. It is not guaranteed the view will
15453     * be able to achieve this minimum width (for example, if its parent layout
15454     * constrains it with less available width).
15455     *
15456     * @param minWidth The minimum width the view will try to be.
15457     *
15458     * @see #getMinimumWidth()
15459     *
15460     * @attr ref android.R.styleable#View_minWidth
15461     */
15462    public void setMinimumWidth(int minWidth) {
15463        mMinWidth = minWidth;
15464        requestLayout();
15465
15466    }
15467
15468    /**
15469     * Get the animation currently associated with this view.
15470     *
15471     * @return The animation that is currently playing or
15472     *         scheduled to play for this view.
15473     */
15474    public Animation getAnimation() {
15475        return mCurrentAnimation;
15476    }
15477
15478    /**
15479     * Start the specified animation now.
15480     *
15481     * @param animation the animation to start now
15482     */
15483    public void startAnimation(Animation animation) {
15484        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15485        setAnimation(animation);
15486        invalidateParentCaches();
15487        invalidate(true);
15488    }
15489
15490    /**
15491     * Cancels any animations for this view.
15492     */
15493    public void clearAnimation() {
15494        if (mCurrentAnimation != null) {
15495            mCurrentAnimation.detach();
15496        }
15497        mCurrentAnimation = null;
15498        invalidateParentIfNeeded();
15499    }
15500
15501    /**
15502     * Sets the next animation to play for this view.
15503     * If you want the animation to play immediately, use
15504     * {@link #startAnimation(android.view.animation.Animation)} instead.
15505     * This method provides allows fine-grained
15506     * control over the start time and invalidation, but you
15507     * must make sure that 1) the animation has a start time set, and
15508     * 2) the view's parent (which controls animations on its children)
15509     * will be invalidated when the animation is supposed to
15510     * start.
15511     *
15512     * @param animation The next animation, or null.
15513     */
15514    public void setAnimation(Animation animation) {
15515        mCurrentAnimation = animation;
15516
15517        if (animation != null) {
15518            // If the screen is off assume the animation start time is now instead of
15519            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15520            // would cause the animation to start when the screen turns back on
15521            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15522                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15523                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15524            }
15525            animation.reset();
15526        }
15527    }
15528
15529    /**
15530     * Invoked by a parent ViewGroup to notify the start of the animation
15531     * currently associated with this view. If you override this method,
15532     * always call super.onAnimationStart();
15533     *
15534     * @see #setAnimation(android.view.animation.Animation)
15535     * @see #getAnimation()
15536     */
15537    protected void onAnimationStart() {
15538        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
15539    }
15540
15541    /**
15542     * Invoked by a parent ViewGroup to notify the end of the animation
15543     * currently associated with this view. If you override this method,
15544     * always call super.onAnimationEnd();
15545     *
15546     * @see #setAnimation(android.view.animation.Animation)
15547     * @see #getAnimation()
15548     */
15549    protected void onAnimationEnd() {
15550        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
15551    }
15552
15553    /**
15554     * Invoked if there is a Transform that involves alpha. Subclass that can
15555     * draw themselves with the specified alpha should return true, and then
15556     * respect that alpha when their onDraw() is called. If this returns false
15557     * then the view may be redirected to draw into an offscreen buffer to
15558     * fulfill the request, which will look fine, but may be slower than if the
15559     * subclass handles it internally. The default implementation returns false.
15560     *
15561     * @param alpha The alpha (0..255) to apply to the view's drawing
15562     * @return true if the view can draw with the specified alpha.
15563     */
15564    protected boolean onSetAlpha(int alpha) {
15565        return false;
15566    }
15567
15568    /**
15569     * This is used by the RootView to perform an optimization when
15570     * the view hierarchy contains one or several SurfaceView.
15571     * SurfaceView is always considered transparent, but its children are not,
15572     * therefore all View objects remove themselves from the global transparent
15573     * region (passed as a parameter to this function).
15574     *
15575     * @param region The transparent region for this ViewAncestor (window).
15576     *
15577     * @return Returns true if the effective visibility of the view at this
15578     * point is opaque, regardless of the transparent region; returns false
15579     * if it is possible for underlying windows to be seen behind the view.
15580     *
15581     * {@hide}
15582     */
15583    public boolean gatherTransparentRegion(Region region) {
15584        final AttachInfo attachInfo = mAttachInfo;
15585        if (region != null && attachInfo != null) {
15586            final int pflags = mPrivateFlags;
15587            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
15588                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15589                // remove it from the transparent region.
15590                final int[] location = attachInfo.mTransparentLocation;
15591                getLocationInWindow(location);
15592                region.op(location[0], location[1], location[0] + mRight - mLeft,
15593                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15594            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15595                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15596                // exists, so we remove the background drawable's non-transparent
15597                // parts from this transparent region.
15598                applyDrawableToTransparentRegion(mBackground, region);
15599            }
15600        }
15601        return true;
15602    }
15603
15604    /**
15605     * Play a sound effect for this view.
15606     *
15607     * <p>The framework will play sound effects for some built in actions, such as
15608     * clicking, but you may wish to play these effects in your widget,
15609     * for instance, for internal navigation.
15610     *
15611     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15612     * {@link #isSoundEffectsEnabled()} is true.
15613     *
15614     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15615     */
15616    public void playSoundEffect(int soundConstant) {
15617        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15618            return;
15619        }
15620        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15621    }
15622
15623    /**
15624     * BZZZTT!!1!
15625     *
15626     * <p>Provide haptic feedback to the user for this view.
15627     *
15628     * <p>The framework will provide haptic feedback for some built in actions,
15629     * such as long presses, but you may wish to provide feedback for your
15630     * own widget.
15631     *
15632     * <p>The feedback will only be performed if
15633     * {@link #isHapticFeedbackEnabled()} is true.
15634     *
15635     * @param feedbackConstant One of the constants defined in
15636     * {@link HapticFeedbackConstants}
15637     */
15638    public boolean performHapticFeedback(int feedbackConstant) {
15639        return performHapticFeedback(feedbackConstant, 0);
15640    }
15641
15642    /**
15643     * BZZZTT!!1!
15644     *
15645     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15646     *
15647     * @param feedbackConstant One of the constants defined in
15648     * {@link HapticFeedbackConstants}
15649     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15650     */
15651    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15652        if (mAttachInfo == null) {
15653            return false;
15654        }
15655        //noinspection SimplifiableIfStatement
15656        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15657                && !isHapticFeedbackEnabled()) {
15658            return false;
15659        }
15660        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15661                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15662    }
15663
15664    /**
15665     * Request that the visibility of the status bar or other screen/window
15666     * decorations be changed.
15667     *
15668     * <p>This method is used to put the over device UI into temporary modes
15669     * where the user's attention is focused more on the application content,
15670     * by dimming or hiding surrounding system affordances.  This is typically
15671     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15672     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15673     * to be placed behind the action bar (and with these flags other system
15674     * affordances) so that smooth transitions between hiding and showing them
15675     * can be done.
15676     *
15677     * <p>Two representative examples of the use of system UI visibility is
15678     * implementing a content browsing application (like a magazine reader)
15679     * and a video playing application.
15680     *
15681     * <p>The first code shows a typical implementation of a View in a content
15682     * browsing application.  In this implementation, the application goes
15683     * into a content-oriented mode by hiding the status bar and action bar,
15684     * and putting the navigation elements into lights out mode.  The user can
15685     * then interact with content while in this mode.  Such an application should
15686     * provide an easy way for the user to toggle out of the mode (such as to
15687     * check information in the status bar or access notifications).  In the
15688     * implementation here, this is done simply by tapping on the content.
15689     *
15690     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15691     *      content}
15692     *
15693     * <p>This second code sample shows a typical implementation of a View
15694     * in a video playing application.  In this situation, while the video is
15695     * playing the application would like to go into a complete full-screen mode,
15696     * to use as much of the display as possible for the video.  When in this state
15697     * the user can not interact with the application; the system intercepts
15698     * touching on the screen to pop the UI out of full screen mode.  See
15699     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15700     *
15701     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15702     *      content}
15703     *
15704     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15705     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15706     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15707     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15708     */
15709    public void setSystemUiVisibility(int visibility) {
15710        if (visibility != mSystemUiVisibility) {
15711            mSystemUiVisibility = visibility;
15712            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15713                mParent.recomputeViewAttributes(this);
15714            }
15715        }
15716    }
15717
15718    /**
15719     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15720     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15721     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15722     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15723     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15724     */
15725    public int getSystemUiVisibility() {
15726        return mSystemUiVisibility;
15727    }
15728
15729    /**
15730     * Returns the current system UI visibility that is currently set for
15731     * the entire window.  This is the combination of the
15732     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15733     * views in the window.
15734     */
15735    public int getWindowSystemUiVisibility() {
15736        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15737    }
15738
15739    /**
15740     * Override to find out when the window's requested system UI visibility
15741     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15742     * This is different from the callbacks recieved through
15743     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15744     * in that this is only telling you about the local request of the window,
15745     * not the actual values applied by the system.
15746     */
15747    public void onWindowSystemUiVisibilityChanged(int visible) {
15748    }
15749
15750    /**
15751     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15752     * the view hierarchy.
15753     */
15754    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15755        onWindowSystemUiVisibilityChanged(visible);
15756    }
15757
15758    /**
15759     * Set a listener to receive callbacks when the visibility of the system bar changes.
15760     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15761     */
15762    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15763        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15764        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15765            mParent.recomputeViewAttributes(this);
15766        }
15767    }
15768
15769    /**
15770     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15771     * the view hierarchy.
15772     */
15773    public void dispatchSystemUiVisibilityChanged(int visibility) {
15774        ListenerInfo li = mListenerInfo;
15775        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15776            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15777                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15778        }
15779    }
15780
15781    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15782        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15783        if (val != mSystemUiVisibility) {
15784            setSystemUiVisibility(val);
15785            return true;
15786        }
15787        return false;
15788    }
15789
15790    /** @hide */
15791    public void setDisabledSystemUiVisibility(int flags) {
15792        if (mAttachInfo != null) {
15793            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15794                mAttachInfo.mDisabledSystemUiVisibility = flags;
15795                if (mParent != null) {
15796                    mParent.recomputeViewAttributes(this);
15797                }
15798            }
15799        }
15800    }
15801
15802    /**
15803     * Creates an image that the system displays during the drag and drop
15804     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15805     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15806     * appearance as the given View. The default also positions the center of the drag shadow
15807     * directly under the touch point. If no View is provided (the constructor with no parameters
15808     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15809     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15810     * default is an invisible drag shadow.
15811     * <p>
15812     * You are not required to use the View you provide to the constructor as the basis of the
15813     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15814     * anything you want as the drag shadow.
15815     * </p>
15816     * <p>
15817     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15818     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15819     *  size and position of the drag shadow. It uses this data to construct a
15820     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15821     *  so that your application can draw the shadow image in the Canvas.
15822     * </p>
15823     *
15824     * <div class="special reference">
15825     * <h3>Developer Guides</h3>
15826     * <p>For a guide to implementing drag and drop features, read the
15827     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15828     * </div>
15829     */
15830    public static class DragShadowBuilder {
15831        private final WeakReference<View> mView;
15832
15833        /**
15834         * Constructs a shadow image builder based on a View. By default, the resulting drag
15835         * shadow will have the same appearance and dimensions as the View, with the touch point
15836         * over the center of the View.
15837         * @param view A View. Any View in scope can be used.
15838         */
15839        public DragShadowBuilder(View view) {
15840            mView = new WeakReference<View>(view);
15841        }
15842
15843        /**
15844         * Construct a shadow builder object with no associated View.  This
15845         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15846         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15847         * to supply the drag shadow's dimensions and appearance without
15848         * reference to any View object. If they are not overridden, then the result is an
15849         * invisible drag shadow.
15850         */
15851        public DragShadowBuilder() {
15852            mView = new WeakReference<View>(null);
15853        }
15854
15855        /**
15856         * Returns the View object that had been passed to the
15857         * {@link #View.DragShadowBuilder(View)}
15858         * constructor.  If that View parameter was {@code null} or if the
15859         * {@link #View.DragShadowBuilder()}
15860         * constructor was used to instantiate the builder object, this method will return
15861         * null.
15862         *
15863         * @return The View object associate with this builder object.
15864         */
15865        @SuppressWarnings({"JavadocReference"})
15866        final public View getView() {
15867            return mView.get();
15868        }
15869
15870        /**
15871         * Provides the metrics for the shadow image. These include the dimensions of
15872         * the shadow image, and the point within that shadow that should
15873         * be centered under the touch location while dragging.
15874         * <p>
15875         * The default implementation sets the dimensions of the shadow to be the
15876         * same as the dimensions of the View itself and centers the shadow under
15877         * the touch point.
15878         * </p>
15879         *
15880         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15881         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15882         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15883         * image.
15884         *
15885         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15886         * shadow image that should be underneath the touch point during the drag and drop
15887         * operation. Your application must set {@link android.graphics.Point#x} to the
15888         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15889         */
15890        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15891            final View view = mView.get();
15892            if (view != null) {
15893                shadowSize.set(view.getWidth(), view.getHeight());
15894                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15895            } else {
15896                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15897            }
15898        }
15899
15900        /**
15901         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15902         * based on the dimensions it received from the
15903         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15904         *
15905         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15906         */
15907        public void onDrawShadow(Canvas canvas) {
15908            final View view = mView.get();
15909            if (view != null) {
15910                view.draw(canvas);
15911            } else {
15912                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15913            }
15914        }
15915    }
15916
15917    /**
15918     * Starts a drag and drop operation. When your application calls this method, it passes a
15919     * {@link android.view.View.DragShadowBuilder} object to the system. The
15920     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15921     * to get metrics for the drag shadow, and then calls the object's
15922     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15923     * <p>
15924     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15925     *  drag events to all the View objects in your application that are currently visible. It does
15926     *  this either by calling the View object's drag listener (an implementation of
15927     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15928     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15929     *  Both are passed a {@link android.view.DragEvent} object that has a
15930     *  {@link android.view.DragEvent#getAction()} value of
15931     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15932     * </p>
15933     * <p>
15934     * Your application can invoke startDrag() on any attached View object. The View object does not
15935     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15936     * be related to the View the user selected for dragging.
15937     * </p>
15938     * @param data A {@link android.content.ClipData} object pointing to the data to be
15939     * transferred by the drag and drop operation.
15940     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15941     * drag shadow.
15942     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15943     * drop operation. This Object is put into every DragEvent object sent by the system during the
15944     * current drag.
15945     * <p>
15946     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15947     * to the target Views. For example, it can contain flags that differentiate between a
15948     * a copy operation and a move operation.
15949     * </p>
15950     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15951     * so the parameter should be set to 0.
15952     * @return {@code true} if the method completes successfully, or
15953     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15954     * do a drag, and so no drag operation is in progress.
15955     */
15956    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15957            Object myLocalState, int flags) {
15958        if (ViewDebug.DEBUG_DRAG) {
15959            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15960        }
15961        boolean okay = false;
15962
15963        Point shadowSize = new Point();
15964        Point shadowTouchPoint = new Point();
15965        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15966
15967        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15968                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15969            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15970        }
15971
15972        if (ViewDebug.DEBUG_DRAG) {
15973            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15974                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15975        }
15976        Surface surface = new Surface();
15977        try {
15978            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15979                    flags, shadowSize.x, shadowSize.y, surface);
15980            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15981                    + " surface=" + surface);
15982            if (token != null) {
15983                Canvas canvas = surface.lockCanvas(null);
15984                try {
15985                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15986                    shadowBuilder.onDrawShadow(canvas);
15987                } finally {
15988                    surface.unlockCanvasAndPost(canvas);
15989                }
15990
15991                final ViewRootImpl root = getViewRootImpl();
15992
15993                // Cache the local state object for delivery with DragEvents
15994                root.setLocalDragState(myLocalState);
15995
15996                // repurpose 'shadowSize' for the last touch point
15997                root.getLastTouchPoint(shadowSize);
15998
15999                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16000                        shadowSize.x, shadowSize.y,
16001                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16002                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16003
16004                // Off and running!  Release our local surface instance; the drag
16005                // shadow surface is now managed by the system process.
16006                surface.release();
16007            }
16008        } catch (Exception e) {
16009            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16010            surface.destroy();
16011        }
16012
16013        return okay;
16014    }
16015
16016    /**
16017     * Handles drag events sent by the system following a call to
16018     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16019     *<p>
16020     * When the system calls this method, it passes a
16021     * {@link android.view.DragEvent} object. A call to
16022     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16023     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16024     * operation.
16025     * @param event The {@link android.view.DragEvent} sent by the system.
16026     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16027     * in DragEvent, indicating the type of drag event represented by this object.
16028     * @return {@code true} if the method was successful, otherwise {@code false}.
16029     * <p>
16030     *  The method should return {@code true} in response to an action type of
16031     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16032     *  operation.
16033     * </p>
16034     * <p>
16035     *  The method should also return {@code true} in response to an action type of
16036     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16037     *  {@code false} if it didn't.
16038     * </p>
16039     */
16040    public boolean onDragEvent(DragEvent event) {
16041        return false;
16042    }
16043
16044    /**
16045     * Detects if this View is enabled and has a drag event listener.
16046     * If both are true, then it calls the drag event listener with the
16047     * {@link android.view.DragEvent} it received. If the drag event listener returns
16048     * {@code true}, then dispatchDragEvent() returns {@code true}.
16049     * <p>
16050     * For all other cases, the method calls the
16051     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16052     * method and returns its result.
16053     * </p>
16054     * <p>
16055     * This ensures that a drag event is always consumed, even if the View does not have a drag
16056     * event listener. However, if the View has a listener and the listener returns true, then
16057     * onDragEvent() is not called.
16058     * </p>
16059     */
16060    public boolean dispatchDragEvent(DragEvent event) {
16061        //noinspection SimplifiableIfStatement
16062        ListenerInfo li = mListenerInfo;
16063        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16064                && li.mOnDragListener.onDrag(this, event)) {
16065            return true;
16066        }
16067        return onDragEvent(event);
16068    }
16069
16070    boolean canAcceptDrag() {
16071        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16072    }
16073
16074    /**
16075     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16076     * it is ever exposed at all.
16077     * @hide
16078     */
16079    public void onCloseSystemDialogs(String reason) {
16080    }
16081
16082    /**
16083     * Given a Drawable whose bounds have been set to draw into this view,
16084     * update a Region being computed for
16085     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16086     * that any non-transparent parts of the Drawable are removed from the
16087     * given transparent region.
16088     *
16089     * @param dr The Drawable whose transparency is to be applied to the region.
16090     * @param region A Region holding the current transparency information,
16091     * where any parts of the region that are set are considered to be
16092     * transparent.  On return, this region will be modified to have the
16093     * transparency information reduced by the corresponding parts of the
16094     * Drawable that are not transparent.
16095     * {@hide}
16096     */
16097    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16098        if (DBG) {
16099            Log.i("View", "Getting transparent region for: " + this);
16100        }
16101        final Region r = dr.getTransparentRegion();
16102        final Rect db = dr.getBounds();
16103        final AttachInfo attachInfo = mAttachInfo;
16104        if (r != null && attachInfo != null) {
16105            final int w = getRight()-getLeft();
16106            final int h = getBottom()-getTop();
16107            if (db.left > 0) {
16108                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16109                r.op(0, 0, db.left, h, Region.Op.UNION);
16110            }
16111            if (db.right < w) {
16112                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16113                r.op(db.right, 0, w, h, Region.Op.UNION);
16114            }
16115            if (db.top > 0) {
16116                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16117                r.op(0, 0, w, db.top, Region.Op.UNION);
16118            }
16119            if (db.bottom < h) {
16120                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16121                r.op(0, db.bottom, w, h, Region.Op.UNION);
16122            }
16123            final int[] location = attachInfo.mTransparentLocation;
16124            getLocationInWindow(location);
16125            r.translate(location[0], location[1]);
16126            region.op(r, Region.Op.INTERSECT);
16127        } else {
16128            region.op(db, Region.Op.DIFFERENCE);
16129        }
16130    }
16131
16132    private void checkForLongClick(int delayOffset) {
16133        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16134            mHasPerformedLongPress = false;
16135
16136            if (mPendingCheckForLongPress == null) {
16137                mPendingCheckForLongPress = new CheckForLongPress();
16138            }
16139            mPendingCheckForLongPress.rememberWindowAttachCount();
16140            postDelayed(mPendingCheckForLongPress,
16141                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16142        }
16143    }
16144
16145    /**
16146     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16147     * LayoutInflater} class, which provides a full range of options for view inflation.
16148     *
16149     * @param context The Context object for your activity or application.
16150     * @param resource The resource ID to inflate
16151     * @param root A view group that will be the parent.  Used to properly inflate the
16152     * layout_* parameters.
16153     * @see LayoutInflater
16154     */
16155    public static View inflate(Context context, int resource, ViewGroup root) {
16156        LayoutInflater factory = LayoutInflater.from(context);
16157        return factory.inflate(resource, root);
16158    }
16159
16160    /**
16161     * Scroll the view with standard behavior for scrolling beyond the normal
16162     * content boundaries. Views that call this method should override
16163     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16164     * results of an over-scroll operation.
16165     *
16166     * Views can use this method to handle any touch or fling-based scrolling.
16167     *
16168     * @param deltaX Change in X in pixels
16169     * @param deltaY Change in Y in pixels
16170     * @param scrollX Current X scroll value in pixels before applying deltaX
16171     * @param scrollY Current Y scroll value in pixels before applying deltaY
16172     * @param scrollRangeX Maximum content scroll range along the X axis
16173     * @param scrollRangeY Maximum content scroll range along the Y axis
16174     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16175     *          along the X axis.
16176     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16177     *          along the Y axis.
16178     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16179     * @return true if scrolling was clamped to an over-scroll boundary along either
16180     *          axis, false otherwise.
16181     */
16182    @SuppressWarnings({"UnusedParameters"})
16183    protected boolean overScrollBy(int deltaX, int deltaY,
16184            int scrollX, int scrollY,
16185            int scrollRangeX, int scrollRangeY,
16186            int maxOverScrollX, int maxOverScrollY,
16187            boolean isTouchEvent) {
16188        final int overScrollMode = mOverScrollMode;
16189        final boolean canScrollHorizontal =
16190                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16191        final boolean canScrollVertical =
16192                computeVerticalScrollRange() > computeVerticalScrollExtent();
16193        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16194                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16195        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16196                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16197
16198        int newScrollX = scrollX + deltaX;
16199        if (!overScrollHorizontal) {
16200            maxOverScrollX = 0;
16201        }
16202
16203        int newScrollY = scrollY + deltaY;
16204        if (!overScrollVertical) {
16205            maxOverScrollY = 0;
16206        }
16207
16208        // Clamp values if at the limits and record
16209        final int left = -maxOverScrollX;
16210        final int right = maxOverScrollX + scrollRangeX;
16211        final int top = -maxOverScrollY;
16212        final int bottom = maxOverScrollY + scrollRangeY;
16213
16214        boolean clampedX = false;
16215        if (newScrollX > right) {
16216            newScrollX = right;
16217            clampedX = true;
16218        } else if (newScrollX < left) {
16219            newScrollX = left;
16220            clampedX = true;
16221        }
16222
16223        boolean clampedY = false;
16224        if (newScrollY > bottom) {
16225            newScrollY = bottom;
16226            clampedY = true;
16227        } else if (newScrollY < top) {
16228            newScrollY = top;
16229            clampedY = true;
16230        }
16231
16232        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16233
16234        return clampedX || clampedY;
16235    }
16236
16237    /**
16238     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16239     * respond to the results of an over-scroll operation.
16240     *
16241     * @param scrollX New X scroll value in pixels
16242     * @param scrollY New Y scroll value in pixels
16243     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16244     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16245     */
16246    protected void onOverScrolled(int scrollX, int scrollY,
16247            boolean clampedX, boolean clampedY) {
16248        // Intentionally empty.
16249    }
16250
16251    /**
16252     * Returns the over-scroll mode for this view. The result will be
16253     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16254     * (allow over-scrolling only if the view content is larger than the container),
16255     * or {@link #OVER_SCROLL_NEVER}.
16256     *
16257     * @return This view's over-scroll mode.
16258     */
16259    public int getOverScrollMode() {
16260        return mOverScrollMode;
16261    }
16262
16263    /**
16264     * Set the over-scroll mode for this view. Valid over-scroll modes are
16265     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16266     * (allow over-scrolling only if the view content is larger than the container),
16267     * or {@link #OVER_SCROLL_NEVER}.
16268     *
16269     * Setting the over-scroll mode of a view will have an effect only if the
16270     * view is capable of scrolling.
16271     *
16272     * @param overScrollMode The new over-scroll mode for this view.
16273     */
16274    public void setOverScrollMode(int overScrollMode) {
16275        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16276                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16277                overScrollMode != OVER_SCROLL_NEVER) {
16278            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16279        }
16280        mOverScrollMode = overScrollMode;
16281    }
16282
16283    /**
16284     * Gets a scale factor that determines the distance the view should scroll
16285     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16286     * @return The vertical scroll scale factor.
16287     * @hide
16288     */
16289    protected float getVerticalScrollFactor() {
16290        if (mVerticalScrollFactor == 0) {
16291            TypedValue outValue = new TypedValue();
16292            if (!mContext.getTheme().resolveAttribute(
16293                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16294                throw new IllegalStateException(
16295                        "Expected theme to define listPreferredItemHeight.");
16296            }
16297            mVerticalScrollFactor = outValue.getDimension(
16298                    mContext.getResources().getDisplayMetrics());
16299        }
16300        return mVerticalScrollFactor;
16301    }
16302
16303    /**
16304     * Gets a scale factor that determines the distance the view should scroll
16305     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16306     * @return The horizontal scroll scale factor.
16307     * @hide
16308     */
16309    protected float getHorizontalScrollFactor() {
16310        // TODO: Should use something else.
16311        return getVerticalScrollFactor();
16312    }
16313
16314    /**
16315     * Return the value specifying the text direction or policy that was set with
16316     * {@link #setTextDirection(int)}.
16317     *
16318     * @return the defined text direction. It can be one of:
16319     *
16320     * {@link #TEXT_DIRECTION_INHERIT},
16321     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16322     * {@link #TEXT_DIRECTION_ANY_RTL},
16323     * {@link #TEXT_DIRECTION_LTR},
16324     * {@link #TEXT_DIRECTION_RTL},
16325     * {@link #TEXT_DIRECTION_LOCALE}
16326     */
16327    @ViewDebug.ExportedProperty(category = "text", mapping = {
16328            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16329            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16330            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16331            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16332            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16333            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16334    })
16335    public int getTextDirection() {
16336        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
16337    }
16338
16339    /**
16340     * Set the text direction.
16341     *
16342     * @param textDirection the direction to set. Should be one of:
16343     *
16344     * {@link #TEXT_DIRECTION_INHERIT},
16345     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16346     * {@link #TEXT_DIRECTION_ANY_RTL},
16347     * {@link #TEXT_DIRECTION_LTR},
16348     * {@link #TEXT_DIRECTION_RTL},
16349     * {@link #TEXT_DIRECTION_LOCALE}
16350     */
16351    public void setTextDirection(int textDirection) {
16352        if (getTextDirection() != textDirection) {
16353            // Reset the current text direction and the resolved one
16354            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
16355            resetResolvedTextDirection();
16356            // Set the new text direction
16357            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
16358            // Refresh
16359            requestLayout();
16360            invalidate(true);
16361        }
16362    }
16363
16364    /**
16365     * Return the resolved text direction.
16366     *
16367     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16368     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16369     * up the parent chain of the view. if there is no parent, then it will return the default
16370     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16371     *
16372     * @return the resolved text direction. Returns one of:
16373     *
16374     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16375     * {@link #TEXT_DIRECTION_ANY_RTL},
16376     * {@link #TEXT_DIRECTION_LTR},
16377     * {@link #TEXT_DIRECTION_RTL},
16378     * {@link #TEXT_DIRECTION_LOCALE}
16379     */
16380    public int getResolvedTextDirection() {
16381        // The text direction will be resolved only if needed
16382        if ((mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) != PFLAG2_TEXT_DIRECTION_RESOLVED) {
16383            resolveTextDirection();
16384        }
16385        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16386    }
16387
16388    /**
16389     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16390     * resolution is done.
16391     */
16392    public void resolveTextDirection() {
16393        // Reset any previous text direction resolution
16394        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
16395
16396        if (hasRtlSupport()) {
16397            // Set resolved text direction flag depending on text direction flag
16398            final int textDirection = getTextDirection();
16399            switch(textDirection) {
16400                case TEXT_DIRECTION_INHERIT:
16401                    if (canResolveTextDirection()) {
16402                        ViewGroup viewGroup = ((ViewGroup) mParent);
16403
16404                        // Set current resolved direction to the same value as the parent's one
16405                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16406                        switch (parentResolvedDirection) {
16407                            case TEXT_DIRECTION_FIRST_STRONG:
16408                            case TEXT_DIRECTION_ANY_RTL:
16409                            case TEXT_DIRECTION_LTR:
16410                            case TEXT_DIRECTION_RTL:
16411                            case TEXT_DIRECTION_LOCALE:
16412                                mPrivateFlags2 |=
16413                                        (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16414                                break;
16415                            default:
16416                                // Default resolved direction is "first strong" heuristic
16417                                mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16418                        }
16419                    } else {
16420                        // We cannot do the resolution if there is no parent, so use the default one
16421                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16422                    }
16423                    break;
16424                case TEXT_DIRECTION_FIRST_STRONG:
16425                case TEXT_DIRECTION_ANY_RTL:
16426                case TEXT_DIRECTION_LTR:
16427                case TEXT_DIRECTION_RTL:
16428                case TEXT_DIRECTION_LOCALE:
16429                    // Resolved direction is the same as text direction
16430                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16431                    break;
16432                default:
16433                    // Default resolved direction is "first strong" heuristic
16434                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16435            }
16436        } else {
16437            // Default resolved direction is "first strong" heuristic
16438            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16439        }
16440
16441        // Set to resolved
16442        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
16443        onResolvedTextDirectionChanged();
16444    }
16445
16446    /**
16447     * Called when text direction has been resolved. Subclasses that care about text direction
16448     * resolution should override this method.
16449     *
16450     * The default implementation does nothing.
16451     */
16452    public void onResolvedTextDirectionChanged() {
16453    }
16454
16455    /**
16456     * Check if text direction resolution can be done.
16457     *
16458     * @return true if text direction resolution can be done otherwise return false.
16459     */
16460    public boolean canResolveTextDirection() {
16461        switch (getTextDirection()) {
16462            case TEXT_DIRECTION_INHERIT:
16463                return (mParent != null) && (mParent instanceof ViewGroup);
16464            default:
16465                return true;
16466        }
16467    }
16468
16469    /**
16470     * Reset resolved text direction. Text direction can be resolved with a call to
16471     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16472     * reset is done.
16473     */
16474    public void resetResolvedTextDirection() {
16475        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
16476        onResolvedTextDirectionReset();
16477    }
16478
16479    /**
16480     * Called when text direction is reset. Subclasses that care about text direction reset should
16481     * override this method and do a reset of the text direction of their children. The default
16482     * implementation does nothing.
16483     */
16484    public void onResolvedTextDirectionReset() {
16485    }
16486
16487    /**
16488     * Return the value specifying the text alignment or policy that was set with
16489     * {@link #setTextAlignment(int)}.
16490     *
16491     * @return the defined text alignment. It can be one of:
16492     *
16493     * {@link #TEXT_ALIGNMENT_INHERIT},
16494     * {@link #TEXT_ALIGNMENT_GRAVITY},
16495     * {@link #TEXT_ALIGNMENT_CENTER},
16496     * {@link #TEXT_ALIGNMENT_TEXT_START},
16497     * {@link #TEXT_ALIGNMENT_TEXT_END},
16498     * {@link #TEXT_ALIGNMENT_VIEW_START},
16499     * {@link #TEXT_ALIGNMENT_VIEW_END}
16500     */
16501    @ViewDebug.ExportedProperty(category = "text", mapping = {
16502            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16503            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16504            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16505            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16506            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16507            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16508            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16509    })
16510    public int getTextAlignment() {
16511        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
16512    }
16513
16514    /**
16515     * Set the text alignment.
16516     *
16517     * @param textAlignment The text alignment to set. Should be one of
16518     *
16519     * {@link #TEXT_ALIGNMENT_INHERIT},
16520     * {@link #TEXT_ALIGNMENT_GRAVITY},
16521     * {@link #TEXT_ALIGNMENT_CENTER},
16522     * {@link #TEXT_ALIGNMENT_TEXT_START},
16523     * {@link #TEXT_ALIGNMENT_TEXT_END},
16524     * {@link #TEXT_ALIGNMENT_VIEW_START},
16525     * {@link #TEXT_ALIGNMENT_VIEW_END}
16526     *
16527     * @attr ref android.R.styleable#View_textAlignment
16528     */
16529    public void setTextAlignment(int textAlignment) {
16530        if (textAlignment != getTextAlignment()) {
16531            // Reset the current and resolved text alignment
16532            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
16533            resetResolvedTextAlignment();
16534            // Set the new text alignment
16535            mPrivateFlags2 |= ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
16536            // Refresh
16537            requestLayout();
16538            invalidate(true);
16539        }
16540    }
16541
16542    /**
16543     * Return the resolved text alignment.
16544     *
16545     * The resolved text alignment. This needs resolution if the value is
16546     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16547     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16548     *
16549     * @return the resolved text alignment. Returns one of:
16550     *
16551     * {@link #TEXT_ALIGNMENT_GRAVITY},
16552     * {@link #TEXT_ALIGNMENT_CENTER},
16553     * {@link #TEXT_ALIGNMENT_TEXT_START},
16554     * {@link #TEXT_ALIGNMENT_TEXT_END},
16555     * {@link #TEXT_ALIGNMENT_VIEW_START},
16556     * {@link #TEXT_ALIGNMENT_VIEW_END}
16557     */
16558    @ViewDebug.ExportedProperty(category = "text", mapping = {
16559            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16560            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16561            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16562            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16563            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16564            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16565            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16566    })
16567    public int getResolvedTextAlignment() {
16568        // If text alignment is not resolved, then resolve it
16569        if ((mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) != PFLAG2_TEXT_ALIGNMENT_RESOLVED) {
16570            resolveTextAlignment();
16571        }
16572        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16573    }
16574
16575    /**
16576     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16577     * resolution is done.
16578     */
16579    public void resolveTextAlignment() {
16580        // Reset any previous text alignment resolution
16581        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
16582
16583        if (hasRtlSupport()) {
16584            // Set resolved text alignment flag depending on text alignment flag
16585            final int textAlignment = getTextAlignment();
16586            switch (textAlignment) {
16587                case TEXT_ALIGNMENT_INHERIT:
16588                    // Check if we can resolve the text alignment
16589                    if (canResolveLayoutDirection() && mParent instanceof View) {
16590                        View view = (View) mParent;
16591
16592                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16593                        switch (parentResolvedTextAlignment) {
16594                            case TEXT_ALIGNMENT_GRAVITY:
16595                            case TEXT_ALIGNMENT_TEXT_START:
16596                            case TEXT_ALIGNMENT_TEXT_END:
16597                            case TEXT_ALIGNMENT_CENTER:
16598                            case TEXT_ALIGNMENT_VIEW_START:
16599                            case TEXT_ALIGNMENT_VIEW_END:
16600                                // Resolved text alignment is the same as the parent resolved
16601                                // text alignment
16602                                mPrivateFlags2 |=
16603                                        (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16604                                break;
16605                            default:
16606                                // Use default resolved text alignment
16607                                mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16608                        }
16609                    }
16610                    else {
16611                        // We cannot do the resolution if there is no parent so use the default
16612                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16613                    }
16614                    break;
16615                case TEXT_ALIGNMENT_GRAVITY:
16616                case TEXT_ALIGNMENT_TEXT_START:
16617                case TEXT_ALIGNMENT_TEXT_END:
16618                case TEXT_ALIGNMENT_CENTER:
16619                case TEXT_ALIGNMENT_VIEW_START:
16620                case TEXT_ALIGNMENT_VIEW_END:
16621                    // Resolved text alignment is the same as text alignment
16622                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16623                    break;
16624                default:
16625                    // Use default resolved text alignment
16626                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16627            }
16628        } else {
16629            // Use default resolved text alignment
16630            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16631        }
16632
16633        // Set the resolved
16634        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
16635        onResolvedTextAlignmentChanged();
16636    }
16637
16638    /**
16639     * Check if text alignment resolution can be done.
16640     *
16641     * @return true if text alignment resolution can be done otherwise return false.
16642     */
16643    public boolean canResolveTextAlignment() {
16644        switch (getTextAlignment()) {
16645            case TEXT_DIRECTION_INHERIT:
16646                return (mParent != null);
16647            default:
16648                return true;
16649        }
16650    }
16651
16652    /**
16653     * Called when text alignment has been resolved. Subclasses that care about text alignment
16654     * resolution should override this method.
16655     *
16656     * The default implementation does nothing.
16657     */
16658    public void onResolvedTextAlignmentChanged() {
16659    }
16660
16661    /**
16662     * Reset resolved text alignment. Text alignment can be resolved with a call to
16663     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16664     * reset is done.
16665     */
16666    public void resetResolvedTextAlignment() {
16667        // Reset any previous text alignment resolution
16668        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
16669        onResolvedTextAlignmentReset();
16670    }
16671
16672    /**
16673     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16674     * override this method and do a reset of the text alignment of their children. The default
16675     * implementation does nothing.
16676     */
16677    public void onResolvedTextAlignmentReset() {
16678    }
16679
16680    /**
16681     * Generate a value suitable for use in {@link #setId(int)}.
16682     * This value will not collide with ID values generated at build time by aapt for R.id.
16683     *
16684     * @return a generated ID value
16685     */
16686    public static int generateViewId() {
16687        for (;;) {
16688            final int result = sNextGeneratedId.get();
16689            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
16690            int newValue = result + 1;
16691            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
16692            if (sNextGeneratedId.compareAndSet(result, newValue)) {
16693                return result;
16694            }
16695        }
16696    }
16697
16698    //
16699    // Properties
16700    //
16701    /**
16702     * A Property wrapper around the <code>alpha</code> functionality handled by the
16703     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16704     */
16705    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16706        @Override
16707        public void setValue(View object, float value) {
16708            object.setAlpha(value);
16709        }
16710
16711        @Override
16712        public Float get(View object) {
16713            return object.getAlpha();
16714        }
16715    };
16716
16717    /**
16718     * A Property wrapper around the <code>translationX</code> functionality handled by the
16719     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16720     */
16721    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16722        @Override
16723        public void setValue(View object, float value) {
16724            object.setTranslationX(value);
16725        }
16726
16727                @Override
16728        public Float get(View object) {
16729            return object.getTranslationX();
16730        }
16731    };
16732
16733    /**
16734     * A Property wrapper around the <code>translationY</code> functionality handled by the
16735     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16736     */
16737    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16738        @Override
16739        public void setValue(View object, float value) {
16740            object.setTranslationY(value);
16741        }
16742
16743        @Override
16744        public Float get(View object) {
16745            return object.getTranslationY();
16746        }
16747    };
16748
16749    /**
16750     * A Property wrapper around the <code>x</code> functionality handled by the
16751     * {@link View#setX(float)} and {@link View#getX()} methods.
16752     */
16753    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16754        @Override
16755        public void setValue(View object, float value) {
16756            object.setX(value);
16757        }
16758
16759        @Override
16760        public Float get(View object) {
16761            return object.getX();
16762        }
16763    };
16764
16765    /**
16766     * A Property wrapper around the <code>y</code> functionality handled by the
16767     * {@link View#setY(float)} and {@link View#getY()} methods.
16768     */
16769    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16770        @Override
16771        public void setValue(View object, float value) {
16772            object.setY(value);
16773        }
16774
16775        @Override
16776        public Float get(View object) {
16777            return object.getY();
16778        }
16779    };
16780
16781    /**
16782     * A Property wrapper around the <code>rotation</code> functionality handled by the
16783     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16784     */
16785    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16786        @Override
16787        public void setValue(View object, float value) {
16788            object.setRotation(value);
16789        }
16790
16791        @Override
16792        public Float get(View object) {
16793            return object.getRotation();
16794        }
16795    };
16796
16797    /**
16798     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16799     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16800     */
16801    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16802        @Override
16803        public void setValue(View object, float value) {
16804            object.setRotationX(value);
16805        }
16806
16807        @Override
16808        public Float get(View object) {
16809            return object.getRotationX();
16810        }
16811    };
16812
16813    /**
16814     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16815     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16816     */
16817    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16818        @Override
16819        public void setValue(View object, float value) {
16820            object.setRotationY(value);
16821        }
16822
16823        @Override
16824        public Float get(View object) {
16825            return object.getRotationY();
16826        }
16827    };
16828
16829    /**
16830     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16831     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16832     */
16833    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16834        @Override
16835        public void setValue(View object, float value) {
16836            object.setScaleX(value);
16837        }
16838
16839        @Override
16840        public Float get(View object) {
16841            return object.getScaleX();
16842        }
16843    };
16844
16845    /**
16846     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16847     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16848     */
16849    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16850        @Override
16851        public void setValue(View object, float value) {
16852            object.setScaleY(value);
16853        }
16854
16855        @Override
16856        public Float get(View object) {
16857            return object.getScaleY();
16858        }
16859    };
16860
16861    /**
16862     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16863     * Each MeasureSpec represents a requirement for either the width or the height.
16864     * A MeasureSpec is comprised of a size and a mode. There are three possible
16865     * modes:
16866     * <dl>
16867     * <dt>UNSPECIFIED</dt>
16868     * <dd>
16869     * The parent has not imposed any constraint on the child. It can be whatever size
16870     * it wants.
16871     * </dd>
16872     *
16873     * <dt>EXACTLY</dt>
16874     * <dd>
16875     * The parent has determined an exact size for the child. The child is going to be
16876     * given those bounds regardless of how big it wants to be.
16877     * </dd>
16878     *
16879     * <dt>AT_MOST</dt>
16880     * <dd>
16881     * The child can be as large as it wants up to the specified size.
16882     * </dd>
16883     * </dl>
16884     *
16885     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16886     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16887     */
16888    public static class MeasureSpec {
16889        private static final int MODE_SHIFT = 30;
16890        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16891
16892        /**
16893         * Measure specification mode: The parent has not imposed any constraint
16894         * on the child. It can be whatever size it wants.
16895         */
16896        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16897
16898        /**
16899         * Measure specification mode: The parent has determined an exact size
16900         * for the child. The child is going to be given those bounds regardless
16901         * of how big it wants to be.
16902         */
16903        public static final int EXACTLY     = 1 << MODE_SHIFT;
16904
16905        /**
16906         * Measure specification mode: The child can be as large as it wants up
16907         * to the specified size.
16908         */
16909        public static final int AT_MOST     = 2 << MODE_SHIFT;
16910
16911        /**
16912         * Creates a measure specification based on the supplied size and mode.
16913         *
16914         * The mode must always be one of the following:
16915         * <ul>
16916         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16917         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16918         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16919         * </ul>
16920         *
16921         * @param size the size of the measure specification
16922         * @param mode the mode of the measure specification
16923         * @return the measure specification based on size and mode
16924         */
16925        public static int makeMeasureSpec(int size, int mode) {
16926            return size + mode;
16927        }
16928
16929        /**
16930         * Extracts the mode from the supplied measure specification.
16931         *
16932         * @param measureSpec the measure specification to extract the mode from
16933         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16934         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16935         *         {@link android.view.View.MeasureSpec#EXACTLY}
16936         */
16937        public static int getMode(int measureSpec) {
16938            return (measureSpec & MODE_MASK);
16939        }
16940
16941        /**
16942         * Extracts the size from the supplied measure specification.
16943         *
16944         * @param measureSpec the measure specification to extract the size from
16945         * @return the size in pixels defined in the supplied measure specification
16946         */
16947        public static int getSize(int measureSpec) {
16948            return (measureSpec & ~MODE_MASK);
16949        }
16950
16951        /**
16952         * Returns a String representation of the specified measure
16953         * specification.
16954         *
16955         * @param measureSpec the measure specification to convert to a String
16956         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16957         */
16958        public static String toString(int measureSpec) {
16959            int mode = getMode(measureSpec);
16960            int size = getSize(measureSpec);
16961
16962            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16963
16964            if (mode == UNSPECIFIED)
16965                sb.append("UNSPECIFIED ");
16966            else if (mode == EXACTLY)
16967                sb.append("EXACTLY ");
16968            else if (mode == AT_MOST)
16969                sb.append("AT_MOST ");
16970            else
16971                sb.append(mode).append(" ");
16972
16973            sb.append(size);
16974            return sb.toString();
16975        }
16976    }
16977
16978    class CheckForLongPress implements Runnable {
16979
16980        private int mOriginalWindowAttachCount;
16981
16982        public void run() {
16983            if (isPressed() && (mParent != null)
16984                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16985                if (performLongClick()) {
16986                    mHasPerformedLongPress = true;
16987                }
16988            }
16989        }
16990
16991        public void rememberWindowAttachCount() {
16992            mOriginalWindowAttachCount = mWindowAttachCount;
16993        }
16994    }
16995
16996    private final class CheckForTap implements Runnable {
16997        public void run() {
16998            mPrivateFlags &= ~PFLAG_PREPRESSED;
16999            setPressed(true);
17000            checkForLongClick(ViewConfiguration.getTapTimeout());
17001        }
17002    }
17003
17004    private final class PerformClick implements Runnable {
17005        public void run() {
17006            performClick();
17007        }
17008    }
17009
17010    /** @hide */
17011    public void hackTurnOffWindowResizeAnim(boolean off) {
17012        mAttachInfo.mTurnOffWindowResizeAnim = off;
17013    }
17014
17015    /**
17016     * This method returns a ViewPropertyAnimator object, which can be used to animate
17017     * specific properties on this View.
17018     *
17019     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17020     */
17021    public ViewPropertyAnimator animate() {
17022        if (mAnimator == null) {
17023            mAnimator = new ViewPropertyAnimator(this);
17024        }
17025        return mAnimator;
17026    }
17027
17028    /**
17029     * Interface definition for a callback to be invoked when a hardware key event is
17030     * dispatched to this view. The callback will be invoked before the key event is
17031     * given to the view. This is only useful for hardware keyboards; a software input
17032     * method has no obligation to trigger this listener.
17033     */
17034    public interface OnKeyListener {
17035        /**
17036         * Called when a hardware key is dispatched to a view. This allows listeners to
17037         * get a chance to respond before the target view.
17038         * <p>Key presses in software keyboards will generally NOT trigger this method,
17039         * although some may elect to do so in some situations. Do not assume a
17040         * software input method has to be key-based; even if it is, it may use key presses
17041         * in a different way than you expect, so there is no way to reliably catch soft
17042         * input key presses.
17043         *
17044         * @param v The view the key has been dispatched to.
17045         * @param keyCode The code for the physical key that was pressed
17046         * @param event The KeyEvent object containing full information about
17047         *        the event.
17048         * @return True if the listener has consumed the event, false otherwise.
17049         */
17050        boolean onKey(View v, int keyCode, KeyEvent event);
17051    }
17052
17053    /**
17054     * Interface definition for a callback to be invoked when a touch event is
17055     * dispatched to this view. The callback will be invoked before the touch
17056     * event is given to the view.
17057     */
17058    public interface OnTouchListener {
17059        /**
17060         * Called when a touch event is dispatched to a view. This allows listeners to
17061         * get a chance to respond before the target view.
17062         *
17063         * @param v The view the touch event has been dispatched to.
17064         * @param event The MotionEvent object containing full information about
17065         *        the event.
17066         * @return True if the listener has consumed the event, false otherwise.
17067         */
17068        boolean onTouch(View v, MotionEvent event);
17069    }
17070
17071    /**
17072     * Interface definition for a callback to be invoked when a hover event is
17073     * dispatched to this view. The callback will be invoked before the hover
17074     * event is given to the view.
17075     */
17076    public interface OnHoverListener {
17077        /**
17078         * Called when a hover event is dispatched to a view. This allows listeners to
17079         * get a chance to respond before the target view.
17080         *
17081         * @param v The view the hover event has been dispatched to.
17082         * @param event The MotionEvent object containing full information about
17083         *        the event.
17084         * @return True if the listener has consumed the event, false otherwise.
17085         */
17086        boolean onHover(View v, MotionEvent event);
17087    }
17088
17089    /**
17090     * Interface definition for a callback to be invoked when a generic motion event is
17091     * dispatched to this view. The callback will be invoked before the generic motion
17092     * event is given to the view.
17093     */
17094    public interface OnGenericMotionListener {
17095        /**
17096         * Called when a generic motion event is dispatched to a view. This allows listeners to
17097         * get a chance to respond before the target view.
17098         *
17099         * @param v The view the generic motion event has been dispatched to.
17100         * @param event The MotionEvent object containing full information about
17101         *        the event.
17102         * @return True if the listener has consumed the event, false otherwise.
17103         */
17104        boolean onGenericMotion(View v, MotionEvent event);
17105    }
17106
17107    /**
17108     * Interface definition for a callback to be invoked when a view has been clicked and held.
17109     */
17110    public interface OnLongClickListener {
17111        /**
17112         * Called when a view has been clicked and held.
17113         *
17114         * @param v The view that was clicked and held.
17115         *
17116         * @return true if the callback consumed the long click, false otherwise.
17117         */
17118        boolean onLongClick(View v);
17119    }
17120
17121    /**
17122     * Interface definition for a callback to be invoked when a drag is being dispatched
17123     * to this view.  The callback will be invoked before the hosting view's own
17124     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17125     * onDrag(event) behavior, it should return 'false' from this callback.
17126     *
17127     * <div class="special reference">
17128     * <h3>Developer Guides</h3>
17129     * <p>For a guide to implementing drag and drop features, read the
17130     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17131     * </div>
17132     */
17133    public interface OnDragListener {
17134        /**
17135         * Called when a drag event is dispatched to a view. This allows listeners
17136         * to get a chance to override base View behavior.
17137         *
17138         * @param v The View that received the drag event.
17139         * @param event The {@link android.view.DragEvent} object for the drag event.
17140         * @return {@code true} if the drag event was handled successfully, or {@code false}
17141         * if the drag event was not handled. Note that {@code false} will trigger the View
17142         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17143         */
17144        boolean onDrag(View v, DragEvent event);
17145    }
17146
17147    /**
17148     * Interface definition for a callback to be invoked when the focus state of
17149     * a view changed.
17150     */
17151    public interface OnFocusChangeListener {
17152        /**
17153         * Called when the focus state of a view has changed.
17154         *
17155         * @param v The view whose state has changed.
17156         * @param hasFocus The new focus state of v.
17157         */
17158        void onFocusChange(View v, boolean hasFocus);
17159    }
17160
17161    /**
17162     * Interface definition for a callback to be invoked when a view is clicked.
17163     */
17164    public interface OnClickListener {
17165        /**
17166         * Called when a view has been clicked.
17167         *
17168         * @param v The view that was clicked.
17169         */
17170        void onClick(View v);
17171    }
17172
17173    /**
17174     * Interface definition for a callback to be invoked when the context menu
17175     * for this view is being built.
17176     */
17177    public interface OnCreateContextMenuListener {
17178        /**
17179         * Called when the context menu for this view is being built. It is not
17180         * safe to hold onto the menu after this method returns.
17181         *
17182         * @param menu The context menu that is being built
17183         * @param v The view for which the context menu is being built
17184         * @param menuInfo Extra information about the item for which the
17185         *            context menu should be shown. This information will vary
17186         *            depending on the class of v.
17187         */
17188        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17189    }
17190
17191    /**
17192     * Interface definition for a callback to be invoked when the status bar changes
17193     * visibility.  This reports <strong>global</strong> changes to the system UI
17194     * state, not what the application is requesting.
17195     *
17196     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17197     */
17198    public interface OnSystemUiVisibilityChangeListener {
17199        /**
17200         * Called when the status bar changes visibility because of a call to
17201         * {@link View#setSystemUiVisibility(int)}.
17202         *
17203         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17204         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17205         * This tells you the <strong>global</strong> state of these UI visibility
17206         * flags, not what your app is currently applying.
17207         */
17208        public void onSystemUiVisibilityChange(int visibility);
17209    }
17210
17211    /**
17212     * Interface definition for a callback to be invoked when this view is attached
17213     * or detached from its window.
17214     */
17215    public interface OnAttachStateChangeListener {
17216        /**
17217         * Called when the view is attached to a window.
17218         * @param v The view that was attached
17219         */
17220        public void onViewAttachedToWindow(View v);
17221        /**
17222         * Called when the view is detached from a window.
17223         * @param v The view that was detached
17224         */
17225        public void onViewDetachedFromWindow(View v);
17226    }
17227
17228    private final class UnsetPressedState implements Runnable {
17229        public void run() {
17230            setPressed(false);
17231        }
17232    }
17233
17234    /**
17235     * Base class for derived classes that want to save and restore their own
17236     * state in {@link android.view.View#onSaveInstanceState()}.
17237     */
17238    public static class BaseSavedState extends AbsSavedState {
17239        /**
17240         * Constructor used when reading from a parcel. Reads the state of the superclass.
17241         *
17242         * @param source
17243         */
17244        public BaseSavedState(Parcel source) {
17245            super(source);
17246        }
17247
17248        /**
17249         * Constructor called by derived classes when creating their SavedState objects
17250         *
17251         * @param superState The state of the superclass of this view
17252         */
17253        public BaseSavedState(Parcelable superState) {
17254            super(superState);
17255        }
17256
17257        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17258                new Parcelable.Creator<BaseSavedState>() {
17259            public BaseSavedState createFromParcel(Parcel in) {
17260                return new BaseSavedState(in);
17261            }
17262
17263            public BaseSavedState[] newArray(int size) {
17264                return new BaseSavedState[size];
17265            }
17266        };
17267    }
17268
17269    /**
17270     * A set of information given to a view when it is attached to its parent
17271     * window.
17272     */
17273    static class AttachInfo {
17274        interface Callbacks {
17275            void playSoundEffect(int effectId);
17276            boolean performHapticFeedback(int effectId, boolean always);
17277        }
17278
17279        /**
17280         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17281         * to a Handler. This class contains the target (View) to invalidate and
17282         * the coordinates of the dirty rectangle.
17283         *
17284         * For performance purposes, this class also implements a pool of up to
17285         * POOL_LIMIT objects that get reused. This reduces memory allocations
17286         * whenever possible.
17287         */
17288        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17289            private static final int POOL_LIMIT = 10;
17290            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17291                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17292                        public InvalidateInfo newInstance() {
17293                            return new InvalidateInfo();
17294                        }
17295
17296                        public void onAcquired(InvalidateInfo element) {
17297                        }
17298
17299                        public void onReleased(InvalidateInfo element) {
17300                            element.target = null;
17301                        }
17302                    }, POOL_LIMIT)
17303            );
17304
17305            private InvalidateInfo mNext;
17306            private boolean mIsPooled;
17307
17308            View target;
17309
17310            int left;
17311            int top;
17312            int right;
17313            int bottom;
17314
17315            public void setNextPoolable(InvalidateInfo element) {
17316                mNext = element;
17317            }
17318
17319            public InvalidateInfo getNextPoolable() {
17320                return mNext;
17321            }
17322
17323            static InvalidateInfo acquire() {
17324                return sPool.acquire();
17325            }
17326
17327            void release() {
17328                sPool.release(this);
17329            }
17330
17331            public boolean isPooled() {
17332                return mIsPooled;
17333            }
17334
17335            public void setPooled(boolean isPooled) {
17336                mIsPooled = isPooled;
17337            }
17338        }
17339
17340        final IWindowSession mSession;
17341
17342        final IWindow mWindow;
17343
17344        final IBinder mWindowToken;
17345
17346        final Display mDisplay;
17347
17348        final Callbacks mRootCallbacks;
17349
17350        HardwareCanvas mHardwareCanvas;
17351
17352        /**
17353         * The top view of the hierarchy.
17354         */
17355        View mRootView;
17356
17357        IBinder mPanelParentWindowToken;
17358        Surface mSurface;
17359
17360        boolean mHardwareAccelerated;
17361        boolean mHardwareAccelerationRequested;
17362        HardwareRenderer mHardwareRenderer;
17363
17364        boolean mScreenOn;
17365
17366        /**
17367         * Scale factor used by the compatibility mode
17368         */
17369        float mApplicationScale;
17370
17371        /**
17372         * Indicates whether the application is in compatibility mode
17373         */
17374        boolean mScalingRequired;
17375
17376        /**
17377         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17378         */
17379        boolean mTurnOffWindowResizeAnim;
17380
17381        /**
17382         * Left position of this view's window
17383         */
17384        int mWindowLeft;
17385
17386        /**
17387         * Top position of this view's window
17388         */
17389        int mWindowTop;
17390
17391        /**
17392         * Indicates whether views need to use 32-bit drawing caches
17393         */
17394        boolean mUse32BitDrawingCache;
17395
17396        /**
17397         * For windows that are full-screen but using insets to layout inside
17398         * of the screen decorations, these are the current insets for the
17399         * content of the window.
17400         */
17401        final Rect mContentInsets = new Rect();
17402
17403        /**
17404         * For windows that are full-screen but using insets to layout inside
17405         * of the screen decorations, these are the current insets for the
17406         * actual visible parts of the window.
17407         */
17408        final Rect mVisibleInsets = new Rect();
17409
17410        /**
17411         * The internal insets given by this window.  This value is
17412         * supplied by the client (through
17413         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17414         * be given to the window manager when changed to be used in laying
17415         * out windows behind it.
17416         */
17417        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17418                = new ViewTreeObserver.InternalInsetsInfo();
17419
17420        /**
17421         * All views in the window's hierarchy that serve as scroll containers,
17422         * used to determine if the window can be resized or must be panned
17423         * to adjust for a soft input area.
17424         */
17425        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17426
17427        final KeyEvent.DispatcherState mKeyDispatchState
17428                = new KeyEvent.DispatcherState();
17429
17430        /**
17431         * Indicates whether the view's window currently has the focus.
17432         */
17433        boolean mHasWindowFocus;
17434
17435        /**
17436         * The current visibility of the window.
17437         */
17438        int mWindowVisibility;
17439
17440        /**
17441         * Indicates the time at which drawing started to occur.
17442         */
17443        long mDrawingTime;
17444
17445        /**
17446         * Indicates whether or not ignoring the DIRTY_MASK flags.
17447         */
17448        boolean mIgnoreDirtyState;
17449
17450        /**
17451         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17452         * to avoid clearing that flag prematurely.
17453         */
17454        boolean mSetIgnoreDirtyState = false;
17455
17456        /**
17457         * Indicates whether the view's window is currently in touch mode.
17458         */
17459        boolean mInTouchMode;
17460
17461        /**
17462         * Indicates that ViewAncestor should trigger a global layout change
17463         * the next time it performs a traversal
17464         */
17465        boolean mRecomputeGlobalAttributes;
17466
17467        /**
17468         * Always report new attributes at next traversal.
17469         */
17470        boolean mForceReportNewAttributes;
17471
17472        /**
17473         * Set during a traveral if any views want to keep the screen on.
17474         */
17475        boolean mKeepScreenOn;
17476
17477        /**
17478         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17479         */
17480        int mSystemUiVisibility;
17481
17482        /**
17483         * Hack to force certain system UI visibility flags to be cleared.
17484         */
17485        int mDisabledSystemUiVisibility;
17486
17487        /**
17488         * Last global system UI visibility reported by the window manager.
17489         */
17490        int mGlobalSystemUiVisibility;
17491
17492        /**
17493         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17494         * attached.
17495         */
17496        boolean mHasSystemUiListeners;
17497
17498        /**
17499         * Set if the visibility of any views has changed.
17500         */
17501        boolean mViewVisibilityChanged;
17502
17503        /**
17504         * Set to true if a view has been scrolled.
17505         */
17506        boolean mViewScrollChanged;
17507
17508        /**
17509         * Global to the view hierarchy used as a temporary for dealing with
17510         * x/y points in the transparent region computations.
17511         */
17512        final int[] mTransparentLocation = new int[2];
17513
17514        /**
17515         * Global to the view hierarchy used as a temporary for dealing with
17516         * x/y points in the ViewGroup.invalidateChild implementation.
17517         */
17518        final int[] mInvalidateChildLocation = new int[2];
17519
17520
17521        /**
17522         * Global to the view hierarchy used as a temporary for dealing with
17523         * x/y location when view is transformed.
17524         */
17525        final float[] mTmpTransformLocation = new float[2];
17526
17527        /**
17528         * The view tree observer used to dispatch global events like
17529         * layout, pre-draw, touch mode change, etc.
17530         */
17531        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17532
17533        /**
17534         * A Canvas used by the view hierarchy to perform bitmap caching.
17535         */
17536        Canvas mCanvas;
17537
17538        /**
17539         * The view root impl.
17540         */
17541        final ViewRootImpl mViewRootImpl;
17542
17543        /**
17544         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17545         * handler can be used to pump events in the UI events queue.
17546         */
17547        final Handler mHandler;
17548
17549        /**
17550         * Temporary for use in computing invalidate rectangles while
17551         * calling up the hierarchy.
17552         */
17553        final Rect mTmpInvalRect = new Rect();
17554
17555        /**
17556         * Temporary for use in computing hit areas with transformed views
17557         */
17558        final RectF mTmpTransformRect = new RectF();
17559
17560        /**
17561         * Temporary for use in transforming invalidation rect
17562         */
17563        final Matrix mTmpMatrix = new Matrix();
17564
17565        /**
17566         * Temporary for use in transforming invalidation rect
17567         */
17568        final Transformation mTmpTransformation = new Transformation();
17569
17570        /**
17571         * Temporary list for use in collecting focusable descendents of a view.
17572         */
17573        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17574
17575        /**
17576         * The id of the window for accessibility purposes.
17577         */
17578        int mAccessibilityWindowId = View.NO_ID;
17579
17580        /**
17581         * Whether to ingore not exposed for accessibility Views when
17582         * reporting the view tree to accessibility services.
17583         */
17584        boolean mIncludeNotImportantViews;
17585
17586        /**
17587         * The drawable for highlighting accessibility focus.
17588         */
17589        Drawable mAccessibilityFocusDrawable;
17590
17591        /**
17592         * Show where the margins, bounds and layout bounds are for each view.
17593         */
17594        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17595
17596        /**
17597         * Point used to compute visible regions.
17598         */
17599        final Point mPoint = new Point();
17600
17601        /**
17602         * Creates a new set of attachment information with the specified
17603         * events handler and thread.
17604         *
17605         * @param handler the events handler the view must use
17606         */
17607        AttachInfo(IWindowSession session, IWindow window, Display display,
17608                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17609            mSession = session;
17610            mWindow = window;
17611            mWindowToken = window.asBinder();
17612            mDisplay = display;
17613            mViewRootImpl = viewRootImpl;
17614            mHandler = handler;
17615            mRootCallbacks = effectPlayer;
17616        }
17617    }
17618
17619    /**
17620     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17621     * is supported. This avoids keeping too many unused fields in most
17622     * instances of View.</p>
17623     */
17624    private static class ScrollabilityCache implements Runnable {
17625
17626        /**
17627         * Scrollbars are not visible
17628         */
17629        public static final int OFF = 0;
17630
17631        /**
17632         * Scrollbars are visible
17633         */
17634        public static final int ON = 1;
17635
17636        /**
17637         * Scrollbars are fading away
17638         */
17639        public static final int FADING = 2;
17640
17641        public boolean fadeScrollBars;
17642
17643        public int fadingEdgeLength;
17644        public int scrollBarDefaultDelayBeforeFade;
17645        public int scrollBarFadeDuration;
17646
17647        public int scrollBarSize;
17648        public ScrollBarDrawable scrollBar;
17649        public float[] interpolatorValues;
17650        public View host;
17651
17652        public final Paint paint;
17653        public final Matrix matrix;
17654        public Shader shader;
17655
17656        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17657
17658        private static final float[] OPAQUE = { 255 };
17659        private static final float[] TRANSPARENT = { 0.0f };
17660
17661        /**
17662         * When fading should start. This time moves into the future every time
17663         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17664         */
17665        public long fadeStartTime;
17666
17667
17668        /**
17669         * The current state of the scrollbars: ON, OFF, or FADING
17670         */
17671        public int state = OFF;
17672
17673        private int mLastColor;
17674
17675        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17676            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17677            scrollBarSize = configuration.getScaledScrollBarSize();
17678            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17679            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17680
17681            paint = new Paint();
17682            matrix = new Matrix();
17683            // use use a height of 1, and then wack the matrix each time we
17684            // actually use it.
17685            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17686            paint.setShader(shader);
17687            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17688
17689            this.host = host;
17690        }
17691
17692        public void setFadeColor(int color) {
17693            if (color != mLastColor) {
17694                mLastColor = color;
17695
17696                if (color != 0) {
17697                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17698                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17699                    paint.setShader(shader);
17700                    // Restore the default transfer mode (src_over)
17701                    paint.setXfermode(null);
17702                } else {
17703                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17704                    paint.setShader(shader);
17705                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17706                }
17707            }
17708        }
17709
17710        public void run() {
17711            long now = AnimationUtils.currentAnimationTimeMillis();
17712            if (now >= fadeStartTime) {
17713
17714                // the animation fades the scrollbars out by changing
17715                // the opacity (alpha) from fully opaque to fully
17716                // transparent
17717                int nextFrame = (int) now;
17718                int framesCount = 0;
17719
17720                Interpolator interpolator = scrollBarInterpolator;
17721
17722                // Start opaque
17723                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17724
17725                // End transparent
17726                nextFrame += scrollBarFadeDuration;
17727                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17728
17729                state = FADING;
17730
17731                // Kick off the fade animation
17732                host.invalidate(true);
17733            }
17734        }
17735    }
17736
17737    /**
17738     * Resuable callback for sending
17739     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17740     */
17741    private class SendViewScrolledAccessibilityEvent implements Runnable {
17742        public volatile boolean mIsPending;
17743
17744        public void run() {
17745            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17746            mIsPending = false;
17747        }
17748    }
17749
17750    /**
17751     * <p>
17752     * This class represents a delegate that can be registered in a {@link View}
17753     * to enhance accessibility support via composition rather via inheritance.
17754     * It is specifically targeted to widget developers that extend basic View
17755     * classes i.e. classes in package android.view, that would like their
17756     * applications to be backwards compatible.
17757     * </p>
17758     * <div class="special reference">
17759     * <h3>Developer Guides</h3>
17760     * <p>For more information about making applications accessible, read the
17761     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17762     * developer guide.</p>
17763     * </div>
17764     * <p>
17765     * A scenario in which a developer would like to use an accessibility delegate
17766     * is overriding a method introduced in a later API version then the minimal API
17767     * version supported by the application. For example, the method
17768     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17769     * in API version 4 when the accessibility APIs were first introduced. If a
17770     * developer would like his application to run on API version 4 devices (assuming
17771     * all other APIs used by the application are version 4 or lower) and take advantage
17772     * of this method, instead of overriding the method which would break the application's
17773     * backwards compatibility, he can override the corresponding method in this
17774     * delegate and register the delegate in the target View if the API version of
17775     * the system is high enough i.e. the API version is same or higher to the API
17776     * version that introduced
17777     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17778     * </p>
17779     * <p>
17780     * Here is an example implementation:
17781     * </p>
17782     * <code><pre><p>
17783     * if (Build.VERSION.SDK_INT >= 14) {
17784     *     // If the API version is equal of higher than the version in
17785     *     // which onInitializeAccessibilityNodeInfo was introduced we
17786     *     // register a delegate with a customized implementation.
17787     *     View view = findViewById(R.id.view_id);
17788     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17789     *         public void onInitializeAccessibilityNodeInfo(View host,
17790     *                 AccessibilityNodeInfo info) {
17791     *             // Let the default implementation populate the info.
17792     *             super.onInitializeAccessibilityNodeInfo(host, info);
17793     *             // Set some other information.
17794     *             info.setEnabled(host.isEnabled());
17795     *         }
17796     *     });
17797     * }
17798     * </code></pre></p>
17799     * <p>
17800     * This delegate contains methods that correspond to the accessibility methods
17801     * in View. If a delegate has been specified the implementation in View hands
17802     * off handling to the corresponding method in this delegate. The default
17803     * implementation the delegate methods behaves exactly as the corresponding
17804     * method in View for the case of no accessibility delegate been set. Hence,
17805     * to customize the behavior of a View method, clients can override only the
17806     * corresponding delegate method without altering the behavior of the rest
17807     * accessibility related methods of the host view.
17808     * </p>
17809     */
17810    public static class AccessibilityDelegate {
17811
17812        /**
17813         * Sends an accessibility event of the given type. If accessibility is not
17814         * enabled this method has no effect.
17815         * <p>
17816         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17817         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17818         * been set.
17819         * </p>
17820         *
17821         * @param host The View hosting the delegate.
17822         * @param eventType The type of the event to send.
17823         *
17824         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17825         */
17826        public void sendAccessibilityEvent(View host, int eventType) {
17827            host.sendAccessibilityEventInternal(eventType);
17828        }
17829
17830        /**
17831         * Performs the specified accessibility action on the view. For
17832         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17833         * <p>
17834         * The default implementation behaves as
17835         * {@link View#performAccessibilityAction(int, Bundle)
17836         *  View#performAccessibilityAction(int, Bundle)} for the case of
17837         *  no accessibility delegate been set.
17838         * </p>
17839         *
17840         * @param action The action to perform.
17841         * @return Whether the action was performed.
17842         *
17843         * @see View#performAccessibilityAction(int, Bundle)
17844         *      View#performAccessibilityAction(int, Bundle)
17845         */
17846        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17847            return host.performAccessibilityActionInternal(action, args);
17848        }
17849
17850        /**
17851         * Sends an accessibility event. This method behaves exactly as
17852         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17853         * empty {@link AccessibilityEvent} and does not perform a check whether
17854         * accessibility is enabled.
17855         * <p>
17856         * The default implementation behaves as
17857         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17858         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17859         * the case of no accessibility delegate been set.
17860         * </p>
17861         *
17862         * @param host The View hosting the delegate.
17863         * @param event The event to send.
17864         *
17865         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17866         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17867         */
17868        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17869            host.sendAccessibilityEventUncheckedInternal(event);
17870        }
17871
17872        /**
17873         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17874         * to its children for adding their text content to the event.
17875         * <p>
17876         * The default implementation behaves as
17877         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17878         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17879         * the case of no accessibility delegate been set.
17880         * </p>
17881         *
17882         * @param host The View hosting the delegate.
17883         * @param event The event.
17884         * @return True if the event population was completed.
17885         *
17886         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17887         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17888         */
17889        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17890            return host.dispatchPopulateAccessibilityEventInternal(event);
17891        }
17892
17893        /**
17894         * Gives a chance to the host View to populate the accessibility event with its
17895         * text content.
17896         * <p>
17897         * The default implementation behaves as
17898         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17899         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17900         * the case of no accessibility delegate been set.
17901         * </p>
17902         *
17903         * @param host The View hosting the delegate.
17904         * @param event The accessibility event which to populate.
17905         *
17906         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17907         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17908         */
17909        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17910            host.onPopulateAccessibilityEventInternal(event);
17911        }
17912
17913        /**
17914         * Initializes an {@link AccessibilityEvent} with information about the
17915         * the host View which is the event source.
17916         * <p>
17917         * The default implementation behaves as
17918         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17919         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17920         * the case of no accessibility delegate been set.
17921         * </p>
17922         *
17923         * @param host The View hosting the delegate.
17924         * @param event The event to initialize.
17925         *
17926         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17927         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17928         */
17929        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17930            host.onInitializeAccessibilityEventInternal(event);
17931        }
17932
17933        /**
17934         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17935         * <p>
17936         * The default implementation behaves as
17937         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17938         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17939         * the case of no accessibility delegate been set.
17940         * </p>
17941         *
17942         * @param host The View hosting the delegate.
17943         * @param info The instance to initialize.
17944         *
17945         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17946         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17947         */
17948        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17949            host.onInitializeAccessibilityNodeInfoInternal(info);
17950        }
17951
17952        /**
17953         * Called when a child of the host View has requested sending an
17954         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17955         * to augment the event.
17956         * <p>
17957         * The default implementation behaves as
17958         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17959         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17960         * the case of no accessibility delegate been set.
17961         * </p>
17962         *
17963         * @param host The View hosting the delegate.
17964         * @param child The child which requests sending the event.
17965         * @param event The event to be sent.
17966         * @return True if the event should be sent
17967         *
17968         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17969         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17970         */
17971        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17972                AccessibilityEvent event) {
17973            return host.onRequestSendAccessibilityEventInternal(child, event);
17974        }
17975
17976        /**
17977         * Gets the provider for managing a virtual view hierarchy rooted at this View
17978         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17979         * that explore the window content.
17980         * <p>
17981         * The default implementation behaves as
17982         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17983         * the case of no accessibility delegate been set.
17984         * </p>
17985         *
17986         * @return The provider.
17987         *
17988         * @see AccessibilityNodeProvider
17989         */
17990        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17991            return null;
17992        }
17993    }
17994}
17995