View.java revision 46bfc4811094e5b1e3196246e457d4c6b58332ec
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.DisplayManagerGlobal;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.IBinder;
46import android.os.Parcel;
47import android.os.Parcelable;
48import android.os.RemoteException;
49import android.os.SystemClock;
50import android.os.SystemProperties;
51import android.text.TextUtils;
52import android.util.AttributeSet;
53import android.util.FloatProperty;
54import android.util.LayoutDirection;
55import android.util.Log;
56import android.util.LongSparseLongArray;
57import android.util.Pools.SynchronizedPool;
58import android.util.Property;
59import android.util.SparseArray;
60import android.util.TypedValue;
61import android.view.ContextMenu.ContextMenuInfo;
62import android.view.AccessibilityIterators.TextSegmentIterator;
63import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
64import android.view.AccessibilityIterators.WordTextSegmentIterator;
65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
66import android.view.accessibility.AccessibilityEvent;
67import android.view.accessibility.AccessibilityEventSource;
68import android.view.accessibility.AccessibilityManager;
69import android.view.accessibility.AccessibilityNodeInfo;
70import android.view.accessibility.AccessibilityNodeProvider;
71import android.view.animation.Animation;
72import android.view.animation.AnimationUtils;
73import android.view.animation.Transformation;
74import android.view.inputmethod.EditorInfo;
75import android.view.inputmethod.InputConnection;
76import android.view.inputmethod.InputMethodManager;
77import android.view.transition.Scene;
78import android.widget.ScrollBarDrawable;
79
80import static android.os.Build.VERSION_CODES.*;
81import static java.lang.Math.max;
82
83import com.android.internal.R;
84import com.android.internal.util.Predicate;
85import com.android.internal.view.menu.MenuBuilder;
86import com.google.android.collect.Lists;
87import com.google.android.collect.Maps;
88
89import java.lang.ref.WeakReference;
90import java.lang.reflect.Field;
91import java.lang.reflect.InvocationTargetException;
92import java.lang.reflect.Method;
93import java.lang.reflect.Modifier;
94import java.util.ArrayList;
95import java.util.Arrays;
96import java.util.Collections;
97import java.util.HashMap;
98import java.util.Locale;
99import java.util.concurrent.CopyOnWriteArrayList;
100import java.util.concurrent.atomic.AtomicInteger;
101
102/**
103 * <p>
104 * This class represents the basic building block for user interface components. A View
105 * occupies a rectangular area on the screen and is responsible for drawing and
106 * event handling. View is the base class for <em>widgets</em>, which are
107 * used to create interactive UI components (buttons, text fields, etc.). The
108 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
109 * are invisible containers that hold other Views (or other ViewGroups) and define
110 * their layout properties.
111 * </p>
112 *
113 * <div class="special reference">
114 * <h3>Developer Guides</h3>
115 * <p>For information about using this class to develop your application's user interface,
116 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
117 * </div>
118 *
119 * <a name="Using"></a>
120 * <h3>Using Views</h3>
121 * <p>
122 * All of the views in a window are arranged in a single tree. You can add views
123 * either from code or by specifying a tree of views in one or more XML layout
124 * files. There are many specialized subclasses of views that act as controls or
125 * are capable of displaying text, images, or other content.
126 * </p>
127 * <p>
128 * Once you have created a tree of views, there are typically a few types of
129 * common operations you may wish to perform:
130 * <ul>
131 * <li><strong>Set properties:</strong> for example setting the text of a
132 * {@link android.widget.TextView}. The available properties and the methods
133 * that set them will vary among the different subclasses of views. Note that
134 * properties that are known at build time can be set in the XML layout
135 * files.</li>
136 * <li><strong>Set focus:</strong> The framework will handled moving focus in
137 * response to user input. To force focus to a specific view, call
138 * {@link #requestFocus}.</li>
139 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
140 * that will be notified when something interesting happens to the view. For
141 * example, all views will let you set a listener to be notified when the view
142 * gains or loses focus. You can register such a listener using
143 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
144 * Other view subclasses offer more specialized listeners. For example, a Button
145 * exposes a listener to notify clients when the button is clicked.</li>
146 * <li><strong>Set visibility:</strong> You can hide or show views using
147 * {@link #setVisibility(int)}.</li>
148 * </ul>
149 * </p>
150 * <p><em>
151 * Note: The Android framework is responsible for measuring, laying out and
152 * drawing views. You should not call methods that perform these actions on
153 * views yourself unless you are actually implementing a
154 * {@link android.view.ViewGroup}.
155 * </em></p>
156 *
157 * <a name="Lifecycle"></a>
158 * <h3>Implementing a Custom View</h3>
159 *
160 * <p>
161 * To implement a custom view, you will usually begin by providing overrides for
162 * some of the standard methods that the framework calls on all views. You do
163 * not need to override all of these methods. In fact, you can start by just
164 * overriding {@link #onDraw(android.graphics.Canvas)}.
165 * <table border="2" width="85%" align="center" cellpadding="5">
166 *     <thead>
167 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
168 *     </thead>
169 *
170 *     <tbody>
171 *     <tr>
172 *         <td rowspan="2">Creation</td>
173 *         <td>Constructors</td>
174 *         <td>There is a form of the constructor that are called when the view
175 *         is created from code and a form that is called when the view is
176 *         inflated from a layout file. The second form should parse and apply
177 *         any attributes defined in the layout file.
178 *         </td>
179 *     </tr>
180 *     <tr>
181 *         <td><code>{@link #onFinishInflate()}</code></td>
182 *         <td>Called after a view and all of its children has been inflated
183 *         from XML.</td>
184 *     </tr>
185 *
186 *     <tr>
187 *         <td rowspan="3">Layout</td>
188 *         <td><code>{@link #onMeasure(int, int)}</code></td>
189 *         <td>Called to determine the size requirements for this view and all
190 *         of its children.
191 *         </td>
192 *     </tr>
193 *     <tr>
194 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
195 *         <td>Called when this view should assign a size and position to all
196 *         of its children.
197 *         </td>
198 *     </tr>
199 *     <tr>
200 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
201 *         <td>Called when the size of this view has changed.
202 *         </td>
203 *     </tr>
204 *
205 *     <tr>
206 *         <td>Drawing</td>
207 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
208 *         <td>Called when the view should render its content.
209 *         </td>
210 *     </tr>
211 *
212 *     <tr>
213 *         <td rowspan="4">Event processing</td>
214 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
215 *         <td>Called when a new hardware key event occurs.
216 *         </td>
217 *     </tr>
218 *     <tr>
219 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
220 *         <td>Called when a hardware key up event occurs.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
225 *         <td>Called when a trackball motion event occurs.
226 *         </td>
227 *     </tr>
228 *     <tr>
229 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
230 *         <td>Called when a touch screen motion event occurs.
231 *         </td>
232 *     </tr>
233 *
234 *     <tr>
235 *         <td rowspan="2">Focus</td>
236 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
237 *         <td>Called when the view gains or loses focus.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
243 *         <td>Called when the window containing the view gains or loses focus.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td rowspan="3">Attaching</td>
249 *         <td><code>{@link #onAttachedToWindow()}</code></td>
250 *         <td>Called when the view is attached to a window.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td><code>{@link #onDetachedFromWindow}</code></td>
256 *         <td>Called when the view is detached from its window.
257 *         </td>
258 *     </tr>
259 *
260 *     <tr>
261 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
262 *         <td>Called when the visibility of the window containing the view
263 *         has changed.
264 *         </td>
265 *     </tr>
266 *     </tbody>
267 *
268 * </table>
269 * </p>
270 *
271 * <a name="IDs"></a>
272 * <h3>IDs</h3>
273 * Views may have an integer id associated with them. These ids are typically
274 * assigned in the layout XML files, and are used to find specific views within
275 * the view tree. A common pattern is to:
276 * <ul>
277 * <li>Define a Button in the layout file and assign it a unique ID.
278 * <pre>
279 * &lt;Button
280 *     android:id="@+id/my_button"
281 *     android:layout_width="wrap_content"
282 *     android:layout_height="wrap_content"
283 *     android:text="@string/my_button_text"/&gt;
284 * </pre></li>
285 * <li>From the onCreate method of an Activity, find the Button
286 * <pre class="prettyprint">
287 *      Button myButton = (Button) findViewById(R.id.my_button);
288 * </pre></li>
289 * </ul>
290 * <p>
291 * View IDs need not be unique throughout the tree, but it is good practice to
292 * ensure that they are at least unique within the part of the tree you are
293 * searching.
294 * </p>
295 *
296 * <a name="Position"></a>
297 * <h3>Position</h3>
298 * <p>
299 * The geometry of a view is that of a rectangle. A view has a location,
300 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
301 * two dimensions, expressed as a width and a height. The unit for location
302 * and dimensions is the pixel.
303 * </p>
304 *
305 * <p>
306 * It is possible to retrieve the location of a view by invoking the methods
307 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
308 * coordinate of the rectangle representing the view. The latter returns the
309 * top, or Y, coordinate of the rectangle representing the view. These methods
310 * both return the location of the view relative to its parent. For instance,
311 * when getLeft() returns 20, that means the view is located 20 pixels to the
312 * right of the left edge of its direct parent.
313 * </p>
314 *
315 * <p>
316 * In addition, several convenience methods are offered to avoid unnecessary
317 * computations, namely {@link #getRight()} and {@link #getBottom()}.
318 * These methods return the coordinates of the right and bottom edges of the
319 * rectangle representing the view. For instance, calling {@link #getRight()}
320 * is similar to the following computation: <code>getLeft() + getWidth()</code>
321 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
322 * </p>
323 *
324 * <a name="SizePaddingMargins"></a>
325 * <h3>Size, padding and margins</h3>
326 * <p>
327 * The size of a view is expressed with a width and a height. A view actually
328 * possess two pairs of width and height values.
329 * </p>
330 *
331 * <p>
332 * The first pair is known as <em>measured width</em> and
333 * <em>measured height</em>. These dimensions define how big a view wants to be
334 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
335 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
336 * and {@link #getMeasuredHeight()}.
337 * </p>
338 *
339 * <p>
340 * The second pair is simply known as <em>width</em> and <em>height</em>, or
341 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
342 * dimensions define the actual size of the view on screen, at drawing time and
343 * after layout. These values may, but do not have to, be different from the
344 * measured width and height. The width and height can be obtained by calling
345 * {@link #getWidth()} and {@link #getHeight()}.
346 * </p>
347 *
348 * <p>
349 * To measure its dimensions, a view takes into account its padding. The padding
350 * is expressed in pixels for the left, top, right and bottom parts of the view.
351 * Padding can be used to offset the content of the view by a specific amount of
352 * pixels. For instance, a left padding of 2 will push the view's content by
353 * 2 pixels to the right of the left edge. Padding can be set using the
354 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
355 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
356 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
357 * {@link #getPaddingEnd()}.
358 * </p>
359 *
360 * <p>
361 * Even though a view can define a padding, it does not provide any support for
362 * margins. However, view groups provide such a support. Refer to
363 * {@link android.view.ViewGroup} and
364 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
365 * </p>
366 *
367 * <a name="Layout"></a>
368 * <h3>Layout</h3>
369 * <p>
370 * Layout is a two pass process: a measure pass and a layout pass. The measuring
371 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
372 * of the view tree. Each view pushes dimension specifications down the tree
373 * during the recursion. At the end of the measure pass, every view has stored
374 * its measurements. The second pass happens in
375 * {@link #layout(int,int,int,int)} and is also top-down. During
376 * this pass each parent is responsible for positioning all of its children
377 * using the sizes computed in the measure pass.
378 * </p>
379 *
380 * <p>
381 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
382 * {@link #getMeasuredHeight()} values must be set, along with those for all of
383 * that view's descendants. A view's measured width and measured height values
384 * must respect the constraints imposed by the view's parents. This guarantees
385 * that at the end of the measure pass, all parents accept all of their
386 * children's measurements. A parent view may call measure() more than once on
387 * its children. For example, the parent may measure each child once with
388 * unspecified dimensions to find out how big they want to be, then call
389 * measure() on them again with actual numbers if the sum of all the children's
390 * unconstrained sizes is too big or too small.
391 * </p>
392 *
393 * <p>
394 * The measure pass uses two classes to communicate dimensions. The
395 * {@link MeasureSpec} class is used by views to tell their parents how they
396 * want to be measured and positioned. The base LayoutParams class just
397 * describes how big the view wants to be for both width and height. For each
398 * dimension, it can specify one of:
399 * <ul>
400 * <li> an exact number
401 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
402 * (minus padding)
403 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
404 * enclose its content (plus padding).
405 * </ul>
406 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
407 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
408 * an X and Y value.
409 * </p>
410 *
411 * <p>
412 * MeasureSpecs are used to push requirements down the tree from parent to
413 * child. A MeasureSpec can be in one of three modes:
414 * <ul>
415 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
416 * of a child view. For example, a LinearLayout may call measure() on its child
417 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
418 * tall the child view wants to be given a width of 240 pixels.
419 * <li>EXACTLY: This is used by the parent to impose an exact size on the
420 * child. The child must use this size, and guarantee that all of its
421 * descendants will fit within this size.
422 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
423 * child. The child must gurantee that it and all of its descendants will fit
424 * within this size.
425 * </ul>
426 * </p>
427 *
428 * <p>
429 * To intiate a layout, call {@link #requestLayout}. This method is typically
430 * called by a view on itself when it believes that is can no longer fit within
431 * its current bounds.
432 * </p>
433 *
434 * <a name="Drawing"></a>
435 * <h3>Drawing</h3>
436 * <p>
437 * Drawing is handled by walking the tree and rendering each view that
438 * intersects the invalid region. Because the tree is traversed in-order,
439 * this means that parents will draw before (i.e., behind) their children, with
440 * siblings drawn in the order they appear in the tree.
441 * If you set a background drawable for a View, then the View will draw it for you
442 * before calling back to its <code>onDraw()</code> method.
443 * </p>
444 *
445 * <p>
446 * Note that the framework will not draw views that are not in the invalid region.
447 * </p>
448 *
449 * <p>
450 * To force a view to draw, call {@link #invalidate()}.
451 * </p>
452 *
453 * <a name="EventHandlingThreading"></a>
454 * <h3>Event Handling and Threading</h3>
455 * <p>
456 * The basic cycle of a view is as follows:
457 * <ol>
458 * <li>An event comes in and is dispatched to the appropriate view. The view
459 * handles the event and notifies any listeners.</li>
460 * <li>If in the course of processing the event, the view's bounds may need
461 * to be changed, the view will call {@link #requestLayout()}.</li>
462 * <li>Similarly, if in the course of processing the event the view's appearance
463 * may need to be changed, the view will call {@link #invalidate()}.</li>
464 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
465 * the framework will take care of measuring, laying out, and drawing the tree
466 * as appropriate.</li>
467 * </ol>
468 * </p>
469 *
470 * <p><em>Note: The entire view tree is single threaded. You must always be on
471 * the UI thread when calling any method on any view.</em>
472 * If you are doing work on other threads and want to update the state of a view
473 * from that thread, you should use a {@link Handler}.
474 * </p>
475 *
476 * <a name="FocusHandling"></a>
477 * <h3>Focus Handling</h3>
478 * <p>
479 * The framework will handle routine focus movement in response to user input.
480 * This includes changing the focus as views are removed or hidden, or as new
481 * views become available. Views indicate their willingness to take focus
482 * through the {@link #isFocusable} method. To change whether a view can take
483 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
484 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
485 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
486 * </p>
487 * <p>
488 * Focus movement is based on an algorithm which finds the nearest neighbor in a
489 * given direction. In rare cases, the default algorithm may not match the
490 * intended behavior of the developer. In these situations, you can provide
491 * explicit overrides by using these XML attributes in the layout file:
492 * <pre>
493 * nextFocusDown
494 * nextFocusLeft
495 * nextFocusRight
496 * nextFocusUp
497 * </pre>
498 * </p>
499 *
500 *
501 * <p>
502 * To get a particular view to take focus, call {@link #requestFocus()}.
503 * </p>
504 *
505 * <a name="TouchMode"></a>
506 * <h3>Touch Mode</h3>
507 * <p>
508 * When a user is navigating a user interface via directional keys such as a D-pad, it is
509 * necessary to give focus to actionable items such as buttons so the user can see
510 * what will take input.  If the device has touch capabilities, however, and the user
511 * begins interacting with the interface by touching it, it is no longer necessary to
512 * always highlight, or give focus to, a particular view.  This motivates a mode
513 * for interaction named 'touch mode'.
514 * </p>
515 * <p>
516 * For a touch capable device, once the user touches the screen, the device
517 * will enter touch mode.  From this point onward, only views for which
518 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
519 * Other views that are touchable, like buttons, will not take focus when touched; they will
520 * only fire the on click listeners.
521 * </p>
522 * <p>
523 * Any time a user hits a directional key, such as a D-pad direction, the view device will
524 * exit touch mode, and find a view to take focus, so that the user may resume interacting
525 * with the user interface without touching the screen again.
526 * </p>
527 * <p>
528 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
529 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
530 * </p>
531 *
532 * <a name="Scrolling"></a>
533 * <h3>Scrolling</h3>
534 * <p>
535 * The framework provides basic support for views that wish to internally
536 * scroll their content. This includes keeping track of the X and Y scroll
537 * offset as well as mechanisms for drawing scrollbars. See
538 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
539 * {@link #awakenScrollBars()} for more details.
540 * </p>
541 *
542 * <a name="Tags"></a>
543 * <h3>Tags</h3>
544 * <p>
545 * Unlike IDs, tags are not used to identify views. Tags are essentially an
546 * extra piece of information that can be associated with a view. They are most
547 * often used as a convenience to store data related to views in the views
548 * themselves rather than by putting them in a separate structure.
549 * </p>
550 *
551 * <a name="Properties"></a>
552 * <h3>Properties</h3>
553 * <p>
554 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
555 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
556 * available both in the {@link Property} form as well as in similarly-named setter/getter
557 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
558 * be used to set persistent state associated with these rendering-related properties on the view.
559 * The properties and methods can also be used in conjunction with
560 * {@link android.animation.Animator Animator}-based animations, described more in the
561 * <a href="#Animation">Animation</a> section.
562 * </p>
563 *
564 * <a name="Animation"></a>
565 * <h3>Animation</h3>
566 * <p>
567 * Starting with Android 3.0, the preferred way of animating views is to use the
568 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
569 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
570 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
571 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
572 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
573 * makes animating these View properties particularly easy and efficient.
574 * </p>
575 * <p>
576 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
577 * You can attach an {@link Animation} object to a view using
578 * {@link #setAnimation(Animation)} or
579 * {@link #startAnimation(Animation)}. The animation can alter the scale,
580 * rotation, translation and alpha of a view over time. If the animation is
581 * attached to a view that has children, the animation will affect the entire
582 * subtree rooted by that node. When an animation is started, the framework will
583 * take care of redrawing the appropriate views until the animation completes.
584 * </p>
585 *
586 * <a name="Security"></a>
587 * <h3>Security</h3>
588 * <p>
589 * Sometimes it is essential that an application be able to verify that an action
590 * is being performed with the full knowledge and consent of the user, such as
591 * granting a permission request, making a purchase or clicking on an advertisement.
592 * Unfortunately, a malicious application could try to spoof the user into
593 * performing these actions, unaware, by concealing the intended purpose of the view.
594 * As a remedy, the framework offers a touch filtering mechanism that can be used to
595 * improve the security of views that provide access to sensitive functionality.
596 * </p><p>
597 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
598 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
599 * will discard touches that are received whenever the view's window is obscured by
600 * another visible window.  As a result, the view will not receive touches whenever a
601 * toast, dialog or other window appears above the view's window.
602 * </p><p>
603 * For more fine-grained control over security, consider overriding the
604 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
605 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
606 * </p>
607 *
608 * @attr ref android.R.styleable#View_alpha
609 * @attr ref android.R.styleable#View_background
610 * @attr ref android.R.styleable#View_clickable
611 * @attr ref android.R.styleable#View_contentDescription
612 * @attr ref android.R.styleable#View_drawingCacheQuality
613 * @attr ref android.R.styleable#View_duplicateParentState
614 * @attr ref android.R.styleable#View_id
615 * @attr ref android.R.styleable#View_requiresFadingEdge
616 * @attr ref android.R.styleable#View_fadeScrollbars
617 * @attr ref android.R.styleable#View_fadingEdgeLength
618 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
619 * @attr ref android.R.styleable#View_fitsSystemWindows
620 * @attr ref android.R.styleable#View_isScrollContainer
621 * @attr ref android.R.styleable#View_focusable
622 * @attr ref android.R.styleable#View_focusableInTouchMode
623 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
624 * @attr ref android.R.styleable#View_keepScreenOn
625 * @attr ref android.R.styleable#View_layerType
626 * @attr ref android.R.styleable#View_layoutDirection
627 * @attr ref android.R.styleable#View_longClickable
628 * @attr ref android.R.styleable#View_minHeight
629 * @attr ref android.R.styleable#View_minWidth
630 * @attr ref android.R.styleable#View_nextFocusDown
631 * @attr ref android.R.styleable#View_nextFocusLeft
632 * @attr ref android.R.styleable#View_nextFocusRight
633 * @attr ref android.R.styleable#View_nextFocusUp
634 * @attr ref android.R.styleable#View_onClick
635 * @attr ref android.R.styleable#View_padding
636 * @attr ref android.R.styleable#View_paddingBottom
637 * @attr ref android.R.styleable#View_paddingLeft
638 * @attr ref android.R.styleable#View_paddingRight
639 * @attr ref android.R.styleable#View_paddingTop
640 * @attr ref android.R.styleable#View_paddingStart
641 * @attr ref android.R.styleable#View_paddingEnd
642 * @attr ref android.R.styleable#View_saveEnabled
643 * @attr ref android.R.styleable#View_rotation
644 * @attr ref android.R.styleable#View_rotationX
645 * @attr ref android.R.styleable#View_rotationY
646 * @attr ref android.R.styleable#View_scaleX
647 * @attr ref android.R.styleable#View_scaleY
648 * @attr ref android.R.styleable#View_scrollX
649 * @attr ref android.R.styleable#View_scrollY
650 * @attr ref android.R.styleable#View_scrollbarSize
651 * @attr ref android.R.styleable#View_scrollbarStyle
652 * @attr ref android.R.styleable#View_scrollbars
653 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
654 * @attr ref android.R.styleable#View_scrollbarFadeDuration
655 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
656 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
657 * @attr ref android.R.styleable#View_scrollbarThumbVertical
658 * @attr ref android.R.styleable#View_scrollbarTrackVertical
659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
660 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
661 * @attr ref android.R.styleable#View_soundEffectsEnabled
662 * @attr ref android.R.styleable#View_tag
663 * @attr ref android.R.styleable#View_textAlignment
664 * @attr ref android.R.styleable#View_textDirection
665 * @attr ref android.R.styleable#View_transformPivotX
666 * @attr ref android.R.styleable#View_transformPivotY
667 * @attr ref android.R.styleable#View_translationX
668 * @attr ref android.R.styleable#View_translationY
669 * @attr ref android.R.styleable#View_visibility
670 *
671 * @see android.view.ViewGroup
672 */
673public class View implements Drawable.Callback, KeyEvent.Callback,
674        AccessibilityEventSource {
675    private static final boolean DBG = false;
676
677    /**
678     * The logging tag used by this class with android.util.Log.
679     */
680    protected static final String VIEW_LOG_TAG = "View";
681
682    /**
683     * When set to true, apps will draw debugging information about their layouts.
684     *
685     * @hide
686     */
687    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
688
689    /**
690     * Used to mark a View that has no ID.
691     */
692    public static final int NO_ID = -1;
693
694    private static boolean sUseBrokenMakeMeasureSpec = false;
695
696    /**
697     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
698     * calling setFlags.
699     */
700    private static final int NOT_FOCUSABLE = 0x00000000;
701
702    /**
703     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
704     * setFlags.
705     */
706    private static final int FOCUSABLE = 0x00000001;
707
708    /**
709     * Mask for use with setFlags indicating bits used for focus.
710     */
711    private static final int FOCUSABLE_MASK = 0x00000001;
712
713    /**
714     * This view will adjust its padding to fit sytem windows (e.g. status bar)
715     */
716    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
717
718    /**
719     * This view is visible.
720     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
721     * android:visibility}.
722     */
723    public static final int VISIBLE = 0x00000000;
724
725    /**
726     * This view is invisible, but it still takes up space for layout purposes.
727     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
728     * android:visibility}.
729     */
730    public static final int INVISIBLE = 0x00000004;
731
732    /**
733     * This view is invisible, and it doesn't take any space for layout
734     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
735     * android:visibility}.
736     */
737    public static final int GONE = 0x00000008;
738
739    /**
740     * Mask for use with setFlags indicating bits used for visibility.
741     * {@hide}
742     */
743    static final int VISIBILITY_MASK = 0x0000000C;
744
745    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
746
747    /**
748     * This view is enabled. Interpretation varies by subclass.
749     * Use with ENABLED_MASK when calling setFlags.
750     * {@hide}
751     */
752    static final int ENABLED = 0x00000000;
753
754    /**
755     * This view is disabled. Interpretation varies by subclass.
756     * Use with ENABLED_MASK when calling setFlags.
757     * {@hide}
758     */
759    static final int DISABLED = 0x00000020;
760
761   /**
762    * Mask for use with setFlags indicating bits used for indicating whether
763    * this view is enabled
764    * {@hide}
765    */
766    static final int ENABLED_MASK = 0x00000020;
767
768    /**
769     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
770     * called and further optimizations will be performed. It is okay to have
771     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
772     * {@hide}
773     */
774    static final int WILL_NOT_DRAW = 0x00000080;
775
776    /**
777     * Mask for use with setFlags indicating bits used for indicating whether
778     * this view is will draw
779     * {@hide}
780     */
781    static final int DRAW_MASK = 0x00000080;
782
783    /**
784     * <p>This view doesn't show scrollbars.</p>
785     * {@hide}
786     */
787    static final int SCROLLBARS_NONE = 0x00000000;
788
789    /**
790     * <p>This view shows horizontal scrollbars.</p>
791     * {@hide}
792     */
793    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
794
795    /**
796     * <p>This view shows vertical scrollbars.</p>
797     * {@hide}
798     */
799    static final int SCROLLBARS_VERTICAL = 0x00000200;
800
801    /**
802     * <p>Mask for use with setFlags indicating bits used for indicating which
803     * scrollbars are enabled.</p>
804     * {@hide}
805     */
806    static final int SCROLLBARS_MASK = 0x00000300;
807
808    /**
809     * Indicates that the view should filter touches when its window is obscured.
810     * Refer to the class comments for more information about this security feature.
811     * {@hide}
812     */
813    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
814
815    /**
816     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
817     * that they are optional and should be skipped if the window has
818     * requested system UI flags that ignore those insets for layout.
819     */
820    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
821
822    /**
823     * <p>This view doesn't show fading edges.</p>
824     * {@hide}
825     */
826    static final int FADING_EDGE_NONE = 0x00000000;
827
828    /**
829     * <p>This view shows horizontal fading edges.</p>
830     * {@hide}
831     */
832    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
833
834    /**
835     * <p>This view shows vertical fading edges.</p>
836     * {@hide}
837     */
838    static final int FADING_EDGE_VERTICAL = 0x00002000;
839
840    /**
841     * <p>Mask for use with setFlags indicating bits used for indicating which
842     * fading edges are enabled.</p>
843     * {@hide}
844     */
845    static final int FADING_EDGE_MASK = 0x00003000;
846
847    /**
848     * <p>Indicates this view can be clicked. When clickable, a View reacts
849     * to clicks by notifying the OnClickListener.<p>
850     * {@hide}
851     */
852    static final int CLICKABLE = 0x00004000;
853
854    /**
855     * <p>Indicates this view is caching its drawing into a bitmap.</p>
856     * {@hide}
857     */
858    static final int DRAWING_CACHE_ENABLED = 0x00008000;
859
860    /**
861     * <p>Indicates that no icicle should be saved for this view.<p>
862     * {@hide}
863     */
864    static final int SAVE_DISABLED = 0x000010000;
865
866    /**
867     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
868     * property.</p>
869     * {@hide}
870     */
871    static final int SAVE_DISABLED_MASK = 0x000010000;
872
873    /**
874     * <p>Indicates that no drawing cache should ever be created for this view.<p>
875     * {@hide}
876     */
877    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
878
879    /**
880     * <p>Indicates this view can take / keep focus when int touch mode.</p>
881     * {@hide}
882     */
883    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
884
885    /**
886     * <p>Enables low quality mode for the drawing cache.</p>
887     */
888    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
889
890    /**
891     * <p>Enables high quality mode for the drawing cache.</p>
892     */
893    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
894
895    /**
896     * <p>Enables automatic quality mode for the drawing cache.</p>
897     */
898    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
899
900    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
901            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
902    };
903
904    /**
905     * <p>Mask for use with setFlags indicating bits used for the cache
906     * quality property.</p>
907     * {@hide}
908     */
909    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
910
911    /**
912     * <p>
913     * Indicates this view can be long clicked. When long clickable, a View
914     * reacts to long clicks by notifying the OnLongClickListener or showing a
915     * context menu.
916     * </p>
917     * {@hide}
918     */
919    static final int LONG_CLICKABLE = 0x00200000;
920
921    /**
922     * <p>Indicates that this view gets its drawable states from its direct parent
923     * and ignores its original internal states.</p>
924     *
925     * @hide
926     */
927    static final int DUPLICATE_PARENT_STATE = 0x00400000;
928
929    /**
930     * The scrollbar style to display the scrollbars inside the content area,
931     * without increasing the padding. The scrollbars will be overlaid with
932     * translucency on the view's content.
933     */
934    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
935
936    /**
937     * The scrollbar style to display the scrollbars inside the padded area,
938     * increasing the padding of the view. The scrollbars will not overlap the
939     * content area of the view.
940     */
941    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
942
943    /**
944     * The scrollbar style to display the scrollbars at the edge of the view,
945     * without increasing the padding. The scrollbars will be overlaid with
946     * translucency.
947     */
948    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
949
950    /**
951     * The scrollbar style to display the scrollbars at the edge of the view,
952     * increasing the padding of the view. The scrollbars will only overlap the
953     * background, if any.
954     */
955    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
956
957    /**
958     * Mask to check if the scrollbar style is overlay or inset.
959     * {@hide}
960     */
961    static final int SCROLLBARS_INSET_MASK = 0x01000000;
962
963    /**
964     * Mask to check if the scrollbar style is inside or outside.
965     * {@hide}
966     */
967    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
968
969    /**
970     * Mask for scrollbar style.
971     * {@hide}
972     */
973    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
974
975    /**
976     * View flag indicating that the screen should remain on while the
977     * window containing this view is visible to the user.  This effectively
978     * takes care of automatically setting the WindowManager's
979     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
980     */
981    public static final int KEEP_SCREEN_ON = 0x04000000;
982
983    /**
984     * View flag indicating whether this view should have sound effects enabled
985     * for events such as clicking and touching.
986     */
987    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
988
989    /**
990     * View flag indicating whether this view should have haptic feedback
991     * enabled for events such as long presses.
992     */
993    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
994
995    /**
996     * <p>Indicates that the view hierarchy should stop saving state when
997     * it reaches this view.  If state saving is initiated immediately at
998     * the view, it will be allowed.
999     * {@hide}
1000     */
1001    static final int PARENT_SAVE_DISABLED = 0x20000000;
1002
1003    /**
1004     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1005     * {@hide}
1006     */
1007    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add all focusable Views regardless if they are focusable in touch mode.
1012     */
1013    public static final int FOCUSABLES_ALL = 0x00000000;
1014
1015    /**
1016     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1017     * should add only Views focusable in touch mode.
1018     */
1019    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1020
1021    /**
1022     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1023     * item.
1024     */
1025    public static final int FOCUS_BACKWARD = 0x00000001;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1029     * item.
1030     */
1031    public static final int FOCUS_FORWARD = 0x00000002;
1032
1033    /**
1034     * Use with {@link #focusSearch(int)}. Move focus to the left.
1035     */
1036    public static final int FOCUS_LEFT = 0x00000011;
1037
1038    /**
1039     * Use with {@link #focusSearch(int)}. Move focus up.
1040     */
1041    public static final int FOCUS_UP = 0x00000021;
1042
1043    /**
1044     * Use with {@link #focusSearch(int)}. Move focus to the right.
1045     */
1046    public static final int FOCUS_RIGHT = 0x00000042;
1047
1048    /**
1049     * Use with {@link #focusSearch(int)}. Move focus down.
1050     */
1051    public static final int FOCUS_DOWN = 0x00000082;
1052
1053    /**
1054     * Bits of {@link #getMeasuredWidthAndState()} and
1055     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1056     */
1057    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1058
1059    /**
1060     * Bits of {@link #getMeasuredWidthAndState()} and
1061     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1062     */
1063    public static final int MEASURED_STATE_MASK = 0xff000000;
1064
1065    /**
1066     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1067     * for functions that combine both width and height into a single int,
1068     * such as {@link #getMeasuredState()} and the childState argument of
1069     * {@link #resolveSizeAndState(int, int, int)}.
1070     */
1071    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1072
1073    /**
1074     * Bit of {@link #getMeasuredWidthAndState()} and
1075     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1076     * is smaller that the space the view would like to have.
1077     */
1078    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1079
1080    /**
1081     * Base View state sets
1082     */
1083    // Singles
1084    /**
1085     * Indicates the view has no states set. States are used with
1086     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1087     * view depending on its state.
1088     *
1089     * @see android.graphics.drawable.Drawable
1090     * @see #getDrawableState()
1091     */
1092    protected static final int[] EMPTY_STATE_SET;
1093    /**
1094     * Indicates the view is enabled. States are used with
1095     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1096     * view depending on its state.
1097     *
1098     * @see android.graphics.drawable.Drawable
1099     * @see #getDrawableState()
1100     */
1101    protected static final int[] ENABLED_STATE_SET;
1102    /**
1103     * Indicates the view is focused. States are used with
1104     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1105     * view depending on its state.
1106     *
1107     * @see android.graphics.drawable.Drawable
1108     * @see #getDrawableState()
1109     */
1110    protected static final int[] FOCUSED_STATE_SET;
1111    /**
1112     * Indicates the view is selected. States are used with
1113     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1114     * view depending on its state.
1115     *
1116     * @see android.graphics.drawable.Drawable
1117     * @see #getDrawableState()
1118     */
1119    protected static final int[] SELECTED_STATE_SET;
1120    /**
1121     * Indicates the view is pressed. States are used with
1122     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1123     * view depending on its state.
1124     *
1125     * @see android.graphics.drawable.Drawable
1126     * @see #getDrawableState()
1127     */
1128    protected static final int[] PRESSED_STATE_SET;
1129    /**
1130     * Indicates the view's window has focus. States are used with
1131     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1132     * view depending on its state.
1133     *
1134     * @see android.graphics.drawable.Drawable
1135     * @see #getDrawableState()
1136     */
1137    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1138    // Doubles
1139    /**
1140     * Indicates the view is enabled and has the focus.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #FOCUSED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled and selected.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #SELECTED_STATE_SET
1151     */
1152    protected static final int[] ENABLED_SELECTED_STATE_SET;
1153    /**
1154     * Indicates the view is enabled and that its window has focus.
1155     *
1156     * @see #ENABLED_STATE_SET
1157     * @see #WINDOW_FOCUSED_STATE_SET
1158     */
1159    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1160    /**
1161     * Indicates the view is focused and selected.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #SELECTED_STATE_SET
1165     */
1166    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1167    /**
1168     * Indicates the view has the focus and that its window has the focus.
1169     *
1170     * @see #FOCUSED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1174    /**
1175     * Indicates the view is selected and that its window has the focus.
1176     *
1177     * @see #SELECTED_STATE_SET
1178     * @see #WINDOW_FOCUSED_STATE_SET
1179     */
1180    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1181    // Triples
1182    /**
1183     * Indicates the view is enabled, focused and selected.
1184     *
1185     * @see #ENABLED_STATE_SET
1186     * @see #FOCUSED_STATE_SET
1187     * @see #SELECTED_STATE_SET
1188     */
1189    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1190    /**
1191     * Indicates the view is enabled, focused and its window has the focus.
1192     *
1193     * @see #ENABLED_STATE_SET
1194     * @see #FOCUSED_STATE_SET
1195     * @see #WINDOW_FOCUSED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is enabled, selected and its window has the focus.
1200     *
1201     * @see #ENABLED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is focused, selected and its window has the focus.
1208     *
1209     * @see #FOCUSED_STATE_SET
1210     * @see #SELECTED_STATE_SET
1211     * @see #WINDOW_FOCUSED_STATE_SET
1212     */
1213    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1214    /**
1215     * Indicates the view is enabled, focused, selected and its window
1216     * has the focus.
1217     *
1218     * @see #ENABLED_STATE_SET
1219     * @see #FOCUSED_STATE_SET
1220     * @see #SELECTED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed and its window has the focus.
1226     *
1227     * @see #PRESSED_STATE_SET
1228     * @see #WINDOW_FOCUSED_STATE_SET
1229     */
1230    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1231    /**
1232     * Indicates the view is pressed and selected.
1233     *
1234     * @see #PRESSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_SELECTED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed, selected and its window has the focus.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed and focused.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, focused and its window has the focus.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #FOCUSED_STATE_SET
1258     * @see #WINDOW_FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed, focused and selected.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     * @see #FOCUSED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, focused, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #SELECTED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed and enabled.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_ENABLED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, enabled and its window has the focus.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #ENABLED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, enabled and selected.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #ENABLED_STATE_SET
1298     * @see #SELECTED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed, enabled, selected and its window has the
1303     * focus.
1304     *
1305     * @see #PRESSED_STATE_SET
1306     * @see #ENABLED_STATE_SET
1307     * @see #SELECTED_STATE_SET
1308     * @see #WINDOW_FOCUSED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled and focused.
1313     *
1314     * @see #PRESSED_STATE_SET
1315     * @see #ENABLED_STATE_SET
1316     * @see #FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed, enabled, focused and its window has the
1321     * focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #FOCUSED_STATE_SET
1326     * @see #WINDOW_FOCUSED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, enabled, focused and selected.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #ENABLED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, enabled, focused, selected and its window
1340     * has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #ENABLED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     * @see #WINDOW_FOCUSED_STATE_SET
1347     */
1348    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1349
1350    /**
1351     * The order here is very important to {@link #getDrawableState()}
1352     */
1353    private static final int[][] VIEW_STATE_SETS;
1354
1355    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1356    static final int VIEW_STATE_SELECTED = 1 << 1;
1357    static final int VIEW_STATE_FOCUSED = 1 << 2;
1358    static final int VIEW_STATE_ENABLED = 1 << 3;
1359    static final int VIEW_STATE_PRESSED = 1 << 4;
1360    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1361    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1362    static final int VIEW_STATE_HOVERED = 1 << 7;
1363    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1364    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1365
1366    static final int[] VIEW_STATE_IDS = new int[] {
1367        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1368        R.attr.state_selected,          VIEW_STATE_SELECTED,
1369        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1370        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1371        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1372        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1373        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1374        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1375        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1376        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1377    };
1378
1379    static {
1380        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1381            throw new IllegalStateException(
1382                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1383        }
1384        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1385        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1386            int viewState = R.styleable.ViewDrawableStates[i];
1387            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1388                if (VIEW_STATE_IDS[j] == viewState) {
1389                    orderedIds[i * 2] = viewState;
1390                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1391                }
1392            }
1393        }
1394        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1395        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1396        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1397            int numBits = Integer.bitCount(i);
1398            int[] set = new int[numBits];
1399            int pos = 0;
1400            for (int j = 0; j < orderedIds.length; j += 2) {
1401                if ((i & orderedIds[j+1]) != 0) {
1402                    set[pos++] = orderedIds[j];
1403                }
1404            }
1405            VIEW_STATE_SETS[i] = set;
1406        }
1407
1408        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1409        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1410        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1411        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1413        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1414        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1416        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1418        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420                | VIEW_STATE_FOCUSED];
1421        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1422        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1424        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1426        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED];
1437        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1439                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1440
1441        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1442        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1444        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1446        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1464                | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1473                | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1476                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1482                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1483                | VIEW_STATE_PRESSED];
1484    }
1485
1486    /**
1487     * Accessibility event types that are dispatched for text population.
1488     */
1489    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1490            AccessibilityEvent.TYPE_VIEW_CLICKED
1491            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1492            | AccessibilityEvent.TYPE_VIEW_SELECTED
1493            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1494            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1495            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1496            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1499            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1500            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1501
1502    /**
1503     * Temporary Rect currently for use in setBackground().  This will probably
1504     * be extended in the future to hold our own class with more than just
1505     * a Rect. :)
1506     */
1507    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1508
1509    /**
1510     * Map used to store views' tags.
1511     */
1512    private SparseArray<Object> mKeyedTags;
1513
1514    /**
1515     * The next available accessibility id.
1516     */
1517    private static int sNextAccessibilityViewId;
1518
1519    /**
1520     * The animation currently associated with this view.
1521     * @hide
1522     */
1523    protected Animation mCurrentAnimation = null;
1524
1525    /**
1526     * Width as measured during measure pass.
1527     * {@hide}
1528     */
1529    @ViewDebug.ExportedProperty(category = "measurement")
1530    int mMeasuredWidth;
1531
1532    /**
1533     * Height as measured during measure pass.
1534     * {@hide}
1535     */
1536    @ViewDebug.ExportedProperty(category = "measurement")
1537    int mMeasuredHeight;
1538
1539    /**
1540     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1541     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1542     * its display list. This flag, used only when hw accelerated, allows us to clear the
1543     * flag while retaining this information until it's needed (at getDisplayList() time and
1544     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1545     *
1546     * {@hide}
1547     */
1548    boolean mRecreateDisplayList = false;
1549
1550    /**
1551     * The view's identifier.
1552     * {@hide}
1553     *
1554     * @see #setId(int)
1555     * @see #getId()
1556     */
1557    @ViewDebug.ExportedProperty(resolveId = true)
1558    int mID = NO_ID;
1559
1560    /**
1561     * The stable ID of this view for accessibility purposes.
1562     */
1563    int mAccessibilityViewId = NO_ID;
1564
1565    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1566
1567    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1568
1569    /**
1570     * The view's tag.
1571     * {@hide}
1572     *
1573     * @see #setTag(Object)
1574     * @see #getTag()
1575     */
1576    protected Object mTag;
1577
1578    private Scene mCurrentScene = null;
1579
1580    // for mPrivateFlags:
1581    /** {@hide} */
1582    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1583    /** {@hide} */
1584    static final int PFLAG_FOCUSED                     = 0x00000002;
1585    /** {@hide} */
1586    static final int PFLAG_SELECTED                    = 0x00000004;
1587    /** {@hide} */
1588    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1589    /** {@hide} */
1590    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1591    /** {@hide} */
1592    static final int PFLAG_DRAWN                       = 0x00000020;
1593    /**
1594     * When this flag is set, this view is running an animation on behalf of its
1595     * children and should therefore not cancel invalidate requests, even if they
1596     * lie outside of this view's bounds.
1597     *
1598     * {@hide}
1599     */
1600    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1601    /** {@hide} */
1602    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1603    /** {@hide} */
1604    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1605    /** {@hide} */
1606    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1607    /** {@hide} */
1608    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1609    /** {@hide} */
1610    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1611    /** {@hide} */
1612    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1613    /** {@hide} */
1614    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1615
1616    private static final int PFLAG_PRESSED             = 0x00004000;
1617
1618    /** {@hide} */
1619    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1620    /**
1621     * Flag used to indicate that this view should be drawn once more (and only once
1622     * more) after its animation has completed.
1623     * {@hide}
1624     */
1625    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1626
1627    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1628
1629    /**
1630     * Indicates that the View returned true when onSetAlpha() was called and that
1631     * the alpha must be restored.
1632     * {@hide}
1633     */
1634    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1635
1636    /**
1637     * Set by {@link #setScrollContainer(boolean)}.
1638     */
1639    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1640
1641    /**
1642     * Set by {@link #setScrollContainer(boolean)}.
1643     */
1644    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1645
1646    /**
1647     * View flag indicating whether this view was invalidated (fully or partially.)
1648     *
1649     * @hide
1650     */
1651    static final int PFLAG_DIRTY                       = 0x00200000;
1652
1653    /**
1654     * View flag indicating whether this view was invalidated by an opaque
1655     * invalidate request.
1656     *
1657     * @hide
1658     */
1659    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1660
1661    /**
1662     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1663     *
1664     * @hide
1665     */
1666    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1667
1668    /**
1669     * Indicates whether the background is opaque.
1670     *
1671     * @hide
1672     */
1673    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1674
1675    /**
1676     * Indicates whether the scrollbars are opaque.
1677     *
1678     * @hide
1679     */
1680    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1681
1682    /**
1683     * Indicates whether the view is opaque.
1684     *
1685     * @hide
1686     */
1687    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1688
1689    /**
1690     * Indicates a prepressed state;
1691     * the short time between ACTION_DOWN and recognizing
1692     * a 'real' press. Prepressed is used to recognize quick taps
1693     * even when they are shorter than ViewConfiguration.getTapTimeout().
1694     *
1695     * @hide
1696     */
1697    private static final int PFLAG_PREPRESSED          = 0x02000000;
1698
1699    /**
1700     * Indicates whether the view is temporarily detached.
1701     *
1702     * @hide
1703     */
1704    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1705
1706    /**
1707     * Indicates that we should awaken scroll bars once attached
1708     *
1709     * @hide
1710     */
1711    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1712
1713    /**
1714     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1715     * @hide
1716     */
1717    private static final int PFLAG_HOVERED             = 0x10000000;
1718
1719    /**
1720     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1721     * for transform operations
1722     *
1723     * @hide
1724     */
1725    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1726
1727    /** {@hide} */
1728    static final int PFLAG_ACTIVATED                   = 0x40000000;
1729
1730    /**
1731     * Indicates that this view was specifically invalidated, not just dirtied because some
1732     * child view was invalidated. The flag is used to determine when we need to recreate
1733     * a view's display list (as opposed to just returning a reference to its existing
1734     * display list).
1735     *
1736     * @hide
1737     */
1738    static final int PFLAG_INVALIDATED                 = 0x80000000;
1739
1740    /**
1741     * Masks for mPrivateFlags2, as generated by dumpFlags():
1742     *
1743     * -------|-------|-------|-------|
1744     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1745     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1746     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1747     *                               1  PFLAG2_DRAG_HOVERED
1748     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1749     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1750     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1751     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1752     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1753     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1754     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1755     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1756     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1757     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1758     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1759     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1760     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1761     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1762     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1763     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1764     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1765     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1766     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1767     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1768     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1769     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1770     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1771     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1772     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1773     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1774     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1775     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1776     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1777     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1778     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1779     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1780     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1781     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1782     *   1                              PFLAG2_PADDING_RESOLVED
1783     * -------|-------|-------|-------|
1784     */
1785
1786    /**
1787     * Indicates that this view has reported that it can accept the current drag's content.
1788     * Cleared when the drag operation concludes.
1789     * @hide
1790     */
1791    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1792
1793    /**
1794     * Indicates that this view is currently directly under the drag location in a
1795     * drag-and-drop operation involving content that it can accept.  Cleared when
1796     * the drag exits the view, or when the drag operation concludes.
1797     * @hide
1798     */
1799    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1800
1801    /**
1802     * Horizontal layout direction of this view is from Left to Right.
1803     * Use with {@link #setLayoutDirection}.
1804     */
1805    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1806
1807    /**
1808     * Horizontal layout direction of this view is from Right to Left.
1809     * Use with {@link #setLayoutDirection}.
1810     */
1811    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1812
1813    /**
1814     * Horizontal layout direction of this view is inherited from its parent.
1815     * Use with {@link #setLayoutDirection}.
1816     */
1817    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1818
1819    /**
1820     * Horizontal layout direction of this view is from deduced from the default language
1821     * script for the locale. Use with {@link #setLayoutDirection}.
1822     */
1823    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1824
1825    /**
1826     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1827     * @hide
1828     */
1829    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1830
1831    /**
1832     * Mask for use with private flags indicating bits used for horizontal layout direction.
1833     * @hide
1834     */
1835    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1836
1837    /**
1838     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1839     * right-to-left direction.
1840     * @hide
1841     */
1842    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1843
1844    /**
1845     * Indicates whether the view horizontal layout direction has been resolved.
1846     * @hide
1847     */
1848    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1849
1850    /**
1851     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1852     * @hide
1853     */
1854    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1855            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1856
1857    /*
1858     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1859     * flag value.
1860     * @hide
1861     */
1862    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1863            LAYOUT_DIRECTION_LTR,
1864            LAYOUT_DIRECTION_RTL,
1865            LAYOUT_DIRECTION_INHERIT,
1866            LAYOUT_DIRECTION_LOCALE
1867    };
1868
1869    /**
1870     * Default horizontal layout direction.
1871     */
1872    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1873
1874    /**
1875     * Default horizontal layout direction.
1876     * @hide
1877     */
1878    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1879
1880    /**
1881     * Indicates that the view is tracking some sort of transient state
1882     * that the app should not need to be aware of, but that the framework
1883     * should take special care to preserve.
1884     *
1885     * @hide
1886     */
1887    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1888
1889    /**
1890     * Text direction is inherited thru {@link ViewGroup}
1891     */
1892    public static final int TEXT_DIRECTION_INHERIT = 0;
1893
1894    /**
1895     * Text direction is using "first strong algorithm". The first strong directional character
1896     * determines the paragraph direction. If there is no strong directional character, the
1897     * paragraph direction is the view's resolved layout direction.
1898     */
1899    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1900
1901    /**
1902     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1903     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1904     * If there are neither, the paragraph direction is the view's resolved layout direction.
1905     */
1906    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1907
1908    /**
1909     * Text direction is forced to LTR.
1910     */
1911    public static final int TEXT_DIRECTION_LTR = 3;
1912
1913    /**
1914     * Text direction is forced to RTL.
1915     */
1916    public static final int TEXT_DIRECTION_RTL = 4;
1917
1918    /**
1919     * Text direction is coming from the system Locale.
1920     */
1921    public static final int TEXT_DIRECTION_LOCALE = 5;
1922
1923    /**
1924     * Default text direction is inherited
1925     */
1926    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1927
1928    /**
1929     * Default resolved text direction
1930     * @hide
1931     */
1932    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1933
1934    /**
1935     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1936     * @hide
1937     */
1938    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1939
1940    /**
1941     * Mask for use with private flags indicating bits used for text direction.
1942     * @hide
1943     */
1944    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1945            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1946
1947    /**
1948     * Array of text direction flags for mapping attribute "textDirection" to correct
1949     * flag value.
1950     * @hide
1951     */
1952    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1953            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1957            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1958            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1959    };
1960
1961    /**
1962     * Indicates whether the view text direction has been resolved.
1963     * @hide
1964     */
1965    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1966            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1967
1968    /**
1969     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1970     * @hide
1971     */
1972    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1973
1974    /**
1975     * Mask for use with private flags indicating bits used for resolved text direction.
1976     * @hide
1977     */
1978    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1979            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1980
1981    /**
1982     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1983     * @hide
1984     */
1985    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1986            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1987
1988    /*
1989     * Default text alignment. The text alignment of this View is inherited from its parent.
1990     * Use with {@link #setTextAlignment(int)}
1991     */
1992    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1993
1994    /**
1995     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1996     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1997     *
1998     * Use with {@link #setTextAlignment(int)}
1999     */
2000    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2001
2002    /**
2003     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2004     *
2005     * Use with {@link #setTextAlignment(int)}
2006     */
2007    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2008
2009    /**
2010     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2011     *
2012     * Use with {@link #setTextAlignment(int)}
2013     */
2014    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2015
2016    /**
2017     * Center the paragraph, e.g. ALIGN_CENTER.
2018     *
2019     * Use with {@link #setTextAlignment(int)}
2020     */
2021    public static final int TEXT_ALIGNMENT_CENTER = 4;
2022
2023    /**
2024     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2025     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2026     *
2027     * Use with {@link #setTextAlignment(int)}
2028     */
2029    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2030
2031    /**
2032     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2033     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2034     *
2035     * Use with {@link #setTextAlignment(int)}
2036     */
2037    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2038
2039    /**
2040     * Default text alignment is inherited
2041     */
2042    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2043
2044    /**
2045     * Default resolved text alignment
2046     * @hide
2047     */
2048    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2049
2050    /**
2051      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2052      * @hide
2053      */
2054    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2055
2056    /**
2057      * Mask for use with private flags indicating bits used for text alignment.
2058      * @hide
2059      */
2060    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2061
2062    /**
2063     * Array of text direction flags for mapping attribute "textAlignment" to correct
2064     * flag value.
2065     * @hide
2066     */
2067    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2068            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2073            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2074            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2075    };
2076
2077    /**
2078     * Indicates whether the view text alignment has been resolved.
2079     * @hide
2080     */
2081    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2082
2083    /**
2084     * Bit shift to get the resolved text alignment.
2085     * @hide
2086     */
2087    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2088
2089    /**
2090     * Mask for use with private flags indicating bits used for text alignment.
2091     * @hide
2092     */
2093    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2094            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2095
2096    /**
2097     * Indicates whether if the view text alignment has been resolved to gravity
2098     */
2099    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2100            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2101
2102    // Accessiblity constants for mPrivateFlags2
2103
2104    /**
2105     * Shift for the bits in {@link #mPrivateFlags2} related to the
2106     * "importantForAccessibility" attribute.
2107     */
2108    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2109
2110    /**
2111     * Automatically determine whether a view is important for accessibility.
2112     */
2113    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2114
2115    /**
2116     * The view is important for accessibility.
2117     */
2118    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2119
2120    /**
2121     * The view is not important for accessibility.
2122     */
2123    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2124
2125    /**
2126     * The default whether the view is important for accessibility.
2127     */
2128    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2129
2130    /**
2131     * Mask for obtainig the bits which specify how to determine
2132     * whether a view is important for accessibility.
2133     */
2134    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2135        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2136        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2137
2138    /**
2139     * Flag indicating whether a view has accessibility focus.
2140     */
2141    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2142
2143    /**
2144     * Flag whether the accessibility state of the subtree rooted at this view changed.
2145     */
2146    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2147
2148    /**
2149     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2150     * is used to check whether later changes to the view's transform should invalidate the
2151     * view to force the quickReject test to run again.
2152     */
2153    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2154
2155    /**
2156     * Flag indicating that start/end padding has been resolved into left/right padding
2157     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2158     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2159     * during measurement. In some special cases this is required such as when an adapter-based
2160     * view measures prospective children without attaching them to a window.
2161     */
2162    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2163
2164    /**
2165     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2166     */
2167    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2168
2169    /**
2170     * Group of bits indicating that RTL properties resolution is done.
2171     */
2172    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2173            PFLAG2_TEXT_DIRECTION_RESOLVED |
2174            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2175            PFLAG2_PADDING_RESOLVED |
2176            PFLAG2_DRAWABLE_RESOLVED;
2177
2178    // There are a couple of flags left in mPrivateFlags2
2179
2180    /* End of masks for mPrivateFlags2 */
2181
2182    /* Masks for mPrivateFlags3 */
2183
2184    /**
2185     * Flag indicating that view has a transform animation set on it. This is used to track whether
2186     * an animation is cleared between successive frames, in order to tell the associated
2187     * DisplayList to clear its animation matrix.
2188     */
2189    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2190
2191    /**
2192     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2193     * animation is cleared between successive frames, in order to tell the associated
2194     * DisplayList to restore its alpha value.
2195     */
2196    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2197
2198    /**
2199     * Flag indicating that the view has been through at least one layout since it
2200     * was last attached to a window.
2201     */
2202    static final int PFLAG3_IS_LAID_OUT = 0x4;
2203
2204    /**
2205     * Flag indicating that a call to measure() was skipped and should be done
2206     * instead when layout() is invoked.
2207     */
2208    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2209
2210
2211    /* End of masks for mPrivateFlags3 */
2212
2213    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2214
2215    /**
2216     * Always allow a user to over-scroll this view, provided it is a
2217     * view that can scroll.
2218     *
2219     * @see #getOverScrollMode()
2220     * @see #setOverScrollMode(int)
2221     */
2222    public static final int OVER_SCROLL_ALWAYS = 0;
2223
2224    /**
2225     * Allow a user to over-scroll this view only if the content is large
2226     * enough to meaningfully scroll, provided it is a view that can scroll.
2227     *
2228     * @see #getOverScrollMode()
2229     * @see #setOverScrollMode(int)
2230     */
2231    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2232
2233    /**
2234     * Never allow a user to over-scroll this view.
2235     *
2236     * @see #getOverScrollMode()
2237     * @see #setOverScrollMode(int)
2238     */
2239    public static final int OVER_SCROLL_NEVER = 2;
2240
2241    /**
2242     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2243     * requested the system UI (status bar) to be visible (the default).
2244     *
2245     * @see #setSystemUiVisibility(int)
2246     */
2247    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2248
2249    /**
2250     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2251     * system UI to enter an unobtrusive "low profile" mode.
2252     *
2253     * <p>This is for use in games, book readers, video players, or any other
2254     * "immersive" application where the usual system chrome is deemed too distracting.
2255     *
2256     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2257     *
2258     * @see #setSystemUiVisibility(int)
2259     */
2260    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2261
2262    /**
2263     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2264     * system navigation be temporarily hidden.
2265     *
2266     * <p>This is an even less obtrusive state than that called for by
2267     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2268     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2269     * those to disappear. This is useful (in conjunction with the
2270     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2271     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2272     * window flags) for displaying content using every last pixel on the display.
2273     *
2274     * <p>There is a limitation: because navigation controls are so important, the least user
2275     * interaction will cause them to reappear immediately.  When this happens, both
2276     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2277     * so that both elements reappear at the same time.
2278     *
2279     * @see #setSystemUiVisibility(int)
2280     */
2281    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2282
2283    /**
2284     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2285     * into the normal fullscreen mode so that its content can take over the screen
2286     * while still allowing the user to interact with the application.
2287     *
2288     * <p>This has the same visual effect as
2289     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2290     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2291     * meaning that non-critical screen decorations (such as the status bar) will be
2292     * hidden while the user is in the View's window, focusing the experience on
2293     * that content.  Unlike the window flag, if you are using ActionBar in
2294     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2295     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2296     * hide the action bar.
2297     *
2298     * <p>This approach to going fullscreen is best used over the window flag when
2299     * it is a transient state -- that is, the application does this at certain
2300     * points in its user interaction where it wants to allow the user to focus
2301     * on content, but not as a continuous state.  For situations where the application
2302     * would like to simply stay full screen the entire time (such as a game that
2303     * wants to take over the screen), the
2304     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2305     * is usually a better approach.  The state set here will be removed by the system
2306     * in various situations (such as the user moving to another application) like
2307     * the other system UI states.
2308     *
2309     * <p>When using this flag, the application should provide some easy facility
2310     * for the user to go out of it.  A common example would be in an e-book
2311     * reader, where tapping on the screen brings back whatever screen and UI
2312     * decorations that had been hidden while the user was immersed in reading
2313     * the book.
2314     *
2315     * @see #setSystemUiVisibility(int)
2316     */
2317    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2318
2319    /**
2320     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2321     * flags, we would like a stable view of the content insets given to
2322     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2323     * will always represent the worst case that the application can expect
2324     * as a continuous state.  In the stock Android UI this is the space for
2325     * the system bar, nav bar, and status bar, but not more transient elements
2326     * such as an input method.
2327     *
2328     * The stable layout your UI sees is based on the system UI modes you can
2329     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2330     * then you will get a stable layout for changes of the
2331     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2332     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2333     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2334     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2335     * with a stable layout.  (Note that you should avoid using
2336     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2337     *
2338     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2339     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2340     * then a hidden status bar will be considered a "stable" state for purposes
2341     * here.  This allows your UI to continually hide the status bar, while still
2342     * using the system UI flags to hide the action bar while still retaining
2343     * a stable layout.  Note that changing the window fullscreen flag will never
2344     * provide a stable layout for a clean transition.
2345     *
2346     * <p>If you are using ActionBar in
2347     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2348     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2349     * insets it adds to those given to the application.
2350     */
2351    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2352
2353    /**
2354     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2355     * to be layed out as if it has requested
2356     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2357     * allows it to avoid artifacts when switching in and out of that mode, at
2358     * the expense that some of its user interface may be covered by screen
2359     * decorations when they are shown.  You can perform layout of your inner
2360     * UI elements to account for the navigation system UI through the
2361     * {@link #fitSystemWindows(Rect)} method.
2362     */
2363    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2364
2365    /**
2366     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2367     * to be layed out as if it has requested
2368     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2369     * allows it to avoid artifacts when switching in and out of that mode, at
2370     * the expense that some of its user interface may be covered by screen
2371     * decorations when they are shown.  You can perform layout of your inner
2372     * UI elements to account for non-fullscreen system UI through the
2373     * {@link #fitSystemWindows(Rect)} method.
2374     */
2375    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2376
2377    /**
2378     * Flag for {@link #setSystemUiVisibility(int)}: View would like to receive touch events
2379     * when hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the
2380     * navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} instead of having the system
2381     * clear these flags upon interaction.  The system may compensate by temporarily overlaying
2382     * semi-transparent system bars while also delivering the event.
2383     */
2384    public static final int SYSTEM_UI_FLAG_ALLOW_TRANSIENT = 0x00000800;
2385
2386    /**
2387     * Flag for {@link #setSystemUiVisibility(int)}: View would like the status bar to have
2388     * transparency.
2389     *
2390     * <p>The transparency request may be denied if the bar is in another mode with a specific
2391     * style, like {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT transient mode}.
2392     */
2393    public static final int SYSTEM_UI_FLAG_TRANSPARENT_STATUS = 0x00001000;
2394
2395    /**
2396     * Flag for {@link #setSystemUiVisibility(int)}: View would like the navigation bar to have
2397     * transparency.
2398     *
2399     * <p>The transparency request may be denied if the bar is in another mode with a specific
2400     * style, like {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT transient mode}.
2401     */
2402    public static final int SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION = 0x00002000;
2403
2404    /**
2405     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2406     */
2407    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2408
2409    /**
2410     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2411     */
2412    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2413
2414    /**
2415     * @hide
2416     *
2417     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2418     * out of the public fields to keep the undefined bits out of the developer's way.
2419     *
2420     * Flag to make the status bar not expandable.  Unless you also
2421     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2422     */
2423    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2424
2425    /**
2426     * @hide
2427     *
2428     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2429     * out of the public fields to keep the undefined bits out of the developer's way.
2430     *
2431     * Flag to hide notification icons and scrolling ticker text.
2432     */
2433    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2434
2435    /**
2436     * @hide
2437     *
2438     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2439     * out of the public fields to keep the undefined bits out of the developer's way.
2440     *
2441     * Flag to disable incoming notification alerts.  This will not block
2442     * icons, but it will block sound, vibrating and other visual or aural notifications.
2443     */
2444    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2445
2446    /**
2447     * @hide
2448     *
2449     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2450     * out of the public fields to keep the undefined bits out of the developer's way.
2451     *
2452     * Flag to hide only the scrolling ticker.  Note that
2453     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2454     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2455     */
2456    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2457
2458    /**
2459     * @hide
2460     *
2461     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2462     * out of the public fields to keep the undefined bits out of the developer's way.
2463     *
2464     * Flag to hide the center system info area.
2465     */
2466    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2467
2468    /**
2469     * @hide
2470     *
2471     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2472     * out of the public fields to keep the undefined bits out of the developer's way.
2473     *
2474     * Flag to hide only the home button.  Don't use this
2475     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2476     */
2477    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2478
2479    /**
2480     * @hide
2481     *
2482     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2483     * out of the public fields to keep the undefined bits out of the developer's way.
2484     *
2485     * Flag to hide only the back button. Don't use this
2486     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2487     */
2488    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2489
2490    /**
2491     * @hide
2492     *
2493     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2494     * out of the public fields to keep the undefined bits out of the developer's way.
2495     *
2496     * Flag to hide only the clock.  You might use this if your activity has
2497     * its own clock making the status bar's clock redundant.
2498     */
2499    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2500
2501    /**
2502     * @hide
2503     *
2504     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2505     * out of the public fields to keep the undefined bits out of the developer's way.
2506     *
2507     * Flag to hide only the recent apps button. Don't use this
2508     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2509     */
2510    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2511
2512    /**
2513     * @hide
2514     *
2515     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2516     * out of the public fields to keep the undefined bits out of the developer's way.
2517     *
2518     * Flag to disable the global search gesture. Don't use this
2519     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2520     */
2521    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2522
2523    /**
2524     * @hide
2525     *
2526     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2527     * out of the public fields to keep the undefined bits out of the developer's way.
2528     *
2529     * Flag to specify that the status bar is displayed in transient mode.
2530     */
2531    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2532
2533    /**
2534     * @hide
2535     *
2536     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2537     * out of the public fields to keep the undefined bits out of the developer's way.
2538     *
2539     * Flag to specify that the navigation bar is displayed in transient mode.
2540     */
2541    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2542
2543    /**
2544     * @hide
2545     */
2546    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2547
2548    /**
2549     * These are the system UI flags that can be cleared by events outside
2550     * of an application.  Currently this is just the ability to tap on the
2551     * screen while hiding the navigation bar to have it return.
2552     * @hide
2553     */
2554    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2555            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2556            | SYSTEM_UI_FLAG_FULLSCREEN;
2557
2558    /**
2559     * Flags that can impact the layout in relation to system UI.
2560     */
2561    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2562            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2563            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2564
2565    /**
2566     * Find views that render the specified text.
2567     *
2568     * @see #findViewsWithText(ArrayList, CharSequence, int)
2569     */
2570    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2571
2572    /**
2573     * Find find views that contain the specified content description.
2574     *
2575     * @see #findViewsWithText(ArrayList, CharSequence, int)
2576     */
2577    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2578
2579    /**
2580     * Find views that contain {@link AccessibilityNodeProvider}. Such
2581     * a View is a root of virtual view hierarchy and may contain the searched
2582     * text. If this flag is set Views with providers are automatically
2583     * added and it is a responsibility of the client to call the APIs of
2584     * the provider to determine whether the virtual tree rooted at this View
2585     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2586     * represeting the virtual views with this text.
2587     *
2588     * @see #findViewsWithText(ArrayList, CharSequence, int)
2589     *
2590     * @hide
2591     */
2592    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2593
2594    /**
2595     * The undefined cursor position.
2596     *
2597     * @hide
2598     */
2599    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2600
2601    /**
2602     * Indicates that the screen has changed state and is now off.
2603     *
2604     * @see #onScreenStateChanged(int)
2605     */
2606    public static final int SCREEN_STATE_OFF = 0x0;
2607
2608    /**
2609     * Indicates that the screen has changed state and is now on.
2610     *
2611     * @see #onScreenStateChanged(int)
2612     */
2613    public static final int SCREEN_STATE_ON = 0x1;
2614
2615    /**
2616     * Controls the over-scroll mode for this view.
2617     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2618     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2619     * and {@link #OVER_SCROLL_NEVER}.
2620     */
2621    private int mOverScrollMode;
2622
2623    /**
2624     * The parent this view is attached to.
2625     * {@hide}
2626     *
2627     * @see #getParent()
2628     */
2629    protected ViewParent mParent;
2630
2631    /**
2632     * {@hide}
2633     */
2634    AttachInfo mAttachInfo;
2635
2636    /**
2637     * {@hide}
2638     */
2639    @ViewDebug.ExportedProperty(flagMapping = {
2640        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2641                name = "FORCE_LAYOUT"),
2642        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2643                name = "LAYOUT_REQUIRED"),
2644        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2645            name = "DRAWING_CACHE_INVALID", outputIf = false),
2646        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2647        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2648        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2649        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2650    })
2651    int mPrivateFlags;
2652    int mPrivateFlags2;
2653    int mPrivateFlags3;
2654
2655    /**
2656     * This view's request for the visibility of the status bar.
2657     * @hide
2658     */
2659    @ViewDebug.ExportedProperty(flagMapping = {
2660        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2661                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2662                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2663        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2664                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2665                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2666        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2667                                equals = SYSTEM_UI_FLAG_VISIBLE,
2668                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2669    })
2670    int mSystemUiVisibility;
2671
2672    /**
2673     * Reference count for transient state.
2674     * @see #setHasTransientState(boolean)
2675     */
2676    int mTransientStateCount = 0;
2677
2678    /**
2679     * Count of how many windows this view has been attached to.
2680     */
2681    int mWindowAttachCount;
2682
2683    /**
2684     * The layout parameters associated with this view and used by the parent
2685     * {@link android.view.ViewGroup} to determine how this view should be
2686     * laid out.
2687     * {@hide}
2688     */
2689    protected ViewGroup.LayoutParams mLayoutParams;
2690
2691    /**
2692     * The view flags hold various views states.
2693     * {@hide}
2694     */
2695    @ViewDebug.ExportedProperty
2696    int mViewFlags;
2697
2698    static class TransformationInfo {
2699        /**
2700         * The transform matrix for the View. This transform is calculated internally
2701         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2702         * is used by default. Do *not* use this variable directly; instead call
2703         * getMatrix(), which will automatically recalculate the matrix if necessary
2704         * to get the correct matrix based on the latest rotation and scale properties.
2705         */
2706        private final Matrix mMatrix = new Matrix();
2707
2708        /**
2709         * The transform matrix for the View. This transform is calculated internally
2710         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2711         * is used by default. Do *not* use this variable directly; instead call
2712         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2713         * to get the correct matrix based on the latest rotation and scale properties.
2714         */
2715        private Matrix mInverseMatrix;
2716
2717        /**
2718         * An internal variable that tracks whether we need to recalculate the
2719         * transform matrix, based on whether the rotation or scaleX/Y properties
2720         * have changed since the matrix was last calculated.
2721         */
2722        boolean mMatrixDirty = false;
2723
2724        /**
2725         * An internal variable that tracks whether we need to recalculate the
2726         * transform matrix, based on whether the rotation or scaleX/Y properties
2727         * have changed since the matrix was last calculated.
2728         */
2729        private boolean mInverseMatrixDirty = true;
2730
2731        /**
2732         * A variable that tracks whether we need to recalculate the
2733         * transform matrix, based on whether the rotation or scaleX/Y properties
2734         * have changed since the matrix was last calculated. This variable
2735         * is only valid after a call to updateMatrix() or to a function that
2736         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2737         */
2738        private boolean mMatrixIsIdentity = true;
2739
2740        /**
2741         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2742         */
2743        private Camera mCamera = null;
2744
2745        /**
2746         * This matrix is used when computing the matrix for 3D rotations.
2747         */
2748        private Matrix matrix3D = null;
2749
2750        /**
2751         * These prev values are used to recalculate a centered pivot point when necessary. The
2752         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2753         * set), so thes values are only used then as well.
2754         */
2755        private int mPrevWidth = -1;
2756        private int mPrevHeight = -1;
2757
2758        /**
2759         * The degrees rotation around the vertical axis through the pivot point.
2760         */
2761        @ViewDebug.ExportedProperty
2762        float mRotationY = 0f;
2763
2764        /**
2765         * The degrees rotation around the horizontal axis through the pivot point.
2766         */
2767        @ViewDebug.ExportedProperty
2768        float mRotationX = 0f;
2769
2770        /**
2771         * The degrees rotation around the pivot point.
2772         */
2773        @ViewDebug.ExportedProperty
2774        float mRotation = 0f;
2775
2776        /**
2777         * The amount of translation of the object away from its left property (post-layout).
2778         */
2779        @ViewDebug.ExportedProperty
2780        float mTranslationX = 0f;
2781
2782        /**
2783         * The amount of translation of the object away from its top property (post-layout).
2784         */
2785        @ViewDebug.ExportedProperty
2786        float mTranslationY = 0f;
2787
2788        /**
2789         * The amount of scale in the x direction around the pivot point. A
2790         * value of 1 means no scaling is applied.
2791         */
2792        @ViewDebug.ExportedProperty
2793        float mScaleX = 1f;
2794
2795        /**
2796         * The amount of scale in the y direction around the pivot point. A
2797         * value of 1 means no scaling is applied.
2798         */
2799        @ViewDebug.ExportedProperty
2800        float mScaleY = 1f;
2801
2802        /**
2803         * The x location of the point around which the view is rotated and scaled.
2804         */
2805        @ViewDebug.ExportedProperty
2806        float mPivotX = 0f;
2807
2808        /**
2809         * The y location of the point around which the view is rotated and scaled.
2810         */
2811        @ViewDebug.ExportedProperty
2812        float mPivotY = 0f;
2813
2814        /**
2815         * The opacity of the View. This is a value from 0 to 1, where 0 means
2816         * completely transparent and 1 means completely opaque.
2817         */
2818        @ViewDebug.ExportedProperty
2819        float mAlpha = 1f;
2820    }
2821
2822    TransformationInfo mTransformationInfo;
2823
2824    /**
2825     * Current clip bounds. to which all drawing of this view are constrained.
2826     */
2827    private Rect mClipBounds = null;
2828
2829    private boolean mLastIsOpaque;
2830
2831    /**
2832     * Convenience value to check for float values that are close enough to zero to be considered
2833     * zero.
2834     */
2835    private static final float NONZERO_EPSILON = .001f;
2836
2837    /**
2838     * The distance in pixels from the left edge of this view's parent
2839     * to the left edge of this view.
2840     * {@hide}
2841     */
2842    @ViewDebug.ExportedProperty(category = "layout")
2843    protected int mLeft;
2844    /**
2845     * The distance in pixels from the left edge of this view's parent
2846     * to the right edge of this view.
2847     * {@hide}
2848     */
2849    @ViewDebug.ExportedProperty(category = "layout")
2850    protected int mRight;
2851    /**
2852     * The distance in pixels from the top edge of this view's parent
2853     * to the top edge of this view.
2854     * {@hide}
2855     */
2856    @ViewDebug.ExportedProperty(category = "layout")
2857    protected int mTop;
2858    /**
2859     * The distance in pixels from the top edge of this view's parent
2860     * to the bottom edge of this view.
2861     * {@hide}
2862     */
2863    @ViewDebug.ExportedProperty(category = "layout")
2864    protected int mBottom;
2865
2866    /**
2867     * The offset, in pixels, by which the content of this view is scrolled
2868     * horizontally.
2869     * {@hide}
2870     */
2871    @ViewDebug.ExportedProperty(category = "scrolling")
2872    protected int mScrollX;
2873    /**
2874     * The offset, in pixels, by which the content of this view is scrolled
2875     * vertically.
2876     * {@hide}
2877     */
2878    @ViewDebug.ExportedProperty(category = "scrolling")
2879    protected int mScrollY;
2880
2881    /**
2882     * The left padding in pixels, that is the distance in pixels between the
2883     * left edge of this view and the left edge of its content.
2884     * {@hide}
2885     */
2886    @ViewDebug.ExportedProperty(category = "padding")
2887    protected int mPaddingLeft = 0;
2888    /**
2889     * The right padding in pixels, that is the distance in pixels between the
2890     * right edge of this view and the right edge of its content.
2891     * {@hide}
2892     */
2893    @ViewDebug.ExportedProperty(category = "padding")
2894    protected int mPaddingRight = 0;
2895    /**
2896     * The top padding in pixels, that is the distance in pixels between the
2897     * top edge of this view and the top edge of its content.
2898     * {@hide}
2899     */
2900    @ViewDebug.ExportedProperty(category = "padding")
2901    protected int mPaddingTop;
2902    /**
2903     * The bottom padding in pixels, that is the distance in pixels between the
2904     * bottom edge of this view and the bottom edge of its content.
2905     * {@hide}
2906     */
2907    @ViewDebug.ExportedProperty(category = "padding")
2908    protected int mPaddingBottom;
2909
2910    /**
2911     * The layout insets in pixels, that is the distance in pixels between the
2912     * visible edges of this view its bounds.
2913     */
2914    private Insets mLayoutInsets;
2915
2916    /**
2917     * Briefly describes the view and is primarily used for accessibility support.
2918     */
2919    private CharSequence mContentDescription;
2920
2921    /**
2922     * Specifies the id of a view for which this view serves as a label for
2923     * accessibility purposes.
2924     */
2925    private int mLabelForId = View.NO_ID;
2926
2927    /**
2928     * Predicate for matching labeled view id with its label for
2929     * accessibility purposes.
2930     */
2931    private MatchLabelForPredicate mMatchLabelForPredicate;
2932
2933    /**
2934     * Predicate for matching a view by its id.
2935     */
2936    private MatchIdPredicate mMatchIdPredicate;
2937
2938    /**
2939     * Cache the paddingRight set by the user to append to the scrollbar's size.
2940     *
2941     * @hide
2942     */
2943    @ViewDebug.ExportedProperty(category = "padding")
2944    protected int mUserPaddingRight;
2945
2946    /**
2947     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2948     *
2949     * @hide
2950     */
2951    @ViewDebug.ExportedProperty(category = "padding")
2952    protected int mUserPaddingBottom;
2953
2954    /**
2955     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2956     *
2957     * @hide
2958     */
2959    @ViewDebug.ExportedProperty(category = "padding")
2960    protected int mUserPaddingLeft;
2961
2962    /**
2963     * Cache the paddingStart set by the user to append to the scrollbar's size.
2964     *
2965     */
2966    @ViewDebug.ExportedProperty(category = "padding")
2967    int mUserPaddingStart;
2968
2969    /**
2970     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2971     *
2972     */
2973    @ViewDebug.ExportedProperty(category = "padding")
2974    int mUserPaddingEnd;
2975
2976    /**
2977     * Cache initial left padding.
2978     *
2979     * @hide
2980     */
2981    int mUserPaddingLeftInitial;
2982
2983    /**
2984     * Cache initial right padding.
2985     *
2986     * @hide
2987     */
2988    int mUserPaddingRightInitial;
2989
2990    /**
2991     * Default undefined padding
2992     */
2993    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2994
2995    /**
2996     * @hide
2997     */
2998    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2999    /**
3000     * @hide
3001     */
3002    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3003
3004    private LongSparseLongArray mMeasureCache;
3005
3006    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3007    private Drawable mBackground;
3008
3009    private int mBackgroundResource;
3010    private boolean mBackgroundSizeChanged;
3011
3012    static class ListenerInfo {
3013        /**
3014         * Listener used to dispatch focus change events.
3015         * This field should be made private, so it is hidden from the SDK.
3016         * {@hide}
3017         */
3018        protected OnFocusChangeListener mOnFocusChangeListener;
3019
3020        /**
3021         * Listeners for layout change events.
3022         */
3023        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3024
3025        /**
3026         * Listeners for attach events.
3027         */
3028        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3029
3030        /**
3031         * Listener used to dispatch click events.
3032         * This field should be made private, so it is hidden from the SDK.
3033         * {@hide}
3034         */
3035        public OnClickListener mOnClickListener;
3036
3037        /**
3038         * Listener used to dispatch long click events.
3039         * This field should be made private, so it is hidden from the SDK.
3040         * {@hide}
3041         */
3042        protected OnLongClickListener mOnLongClickListener;
3043
3044        /**
3045         * Listener used to build the context menu.
3046         * This field should be made private, so it is hidden from the SDK.
3047         * {@hide}
3048         */
3049        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3050
3051        private OnKeyListener mOnKeyListener;
3052
3053        private OnTouchListener mOnTouchListener;
3054
3055        private OnHoverListener mOnHoverListener;
3056
3057        private OnGenericMotionListener mOnGenericMotionListener;
3058
3059        private OnDragListener mOnDragListener;
3060
3061        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3062    }
3063
3064    ListenerInfo mListenerInfo;
3065
3066    /**
3067     * The application environment this view lives in.
3068     * This field should be made private, so it is hidden from the SDK.
3069     * {@hide}
3070     */
3071    protected Context mContext;
3072
3073    private final Resources mResources;
3074
3075    private ScrollabilityCache mScrollCache;
3076
3077    private int[] mDrawableState = null;
3078
3079    /**
3080     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3081     * the user may specify which view to go to next.
3082     */
3083    private int mNextFocusLeftId = View.NO_ID;
3084
3085    /**
3086     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3087     * the user may specify which view to go to next.
3088     */
3089    private int mNextFocusRightId = View.NO_ID;
3090
3091    /**
3092     * When this view has focus and the next focus is {@link #FOCUS_UP},
3093     * the user may specify which view to go to next.
3094     */
3095    private int mNextFocusUpId = View.NO_ID;
3096
3097    /**
3098     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3099     * the user may specify which view to go to next.
3100     */
3101    private int mNextFocusDownId = View.NO_ID;
3102
3103    /**
3104     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3105     * the user may specify which view to go to next.
3106     */
3107    int mNextFocusForwardId = View.NO_ID;
3108
3109    private CheckForLongPress mPendingCheckForLongPress;
3110    private CheckForTap mPendingCheckForTap = null;
3111    private PerformClick mPerformClick;
3112    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3113
3114    private UnsetPressedState mUnsetPressedState;
3115
3116    /**
3117     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3118     * up event while a long press is invoked as soon as the long press duration is reached, so
3119     * a long press could be performed before the tap is checked, in which case the tap's action
3120     * should not be invoked.
3121     */
3122    private boolean mHasPerformedLongPress;
3123
3124    /**
3125     * The minimum height of the view. We'll try our best to have the height
3126     * of this view to at least this amount.
3127     */
3128    @ViewDebug.ExportedProperty(category = "measurement")
3129    private int mMinHeight;
3130
3131    /**
3132     * The minimum width of the view. We'll try our best to have the width
3133     * of this view to at least this amount.
3134     */
3135    @ViewDebug.ExportedProperty(category = "measurement")
3136    private int mMinWidth;
3137
3138    /**
3139     * The delegate to handle touch events that are physically in this view
3140     * but should be handled by another view.
3141     */
3142    private TouchDelegate mTouchDelegate = null;
3143
3144    /**
3145     * Solid color to use as a background when creating the drawing cache. Enables
3146     * the cache to use 16 bit bitmaps instead of 32 bit.
3147     */
3148    private int mDrawingCacheBackgroundColor = 0;
3149
3150    /**
3151     * Special tree observer used when mAttachInfo is null.
3152     */
3153    private ViewTreeObserver mFloatingTreeObserver;
3154
3155    /**
3156     * Cache the touch slop from the context that created the view.
3157     */
3158    private int mTouchSlop;
3159
3160    /**
3161     * Object that handles automatic animation of view properties.
3162     */
3163    private ViewPropertyAnimator mAnimator = null;
3164
3165    /**
3166     * Flag indicating that a drag can cross window boundaries.  When
3167     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3168     * with this flag set, all visible applications will be able to participate
3169     * in the drag operation and receive the dragged content.
3170     *
3171     * @hide
3172     */
3173    public static final int DRAG_FLAG_GLOBAL = 1;
3174
3175    /**
3176     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3177     */
3178    private float mVerticalScrollFactor;
3179
3180    /**
3181     * Position of the vertical scroll bar.
3182     */
3183    private int mVerticalScrollbarPosition;
3184
3185    /**
3186     * Position the scroll bar at the default position as determined by the system.
3187     */
3188    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3189
3190    /**
3191     * Position the scroll bar along the left edge.
3192     */
3193    public static final int SCROLLBAR_POSITION_LEFT = 1;
3194
3195    /**
3196     * Position the scroll bar along the right edge.
3197     */
3198    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3199
3200    /**
3201     * Indicates that the view does not have a layer.
3202     *
3203     * @see #getLayerType()
3204     * @see #setLayerType(int, android.graphics.Paint)
3205     * @see #LAYER_TYPE_SOFTWARE
3206     * @see #LAYER_TYPE_HARDWARE
3207     */
3208    public static final int LAYER_TYPE_NONE = 0;
3209
3210    /**
3211     * <p>Indicates that the view has a software layer. A software layer is backed
3212     * by a bitmap and causes the view to be rendered using Android's software
3213     * rendering pipeline, even if hardware acceleration is enabled.</p>
3214     *
3215     * <p>Software layers have various usages:</p>
3216     * <p>When the application is not using hardware acceleration, a software layer
3217     * is useful to apply a specific color filter and/or blending mode and/or
3218     * translucency to a view and all its children.</p>
3219     * <p>When the application is using hardware acceleration, a software layer
3220     * is useful to render drawing primitives not supported by the hardware
3221     * accelerated pipeline. It can also be used to cache a complex view tree
3222     * into a texture and reduce the complexity of drawing operations. For instance,
3223     * when animating a complex view tree with a translation, a software layer can
3224     * be used to render the view tree only once.</p>
3225     * <p>Software layers should be avoided when the affected view tree updates
3226     * often. Every update will require to re-render the software layer, which can
3227     * potentially be slow (particularly when hardware acceleration is turned on
3228     * since the layer will have to be uploaded into a hardware texture after every
3229     * update.)</p>
3230     *
3231     * @see #getLayerType()
3232     * @see #setLayerType(int, android.graphics.Paint)
3233     * @see #LAYER_TYPE_NONE
3234     * @see #LAYER_TYPE_HARDWARE
3235     */
3236    public static final int LAYER_TYPE_SOFTWARE = 1;
3237
3238    /**
3239     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3240     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3241     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3242     * rendering pipeline, but only if hardware acceleration is turned on for the
3243     * view hierarchy. When hardware acceleration is turned off, hardware layers
3244     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3245     *
3246     * <p>A hardware layer is useful to apply a specific color filter and/or
3247     * blending mode and/or translucency to a view and all its children.</p>
3248     * <p>A hardware layer can be used to cache a complex view tree into a
3249     * texture and reduce the complexity of drawing operations. For instance,
3250     * when animating a complex view tree with a translation, a hardware layer can
3251     * be used to render the view tree only once.</p>
3252     * <p>A hardware layer can also be used to increase the rendering quality when
3253     * rotation transformations are applied on a view. It can also be used to
3254     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3255     *
3256     * @see #getLayerType()
3257     * @see #setLayerType(int, android.graphics.Paint)
3258     * @see #LAYER_TYPE_NONE
3259     * @see #LAYER_TYPE_SOFTWARE
3260     */
3261    public static final int LAYER_TYPE_HARDWARE = 2;
3262
3263    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3264            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3265            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3266            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3267    })
3268    int mLayerType = LAYER_TYPE_NONE;
3269    Paint mLayerPaint;
3270    Rect mLocalDirtyRect;
3271    private HardwareLayer mHardwareLayer;
3272
3273    /**
3274     * Set to true when drawing cache is enabled and cannot be created.
3275     *
3276     * @hide
3277     */
3278    public boolean mCachingFailed;
3279    private Bitmap mDrawingCache;
3280    private Bitmap mUnscaledDrawingCache;
3281
3282    DisplayList mDisplayList;
3283
3284    /**
3285     * Set to true when the view is sending hover accessibility events because it
3286     * is the innermost hovered view.
3287     */
3288    private boolean mSendingHoverAccessibilityEvents;
3289
3290    /**
3291     * Delegate for injecting accessibility functionality.
3292     */
3293    AccessibilityDelegate mAccessibilityDelegate;
3294
3295    /**
3296     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3297     * and add/remove objects to/from the overlay directly through the Overlay methods.
3298     */
3299    ViewOverlay mOverlay;
3300
3301    /**
3302     * Consistency verifier for debugging purposes.
3303     * @hide
3304     */
3305    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3306            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3307                    new InputEventConsistencyVerifier(this, 0) : null;
3308
3309    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3310
3311    /**
3312     * Simple constructor to use when creating a view from code.
3313     *
3314     * @param context The Context the view is running in, through which it can
3315     *        access the current theme, resources, etc.
3316     */
3317    public View(Context context) {
3318        mContext = context;
3319        mResources = context != null ? context.getResources() : null;
3320        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3321        // Set some flags defaults
3322        mPrivateFlags2 =
3323                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3324                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3325                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3326                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3327                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3328                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3329        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3330        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3331        mUserPaddingStart = UNDEFINED_PADDING;
3332        mUserPaddingEnd = UNDEFINED_PADDING;
3333
3334        if (!sUseBrokenMakeMeasureSpec && context != null &&
3335                context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) {
3336            // Older apps may need this compatibility hack for measurement.
3337            sUseBrokenMakeMeasureSpec = true;
3338        }
3339    }
3340
3341    /**
3342     * Constructor that is called when inflating a view from XML. This is called
3343     * when a view is being constructed from an XML file, supplying attributes
3344     * that were specified in the XML file. This version uses a default style of
3345     * 0, so the only attribute values applied are those in the Context's Theme
3346     * and the given AttributeSet.
3347     *
3348     * <p>
3349     * The method onFinishInflate() will be called after all children have been
3350     * added.
3351     *
3352     * @param context The Context the view is running in, through which it can
3353     *        access the current theme, resources, etc.
3354     * @param attrs The attributes of the XML tag that is inflating the view.
3355     * @see #View(Context, AttributeSet, int)
3356     */
3357    public View(Context context, AttributeSet attrs) {
3358        this(context, attrs, 0);
3359    }
3360
3361    /**
3362     * Perform inflation from XML and apply a class-specific base style. This
3363     * constructor of View allows subclasses to use their own base style when
3364     * they are inflating. For example, a Button class's constructor would call
3365     * this version of the super class constructor and supply
3366     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3367     * the theme's button style to modify all of the base view attributes (in
3368     * particular its background) as well as the Button class's attributes.
3369     *
3370     * @param context The Context the view is running in, through which it can
3371     *        access the current theme, resources, etc.
3372     * @param attrs The attributes of the XML tag that is inflating the view.
3373     * @param defStyle The default style to apply to this view. If 0, no style
3374     *        will be applied (beyond what is included in the theme). This may
3375     *        either be an attribute resource, whose value will be retrieved
3376     *        from the current theme, or an explicit style resource.
3377     * @see #View(Context, AttributeSet)
3378     */
3379    public View(Context context, AttributeSet attrs, int defStyle) {
3380        this(context);
3381
3382        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3383                defStyle, 0);
3384
3385        Drawable background = null;
3386
3387        int leftPadding = -1;
3388        int topPadding = -1;
3389        int rightPadding = -1;
3390        int bottomPadding = -1;
3391        int startPadding = UNDEFINED_PADDING;
3392        int endPadding = UNDEFINED_PADDING;
3393
3394        int padding = -1;
3395
3396        int viewFlagValues = 0;
3397        int viewFlagMasks = 0;
3398
3399        boolean setScrollContainer = false;
3400
3401        int x = 0;
3402        int y = 0;
3403
3404        float tx = 0;
3405        float ty = 0;
3406        float rotation = 0;
3407        float rotationX = 0;
3408        float rotationY = 0;
3409        float sx = 1f;
3410        float sy = 1f;
3411        boolean transformSet = false;
3412
3413        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3414        int overScrollMode = mOverScrollMode;
3415        boolean initializeScrollbars = false;
3416
3417        boolean leftPaddingDefined = false;
3418        boolean rightPaddingDefined = false;
3419        boolean startPaddingDefined = false;
3420        boolean endPaddingDefined = false;
3421
3422        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3423
3424        final int N = a.getIndexCount();
3425        for (int i = 0; i < N; i++) {
3426            int attr = a.getIndex(i);
3427            switch (attr) {
3428                case com.android.internal.R.styleable.View_background:
3429                    background = a.getDrawable(attr);
3430                    break;
3431                case com.android.internal.R.styleable.View_padding:
3432                    padding = a.getDimensionPixelSize(attr, -1);
3433                    mUserPaddingLeftInitial = padding;
3434                    mUserPaddingRightInitial = padding;
3435                    leftPaddingDefined = true;
3436                    rightPaddingDefined = true;
3437                    break;
3438                 case com.android.internal.R.styleable.View_paddingLeft:
3439                    leftPadding = a.getDimensionPixelSize(attr, -1);
3440                    mUserPaddingLeftInitial = leftPadding;
3441                    leftPaddingDefined = true;
3442                    break;
3443                case com.android.internal.R.styleable.View_paddingTop:
3444                    topPadding = a.getDimensionPixelSize(attr, -1);
3445                    break;
3446                case com.android.internal.R.styleable.View_paddingRight:
3447                    rightPadding = a.getDimensionPixelSize(attr, -1);
3448                    mUserPaddingRightInitial = rightPadding;
3449                    rightPaddingDefined = true;
3450                    break;
3451                case com.android.internal.R.styleable.View_paddingBottom:
3452                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3453                    break;
3454                case com.android.internal.R.styleable.View_paddingStart:
3455                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3456                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3457                    break;
3458                case com.android.internal.R.styleable.View_paddingEnd:
3459                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3460                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3461                    break;
3462                case com.android.internal.R.styleable.View_scrollX:
3463                    x = a.getDimensionPixelOffset(attr, 0);
3464                    break;
3465                case com.android.internal.R.styleable.View_scrollY:
3466                    y = a.getDimensionPixelOffset(attr, 0);
3467                    break;
3468                case com.android.internal.R.styleable.View_alpha:
3469                    setAlpha(a.getFloat(attr, 1f));
3470                    break;
3471                case com.android.internal.R.styleable.View_transformPivotX:
3472                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3473                    break;
3474                case com.android.internal.R.styleable.View_transformPivotY:
3475                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3476                    break;
3477                case com.android.internal.R.styleable.View_translationX:
3478                    tx = a.getDimensionPixelOffset(attr, 0);
3479                    transformSet = true;
3480                    break;
3481                case com.android.internal.R.styleable.View_translationY:
3482                    ty = a.getDimensionPixelOffset(attr, 0);
3483                    transformSet = true;
3484                    break;
3485                case com.android.internal.R.styleable.View_rotation:
3486                    rotation = a.getFloat(attr, 0);
3487                    transformSet = true;
3488                    break;
3489                case com.android.internal.R.styleable.View_rotationX:
3490                    rotationX = a.getFloat(attr, 0);
3491                    transformSet = true;
3492                    break;
3493                case com.android.internal.R.styleable.View_rotationY:
3494                    rotationY = a.getFloat(attr, 0);
3495                    transformSet = true;
3496                    break;
3497                case com.android.internal.R.styleable.View_scaleX:
3498                    sx = a.getFloat(attr, 1f);
3499                    transformSet = true;
3500                    break;
3501                case com.android.internal.R.styleable.View_scaleY:
3502                    sy = a.getFloat(attr, 1f);
3503                    transformSet = true;
3504                    break;
3505                case com.android.internal.R.styleable.View_id:
3506                    mID = a.getResourceId(attr, NO_ID);
3507                    break;
3508                case com.android.internal.R.styleable.View_tag:
3509                    mTag = a.getText(attr);
3510                    break;
3511                case com.android.internal.R.styleable.View_fitsSystemWindows:
3512                    if (a.getBoolean(attr, false)) {
3513                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3514                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3515                    }
3516                    break;
3517                case com.android.internal.R.styleable.View_focusable:
3518                    if (a.getBoolean(attr, false)) {
3519                        viewFlagValues |= FOCUSABLE;
3520                        viewFlagMasks |= FOCUSABLE_MASK;
3521                    }
3522                    break;
3523                case com.android.internal.R.styleable.View_focusableInTouchMode:
3524                    if (a.getBoolean(attr, false)) {
3525                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3526                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3527                    }
3528                    break;
3529                case com.android.internal.R.styleable.View_clickable:
3530                    if (a.getBoolean(attr, false)) {
3531                        viewFlagValues |= CLICKABLE;
3532                        viewFlagMasks |= CLICKABLE;
3533                    }
3534                    break;
3535                case com.android.internal.R.styleable.View_longClickable:
3536                    if (a.getBoolean(attr, false)) {
3537                        viewFlagValues |= LONG_CLICKABLE;
3538                        viewFlagMasks |= LONG_CLICKABLE;
3539                    }
3540                    break;
3541                case com.android.internal.R.styleable.View_saveEnabled:
3542                    if (!a.getBoolean(attr, true)) {
3543                        viewFlagValues |= SAVE_DISABLED;
3544                        viewFlagMasks |= SAVE_DISABLED_MASK;
3545                    }
3546                    break;
3547                case com.android.internal.R.styleable.View_duplicateParentState:
3548                    if (a.getBoolean(attr, false)) {
3549                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3550                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3551                    }
3552                    break;
3553                case com.android.internal.R.styleable.View_visibility:
3554                    final int visibility = a.getInt(attr, 0);
3555                    if (visibility != 0) {
3556                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3557                        viewFlagMasks |= VISIBILITY_MASK;
3558                    }
3559                    break;
3560                case com.android.internal.R.styleable.View_layoutDirection:
3561                    // Clear any layout direction flags (included resolved bits) already set
3562                    mPrivateFlags2 &=
3563                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3564                    // Set the layout direction flags depending on the value of the attribute
3565                    final int layoutDirection = a.getInt(attr, -1);
3566                    final int value = (layoutDirection != -1) ?
3567                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3568                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3569                    break;
3570                case com.android.internal.R.styleable.View_drawingCacheQuality:
3571                    final int cacheQuality = a.getInt(attr, 0);
3572                    if (cacheQuality != 0) {
3573                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3574                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3575                    }
3576                    break;
3577                case com.android.internal.R.styleable.View_contentDescription:
3578                    setContentDescription(a.getString(attr));
3579                    break;
3580                case com.android.internal.R.styleable.View_labelFor:
3581                    setLabelFor(a.getResourceId(attr, NO_ID));
3582                    break;
3583                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3584                    if (!a.getBoolean(attr, true)) {
3585                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3586                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3587                    }
3588                    break;
3589                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3590                    if (!a.getBoolean(attr, true)) {
3591                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3592                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3593                    }
3594                    break;
3595                case R.styleable.View_scrollbars:
3596                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3597                    if (scrollbars != SCROLLBARS_NONE) {
3598                        viewFlagValues |= scrollbars;
3599                        viewFlagMasks |= SCROLLBARS_MASK;
3600                        initializeScrollbars = true;
3601                    }
3602                    break;
3603                //noinspection deprecation
3604                case R.styleable.View_fadingEdge:
3605                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3606                        // Ignore the attribute starting with ICS
3607                        break;
3608                    }
3609                    // With builds < ICS, fall through and apply fading edges
3610                case R.styleable.View_requiresFadingEdge:
3611                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3612                    if (fadingEdge != FADING_EDGE_NONE) {
3613                        viewFlagValues |= fadingEdge;
3614                        viewFlagMasks |= FADING_EDGE_MASK;
3615                        initializeFadingEdge(a);
3616                    }
3617                    break;
3618                case R.styleable.View_scrollbarStyle:
3619                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3620                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3621                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3622                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3623                    }
3624                    break;
3625                case R.styleable.View_isScrollContainer:
3626                    setScrollContainer = true;
3627                    if (a.getBoolean(attr, false)) {
3628                        setScrollContainer(true);
3629                    }
3630                    break;
3631                case com.android.internal.R.styleable.View_keepScreenOn:
3632                    if (a.getBoolean(attr, false)) {
3633                        viewFlagValues |= KEEP_SCREEN_ON;
3634                        viewFlagMasks |= KEEP_SCREEN_ON;
3635                    }
3636                    break;
3637                case R.styleable.View_filterTouchesWhenObscured:
3638                    if (a.getBoolean(attr, false)) {
3639                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3640                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3641                    }
3642                    break;
3643                case R.styleable.View_nextFocusLeft:
3644                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3645                    break;
3646                case R.styleable.View_nextFocusRight:
3647                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3648                    break;
3649                case R.styleable.View_nextFocusUp:
3650                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3651                    break;
3652                case R.styleable.View_nextFocusDown:
3653                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3654                    break;
3655                case R.styleable.View_nextFocusForward:
3656                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3657                    break;
3658                case R.styleable.View_minWidth:
3659                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3660                    break;
3661                case R.styleable.View_minHeight:
3662                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3663                    break;
3664                case R.styleable.View_onClick:
3665                    if (context.isRestricted()) {
3666                        throw new IllegalStateException("The android:onClick attribute cannot "
3667                                + "be used within a restricted context");
3668                    }
3669
3670                    final String handlerName = a.getString(attr);
3671                    if (handlerName != null) {
3672                        setOnClickListener(new OnClickListener() {
3673                            private Method mHandler;
3674
3675                            public void onClick(View v) {
3676                                if (mHandler == null) {
3677                                    try {
3678                                        mHandler = getContext().getClass().getMethod(handlerName,
3679                                                View.class);
3680                                    } catch (NoSuchMethodException e) {
3681                                        int id = getId();
3682                                        String idText = id == NO_ID ? "" : " with id '"
3683                                                + getContext().getResources().getResourceEntryName(
3684                                                    id) + "'";
3685                                        throw new IllegalStateException("Could not find a method " +
3686                                                handlerName + "(View) in the activity "
3687                                                + getContext().getClass() + " for onClick handler"
3688                                                + " on view " + View.this.getClass() + idText, e);
3689                                    }
3690                                }
3691
3692                                try {
3693                                    mHandler.invoke(getContext(), View.this);
3694                                } catch (IllegalAccessException e) {
3695                                    throw new IllegalStateException("Could not execute non "
3696                                            + "public method of the activity", e);
3697                                } catch (InvocationTargetException e) {
3698                                    throw new IllegalStateException("Could not execute "
3699                                            + "method of the activity", e);
3700                                }
3701                            }
3702                        });
3703                    }
3704                    break;
3705                case R.styleable.View_overScrollMode:
3706                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3707                    break;
3708                case R.styleable.View_verticalScrollbarPosition:
3709                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3710                    break;
3711                case R.styleable.View_layerType:
3712                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3713                    break;
3714                case R.styleable.View_textDirection:
3715                    // Clear any text direction flag already set
3716                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3717                    // Set the text direction flags depending on the value of the attribute
3718                    final int textDirection = a.getInt(attr, -1);
3719                    if (textDirection != -1) {
3720                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3721                    }
3722                    break;
3723                case R.styleable.View_textAlignment:
3724                    // Clear any text alignment flag already set
3725                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3726                    // Set the text alignment flag depending on the value of the attribute
3727                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3728                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3729                    break;
3730                case R.styleable.View_importantForAccessibility:
3731                    setImportantForAccessibility(a.getInt(attr,
3732                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3733                    break;
3734            }
3735        }
3736
3737        setOverScrollMode(overScrollMode);
3738
3739        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3740        // the resolved layout direction). Those cached values will be used later during padding
3741        // resolution.
3742        mUserPaddingStart = startPadding;
3743        mUserPaddingEnd = endPadding;
3744
3745        if (background != null) {
3746            setBackground(background);
3747        }
3748
3749        if (padding >= 0) {
3750            leftPadding = padding;
3751            topPadding = padding;
3752            rightPadding = padding;
3753            bottomPadding = padding;
3754            mUserPaddingLeftInitial = padding;
3755            mUserPaddingRightInitial = padding;
3756        }
3757
3758        if (isRtlCompatibilityMode()) {
3759            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3760            // left / right padding are used if defined (meaning here nothing to do). If they are not
3761            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3762            // start / end and resolve them as left / right (layout direction is not taken into account).
3763            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3764            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3765            // defined.
3766            if (!leftPaddingDefined && startPaddingDefined) {
3767                leftPadding = startPadding;
3768            }
3769            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3770            if (!rightPaddingDefined && endPaddingDefined) {
3771                rightPadding = endPadding;
3772            }
3773            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3774        } else {
3775            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3776            // values defined. Otherwise, left /right values are used.
3777            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3778            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3779            // defined.
3780            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3781
3782            if (leftPaddingDefined && !hasRelativePadding) {
3783                mUserPaddingLeftInitial = leftPadding;
3784            }
3785            if (rightPaddingDefined && !hasRelativePadding) {
3786                mUserPaddingRightInitial = rightPadding;
3787            }
3788        }
3789
3790        internalSetPadding(
3791                mUserPaddingLeftInitial,
3792                topPadding >= 0 ? topPadding : mPaddingTop,
3793                mUserPaddingRightInitial,
3794                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3795
3796        if (viewFlagMasks != 0) {
3797            setFlags(viewFlagValues, viewFlagMasks);
3798        }
3799
3800        if (initializeScrollbars) {
3801            initializeScrollbars(a);
3802        }
3803
3804        a.recycle();
3805
3806        // Needs to be called after mViewFlags is set
3807        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3808            recomputePadding();
3809        }
3810
3811        if (x != 0 || y != 0) {
3812            scrollTo(x, y);
3813        }
3814
3815        if (transformSet) {
3816            setTranslationX(tx);
3817            setTranslationY(ty);
3818            setRotation(rotation);
3819            setRotationX(rotationX);
3820            setRotationY(rotationY);
3821            setScaleX(sx);
3822            setScaleY(sy);
3823        }
3824
3825        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3826            setScrollContainer(true);
3827        }
3828
3829        computeOpaqueFlags();
3830    }
3831
3832    /**
3833     * Non-public constructor for use in testing
3834     */
3835    View() {
3836        mResources = null;
3837    }
3838
3839    public String toString() {
3840        StringBuilder out = new StringBuilder(128);
3841        out.append(getClass().getName());
3842        out.append('{');
3843        out.append(Integer.toHexString(System.identityHashCode(this)));
3844        out.append(' ');
3845        switch (mViewFlags&VISIBILITY_MASK) {
3846            case VISIBLE: out.append('V'); break;
3847            case INVISIBLE: out.append('I'); break;
3848            case GONE: out.append('G'); break;
3849            default: out.append('.'); break;
3850        }
3851        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3852        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3853        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3854        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3855        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3856        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3857        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3858        out.append(' ');
3859        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3860        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3861        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3862        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3863            out.append('p');
3864        } else {
3865            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3866        }
3867        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3868        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3869        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3870        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3871        out.append(' ');
3872        out.append(mLeft);
3873        out.append(',');
3874        out.append(mTop);
3875        out.append('-');
3876        out.append(mRight);
3877        out.append(',');
3878        out.append(mBottom);
3879        final int id = getId();
3880        if (id != NO_ID) {
3881            out.append(" #");
3882            out.append(Integer.toHexString(id));
3883            final Resources r = mResources;
3884            if (id != 0 && r != null) {
3885                try {
3886                    String pkgname;
3887                    switch (id&0xff000000) {
3888                        case 0x7f000000:
3889                            pkgname="app";
3890                            break;
3891                        case 0x01000000:
3892                            pkgname="android";
3893                            break;
3894                        default:
3895                            pkgname = r.getResourcePackageName(id);
3896                            break;
3897                    }
3898                    String typename = r.getResourceTypeName(id);
3899                    String entryname = r.getResourceEntryName(id);
3900                    out.append(" ");
3901                    out.append(pkgname);
3902                    out.append(":");
3903                    out.append(typename);
3904                    out.append("/");
3905                    out.append(entryname);
3906                } catch (Resources.NotFoundException e) {
3907                }
3908            }
3909        }
3910        out.append("}");
3911        return out.toString();
3912    }
3913
3914    /**
3915     * <p>
3916     * Initializes the fading edges from a given set of styled attributes. This
3917     * method should be called by subclasses that need fading edges and when an
3918     * instance of these subclasses is created programmatically rather than
3919     * being inflated from XML. This method is automatically called when the XML
3920     * is inflated.
3921     * </p>
3922     *
3923     * @param a the styled attributes set to initialize the fading edges from
3924     */
3925    protected void initializeFadingEdge(TypedArray a) {
3926        initScrollCache();
3927
3928        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3929                R.styleable.View_fadingEdgeLength,
3930                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3931    }
3932
3933    /**
3934     * Returns the size of the vertical faded edges used to indicate that more
3935     * content in this view is visible.
3936     *
3937     * @return The size in pixels of the vertical faded edge or 0 if vertical
3938     *         faded edges are not enabled for this view.
3939     * @attr ref android.R.styleable#View_fadingEdgeLength
3940     */
3941    public int getVerticalFadingEdgeLength() {
3942        if (isVerticalFadingEdgeEnabled()) {
3943            ScrollabilityCache cache = mScrollCache;
3944            if (cache != null) {
3945                return cache.fadingEdgeLength;
3946            }
3947        }
3948        return 0;
3949    }
3950
3951    /**
3952     * Set the size of the faded edge used to indicate that more content in this
3953     * view is available.  Will not change whether the fading edge is enabled; use
3954     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3955     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3956     * for the vertical or horizontal fading edges.
3957     *
3958     * @param length The size in pixels of the faded edge used to indicate that more
3959     *        content in this view is visible.
3960     */
3961    public void setFadingEdgeLength(int length) {
3962        initScrollCache();
3963        mScrollCache.fadingEdgeLength = length;
3964    }
3965
3966    /**
3967     * Returns the size of the horizontal faded edges used to indicate that more
3968     * content in this view is visible.
3969     *
3970     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3971     *         faded edges are not enabled for this view.
3972     * @attr ref android.R.styleable#View_fadingEdgeLength
3973     */
3974    public int getHorizontalFadingEdgeLength() {
3975        if (isHorizontalFadingEdgeEnabled()) {
3976            ScrollabilityCache cache = mScrollCache;
3977            if (cache != null) {
3978                return cache.fadingEdgeLength;
3979            }
3980        }
3981        return 0;
3982    }
3983
3984    /**
3985     * Returns the width of the vertical scrollbar.
3986     *
3987     * @return The width in pixels of the vertical scrollbar or 0 if there
3988     *         is no vertical scrollbar.
3989     */
3990    public int getVerticalScrollbarWidth() {
3991        ScrollabilityCache cache = mScrollCache;
3992        if (cache != null) {
3993            ScrollBarDrawable scrollBar = cache.scrollBar;
3994            if (scrollBar != null) {
3995                int size = scrollBar.getSize(true);
3996                if (size <= 0) {
3997                    size = cache.scrollBarSize;
3998                }
3999                return size;
4000            }
4001            return 0;
4002        }
4003        return 0;
4004    }
4005
4006    /**
4007     * Returns the height of the horizontal scrollbar.
4008     *
4009     * @return The height in pixels of the horizontal scrollbar or 0 if
4010     *         there is no horizontal scrollbar.
4011     */
4012    protected int getHorizontalScrollbarHeight() {
4013        ScrollabilityCache cache = mScrollCache;
4014        if (cache != null) {
4015            ScrollBarDrawable scrollBar = cache.scrollBar;
4016            if (scrollBar != null) {
4017                int size = scrollBar.getSize(false);
4018                if (size <= 0) {
4019                    size = cache.scrollBarSize;
4020                }
4021                return size;
4022            }
4023            return 0;
4024        }
4025        return 0;
4026    }
4027
4028    /**
4029     * <p>
4030     * Initializes the scrollbars from a given set of styled attributes. This
4031     * method should be called by subclasses that need scrollbars and when an
4032     * instance of these subclasses is created programmatically rather than
4033     * being inflated from XML. This method is automatically called when the XML
4034     * is inflated.
4035     * </p>
4036     *
4037     * @param a the styled attributes set to initialize the scrollbars from
4038     */
4039    protected void initializeScrollbars(TypedArray a) {
4040        initScrollCache();
4041
4042        final ScrollabilityCache scrollabilityCache = mScrollCache;
4043
4044        if (scrollabilityCache.scrollBar == null) {
4045            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4046        }
4047
4048        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4049
4050        if (!fadeScrollbars) {
4051            scrollabilityCache.state = ScrollabilityCache.ON;
4052        }
4053        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4054
4055
4056        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4057                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4058                        .getScrollBarFadeDuration());
4059        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4060                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4061                ViewConfiguration.getScrollDefaultDelay());
4062
4063
4064        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4065                com.android.internal.R.styleable.View_scrollbarSize,
4066                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4067
4068        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4069        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4070
4071        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4072        if (thumb != null) {
4073            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4074        }
4075
4076        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4077                false);
4078        if (alwaysDraw) {
4079            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4080        }
4081
4082        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4083        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4084
4085        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4086        if (thumb != null) {
4087            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4088        }
4089
4090        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4091                false);
4092        if (alwaysDraw) {
4093            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4094        }
4095
4096        // Apply layout direction to the new Drawables if needed
4097        final int layoutDirection = getLayoutDirection();
4098        if (track != null) {
4099            track.setLayoutDirection(layoutDirection);
4100        }
4101        if (thumb != null) {
4102            thumb.setLayoutDirection(layoutDirection);
4103        }
4104
4105        // Re-apply user/background padding so that scrollbar(s) get added
4106        resolvePadding();
4107    }
4108
4109    /**
4110     * <p>
4111     * Initalizes the scrollability cache if necessary.
4112     * </p>
4113     */
4114    private void initScrollCache() {
4115        if (mScrollCache == null) {
4116            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4117        }
4118    }
4119
4120    private ScrollabilityCache getScrollCache() {
4121        initScrollCache();
4122        return mScrollCache;
4123    }
4124
4125    /**
4126     * Set the position of the vertical scroll bar. Should be one of
4127     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4128     * {@link #SCROLLBAR_POSITION_RIGHT}.
4129     *
4130     * @param position Where the vertical scroll bar should be positioned.
4131     */
4132    public void setVerticalScrollbarPosition(int position) {
4133        if (mVerticalScrollbarPosition != position) {
4134            mVerticalScrollbarPosition = position;
4135            computeOpaqueFlags();
4136            resolvePadding();
4137        }
4138    }
4139
4140    /**
4141     * @return The position where the vertical scroll bar will show, if applicable.
4142     * @see #setVerticalScrollbarPosition(int)
4143     */
4144    public int getVerticalScrollbarPosition() {
4145        return mVerticalScrollbarPosition;
4146    }
4147
4148    ListenerInfo getListenerInfo() {
4149        if (mListenerInfo != null) {
4150            return mListenerInfo;
4151        }
4152        mListenerInfo = new ListenerInfo();
4153        return mListenerInfo;
4154    }
4155
4156    /**
4157     * Register a callback to be invoked when focus of this view changed.
4158     *
4159     * @param l The callback that will run.
4160     */
4161    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4162        getListenerInfo().mOnFocusChangeListener = l;
4163    }
4164
4165    /**
4166     * Add a listener that will be called when the bounds of the view change due to
4167     * layout processing.
4168     *
4169     * @param listener The listener that will be called when layout bounds change.
4170     */
4171    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4172        ListenerInfo li = getListenerInfo();
4173        if (li.mOnLayoutChangeListeners == null) {
4174            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4175        }
4176        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4177            li.mOnLayoutChangeListeners.add(listener);
4178        }
4179    }
4180
4181    /**
4182     * Remove a listener for layout changes.
4183     *
4184     * @param listener The listener for layout bounds change.
4185     */
4186    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4187        ListenerInfo li = mListenerInfo;
4188        if (li == null || li.mOnLayoutChangeListeners == null) {
4189            return;
4190        }
4191        li.mOnLayoutChangeListeners.remove(listener);
4192    }
4193
4194    /**
4195     * Add a listener for attach state changes.
4196     *
4197     * This listener will be called whenever this view is attached or detached
4198     * from a window. Remove the listener using
4199     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4200     *
4201     * @param listener Listener to attach
4202     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4203     */
4204    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4205        ListenerInfo li = getListenerInfo();
4206        if (li.mOnAttachStateChangeListeners == null) {
4207            li.mOnAttachStateChangeListeners
4208                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4209        }
4210        li.mOnAttachStateChangeListeners.add(listener);
4211    }
4212
4213    /**
4214     * Remove a listener for attach state changes. The listener will receive no further
4215     * notification of window attach/detach events.
4216     *
4217     * @param listener Listener to remove
4218     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4219     */
4220    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4221        ListenerInfo li = mListenerInfo;
4222        if (li == null || li.mOnAttachStateChangeListeners == null) {
4223            return;
4224        }
4225        li.mOnAttachStateChangeListeners.remove(listener);
4226    }
4227
4228    /**
4229     * Returns the focus-change callback registered for this view.
4230     *
4231     * @return The callback, or null if one is not registered.
4232     */
4233    public OnFocusChangeListener getOnFocusChangeListener() {
4234        ListenerInfo li = mListenerInfo;
4235        return li != null ? li.mOnFocusChangeListener : null;
4236    }
4237
4238    /**
4239     * Register a callback to be invoked when this view is clicked. If this view is not
4240     * clickable, it becomes clickable.
4241     *
4242     * @param l The callback that will run
4243     *
4244     * @see #setClickable(boolean)
4245     */
4246    public void setOnClickListener(OnClickListener l) {
4247        if (!isClickable()) {
4248            setClickable(true);
4249        }
4250        getListenerInfo().mOnClickListener = l;
4251    }
4252
4253    /**
4254     * Return whether this view has an attached OnClickListener.  Returns
4255     * true if there is a listener, false if there is none.
4256     */
4257    public boolean hasOnClickListeners() {
4258        ListenerInfo li = mListenerInfo;
4259        return (li != null && li.mOnClickListener != null);
4260    }
4261
4262    /**
4263     * Register a callback to be invoked when this view is clicked and held. If this view is not
4264     * long clickable, it becomes long clickable.
4265     *
4266     * @param l The callback that will run
4267     *
4268     * @see #setLongClickable(boolean)
4269     */
4270    public void setOnLongClickListener(OnLongClickListener l) {
4271        if (!isLongClickable()) {
4272            setLongClickable(true);
4273        }
4274        getListenerInfo().mOnLongClickListener = l;
4275    }
4276
4277    /**
4278     * Register a callback to be invoked when the context menu for this view is
4279     * being built. If this view is not long clickable, it becomes long clickable.
4280     *
4281     * @param l The callback that will run
4282     *
4283     */
4284    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4285        if (!isLongClickable()) {
4286            setLongClickable(true);
4287        }
4288        getListenerInfo().mOnCreateContextMenuListener = l;
4289    }
4290
4291    /**
4292     * Call this view's OnClickListener, if it is defined.  Performs all normal
4293     * actions associated with clicking: reporting accessibility event, playing
4294     * a sound, etc.
4295     *
4296     * @return True there was an assigned OnClickListener that was called, false
4297     *         otherwise is returned.
4298     */
4299    public boolean performClick() {
4300        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4301
4302        ListenerInfo li = mListenerInfo;
4303        if (li != null && li.mOnClickListener != null) {
4304            playSoundEffect(SoundEffectConstants.CLICK);
4305            li.mOnClickListener.onClick(this);
4306            return true;
4307        }
4308
4309        return false;
4310    }
4311
4312    /**
4313     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4314     * this only calls the listener, and does not do any associated clicking
4315     * actions like reporting an accessibility event.
4316     *
4317     * @return True there was an assigned OnClickListener that was called, false
4318     *         otherwise is returned.
4319     */
4320    public boolean callOnClick() {
4321        ListenerInfo li = mListenerInfo;
4322        if (li != null && li.mOnClickListener != null) {
4323            li.mOnClickListener.onClick(this);
4324            return true;
4325        }
4326        return false;
4327    }
4328
4329    /**
4330     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4331     * OnLongClickListener did not consume the event.
4332     *
4333     * @return True if one of the above receivers consumed the event, false otherwise.
4334     */
4335    public boolean performLongClick() {
4336        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4337
4338        boolean handled = false;
4339        ListenerInfo li = mListenerInfo;
4340        if (li != null && li.mOnLongClickListener != null) {
4341            handled = li.mOnLongClickListener.onLongClick(View.this);
4342        }
4343        if (!handled) {
4344            handled = showContextMenu();
4345        }
4346        if (handled) {
4347            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4348        }
4349        return handled;
4350    }
4351
4352    /**
4353     * Performs button-related actions during a touch down event.
4354     *
4355     * @param event The event.
4356     * @return True if the down was consumed.
4357     *
4358     * @hide
4359     */
4360    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4361        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4362            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4363                return true;
4364            }
4365        }
4366        return false;
4367    }
4368
4369    /**
4370     * Bring up the context menu for this view.
4371     *
4372     * @return Whether a context menu was displayed.
4373     */
4374    public boolean showContextMenu() {
4375        return getParent().showContextMenuForChild(this);
4376    }
4377
4378    /**
4379     * Bring up the context menu for this view, referring to the item under the specified point.
4380     *
4381     * @param x The referenced x coordinate.
4382     * @param y The referenced y coordinate.
4383     * @param metaState The keyboard modifiers that were pressed.
4384     * @return Whether a context menu was displayed.
4385     *
4386     * @hide
4387     */
4388    public boolean showContextMenu(float x, float y, int metaState) {
4389        return showContextMenu();
4390    }
4391
4392    /**
4393     * Start an action mode.
4394     *
4395     * @param callback Callback that will control the lifecycle of the action mode
4396     * @return The new action mode if it is started, null otherwise
4397     *
4398     * @see ActionMode
4399     */
4400    public ActionMode startActionMode(ActionMode.Callback callback) {
4401        ViewParent parent = getParent();
4402        if (parent == null) return null;
4403        return parent.startActionModeForChild(this, callback);
4404    }
4405
4406    /**
4407     * Register a callback to be invoked when a hardware key is pressed in this view.
4408     * Key presses in software input methods will generally not trigger the methods of
4409     * this listener.
4410     * @param l the key listener to attach to this view
4411     */
4412    public void setOnKeyListener(OnKeyListener l) {
4413        getListenerInfo().mOnKeyListener = l;
4414    }
4415
4416    /**
4417     * Register a callback to be invoked when a touch event is sent to this view.
4418     * @param l the touch listener to attach to this view
4419     */
4420    public void setOnTouchListener(OnTouchListener l) {
4421        getListenerInfo().mOnTouchListener = l;
4422    }
4423
4424    /**
4425     * Register a callback to be invoked when a generic motion event is sent to this view.
4426     * @param l the generic motion listener to attach to this view
4427     */
4428    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4429        getListenerInfo().mOnGenericMotionListener = l;
4430    }
4431
4432    /**
4433     * Register a callback to be invoked when a hover event is sent to this view.
4434     * @param l the hover listener to attach to this view
4435     */
4436    public void setOnHoverListener(OnHoverListener l) {
4437        getListenerInfo().mOnHoverListener = l;
4438    }
4439
4440    /**
4441     * Register a drag event listener callback object for this View. The parameter is
4442     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4443     * View, the system calls the
4444     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4445     * @param l An implementation of {@link android.view.View.OnDragListener}.
4446     */
4447    public void setOnDragListener(OnDragListener l) {
4448        getListenerInfo().mOnDragListener = l;
4449    }
4450
4451    /**
4452     * Give this view focus. This will cause
4453     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4454     *
4455     * Note: this does not check whether this {@link View} should get focus, it just
4456     * gives it focus no matter what.  It should only be called internally by framework
4457     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4458     *
4459     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4460     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4461     *        focus moved when requestFocus() is called. It may not always
4462     *        apply, in which case use the default View.FOCUS_DOWN.
4463     * @param previouslyFocusedRect The rectangle of the view that had focus
4464     *        prior in this View's coordinate system.
4465     */
4466    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4467        if (DBG) {
4468            System.out.println(this + " requestFocus()");
4469        }
4470
4471        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4472            mPrivateFlags |= PFLAG_FOCUSED;
4473
4474            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4475
4476            if (mParent != null) {
4477                mParent.requestChildFocus(this, this);
4478            }
4479
4480            if (mAttachInfo != null) {
4481                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4482            }
4483
4484            onFocusChanged(true, direction, previouslyFocusedRect);
4485            refreshDrawableState();
4486        }
4487    }
4488
4489    /**
4490     * Request that a rectangle of this view be visible on the screen,
4491     * scrolling if necessary just enough.
4492     *
4493     * <p>A View should call this if it maintains some notion of which part
4494     * of its content is interesting.  For example, a text editing view
4495     * should call this when its cursor moves.
4496     *
4497     * @param rectangle The rectangle.
4498     * @return Whether any parent scrolled.
4499     */
4500    public boolean requestRectangleOnScreen(Rect rectangle) {
4501        return requestRectangleOnScreen(rectangle, false);
4502    }
4503
4504    /**
4505     * Request that a rectangle of this view be visible on the screen,
4506     * scrolling if necessary just enough.
4507     *
4508     * <p>A View should call this if it maintains some notion of which part
4509     * of its content is interesting.  For example, a text editing view
4510     * should call this when its cursor moves.
4511     *
4512     * <p>When <code>immediate</code> is set to true, scrolling will not be
4513     * animated.
4514     *
4515     * @param rectangle The rectangle.
4516     * @param immediate True to forbid animated scrolling, false otherwise
4517     * @return Whether any parent scrolled.
4518     */
4519    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4520        if (mParent == null) {
4521            return false;
4522        }
4523
4524        View child = this;
4525
4526        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4527        position.set(rectangle);
4528
4529        ViewParent parent = mParent;
4530        boolean scrolled = false;
4531        while (parent != null) {
4532            rectangle.set((int) position.left, (int) position.top,
4533                    (int) position.right, (int) position.bottom);
4534
4535            scrolled |= parent.requestChildRectangleOnScreen(child,
4536                    rectangle, immediate);
4537
4538            if (!child.hasIdentityMatrix()) {
4539                child.getMatrix().mapRect(position);
4540            }
4541
4542            position.offset(child.mLeft, child.mTop);
4543
4544            if (!(parent instanceof View)) {
4545                break;
4546            }
4547
4548            View parentView = (View) parent;
4549
4550            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4551
4552            child = parentView;
4553            parent = child.getParent();
4554        }
4555
4556        return scrolled;
4557    }
4558
4559    /**
4560     * Called when this view wants to give up focus. If focus is cleared
4561     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4562     * <p>
4563     * <strong>Note:</strong> When a View clears focus the framework is trying
4564     * to give focus to the first focusable View from the top. Hence, if this
4565     * View is the first from the top that can take focus, then all callbacks
4566     * related to clearing focus will be invoked after wich the framework will
4567     * give focus to this view.
4568     * </p>
4569     */
4570    public void clearFocus() {
4571        if (DBG) {
4572            System.out.println(this + " clearFocus()");
4573        }
4574
4575        clearFocusInternal(true, true);
4576    }
4577
4578    /**
4579     * Clears focus from the view, optionally propagating the change up through
4580     * the parent hierarchy and requesting that the root view place new focus.
4581     *
4582     * @param propagate whether to propagate the change up through the parent
4583     *            hierarchy
4584     * @param refocus when propagate is true, specifies whether to request the
4585     *            root view place new focus
4586     */
4587    void clearFocusInternal(boolean propagate, boolean refocus) {
4588        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4589            mPrivateFlags &= ~PFLAG_FOCUSED;
4590
4591            if (propagate && mParent != null) {
4592                mParent.clearChildFocus(this);
4593            }
4594
4595            onFocusChanged(false, 0, null);
4596
4597            refreshDrawableState();
4598
4599            if (propagate && (!refocus || !rootViewRequestFocus())) {
4600                notifyGlobalFocusCleared(this);
4601            }
4602        }
4603    }
4604
4605    void notifyGlobalFocusCleared(View oldFocus) {
4606        if (oldFocus != null && mAttachInfo != null) {
4607            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4608        }
4609    }
4610
4611    boolean rootViewRequestFocus() {
4612        final View root = getRootView();
4613        return root != null && root.requestFocus();
4614    }
4615
4616    /**
4617     * Called internally by the view system when a new view is getting focus.
4618     * This is what clears the old focus.
4619     * <p>
4620     * <b>NOTE:</b> The parent view's focused child must be updated manually
4621     * after calling this method. Otherwise, the view hierarchy may be left in
4622     * an inconstent state.
4623     */
4624    void unFocus() {
4625        if (DBG) {
4626            System.out.println(this + " unFocus()");
4627        }
4628
4629        clearFocusInternal(false, false);
4630    }
4631
4632    /**
4633     * Returns true if this view has focus iteself, or is the ancestor of the
4634     * view that has focus.
4635     *
4636     * @return True if this view has or contains focus, false otherwise.
4637     */
4638    @ViewDebug.ExportedProperty(category = "focus")
4639    public boolean hasFocus() {
4640        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4641    }
4642
4643    /**
4644     * Returns true if this view is focusable or if it contains a reachable View
4645     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4646     * is a View whose parents do not block descendants focus.
4647     *
4648     * Only {@link #VISIBLE} views are considered focusable.
4649     *
4650     * @return True if the view is focusable or if the view contains a focusable
4651     *         View, false otherwise.
4652     *
4653     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4654     */
4655    public boolean hasFocusable() {
4656        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4657    }
4658
4659    /**
4660     * Called by the view system when the focus state of this view changes.
4661     * When the focus change event is caused by directional navigation, direction
4662     * and previouslyFocusedRect provide insight into where the focus is coming from.
4663     * When overriding, be sure to call up through to the super class so that
4664     * the standard focus handling will occur.
4665     *
4666     * @param gainFocus True if the View has focus; false otherwise.
4667     * @param direction The direction focus has moved when requestFocus()
4668     *                  is called to give this view focus. Values are
4669     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4670     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4671     *                  It may not always apply, in which case use the default.
4672     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4673     *        system, of the previously focused view.  If applicable, this will be
4674     *        passed in as finer grained information about where the focus is coming
4675     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4676     */
4677    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4678        if (gainFocus) {
4679            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4680        } else {
4681            notifyViewAccessibilityStateChangedIfNeeded();
4682        }
4683
4684        InputMethodManager imm = InputMethodManager.peekInstance();
4685        if (!gainFocus) {
4686            if (isPressed()) {
4687                setPressed(false);
4688            }
4689            if (imm != null && mAttachInfo != null
4690                    && mAttachInfo.mHasWindowFocus) {
4691                imm.focusOut(this);
4692            }
4693            onFocusLost();
4694        } else if (imm != null && mAttachInfo != null
4695                && mAttachInfo.mHasWindowFocus) {
4696            imm.focusIn(this);
4697        }
4698
4699        invalidate(true);
4700        ListenerInfo li = mListenerInfo;
4701        if (li != null && li.mOnFocusChangeListener != null) {
4702            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4703        }
4704
4705        if (mAttachInfo != null) {
4706            mAttachInfo.mKeyDispatchState.reset(this);
4707        }
4708    }
4709
4710    /**
4711     * Sends an accessibility event of the given type. If accessibility is
4712     * not enabled this method has no effect. The default implementation calls
4713     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4714     * to populate information about the event source (this View), then calls
4715     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4716     * populate the text content of the event source including its descendants,
4717     * and last calls
4718     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4719     * on its parent to resuest sending of the event to interested parties.
4720     * <p>
4721     * If an {@link AccessibilityDelegate} has been specified via calling
4722     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4723     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4724     * responsible for handling this call.
4725     * </p>
4726     *
4727     * @param eventType The type of the event to send, as defined by several types from
4728     * {@link android.view.accessibility.AccessibilityEvent}, such as
4729     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4730     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4731     *
4732     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4733     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4734     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4735     * @see AccessibilityDelegate
4736     */
4737    public void sendAccessibilityEvent(int eventType) {
4738        // Excluded views do not send accessibility events.
4739        if (!includeForAccessibility()) {
4740            return;
4741        }
4742        if (mAccessibilityDelegate != null) {
4743            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4744        } else {
4745            sendAccessibilityEventInternal(eventType);
4746        }
4747    }
4748
4749    /**
4750     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4751     * {@link AccessibilityEvent} to make an announcement which is related to some
4752     * sort of a context change for which none of the events representing UI transitions
4753     * is a good fit. For example, announcing a new page in a book. If accessibility
4754     * is not enabled this method does nothing.
4755     *
4756     * @param text The announcement text.
4757     */
4758    public void announceForAccessibility(CharSequence text) {
4759        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4760            AccessibilityEvent event = AccessibilityEvent.obtain(
4761                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4762            onInitializeAccessibilityEvent(event);
4763            event.getText().add(text);
4764            event.setContentDescription(null);
4765            mParent.requestSendAccessibilityEvent(this, event);
4766        }
4767    }
4768
4769    /**
4770     * @see #sendAccessibilityEvent(int)
4771     *
4772     * Note: Called from the default {@link AccessibilityDelegate}.
4773     */
4774    void sendAccessibilityEventInternal(int eventType) {
4775        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4776            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4777        }
4778    }
4779
4780    /**
4781     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4782     * takes as an argument an empty {@link AccessibilityEvent} and does not
4783     * perform a check whether accessibility is enabled.
4784     * <p>
4785     * If an {@link AccessibilityDelegate} has been specified via calling
4786     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4787     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4788     * is responsible for handling this call.
4789     * </p>
4790     *
4791     * @param event The event to send.
4792     *
4793     * @see #sendAccessibilityEvent(int)
4794     */
4795    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4796        if (mAccessibilityDelegate != null) {
4797            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4798        } else {
4799            sendAccessibilityEventUncheckedInternal(event);
4800        }
4801    }
4802
4803    /**
4804     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4805     *
4806     * Note: Called from the default {@link AccessibilityDelegate}.
4807     */
4808    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4809        if (!isShown()) {
4810            return;
4811        }
4812        onInitializeAccessibilityEvent(event);
4813        // Only a subset of accessibility events populates text content.
4814        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4815            dispatchPopulateAccessibilityEvent(event);
4816        }
4817        // In the beginning we called #isShown(), so we know that getParent() is not null.
4818        getParent().requestSendAccessibilityEvent(this, event);
4819    }
4820
4821    /**
4822     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4823     * to its children for adding their text content to the event. Note that the
4824     * event text is populated in a separate dispatch path since we add to the
4825     * event not only the text of the source but also the text of all its descendants.
4826     * A typical implementation will call
4827     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4828     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4829     * on each child. Override this method if custom population of the event text
4830     * content is required.
4831     * <p>
4832     * If an {@link AccessibilityDelegate} has been specified via calling
4833     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4834     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4835     * is responsible for handling this call.
4836     * </p>
4837     * <p>
4838     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4839     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4840     * </p>
4841     *
4842     * @param event The event.
4843     *
4844     * @return True if the event population was completed.
4845     */
4846    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4847        if (mAccessibilityDelegate != null) {
4848            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4849        } else {
4850            return dispatchPopulateAccessibilityEventInternal(event);
4851        }
4852    }
4853
4854    /**
4855     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4856     *
4857     * Note: Called from the default {@link AccessibilityDelegate}.
4858     */
4859    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4860        onPopulateAccessibilityEvent(event);
4861        return false;
4862    }
4863
4864    /**
4865     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4866     * giving a chance to this View to populate the accessibility event with its
4867     * text content. While this method is free to modify event
4868     * attributes other than text content, doing so should normally be performed in
4869     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4870     * <p>
4871     * Example: Adding formatted date string to an accessibility event in addition
4872     *          to the text added by the super implementation:
4873     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4874     *     super.onPopulateAccessibilityEvent(event);
4875     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4876     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4877     *         mCurrentDate.getTimeInMillis(), flags);
4878     *     event.getText().add(selectedDateUtterance);
4879     * }</pre>
4880     * <p>
4881     * If an {@link AccessibilityDelegate} has been specified via calling
4882     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4883     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4884     * is responsible for handling this call.
4885     * </p>
4886     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4887     * information to the event, in case the default implementation has basic information to add.
4888     * </p>
4889     *
4890     * @param event The accessibility event which to populate.
4891     *
4892     * @see #sendAccessibilityEvent(int)
4893     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4894     */
4895    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4896        if (mAccessibilityDelegate != null) {
4897            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4898        } else {
4899            onPopulateAccessibilityEventInternal(event);
4900        }
4901    }
4902
4903    /**
4904     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4905     *
4906     * Note: Called from the default {@link AccessibilityDelegate}.
4907     */
4908    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4909    }
4910
4911    /**
4912     * Initializes an {@link AccessibilityEvent} with information about
4913     * this View which is the event source. In other words, the source of
4914     * an accessibility event is the view whose state change triggered firing
4915     * the event.
4916     * <p>
4917     * Example: Setting the password property of an event in addition
4918     *          to properties set by the super implementation:
4919     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4920     *     super.onInitializeAccessibilityEvent(event);
4921     *     event.setPassword(true);
4922     * }</pre>
4923     * <p>
4924     * If an {@link AccessibilityDelegate} has been specified via calling
4925     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4926     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4927     * is responsible for handling this call.
4928     * </p>
4929     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4930     * information to the event, in case the default implementation has basic information to add.
4931     * </p>
4932     * @param event The event to initialize.
4933     *
4934     * @see #sendAccessibilityEvent(int)
4935     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4936     */
4937    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4938        if (mAccessibilityDelegate != null) {
4939            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4940        } else {
4941            onInitializeAccessibilityEventInternal(event);
4942        }
4943    }
4944
4945    /**
4946     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4947     *
4948     * Note: Called from the default {@link AccessibilityDelegate}.
4949     */
4950    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4951        event.setSource(this);
4952        event.setClassName(View.class.getName());
4953        event.setPackageName(getContext().getPackageName());
4954        event.setEnabled(isEnabled());
4955        event.setContentDescription(mContentDescription);
4956
4957        switch (event.getEventType()) {
4958            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4959                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4960                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4961                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4962                event.setItemCount(focusablesTempList.size());
4963                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4964                if (mAttachInfo != null) {
4965                    focusablesTempList.clear();
4966                }
4967            } break;
4968            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4969                CharSequence text = getIterableTextForAccessibility();
4970                if (text != null && text.length() > 0) {
4971                    event.setFromIndex(getAccessibilitySelectionStart());
4972                    event.setToIndex(getAccessibilitySelectionEnd());
4973                    event.setItemCount(text.length());
4974                }
4975            } break;
4976        }
4977    }
4978
4979    /**
4980     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4981     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4982     * This method is responsible for obtaining an accessibility node info from a
4983     * pool of reusable instances and calling
4984     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4985     * initialize the former.
4986     * <p>
4987     * Note: The client is responsible for recycling the obtained instance by calling
4988     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4989     * </p>
4990     *
4991     * @return A populated {@link AccessibilityNodeInfo}.
4992     *
4993     * @see AccessibilityNodeInfo
4994     */
4995    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4996        if (mAccessibilityDelegate != null) {
4997            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
4998        } else {
4999            return createAccessibilityNodeInfoInternal();
5000        }
5001    }
5002
5003    /**
5004     * @see #createAccessibilityNodeInfo()
5005     */
5006    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5007        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5008        if (provider != null) {
5009            return provider.createAccessibilityNodeInfo(View.NO_ID);
5010        } else {
5011            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5012            onInitializeAccessibilityNodeInfo(info);
5013            return info;
5014        }
5015    }
5016
5017    /**
5018     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5019     * The base implementation sets:
5020     * <ul>
5021     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5022     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5023     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5024     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5025     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5026     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5027     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5028     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5029     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5030     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5031     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5032     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5033     * </ul>
5034     * <p>
5035     * Subclasses should override this method, call the super implementation,
5036     * and set additional attributes.
5037     * </p>
5038     * <p>
5039     * If an {@link AccessibilityDelegate} has been specified via calling
5040     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5041     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5042     * is responsible for handling this call.
5043     * </p>
5044     *
5045     * @param info The instance to initialize.
5046     */
5047    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5048        if (mAccessibilityDelegate != null) {
5049            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5050        } else {
5051            onInitializeAccessibilityNodeInfoInternal(info);
5052        }
5053    }
5054
5055    /**
5056     * Gets the location of this view in screen coordintates.
5057     *
5058     * @param outRect The output location
5059     */
5060    void getBoundsOnScreen(Rect outRect) {
5061        if (mAttachInfo == null) {
5062            return;
5063        }
5064
5065        RectF position = mAttachInfo.mTmpTransformRect;
5066        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5067
5068        if (!hasIdentityMatrix()) {
5069            getMatrix().mapRect(position);
5070        }
5071
5072        position.offset(mLeft, mTop);
5073
5074        ViewParent parent = mParent;
5075        while (parent instanceof View) {
5076            View parentView = (View) parent;
5077
5078            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5079
5080            if (!parentView.hasIdentityMatrix()) {
5081                parentView.getMatrix().mapRect(position);
5082            }
5083
5084            position.offset(parentView.mLeft, parentView.mTop);
5085
5086            parent = parentView.mParent;
5087        }
5088
5089        if (parent instanceof ViewRootImpl) {
5090            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5091            position.offset(0, -viewRootImpl.mCurScrollY);
5092        }
5093
5094        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5095
5096        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5097                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5098    }
5099
5100    /**
5101     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5102     *
5103     * Note: Called from the default {@link AccessibilityDelegate}.
5104     */
5105    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5106        Rect bounds = mAttachInfo.mTmpInvalRect;
5107
5108        getDrawingRect(bounds);
5109        info.setBoundsInParent(bounds);
5110
5111        getBoundsOnScreen(bounds);
5112        info.setBoundsInScreen(bounds);
5113
5114        ViewParent parent = getParentForAccessibility();
5115        if (parent instanceof View) {
5116            info.setParent((View) parent);
5117        }
5118
5119        if (mID != View.NO_ID) {
5120            View rootView = getRootView();
5121            if (rootView == null) {
5122                rootView = this;
5123            }
5124            View label = rootView.findLabelForView(this, mID);
5125            if (label != null) {
5126                info.setLabeledBy(label);
5127            }
5128
5129            if ((mAttachInfo.mAccessibilityFetchFlags
5130                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5131                    && Resources.resourceHasPackage(mID)) {
5132                try {
5133                    String viewId = getResources().getResourceName(mID);
5134                    info.setViewIdResourceName(viewId);
5135                } catch (Resources.NotFoundException nfe) {
5136                    /* ignore */
5137                }
5138            }
5139        }
5140
5141        if (mLabelForId != View.NO_ID) {
5142            View rootView = getRootView();
5143            if (rootView == null) {
5144                rootView = this;
5145            }
5146            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5147            if (labeled != null) {
5148                info.setLabelFor(labeled);
5149            }
5150        }
5151
5152        info.setVisibleToUser(isVisibleToUser());
5153
5154        info.setPackageName(mContext.getPackageName());
5155        info.setClassName(View.class.getName());
5156        info.setContentDescription(getContentDescription());
5157
5158        info.setEnabled(isEnabled());
5159        info.setClickable(isClickable());
5160        info.setFocusable(isFocusable());
5161        info.setFocused(isFocused());
5162        info.setAccessibilityFocused(isAccessibilityFocused());
5163        info.setSelected(isSelected());
5164        info.setLongClickable(isLongClickable());
5165
5166        // TODO: These make sense only if we are in an AdapterView but all
5167        // views can be selected. Maybe from accessibility perspective
5168        // we should report as selectable view in an AdapterView.
5169        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5170        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5171
5172        if (isFocusable()) {
5173            if (isFocused()) {
5174                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5175            } else {
5176                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5177            }
5178        }
5179
5180        if (!isAccessibilityFocused()) {
5181            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5182        } else {
5183            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5184        }
5185
5186        if (isClickable() && isEnabled()) {
5187            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5188        }
5189
5190        if (isLongClickable() && isEnabled()) {
5191            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5192        }
5193
5194        CharSequence text = getIterableTextForAccessibility();
5195        if (text != null && text.length() > 0) {
5196            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5197
5198            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5199            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5200            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5201            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5202                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5203                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5204        }
5205    }
5206
5207    private View findLabelForView(View view, int labeledId) {
5208        if (mMatchLabelForPredicate == null) {
5209            mMatchLabelForPredicate = new MatchLabelForPredicate();
5210        }
5211        mMatchLabelForPredicate.mLabeledId = labeledId;
5212        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5213    }
5214
5215    /**
5216     * Computes whether this view is visible to the user. Such a view is
5217     * attached, visible, all its predecessors are visible, it is not clipped
5218     * entirely by its predecessors, and has an alpha greater than zero.
5219     *
5220     * @return Whether the view is visible on the screen.
5221     *
5222     * @hide
5223     */
5224    protected boolean isVisibleToUser() {
5225        return isVisibleToUser(null);
5226    }
5227
5228    /**
5229     * Computes whether the given portion of this view is visible to the user.
5230     * Such a view is attached, visible, all its predecessors are visible,
5231     * has an alpha greater than zero, and the specified portion is not
5232     * clipped entirely by its predecessors.
5233     *
5234     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5235     *                    <code>null</code>, and the entire view will be tested in this case.
5236     *                    When <code>true</code> is returned by the function, the actual visible
5237     *                    region will be stored in this parameter; that is, if boundInView is fully
5238     *                    contained within the view, no modification will be made, otherwise regions
5239     *                    outside of the visible area of the view will be clipped.
5240     *
5241     * @return Whether the specified portion of the view is visible on the screen.
5242     *
5243     * @hide
5244     */
5245    protected boolean isVisibleToUser(Rect boundInView) {
5246        if (mAttachInfo != null) {
5247            // Attached to invisible window means this view is not visible.
5248            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5249                return false;
5250            }
5251            // An invisible predecessor or one with alpha zero means
5252            // that this view is not visible to the user.
5253            Object current = this;
5254            while (current instanceof View) {
5255                View view = (View) current;
5256                // We have attach info so this view is attached and there is no
5257                // need to check whether we reach to ViewRootImpl on the way up.
5258                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5259                    return false;
5260                }
5261                current = view.mParent;
5262            }
5263            // Check if the view is entirely covered by its predecessors.
5264            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5265            Point offset = mAttachInfo.mPoint;
5266            if (!getGlobalVisibleRect(visibleRect, offset)) {
5267                return false;
5268            }
5269            // Check if the visible portion intersects the rectangle of interest.
5270            if (boundInView != null) {
5271                visibleRect.offset(-offset.x, -offset.y);
5272                return boundInView.intersect(visibleRect);
5273            }
5274            return true;
5275        }
5276        return false;
5277    }
5278
5279    /**
5280     * Returns the delegate for implementing accessibility support via
5281     * composition. For more details see {@link AccessibilityDelegate}.
5282     *
5283     * @return The delegate, or null if none set.
5284     *
5285     * @hide
5286     */
5287    public AccessibilityDelegate getAccessibilityDelegate() {
5288        return mAccessibilityDelegate;
5289    }
5290
5291    /**
5292     * Sets a delegate for implementing accessibility support via composition as
5293     * opposed to inheritance. The delegate's primary use is for implementing
5294     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5295     *
5296     * @param delegate The delegate instance.
5297     *
5298     * @see AccessibilityDelegate
5299     */
5300    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5301        mAccessibilityDelegate = delegate;
5302    }
5303
5304    /**
5305     * Gets the provider for managing a virtual view hierarchy rooted at this View
5306     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5307     * that explore the window content.
5308     * <p>
5309     * If this method returns an instance, this instance is responsible for managing
5310     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5311     * View including the one representing the View itself. Similarly the returned
5312     * instance is responsible for performing accessibility actions on any virtual
5313     * view or the root view itself.
5314     * </p>
5315     * <p>
5316     * If an {@link AccessibilityDelegate} has been specified via calling
5317     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5318     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5319     * is responsible for handling this call.
5320     * </p>
5321     *
5322     * @return The provider.
5323     *
5324     * @see AccessibilityNodeProvider
5325     */
5326    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5327        if (mAccessibilityDelegate != null) {
5328            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5329        } else {
5330            return null;
5331        }
5332    }
5333
5334    /**
5335     * Gets the unique identifier of this view on the screen for accessibility purposes.
5336     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5337     *
5338     * @return The view accessibility id.
5339     *
5340     * @hide
5341     */
5342    public int getAccessibilityViewId() {
5343        if (mAccessibilityViewId == NO_ID) {
5344            mAccessibilityViewId = sNextAccessibilityViewId++;
5345        }
5346        return mAccessibilityViewId;
5347    }
5348
5349    /**
5350     * Gets the unique identifier of the window in which this View reseides.
5351     *
5352     * @return The window accessibility id.
5353     *
5354     * @hide
5355     */
5356    public int getAccessibilityWindowId() {
5357        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5358    }
5359
5360    /**
5361     * Gets the {@link View} description. It briefly describes the view and is
5362     * primarily used for accessibility support. Set this property to enable
5363     * better accessibility support for your application. This is especially
5364     * true for views that do not have textual representation (For example,
5365     * ImageButton).
5366     *
5367     * @return The content description.
5368     *
5369     * @attr ref android.R.styleable#View_contentDescription
5370     */
5371    @ViewDebug.ExportedProperty(category = "accessibility")
5372    public CharSequence getContentDescription() {
5373        return mContentDescription;
5374    }
5375
5376    /**
5377     * Sets the {@link View} description. It briefly describes the view and is
5378     * primarily used for accessibility support. Set this property to enable
5379     * better accessibility support for your application. This is especially
5380     * true for views that do not have textual representation (For example,
5381     * ImageButton).
5382     *
5383     * @param contentDescription The content description.
5384     *
5385     * @attr ref android.R.styleable#View_contentDescription
5386     */
5387    @RemotableViewMethod
5388    public void setContentDescription(CharSequence contentDescription) {
5389        if (mContentDescription == null) {
5390            if (contentDescription == null) {
5391                return;
5392            }
5393        } else if (mContentDescription.equals(contentDescription)) {
5394            return;
5395        }
5396        mContentDescription = contentDescription;
5397        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5398        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5399            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5400            notifySubtreeAccessibilityStateChangedIfNeeded();
5401        } else {
5402            notifyViewAccessibilityStateChangedIfNeeded();
5403        }
5404    }
5405
5406    /**
5407     * Gets the id of a view for which this view serves as a label for
5408     * accessibility purposes.
5409     *
5410     * @return The labeled view id.
5411     */
5412    @ViewDebug.ExportedProperty(category = "accessibility")
5413    public int getLabelFor() {
5414        return mLabelForId;
5415    }
5416
5417    /**
5418     * Sets the id of a view for which this view serves as a label for
5419     * accessibility purposes.
5420     *
5421     * @param id The labeled view id.
5422     */
5423    @RemotableViewMethod
5424    public void setLabelFor(int id) {
5425        mLabelForId = id;
5426        if (mLabelForId != View.NO_ID
5427                && mID == View.NO_ID) {
5428            mID = generateViewId();
5429        }
5430    }
5431
5432    /**
5433     * Invoked whenever this view loses focus, either by losing window focus or by losing
5434     * focus within its window. This method can be used to clear any state tied to the
5435     * focus. For instance, if a button is held pressed with the trackball and the window
5436     * loses focus, this method can be used to cancel the press.
5437     *
5438     * Subclasses of View overriding this method should always call super.onFocusLost().
5439     *
5440     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5441     * @see #onWindowFocusChanged(boolean)
5442     *
5443     * @hide pending API council approval
5444     */
5445    protected void onFocusLost() {
5446        resetPressedState();
5447    }
5448
5449    private void resetPressedState() {
5450        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5451            return;
5452        }
5453
5454        if (isPressed()) {
5455            setPressed(false);
5456
5457            if (!mHasPerformedLongPress) {
5458                removeLongPressCallback();
5459            }
5460        }
5461    }
5462
5463    /**
5464     * Returns true if this view has focus
5465     *
5466     * @return True if this view has focus, false otherwise.
5467     */
5468    @ViewDebug.ExportedProperty(category = "focus")
5469    public boolean isFocused() {
5470        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5471    }
5472
5473    /**
5474     * Find the view in the hierarchy rooted at this view that currently has
5475     * focus.
5476     *
5477     * @return The view that currently has focus, or null if no focused view can
5478     *         be found.
5479     */
5480    public View findFocus() {
5481        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5482    }
5483
5484    /**
5485     * Indicates whether this view is one of the set of scrollable containers in
5486     * its window.
5487     *
5488     * @return whether this view is one of the set of scrollable containers in
5489     * its window
5490     *
5491     * @attr ref android.R.styleable#View_isScrollContainer
5492     */
5493    public boolean isScrollContainer() {
5494        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5495    }
5496
5497    /**
5498     * Change whether this view is one of the set of scrollable containers in
5499     * its window.  This will be used to determine whether the window can
5500     * resize or must pan when a soft input area is open -- scrollable
5501     * containers allow the window to use resize mode since the container
5502     * will appropriately shrink.
5503     *
5504     * @attr ref android.R.styleable#View_isScrollContainer
5505     */
5506    public void setScrollContainer(boolean isScrollContainer) {
5507        if (isScrollContainer) {
5508            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5509                mAttachInfo.mScrollContainers.add(this);
5510                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5511            }
5512            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5513        } else {
5514            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5515                mAttachInfo.mScrollContainers.remove(this);
5516            }
5517            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5518        }
5519    }
5520
5521    /**
5522     * Returns the quality of the drawing cache.
5523     *
5524     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5525     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5526     *
5527     * @see #setDrawingCacheQuality(int)
5528     * @see #setDrawingCacheEnabled(boolean)
5529     * @see #isDrawingCacheEnabled()
5530     *
5531     * @attr ref android.R.styleable#View_drawingCacheQuality
5532     */
5533    public int getDrawingCacheQuality() {
5534        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5535    }
5536
5537    /**
5538     * Set the drawing cache quality of this view. This value is used only when the
5539     * drawing cache is enabled
5540     *
5541     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5542     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5543     *
5544     * @see #getDrawingCacheQuality()
5545     * @see #setDrawingCacheEnabled(boolean)
5546     * @see #isDrawingCacheEnabled()
5547     *
5548     * @attr ref android.R.styleable#View_drawingCacheQuality
5549     */
5550    public void setDrawingCacheQuality(int quality) {
5551        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5552    }
5553
5554    /**
5555     * Returns whether the screen should remain on, corresponding to the current
5556     * value of {@link #KEEP_SCREEN_ON}.
5557     *
5558     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5559     *
5560     * @see #setKeepScreenOn(boolean)
5561     *
5562     * @attr ref android.R.styleable#View_keepScreenOn
5563     */
5564    public boolean getKeepScreenOn() {
5565        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5566    }
5567
5568    /**
5569     * Controls whether the screen should remain on, modifying the
5570     * value of {@link #KEEP_SCREEN_ON}.
5571     *
5572     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5573     *
5574     * @see #getKeepScreenOn()
5575     *
5576     * @attr ref android.R.styleable#View_keepScreenOn
5577     */
5578    public void setKeepScreenOn(boolean keepScreenOn) {
5579        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5580    }
5581
5582    /**
5583     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5584     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5585     *
5586     * @attr ref android.R.styleable#View_nextFocusLeft
5587     */
5588    public int getNextFocusLeftId() {
5589        return mNextFocusLeftId;
5590    }
5591
5592    /**
5593     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5594     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5595     * decide automatically.
5596     *
5597     * @attr ref android.R.styleable#View_nextFocusLeft
5598     */
5599    public void setNextFocusLeftId(int nextFocusLeftId) {
5600        mNextFocusLeftId = nextFocusLeftId;
5601    }
5602
5603    /**
5604     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5605     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5606     *
5607     * @attr ref android.R.styleable#View_nextFocusRight
5608     */
5609    public int getNextFocusRightId() {
5610        return mNextFocusRightId;
5611    }
5612
5613    /**
5614     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5615     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5616     * decide automatically.
5617     *
5618     * @attr ref android.R.styleable#View_nextFocusRight
5619     */
5620    public void setNextFocusRightId(int nextFocusRightId) {
5621        mNextFocusRightId = nextFocusRightId;
5622    }
5623
5624    /**
5625     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5626     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5627     *
5628     * @attr ref android.R.styleable#View_nextFocusUp
5629     */
5630    public int getNextFocusUpId() {
5631        return mNextFocusUpId;
5632    }
5633
5634    /**
5635     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5636     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5637     * decide automatically.
5638     *
5639     * @attr ref android.R.styleable#View_nextFocusUp
5640     */
5641    public void setNextFocusUpId(int nextFocusUpId) {
5642        mNextFocusUpId = nextFocusUpId;
5643    }
5644
5645    /**
5646     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5647     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5648     *
5649     * @attr ref android.R.styleable#View_nextFocusDown
5650     */
5651    public int getNextFocusDownId() {
5652        return mNextFocusDownId;
5653    }
5654
5655    /**
5656     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5657     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5658     * decide automatically.
5659     *
5660     * @attr ref android.R.styleable#View_nextFocusDown
5661     */
5662    public void setNextFocusDownId(int nextFocusDownId) {
5663        mNextFocusDownId = nextFocusDownId;
5664    }
5665
5666    /**
5667     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5668     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5669     *
5670     * @attr ref android.R.styleable#View_nextFocusForward
5671     */
5672    public int getNextFocusForwardId() {
5673        return mNextFocusForwardId;
5674    }
5675
5676    /**
5677     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5678     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5679     * decide automatically.
5680     *
5681     * @attr ref android.R.styleable#View_nextFocusForward
5682     */
5683    public void setNextFocusForwardId(int nextFocusForwardId) {
5684        mNextFocusForwardId = nextFocusForwardId;
5685    }
5686
5687    /**
5688     * Returns the visibility of this view and all of its ancestors
5689     *
5690     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5691     */
5692    public boolean isShown() {
5693        View current = this;
5694        //noinspection ConstantConditions
5695        do {
5696            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5697                return false;
5698            }
5699            ViewParent parent = current.mParent;
5700            if (parent == null) {
5701                return false; // We are not attached to the view root
5702            }
5703            if (!(parent instanceof View)) {
5704                return true;
5705            }
5706            current = (View) parent;
5707        } while (current != null);
5708
5709        return false;
5710    }
5711
5712    /**
5713     * Called by the view hierarchy when the content insets for a window have
5714     * changed, to allow it to adjust its content to fit within those windows.
5715     * The content insets tell you the space that the status bar, input method,
5716     * and other system windows infringe on the application's window.
5717     *
5718     * <p>You do not normally need to deal with this function, since the default
5719     * window decoration given to applications takes care of applying it to the
5720     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5721     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5722     * and your content can be placed under those system elements.  You can then
5723     * use this method within your view hierarchy if you have parts of your UI
5724     * which you would like to ensure are not being covered.
5725     *
5726     * <p>The default implementation of this method simply applies the content
5727     * insets to the view's padding, consuming that content (modifying the
5728     * insets to be 0), and returning true.  This behavior is off by default, but can
5729     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5730     *
5731     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5732     * insets object is propagated down the hierarchy, so any changes made to it will
5733     * be seen by all following views (including potentially ones above in
5734     * the hierarchy since this is a depth-first traversal).  The first view
5735     * that returns true will abort the entire traversal.
5736     *
5737     * <p>The default implementation works well for a situation where it is
5738     * used with a container that covers the entire window, allowing it to
5739     * apply the appropriate insets to its content on all edges.  If you need
5740     * a more complicated layout (such as two different views fitting system
5741     * windows, one on the top of the window, and one on the bottom),
5742     * you can override the method and handle the insets however you would like.
5743     * Note that the insets provided by the framework are always relative to the
5744     * far edges of the window, not accounting for the location of the called view
5745     * within that window.  (In fact when this method is called you do not yet know
5746     * where the layout will place the view, as it is done before layout happens.)
5747     *
5748     * <p>Note: unlike many View methods, there is no dispatch phase to this
5749     * call.  If you are overriding it in a ViewGroup and want to allow the
5750     * call to continue to your children, you must be sure to call the super
5751     * implementation.
5752     *
5753     * <p>Here is a sample layout that makes use of fitting system windows
5754     * to have controls for a video view placed inside of the window decorations
5755     * that it hides and shows.  This can be used with code like the second
5756     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5757     *
5758     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5759     *
5760     * @param insets Current content insets of the window.  Prior to
5761     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5762     * the insets or else you and Android will be unhappy.
5763     *
5764     * @return {@code true} if this view applied the insets and it should not
5765     * continue propagating further down the hierarchy, {@code false} otherwise.
5766     * @see #getFitsSystemWindows()
5767     * @see #setFitsSystemWindows(boolean)
5768     * @see #setSystemUiVisibility(int)
5769     */
5770    protected boolean fitSystemWindows(Rect insets) {
5771        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5772            mUserPaddingStart = UNDEFINED_PADDING;
5773            mUserPaddingEnd = UNDEFINED_PADDING;
5774            Rect localInsets = sThreadLocal.get();
5775            if (localInsets == null) {
5776                localInsets = new Rect();
5777                sThreadLocal.set(localInsets);
5778            }
5779            boolean res = computeFitSystemWindows(insets, localInsets);
5780            internalSetPadding(localInsets.left, localInsets.top,
5781                    localInsets.right, localInsets.bottom);
5782            return res;
5783        }
5784        return false;
5785    }
5786
5787    /**
5788     * @hide Compute the insets that should be consumed by this view and the ones
5789     * that should propagate to those under it.
5790     */
5791    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5792        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5793                || mAttachInfo == null
5794                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5795                        && !mAttachInfo.mOverscanRequested)) {
5796            outLocalInsets.set(inoutInsets);
5797            inoutInsets.set(0, 0, 0, 0);
5798            return true;
5799        } else {
5800            // The application wants to take care of fitting system window for
5801            // the content...  however we still need to take care of any overscan here.
5802            final Rect overscan = mAttachInfo.mOverscanInsets;
5803            outLocalInsets.set(overscan);
5804            inoutInsets.left -= overscan.left;
5805            inoutInsets.top -= overscan.top;
5806            inoutInsets.right -= overscan.right;
5807            inoutInsets.bottom -= overscan.bottom;
5808            return false;
5809        }
5810    }
5811
5812    /**
5813     * Sets whether or not this view should account for system screen decorations
5814     * such as the status bar and inset its content; that is, controlling whether
5815     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5816     * executed.  See that method for more details.
5817     *
5818     * <p>Note that if you are providing your own implementation of
5819     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5820     * flag to true -- your implementation will be overriding the default
5821     * implementation that checks this flag.
5822     *
5823     * @param fitSystemWindows If true, then the default implementation of
5824     * {@link #fitSystemWindows(Rect)} will be executed.
5825     *
5826     * @attr ref android.R.styleable#View_fitsSystemWindows
5827     * @see #getFitsSystemWindows()
5828     * @see #fitSystemWindows(Rect)
5829     * @see #setSystemUiVisibility(int)
5830     */
5831    public void setFitsSystemWindows(boolean fitSystemWindows) {
5832        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5833    }
5834
5835    /**
5836     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
5837     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
5838     * will be executed.
5839     *
5840     * @return {@code true} if the default implementation of
5841     * {@link #fitSystemWindows(Rect)} will be executed.
5842     *
5843     * @attr ref android.R.styleable#View_fitsSystemWindows
5844     * @see #setFitsSystemWindows(boolean)
5845     * @see #fitSystemWindows(Rect)
5846     * @see #setSystemUiVisibility(int)
5847     */
5848    public boolean getFitsSystemWindows() {
5849        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5850    }
5851
5852    /** @hide */
5853    public boolean fitsSystemWindows() {
5854        return getFitsSystemWindows();
5855    }
5856
5857    /**
5858     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5859     */
5860    public void requestFitSystemWindows() {
5861        if (mParent != null) {
5862            mParent.requestFitSystemWindows();
5863        }
5864    }
5865
5866    /**
5867     * For use by PhoneWindow to make its own system window fitting optional.
5868     * @hide
5869     */
5870    public void makeOptionalFitsSystemWindows() {
5871        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5872    }
5873
5874    /**
5875     * Returns the visibility status for this view.
5876     *
5877     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5878     * @attr ref android.R.styleable#View_visibility
5879     */
5880    @ViewDebug.ExportedProperty(mapping = {
5881        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5882        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5883        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5884    })
5885    public int getVisibility() {
5886        return mViewFlags & VISIBILITY_MASK;
5887    }
5888
5889    /**
5890     * Set the enabled state of this view.
5891     *
5892     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5893     * @attr ref android.R.styleable#View_visibility
5894     */
5895    @RemotableViewMethod
5896    public void setVisibility(int visibility) {
5897        setFlags(visibility, VISIBILITY_MASK);
5898        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5899    }
5900
5901    /**
5902     * Returns the enabled status for this view. The interpretation of the
5903     * enabled state varies by subclass.
5904     *
5905     * @return True if this view is enabled, false otherwise.
5906     */
5907    @ViewDebug.ExportedProperty
5908    public boolean isEnabled() {
5909        return (mViewFlags & ENABLED_MASK) == ENABLED;
5910    }
5911
5912    /**
5913     * Set the enabled state of this view. The interpretation of the enabled
5914     * state varies by subclass.
5915     *
5916     * @param enabled True if this view is enabled, false otherwise.
5917     */
5918    @RemotableViewMethod
5919    public void setEnabled(boolean enabled) {
5920        if (enabled == isEnabled()) return;
5921
5922        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5923
5924        /*
5925         * The View most likely has to change its appearance, so refresh
5926         * the drawable state.
5927         */
5928        refreshDrawableState();
5929
5930        // Invalidate too, since the default behavior for views is to be
5931        // be drawn at 50% alpha rather than to change the drawable.
5932        invalidate(true);
5933    }
5934
5935    /**
5936     * Set whether this view can receive the focus.
5937     *
5938     * Setting this to false will also ensure that this view is not focusable
5939     * in touch mode.
5940     *
5941     * @param focusable If true, this view can receive the focus.
5942     *
5943     * @see #setFocusableInTouchMode(boolean)
5944     * @attr ref android.R.styleable#View_focusable
5945     */
5946    public void setFocusable(boolean focusable) {
5947        if (!focusable) {
5948            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5949        }
5950        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5951    }
5952
5953    /**
5954     * Set whether this view can receive focus while in touch mode.
5955     *
5956     * Setting this to true will also ensure that this view is focusable.
5957     *
5958     * @param focusableInTouchMode If true, this view can receive the focus while
5959     *   in touch mode.
5960     *
5961     * @see #setFocusable(boolean)
5962     * @attr ref android.R.styleable#View_focusableInTouchMode
5963     */
5964    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5965        // Focusable in touch mode should always be set before the focusable flag
5966        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5967        // which, in touch mode, will not successfully request focus on this view
5968        // because the focusable in touch mode flag is not set
5969        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5970        if (focusableInTouchMode) {
5971            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5972        }
5973    }
5974
5975    /**
5976     * Set whether this view should have sound effects enabled for events such as
5977     * clicking and touching.
5978     *
5979     * <p>You may wish to disable sound effects for a view if you already play sounds,
5980     * for instance, a dial key that plays dtmf tones.
5981     *
5982     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5983     * @see #isSoundEffectsEnabled()
5984     * @see #playSoundEffect(int)
5985     * @attr ref android.R.styleable#View_soundEffectsEnabled
5986     */
5987    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5988        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5989    }
5990
5991    /**
5992     * @return whether this view should have sound effects enabled for events such as
5993     *     clicking and touching.
5994     *
5995     * @see #setSoundEffectsEnabled(boolean)
5996     * @see #playSoundEffect(int)
5997     * @attr ref android.R.styleable#View_soundEffectsEnabled
5998     */
5999    @ViewDebug.ExportedProperty
6000    public boolean isSoundEffectsEnabled() {
6001        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6002    }
6003
6004    /**
6005     * Set whether this view should have haptic feedback for events such as
6006     * long presses.
6007     *
6008     * <p>You may wish to disable haptic feedback if your view already controls
6009     * its own haptic feedback.
6010     *
6011     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6012     * @see #isHapticFeedbackEnabled()
6013     * @see #performHapticFeedback(int)
6014     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6015     */
6016    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6017        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6018    }
6019
6020    /**
6021     * @return whether this view should have haptic feedback enabled for events
6022     * long presses.
6023     *
6024     * @see #setHapticFeedbackEnabled(boolean)
6025     * @see #performHapticFeedback(int)
6026     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6027     */
6028    @ViewDebug.ExportedProperty
6029    public boolean isHapticFeedbackEnabled() {
6030        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6031    }
6032
6033    /**
6034     * Returns the layout direction for this view.
6035     *
6036     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6037     *   {@link #LAYOUT_DIRECTION_RTL},
6038     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6039     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6040     *
6041     * @attr ref android.R.styleable#View_layoutDirection
6042     *
6043     * @hide
6044     */
6045    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6046        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6047        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6048        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6049        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6050    })
6051    public int getRawLayoutDirection() {
6052        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6053    }
6054
6055    /**
6056     * Set the layout direction for this view. This will propagate a reset of layout direction
6057     * resolution to the view's children and resolve layout direction for this view.
6058     *
6059     * @param layoutDirection the layout direction to set. Should be one of:
6060     *
6061     * {@link #LAYOUT_DIRECTION_LTR},
6062     * {@link #LAYOUT_DIRECTION_RTL},
6063     * {@link #LAYOUT_DIRECTION_INHERIT},
6064     * {@link #LAYOUT_DIRECTION_LOCALE}.
6065     *
6066     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6067     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6068     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6069     *
6070     * @attr ref android.R.styleable#View_layoutDirection
6071     */
6072    @RemotableViewMethod
6073    public void setLayoutDirection(int layoutDirection) {
6074        if (getRawLayoutDirection() != layoutDirection) {
6075            // Reset the current layout direction and the resolved one
6076            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6077            resetRtlProperties();
6078            // Set the new layout direction (filtered)
6079            mPrivateFlags2 |=
6080                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6081            // We need to resolve all RTL properties as they all depend on layout direction
6082            resolveRtlPropertiesIfNeeded();
6083            requestLayout();
6084            invalidate(true);
6085        }
6086    }
6087
6088    /**
6089     * Returns the resolved layout direction for this view.
6090     *
6091     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6092     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6093     *
6094     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6095     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6096     *
6097     * @attr ref android.R.styleable#View_layoutDirection
6098     */
6099    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6100        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6101        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6102    })
6103    public int getLayoutDirection() {
6104        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6105        if (targetSdkVersion < JELLY_BEAN_MR1) {
6106            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6107            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6108        }
6109        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6110                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6111    }
6112
6113    /**
6114     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6115     * layout attribute and/or the inherited value from the parent
6116     *
6117     * @return true if the layout is right-to-left.
6118     *
6119     * @hide
6120     */
6121    @ViewDebug.ExportedProperty(category = "layout")
6122    public boolean isLayoutRtl() {
6123        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6124    }
6125
6126    /**
6127     * Indicates whether the view is currently tracking transient state that the
6128     * app should not need to concern itself with saving and restoring, but that
6129     * the framework should take special note to preserve when possible.
6130     *
6131     * <p>A view with transient state cannot be trivially rebound from an external
6132     * data source, such as an adapter binding item views in a list. This may be
6133     * because the view is performing an animation, tracking user selection
6134     * of content, or similar.</p>
6135     *
6136     * @return true if the view has transient state
6137     */
6138    @ViewDebug.ExportedProperty(category = "layout")
6139    public boolean hasTransientState() {
6140        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6141    }
6142
6143    /**
6144     * Set whether this view is currently tracking transient state that the
6145     * framework should attempt to preserve when possible. This flag is reference counted,
6146     * so every call to setHasTransientState(true) should be paired with a later call
6147     * to setHasTransientState(false).
6148     *
6149     * <p>A view with transient state cannot be trivially rebound from an external
6150     * data source, such as an adapter binding item views in a list. This may be
6151     * because the view is performing an animation, tracking user selection
6152     * of content, or similar.</p>
6153     *
6154     * @param hasTransientState true if this view has transient state
6155     */
6156    public void setHasTransientState(boolean hasTransientState) {
6157        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6158                mTransientStateCount - 1;
6159        if (mTransientStateCount < 0) {
6160            mTransientStateCount = 0;
6161            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6162                    "unmatched pair of setHasTransientState calls");
6163        } else if ((hasTransientState && mTransientStateCount == 1) ||
6164                (!hasTransientState && mTransientStateCount == 0)) {
6165            // update flag if we've just incremented up from 0 or decremented down to 0
6166            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6167                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6168            if (mParent != null) {
6169                try {
6170                    mParent.childHasTransientStateChanged(this, hasTransientState);
6171                } catch (AbstractMethodError e) {
6172                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6173                            " does not fully implement ViewParent", e);
6174                }
6175            }
6176        }
6177    }
6178
6179    /**
6180     * Returns true if this view is currently attached to a window.
6181     */
6182    public boolean isAttachedToWindow() {
6183        return mAttachInfo != null;
6184    }
6185
6186    /**
6187     * Returns true if this view has been through at least one layout since it
6188     * was last attached to or detached from a window.
6189     */
6190    public boolean isLaidOut() {
6191        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6192    }
6193
6194    /**
6195     * If this view doesn't do any drawing on its own, set this flag to
6196     * allow further optimizations. By default, this flag is not set on
6197     * View, but could be set on some View subclasses such as ViewGroup.
6198     *
6199     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6200     * you should clear this flag.
6201     *
6202     * @param willNotDraw whether or not this View draw on its own
6203     */
6204    public void setWillNotDraw(boolean willNotDraw) {
6205        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6206    }
6207
6208    /**
6209     * Returns whether or not this View draws on its own.
6210     *
6211     * @return true if this view has nothing to draw, false otherwise
6212     */
6213    @ViewDebug.ExportedProperty(category = "drawing")
6214    public boolean willNotDraw() {
6215        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6216    }
6217
6218    /**
6219     * When a View's drawing cache is enabled, drawing is redirected to an
6220     * offscreen bitmap. Some views, like an ImageView, must be able to
6221     * bypass this mechanism if they already draw a single bitmap, to avoid
6222     * unnecessary usage of the memory.
6223     *
6224     * @param willNotCacheDrawing true if this view does not cache its
6225     *        drawing, false otherwise
6226     */
6227    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6228        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6229    }
6230
6231    /**
6232     * Returns whether or not this View can cache its drawing or not.
6233     *
6234     * @return true if this view does not cache its drawing, false otherwise
6235     */
6236    @ViewDebug.ExportedProperty(category = "drawing")
6237    public boolean willNotCacheDrawing() {
6238        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6239    }
6240
6241    /**
6242     * Indicates whether this view reacts to click events or not.
6243     *
6244     * @return true if the view is clickable, false otherwise
6245     *
6246     * @see #setClickable(boolean)
6247     * @attr ref android.R.styleable#View_clickable
6248     */
6249    @ViewDebug.ExportedProperty
6250    public boolean isClickable() {
6251        return (mViewFlags & CLICKABLE) == CLICKABLE;
6252    }
6253
6254    /**
6255     * Enables or disables click events for this view. When a view
6256     * is clickable it will change its state to "pressed" on every click.
6257     * Subclasses should set the view clickable to visually react to
6258     * user's clicks.
6259     *
6260     * @param clickable true to make the view clickable, false otherwise
6261     *
6262     * @see #isClickable()
6263     * @attr ref android.R.styleable#View_clickable
6264     */
6265    public void setClickable(boolean clickable) {
6266        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6267    }
6268
6269    /**
6270     * Indicates whether this view reacts to long click events or not.
6271     *
6272     * @return true if the view is long clickable, false otherwise
6273     *
6274     * @see #setLongClickable(boolean)
6275     * @attr ref android.R.styleable#View_longClickable
6276     */
6277    public boolean isLongClickable() {
6278        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6279    }
6280
6281    /**
6282     * Enables or disables long click events for this view. When a view is long
6283     * clickable it reacts to the user holding down the button for a longer
6284     * duration than a tap. This event can either launch the listener or a
6285     * context menu.
6286     *
6287     * @param longClickable true to make the view long clickable, false otherwise
6288     * @see #isLongClickable()
6289     * @attr ref android.R.styleable#View_longClickable
6290     */
6291    public void setLongClickable(boolean longClickable) {
6292        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6293    }
6294
6295    /**
6296     * Sets the pressed state for this view.
6297     *
6298     * @see #isClickable()
6299     * @see #setClickable(boolean)
6300     *
6301     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6302     *        the View's internal state from a previously set "pressed" state.
6303     */
6304    public void setPressed(boolean pressed) {
6305        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6306
6307        if (pressed) {
6308            mPrivateFlags |= PFLAG_PRESSED;
6309        } else {
6310            mPrivateFlags &= ~PFLAG_PRESSED;
6311        }
6312
6313        if (needsRefresh) {
6314            refreshDrawableState();
6315        }
6316        dispatchSetPressed(pressed);
6317    }
6318
6319    /**
6320     * Dispatch setPressed to all of this View's children.
6321     *
6322     * @see #setPressed(boolean)
6323     *
6324     * @param pressed The new pressed state
6325     */
6326    protected void dispatchSetPressed(boolean pressed) {
6327    }
6328
6329    /**
6330     * Indicates whether the view is currently in pressed state. Unless
6331     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6332     * the pressed state.
6333     *
6334     * @see #setPressed(boolean)
6335     * @see #isClickable()
6336     * @see #setClickable(boolean)
6337     *
6338     * @return true if the view is currently pressed, false otherwise
6339     */
6340    public boolean isPressed() {
6341        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6342    }
6343
6344    /**
6345     * Indicates whether this view will save its state (that is,
6346     * whether its {@link #onSaveInstanceState} method will be called).
6347     *
6348     * @return Returns true if the view state saving is enabled, else false.
6349     *
6350     * @see #setSaveEnabled(boolean)
6351     * @attr ref android.R.styleable#View_saveEnabled
6352     */
6353    public boolean isSaveEnabled() {
6354        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6355    }
6356
6357    /**
6358     * Controls whether the saving of this view's state is
6359     * enabled (that is, whether its {@link #onSaveInstanceState} method
6360     * will be called).  Note that even if freezing is enabled, the
6361     * view still must have an id assigned to it (via {@link #setId(int)})
6362     * for its state to be saved.  This flag can only disable the
6363     * saving of this view; any child views may still have their state saved.
6364     *
6365     * @param enabled Set to false to <em>disable</em> state saving, or true
6366     * (the default) to allow it.
6367     *
6368     * @see #isSaveEnabled()
6369     * @see #setId(int)
6370     * @see #onSaveInstanceState()
6371     * @attr ref android.R.styleable#View_saveEnabled
6372     */
6373    public void setSaveEnabled(boolean enabled) {
6374        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6375    }
6376
6377    /**
6378     * Gets whether the framework should discard touches when the view's
6379     * window is obscured by another visible window.
6380     * Refer to the {@link View} security documentation for more details.
6381     *
6382     * @return True if touch filtering is enabled.
6383     *
6384     * @see #setFilterTouchesWhenObscured(boolean)
6385     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6386     */
6387    @ViewDebug.ExportedProperty
6388    public boolean getFilterTouchesWhenObscured() {
6389        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6390    }
6391
6392    /**
6393     * Sets whether the framework should discard touches when the view's
6394     * window is obscured by another visible window.
6395     * Refer to the {@link View} security documentation for more details.
6396     *
6397     * @param enabled True if touch filtering should be enabled.
6398     *
6399     * @see #getFilterTouchesWhenObscured
6400     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6401     */
6402    public void setFilterTouchesWhenObscured(boolean enabled) {
6403        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6404                FILTER_TOUCHES_WHEN_OBSCURED);
6405    }
6406
6407    /**
6408     * Indicates whether the entire hierarchy under this view will save its
6409     * state when a state saving traversal occurs from its parent.  The default
6410     * is true; if false, these views will not be saved unless
6411     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6412     *
6413     * @return Returns true if the view state saving from parent is enabled, else false.
6414     *
6415     * @see #setSaveFromParentEnabled(boolean)
6416     */
6417    public boolean isSaveFromParentEnabled() {
6418        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6419    }
6420
6421    /**
6422     * Controls whether the entire hierarchy under this view will save its
6423     * state when a state saving traversal occurs from its parent.  The default
6424     * is true; if false, these views will not be saved unless
6425     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6426     *
6427     * @param enabled Set to false to <em>disable</em> state saving, or true
6428     * (the default) to allow it.
6429     *
6430     * @see #isSaveFromParentEnabled()
6431     * @see #setId(int)
6432     * @see #onSaveInstanceState()
6433     */
6434    public void setSaveFromParentEnabled(boolean enabled) {
6435        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6436    }
6437
6438
6439    /**
6440     * Returns whether this View is able to take focus.
6441     *
6442     * @return True if this view can take focus, or false otherwise.
6443     * @attr ref android.R.styleable#View_focusable
6444     */
6445    @ViewDebug.ExportedProperty(category = "focus")
6446    public final boolean isFocusable() {
6447        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6448    }
6449
6450    /**
6451     * When a view is focusable, it may not want to take focus when in touch mode.
6452     * For example, a button would like focus when the user is navigating via a D-pad
6453     * so that the user can click on it, but once the user starts touching the screen,
6454     * the button shouldn't take focus
6455     * @return Whether the view is focusable in touch mode.
6456     * @attr ref android.R.styleable#View_focusableInTouchMode
6457     */
6458    @ViewDebug.ExportedProperty
6459    public final boolean isFocusableInTouchMode() {
6460        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6461    }
6462
6463    /**
6464     * Find the nearest view in the specified direction that can take focus.
6465     * This does not actually give focus to that view.
6466     *
6467     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6468     *
6469     * @return The nearest focusable in the specified direction, or null if none
6470     *         can be found.
6471     */
6472    public View focusSearch(int direction) {
6473        if (mParent != null) {
6474            return mParent.focusSearch(this, direction);
6475        } else {
6476            return null;
6477        }
6478    }
6479
6480    /**
6481     * This method is the last chance for the focused view and its ancestors to
6482     * respond to an arrow key. This is called when the focused view did not
6483     * consume the key internally, nor could the view system find a new view in
6484     * the requested direction to give focus to.
6485     *
6486     * @param focused The currently focused view.
6487     * @param direction The direction focus wants to move. One of FOCUS_UP,
6488     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6489     * @return True if the this view consumed this unhandled move.
6490     */
6491    public boolean dispatchUnhandledMove(View focused, int direction) {
6492        return false;
6493    }
6494
6495    /**
6496     * If a user manually specified the next view id for a particular direction,
6497     * use the root to look up the view.
6498     * @param root The root view of the hierarchy containing this view.
6499     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6500     * or FOCUS_BACKWARD.
6501     * @return The user specified next view, or null if there is none.
6502     */
6503    View findUserSetNextFocus(View root, int direction) {
6504        switch (direction) {
6505            case FOCUS_LEFT:
6506                if (mNextFocusLeftId == View.NO_ID) return null;
6507                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6508            case FOCUS_RIGHT:
6509                if (mNextFocusRightId == View.NO_ID) return null;
6510                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6511            case FOCUS_UP:
6512                if (mNextFocusUpId == View.NO_ID) return null;
6513                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6514            case FOCUS_DOWN:
6515                if (mNextFocusDownId == View.NO_ID) return null;
6516                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6517            case FOCUS_FORWARD:
6518                if (mNextFocusForwardId == View.NO_ID) return null;
6519                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6520            case FOCUS_BACKWARD: {
6521                if (mID == View.NO_ID) return null;
6522                final int id = mID;
6523                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6524                    @Override
6525                    public boolean apply(View t) {
6526                        return t.mNextFocusForwardId == id;
6527                    }
6528                });
6529            }
6530        }
6531        return null;
6532    }
6533
6534    private View findViewInsideOutShouldExist(View root, int id) {
6535        if (mMatchIdPredicate == null) {
6536            mMatchIdPredicate = new MatchIdPredicate();
6537        }
6538        mMatchIdPredicate.mId = id;
6539        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6540        if (result == null) {
6541            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6542        }
6543        return result;
6544    }
6545
6546    /**
6547     * Find and return all focusable views that are descendants of this view,
6548     * possibly including this view if it is focusable itself.
6549     *
6550     * @param direction The direction of the focus
6551     * @return A list of focusable views
6552     */
6553    public ArrayList<View> getFocusables(int direction) {
6554        ArrayList<View> result = new ArrayList<View>(24);
6555        addFocusables(result, direction);
6556        return result;
6557    }
6558
6559    /**
6560     * Add any focusable views that are descendants of this view (possibly
6561     * including this view if it is focusable itself) to views.  If we are in touch mode,
6562     * only add views that are also focusable in touch mode.
6563     *
6564     * @param views Focusable views found so far
6565     * @param direction The direction of the focus
6566     */
6567    public void addFocusables(ArrayList<View> views, int direction) {
6568        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6569    }
6570
6571    /**
6572     * Adds any focusable views that are descendants of this view (possibly
6573     * including this view if it is focusable itself) to views. This method
6574     * adds all focusable views regardless if we are in touch mode or
6575     * only views focusable in touch mode if we are in touch mode or
6576     * only views that can take accessibility focus if accessibility is enabeld
6577     * depending on the focusable mode paramater.
6578     *
6579     * @param views Focusable views found so far or null if all we are interested is
6580     *        the number of focusables.
6581     * @param direction The direction of the focus.
6582     * @param focusableMode The type of focusables to be added.
6583     *
6584     * @see #FOCUSABLES_ALL
6585     * @see #FOCUSABLES_TOUCH_MODE
6586     */
6587    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6588        if (views == null) {
6589            return;
6590        }
6591        if (!isFocusable()) {
6592            return;
6593        }
6594        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6595                && isInTouchMode() && !isFocusableInTouchMode()) {
6596            return;
6597        }
6598        views.add(this);
6599    }
6600
6601    /**
6602     * Finds the Views that contain given text. The containment is case insensitive.
6603     * The search is performed by either the text that the View renders or the content
6604     * description that describes the view for accessibility purposes and the view does
6605     * not render or both. Clients can specify how the search is to be performed via
6606     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6607     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6608     *
6609     * @param outViews The output list of matching Views.
6610     * @param searched The text to match against.
6611     *
6612     * @see #FIND_VIEWS_WITH_TEXT
6613     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6614     * @see #setContentDescription(CharSequence)
6615     */
6616    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6617        if (getAccessibilityNodeProvider() != null) {
6618            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6619                outViews.add(this);
6620            }
6621        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6622                && (searched != null && searched.length() > 0)
6623                && (mContentDescription != null && mContentDescription.length() > 0)) {
6624            String searchedLowerCase = searched.toString().toLowerCase();
6625            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6626            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6627                outViews.add(this);
6628            }
6629        }
6630    }
6631
6632    /**
6633     * Find and return all touchable views that are descendants of this view,
6634     * possibly including this view if it is touchable itself.
6635     *
6636     * @return A list of touchable views
6637     */
6638    public ArrayList<View> getTouchables() {
6639        ArrayList<View> result = new ArrayList<View>();
6640        addTouchables(result);
6641        return result;
6642    }
6643
6644    /**
6645     * Add any touchable views that are descendants of this view (possibly
6646     * including this view if it is touchable itself) to views.
6647     *
6648     * @param views Touchable views found so far
6649     */
6650    public void addTouchables(ArrayList<View> views) {
6651        final int viewFlags = mViewFlags;
6652
6653        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6654                && (viewFlags & ENABLED_MASK) == ENABLED) {
6655            views.add(this);
6656        }
6657    }
6658
6659    /**
6660     * Returns whether this View is accessibility focused.
6661     *
6662     * @return True if this View is accessibility focused.
6663     */
6664    boolean isAccessibilityFocused() {
6665        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6666    }
6667
6668    /**
6669     * Call this to try to give accessibility focus to this view.
6670     *
6671     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6672     * returns false or the view is no visible or the view already has accessibility
6673     * focus.
6674     *
6675     * See also {@link #focusSearch(int)}, which is what you call to say that you
6676     * have focus, and you want your parent to look for the next one.
6677     *
6678     * @return Whether this view actually took accessibility focus.
6679     *
6680     * @hide
6681     */
6682    public boolean requestAccessibilityFocus() {
6683        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6684        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6685            return false;
6686        }
6687        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6688            return false;
6689        }
6690        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6691            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6692            ViewRootImpl viewRootImpl = getViewRootImpl();
6693            if (viewRootImpl != null) {
6694                viewRootImpl.setAccessibilityFocus(this, null);
6695            }
6696            invalidate();
6697            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6698            return true;
6699        }
6700        return false;
6701    }
6702
6703    /**
6704     * Call this to try to clear accessibility focus of this view.
6705     *
6706     * See also {@link #focusSearch(int)}, which is what you call to say that you
6707     * have focus, and you want your parent to look for the next one.
6708     *
6709     * @hide
6710     */
6711    public void clearAccessibilityFocus() {
6712        clearAccessibilityFocusNoCallbacks();
6713        // Clear the global reference of accessibility focus if this
6714        // view or any of its descendants had accessibility focus.
6715        ViewRootImpl viewRootImpl = getViewRootImpl();
6716        if (viewRootImpl != null) {
6717            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6718            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6719                viewRootImpl.setAccessibilityFocus(null, null);
6720            }
6721        }
6722    }
6723
6724    private void sendAccessibilityHoverEvent(int eventType) {
6725        // Since we are not delivering to a client accessibility events from not
6726        // important views (unless the clinet request that) we need to fire the
6727        // event from the deepest view exposed to the client. As a consequence if
6728        // the user crosses a not exposed view the client will see enter and exit
6729        // of the exposed predecessor followed by and enter and exit of that same
6730        // predecessor when entering and exiting the not exposed descendant. This
6731        // is fine since the client has a clear idea which view is hovered at the
6732        // price of a couple more events being sent. This is a simple and
6733        // working solution.
6734        View source = this;
6735        while (true) {
6736            if (source.includeForAccessibility()) {
6737                source.sendAccessibilityEvent(eventType);
6738                return;
6739            }
6740            ViewParent parent = source.getParent();
6741            if (parent instanceof View) {
6742                source = (View) parent;
6743            } else {
6744                return;
6745            }
6746        }
6747    }
6748
6749    /**
6750     * Clears accessibility focus without calling any callback methods
6751     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6752     * is used for clearing accessibility focus when giving this focus to
6753     * another view.
6754     */
6755    void clearAccessibilityFocusNoCallbacks() {
6756        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6757            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6758            invalidate();
6759            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6760        }
6761    }
6762
6763    /**
6764     * Call this to try to give focus to a specific view or to one of its
6765     * descendants.
6766     *
6767     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6768     * false), or if it is focusable and it is not focusable in touch mode
6769     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6770     *
6771     * See also {@link #focusSearch(int)}, which is what you call to say that you
6772     * have focus, and you want your parent to look for the next one.
6773     *
6774     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6775     * {@link #FOCUS_DOWN} and <code>null</code>.
6776     *
6777     * @return Whether this view or one of its descendants actually took focus.
6778     */
6779    public final boolean requestFocus() {
6780        return requestFocus(View.FOCUS_DOWN);
6781    }
6782
6783    /**
6784     * Call this to try to give focus to a specific view or to one of its
6785     * descendants and give it a hint about what direction focus is heading.
6786     *
6787     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6788     * false), or if it is focusable and it is not focusable in touch mode
6789     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6790     *
6791     * See also {@link #focusSearch(int)}, which is what you call to say that you
6792     * have focus, and you want your parent to look for the next one.
6793     *
6794     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6795     * <code>null</code> set for the previously focused rectangle.
6796     *
6797     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6798     * @return Whether this view or one of its descendants actually took focus.
6799     */
6800    public final boolean requestFocus(int direction) {
6801        return requestFocus(direction, null);
6802    }
6803
6804    /**
6805     * Call this to try to give focus to a specific view or to one of its descendants
6806     * and give it hints about the direction and a specific rectangle that the focus
6807     * is coming from.  The rectangle can help give larger views a finer grained hint
6808     * about where focus is coming from, and therefore, where to show selection, or
6809     * forward focus change internally.
6810     *
6811     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6812     * false), or if it is focusable and it is not focusable in touch mode
6813     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6814     *
6815     * A View will not take focus if it is not visible.
6816     *
6817     * A View will not take focus if one of its parents has
6818     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6819     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6820     *
6821     * See also {@link #focusSearch(int)}, which is what you call to say that you
6822     * have focus, and you want your parent to look for the next one.
6823     *
6824     * You may wish to override this method if your custom {@link View} has an internal
6825     * {@link View} that it wishes to forward the request to.
6826     *
6827     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6828     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6829     *        to give a finer grained hint about where focus is coming from.  May be null
6830     *        if there is no hint.
6831     * @return Whether this view or one of its descendants actually took focus.
6832     */
6833    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6834        return requestFocusNoSearch(direction, previouslyFocusedRect);
6835    }
6836
6837    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6838        // need to be focusable
6839        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6840                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6841            return false;
6842        }
6843
6844        // need to be focusable in touch mode if in touch mode
6845        if (isInTouchMode() &&
6846            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6847               return false;
6848        }
6849
6850        // need to not have any parents blocking us
6851        if (hasAncestorThatBlocksDescendantFocus()) {
6852            return false;
6853        }
6854
6855        handleFocusGainInternal(direction, previouslyFocusedRect);
6856        return true;
6857    }
6858
6859    /**
6860     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6861     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6862     * touch mode to request focus when they are touched.
6863     *
6864     * @return Whether this view or one of its descendants actually took focus.
6865     *
6866     * @see #isInTouchMode()
6867     *
6868     */
6869    public final boolean requestFocusFromTouch() {
6870        // Leave touch mode if we need to
6871        if (isInTouchMode()) {
6872            ViewRootImpl viewRoot = getViewRootImpl();
6873            if (viewRoot != null) {
6874                viewRoot.ensureTouchMode(false);
6875            }
6876        }
6877        return requestFocus(View.FOCUS_DOWN);
6878    }
6879
6880    /**
6881     * @return Whether any ancestor of this view blocks descendant focus.
6882     */
6883    private boolean hasAncestorThatBlocksDescendantFocus() {
6884        ViewParent ancestor = mParent;
6885        while (ancestor instanceof ViewGroup) {
6886            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6887            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6888                return true;
6889            } else {
6890                ancestor = vgAncestor.getParent();
6891            }
6892        }
6893        return false;
6894    }
6895
6896    /**
6897     * Gets the mode for determining whether this View is important for accessibility
6898     * which is if it fires accessibility events and if it is reported to
6899     * accessibility services that query the screen.
6900     *
6901     * @return The mode for determining whether a View is important for accessibility.
6902     *
6903     * @attr ref android.R.styleable#View_importantForAccessibility
6904     *
6905     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6906     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6907     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6908     */
6909    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6910            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6911            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6912            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6913        })
6914    public int getImportantForAccessibility() {
6915        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6916                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6917    }
6918
6919    /**
6920     * Sets how to determine whether this view is important for accessibility
6921     * which is if it fires accessibility events and if it is reported to
6922     * accessibility services that query the screen.
6923     *
6924     * @param mode How to determine whether this view is important for accessibility.
6925     *
6926     * @attr ref android.R.styleable#View_importantForAccessibility
6927     *
6928     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6929     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6930     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6931     */
6932    public void setImportantForAccessibility(int mode) {
6933        final boolean oldIncludeForAccessibility = includeForAccessibility();
6934        if (mode != getImportantForAccessibility()) {
6935            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6936            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6937                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6938            if (oldIncludeForAccessibility != includeForAccessibility()) {
6939                notifySubtreeAccessibilityStateChangedIfNeeded();
6940            } else {
6941                notifyViewAccessibilityStateChangedIfNeeded();
6942            }
6943        }
6944    }
6945
6946    /**
6947     * Gets whether this view should be exposed for accessibility.
6948     *
6949     * @return Whether the view is exposed for accessibility.
6950     *
6951     * @hide
6952     */
6953    public boolean isImportantForAccessibility() {
6954        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6955                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6956        switch (mode) {
6957            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6958                return true;
6959            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6960                return false;
6961            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6962                return isActionableForAccessibility() || hasListenersForAccessibility()
6963                        || getAccessibilityNodeProvider() != null;
6964            default:
6965                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6966                        + mode);
6967        }
6968    }
6969
6970    /**
6971     * Gets the parent for accessibility purposes. Note that the parent for
6972     * accessibility is not necessary the immediate parent. It is the first
6973     * predecessor that is important for accessibility.
6974     *
6975     * @return The parent for accessibility purposes.
6976     */
6977    public ViewParent getParentForAccessibility() {
6978        if (mParent instanceof View) {
6979            View parentView = (View) mParent;
6980            if (parentView.includeForAccessibility()) {
6981                return mParent;
6982            } else {
6983                return mParent.getParentForAccessibility();
6984            }
6985        }
6986        return null;
6987    }
6988
6989    /**
6990     * Adds the children of a given View for accessibility. Since some Views are
6991     * not important for accessibility the children for accessibility are not
6992     * necessarily direct children of the view, rather they are the first level of
6993     * descendants important for accessibility.
6994     *
6995     * @param children The list of children for accessibility.
6996     */
6997    public void addChildrenForAccessibility(ArrayList<View> children) {
6998        if (includeForAccessibility()) {
6999            children.add(this);
7000        }
7001    }
7002
7003    /**
7004     * Whether to regard this view for accessibility. A view is regarded for
7005     * accessibility if it is important for accessibility or the querying
7006     * accessibility service has explicitly requested that view not
7007     * important for accessibility are regarded.
7008     *
7009     * @return Whether to regard the view for accessibility.
7010     *
7011     * @hide
7012     */
7013    public boolean includeForAccessibility() {
7014        //noinspection SimplifiableIfStatement
7015        if (mAttachInfo != null) {
7016            return (mAttachInfo.mAccessibilityFetchFlags
7017                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7018                    || isImportantForAccessibility();
7019        }
7020        return false;
7021    }
7022
7023    /**
7024     * Returns whether the View is considered actionable from
7025     * accessibility perspective. Such view are important for
7026     * accessibility.
7027     *
7028     * @return True if the view is actionable for accessibility.
7029     *
7030     * @hide
7031     */
7032    public boolean isActionableForAccessibility() {
7033        return (isClickable() || isLongClickable() || isFocusable());
7034    }
7035
7036    /**
7037     * Returns whether the View has registered callbacks wich makes it
7038     * important for accessibility.
7039     *
7040     * @return True if the view is actionable for accessibility.
7041     */
7042    private boolean hasListenersForAccessibility() {
7043        ListenerInfo info = getListenerInfo();
7044        return mTouchDelegate != null || info.mOnKeyListener != null
7045                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7046                || info.mOnHoverListener != null || info.mOnDragListener != null;
7047    }
7048
7049    /**
7050     * Notifies that the accessibility state of this view changed. The change
7051     * is local to this view and does not represent structural changes such
7052     * as children and parent. For example, the view became focusable. The
7053     * notification is at at most once every
7054     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7055     * to avoid unnecessary load to the system. Also once a view has a pending
7056     * notifucation this method is a NOP until the notification has been sent.
7057     *
7058     * @hide
7059     */
7060    public void notifyViewAccessibilityStateChangedIfNeeded() {
7061        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7062            return;
7063        }
7064        if (mSendViewStateChangedAccessibilityEvent == null) {
7065            mSendViewStateChangedAccessibilityEvent =
7066                    new SendViewStateChangedAccessibilityEvent();
7067        }
7068        mSendViewStateChangedAccessibilityEvent.runOrPost();
7069    }
7070
7071    /**
7072     * Notifies that the accessibility state of this view changed. The change
7073     * is *not* local to this view and does represent structural changes such
7074     * as children and parent. For example, the view size changed. The
7075     * notification is at at most once every
7076     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7077     * to avoid unnecessary load to the system. Also once a view has a pending
7078     * notifucation this method is a NOP until the notification has been sent.
7079     *
7080     * @hide
7081     */
7082    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7083        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7084            return;
7085        }
7086        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7087            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7088            if (mParent != null) {
7089                try {
7090                    mParent.childAccessibilityStateChanged(this);
7091                } catch (AbstractMethodError e) {
7092                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7093                            " does not fully implement ViewParent", e);
7094                }
7095            }
7096        }
7097    }
7098
7099    /**
7100     * Reset the flag indicating the accessibility state of the subtree rooted
7101     * at this view changed.
7102     */
7103    void resetSubtreeAccessibilityStateChanged() {
7104        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7105    }
7106
7107    /**
7108     * Performs the specified accessibility action on the view. For
7109     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7110     * <p>
7111     * If an {@link AccessibilityDelegate} has been specified via calling
7112     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7113     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7114     * is responsible for handling this call.
7115     * </p>
7116     *
7117     * @param action The action to perform.
7118     * @param arguments Optional action arguments.
7119     * @return Whether the action was performed.
7120     */
7121    public boolean performAccessibilityAction(int action, Bundle arguments) {
7122      if (mAccessibilityDelegate != null) {
7123          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7124      } else {
7125          return performAccessibilityActionInternal(action, arguments);
7126      }
7127    }
7128
7129   /**
7130    * @see #performAccessibilityAction(int, Bundle)
7131    *
7132    * Note: Called from the default {@link AccessibilityDelegate}.
7133    */
7134    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7135        switch (action) {
7136            case AccessibilityNodeInfo.ACTION_CLICK: {
7137                if (isClickable()) {
7138                    performClick();
7139                    return true;
7140                }
7141            } break;
7142            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7143                if (isLongClickable()) {
7144                    performLongClick();
7145                    return true;
7146                }
7147            } break;
7148            case AccessibilityNodeInfo.ACTION_FOCUS: {
7149                if (!hasFocus()) {
7150                    // Get out of touch mode since accessibility
7151                    // wants to move focus around.
7152                    getViewRootImpl().ensureTouchMode(false);
7153                    return requestFocus();
7154                }
7155            } break;
7156            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7157                if (hasFocus()) {
7158                    clearFocus();
7159                    return !isFocused();
7160                }
7161            } break;
7162            case AccessibilityNodeInfo.ACTION_SELECT: {
7163                if (!isSelected()) {
7164                    setSelected(true);
7165                    return isSelected();
7166                }
7167            } break;
7168            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7169                if (isSelected()) {
7170                    setSelected(false);
7171                    return !isSelected();
7172                }
7173            } break;
7174            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7175                if (!isAccessibilityFocused()) {
7176                    return requestAccessibilityFocus();
7177                }
7178            } break;
7179            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7180                if (isAccessibilityFocused()) {
7181                    clearAccessibilityFocus();
7182                    return true;
7183                }
7184            } break;
7185            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7186                if (arguments != null) {
7187                    final int granularity = arguments.getInt(
7188                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7189                    final boolean extendSelection = arguments.getBoolean(
7190                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7191                    return traverseAtGranularity(granularity, true, extendSelection);
7192                }
7193            } break;
7194            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7195                if (arguments != null) {
7196                    final int granularity = arguments.getInt(
7197                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7198                    final boolean extendSelection = arguments.getBoolean(
7199                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7200                    return traverseAtGranularity(granularity, false, extendSelection);
7201                }
7202            } break;
7203            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7204                CharSequence text = getIterableTextForAccessibility();
7205                if (text == null) {
7206                    return false;
7207                }
7208                final int start = (arguments != null) ? arguments.getInt(
7209                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7210                final int end = (arguments != null) ? arguments.getInt(
7211                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7212                // Only cursor position can be specified (selection length == 0)
7213                if ((getAccessibilitySelectionStart() != start
7214                        || getAccessibilitySelectionEnd() != end)
7215                        && (start == end)) {
7216                    setAccessibilitySelection(start, end);
7217                    notifyViewAccessibilityStateChangedIfNeeded();
7218                    return true;
7219                }
7220            } break;
7221        }
7222        return false;
7223    }
7224
7225    private boolean traverseAtGranularity(int granularity, boolean forward,
7226            boolean extendSelection) {
7227        CharSequence text = getIterableTextForAccessibility();
7228        if (text == null || text.length() == 0) {
7229            return false;
7230        }
7231        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7232        if (iterator == null) {
7233            return false;
7234        }
7235        int current = getAccessibilitySelectionEnd();
7236        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7237            current = forward ? 0 : text.length();
7238        }
7239        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7240        if (range == null) {
7241            return false;
7242        }
7243        final int segmentStart = range[0];
7244        final int segmentEnd = range[1];
7245        int selectionStart;
7246        int selectionEnd;
7247        if (extendSelection && isAccessibilitySelectionExtendable()) {
7248            selectionStart = getAccessibilitySelectionStart();
7249            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7250                selectionStart = forward ? segmentStart : segmentEnd;
7251            }
7252            selectionEnd = forward ? segmentEnd : segmentStart;
7253        } else {
7254            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7255        }
7256        setAccessibilitySelection(selectionStart, selectionEnd);
7257        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7258                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7259        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7260        return true;
7261    }
7262
7263    /**
7264     * Gets the text reported for accessibility purposes.
7265     *
7266     * @return The accessibility text.
7267     *
7268     * @hide
7269     */
7270    public CharSequence getIterableTextForAccessibility() {
7271        return getContentDescription();
7272    }
7273
7274    /**
7275     * Gets whether accessibility selection can be extended.
7276     *
7277     * @return If selection is extensible.
7278     *
7279     * @hide
7280     */
7281    public boolean isAccessibilitySelectionExtendable() {
7282        return false;
7283    }
7284
7285    /**
7286     * @hide
7287     */
7288    public int getAccessibilitySelectionStart() {
7289        return mAccessibilityCursorPosition;
7290    }
7291
7292    /**
7293     * @hide
7294     */
7295    public int getAccessibilitySelectionEnd() {
7296        return getAccessibilitySelectionStart();
7297    }
7298
7299    /**
7300     * @hide
7301     */
7302    public void setAccessibilitySelection(int start, int end) {
7303        if (start ==  end && end == mAccessibilityCursorPosition) {
7304            return;
7305        }
7306        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7307            mAccessibilityCursorPosition = start;
7308        } else {
7309            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7310        }
7311        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7312    }
7313
7314    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7315            int fromIndex, int toIndex) {
7316        if (mParent == null) {
7317            return;
7318        }
7319        AccessibilityEvent event = AccessibilityEvent.obtain(
7320                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7321        onInitializeAccessibilityEvent(event);
7322        onPopulateAccessibilityEvent(event);
7323        event.setFromIndex(fromIndex);
7324        event.setToIndex(toIndex);
7325        event.setAction(action);
7326        event.setMovementGranularity(granularity);
7327        mParent.requestSendAccessibilityEvent(this, event);
7328    }
7329
7330    /**
7331     * @hide
7332     */
7333    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7334        switch (granularity) {
7335            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7336                CharSequence text = getIterableTextForAccessibility();
7337                if (text != null && text.length() > 0) {
7338                    CharacterTextSegmentIterator iterator =
7339                        CharacterTextSegmentIterator.getInstance(
7340                                mContext.getResources().getConfiguration().locale);
7341                    iterator.initialize(text.toString());
7342                    return iterator;
7343                }
7344            } break;
7345            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7346                CharSequence text = getIterableTextForAccessibility();
7347                if (text != null && text.length() > 0) {
7348                    WordTextSegmentIterator iterator =
7349                        WordTextSegmentIterator.getInstance(
7350                                mContext.getResources().getConfiguration().locale);
7351                    iterator.initialize(text.toString());
7352                    return iterator;
7353                }
7354            } break;
7355            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7356                CharSequence text = getIterableTextForAccessibility();
7357                if (text != null && text.length() > 0) {
7358                    ParagraphTextSegmentIterator iterator =
7359                        ParagraphTextSegmentIterator.getInstance();
7360                    iterator.initialize(text.toString());
7361                    return iterator;
7362                }
7363            } break;
7364        }
7365        return null;
7366    }
7367
7368    /**
7369     * @hide
7370     */
7371    public void dispatchStartTemporaryDetach() {
7372        clearAccessibilityFocus();
7373        clearDisplayList();
7374
7375        onStartTemporaryDetach();
7376    }
7377
7378    /**
7379     * This is called when a container is going to temporarily detach a child, with
7380     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7381     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7382     * {@link #onDetachedFromWindow()} when the container is done.
7383     */
7384    public void onStartTemporaryDetach() {
7385        removeUnsetPressCallback();
7386        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7387    }
7388
7389    /**
7390     * @hide
7391     */
7392    public void dispatchFinishTemporaryDetach() {
7393        onFinishTemporaryDetach();
7394    }
7395
7396    /**
7397     * Called after {@link #onStartTemporaryDetach} when the container is done
7398     * changing the view.
7399     */
7400    public void onFinishTemporaryDetach() {
7401    }
7402
7403    /**
7404     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7405     * for this view's window.  Returns null if the view is not currently attached
7406     * to the window.  Normally you will not need to use this directly, but
7407     * just use the standard high-level event callbacks like
7408     * {@link #onKeyDown(int, KeyEvent)}.
7409     */
7410    public KeyEvent.DispatcherState getKeyDispatcherState() {
7411        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7412    }
7413
7414    /**
7415     * Dispatch a key event before it is processed by any input method
7416     * associated with the view hierarchy.  This can be used to intercept
7417     * key events in special situations before the IME consumes them; a
7418     * typical example would be handling the BACK key to update the application's
7419     * UI instead of allowing the IME to see it and close itself.
7420     *
7421     * @param event The key event to be dispatched.
7422     * @return True if the event was handled, false otherwise.
7423     */
7424    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7425        return onKeyPreIme(event.getKeyCode(), event);
7426    }
7427
7428    /**
7429     * Dispatch a key event to the next view on the focus path. This path runs
7430     * from the top of the view tree down to the currently focused view. If this
7431     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7432     * the next node down the focus path. This method also fires any key
7433     * listeners.
7434     *
7435     * @param event The key event to be dispatched.
7436     * @return True if the event was handled, false otherwise.
7437     */
7438    public boolean dispatchKeyEvent(KeyEvent event) {
7439        if (mInputEventConsistencyVerifier != null) {
7440            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7441        }
7442
7443        // Give any attached key listener a first crack at the event.
7444        //noinspection SimplifiableIfStatement
7445        ListenerInfo li = mListenerInfo;
7446        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7447                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7448            return true;
7449        }
7450
7451        if (event.dispatch(this, mAttachInfo != null
7452                ? mAttachInfo.mKeyDispatchState : null, this)) {
7453            return true;
7454        }
7455
7456        if (mInputEventConsistencyVerifier != null) {
7457            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7458        }
7459        return false;
7460    }
7461
7462    /**
7463     * Dispatches a key shortcut event.
7464     *
7465     * @param event The key event to be dispatched.
7466     * @return True if the event was handled by the view, false otherwise.
7467     */
7468    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7469        return onKeyShortcut(event.getKeyCode(), event);
7470    }
7471
7472    /**
7473     * Pass the touch screen motion event down to the target view, or this
7474     * view if it is the target.
7475     *
7476     * @param event The motion event to be dispatched.
7477     * @return True if the event was handled by the view, false otherwise.
7478     */
7479    public boolean dispatchTouchEvent(MotionEvent event) {
7480        if (mInputEventConsistencyVerifier != null) {
7481            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7482        }
7483
7484        if (onFilterTouchEventForSecurity(event)) {
7485            //noinspection SimplifiableIfStatement
7486            ListenerInfo li = mListenerInfo;
7487            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7488                    && li.mOnTouchListener.onTouch(this, event)) {
7489                return true;
7490            }
7491
7492            if (onTouchEvent(event)) {
7493                return true;
7494            }
7495        }
7496
7497        if (mInputEventConsistencyVerifier != null) {
7498            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7499        }
7500        return false;
7501    }
7502
7503    /**
7504     * Filter the touch event to apply security policies.
7505     *
7506     * @param event The motion event to be filtered.
7507     * @return True if the event should be dispatched, false if the event should be dropped.
7508     *
7509     * @see #getFilterTouchesWhenObscured
7510     */
7511    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7512        //noinspection RedundantIfStatement
7513        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7514                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7515            // Window is obscured, drop this touch.
7516            return false;
7517        }
7518        return true;
7519    }
7520
7521    /**
7522     * Pass a trackball motion event down to the focused view.
7523     *
7524     * @param event The motion event to be dispatched.
7525     * @return True if the event was handled by the view, false otherwise.
7526     */
7527    public boolean dispatchTrackballEvent(MotionEvent event) {
7528        if (mInputEventConsistencyVerifier != null) {
7529            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7530        }
7531
7532        return onTrackballEvent(event);
7533    }
7534
7535    /**
7536     * Dispatch a generic motion event.
7537     * <p>
7538     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7539     * are delivered to the view under the pointer.  All other generic motion events are
7540     * delivered to the focused view.  Hover events are handled specially and are delivered
7541     * to {@link #onHoverEvent(MotionEvent)}.
7542     * </p>
7543     *
7544     * @param event The motion event to be dispatched.
7545     * @return True if the event was handled by the view, false otherwise.
7546     */
7547    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7548        if (mInputEventConsistencyVerifier != null) {
7549            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7550        }
7551
7552        final int source = event.getSource();
7553        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7554            final int action = event.getAction();
7555            if (action == MotionEvent.ACTION_HOVER_ENTER
7556                    || action == MotionEvent.ACTION_HOVER_MOVE
7557                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7558                if (dispatchHoverEvent(event)) {
7559                    return true;
7560                }
7561            } else if (dispatchGenericPointerEvent(event)) {
7562                return true;
7563            }
7564        } else if (dispatchGenericFocusedEvent(event)) {
7565            return true;
7566        }
7567
7568        if (dispatchGenericMotionEventInternal(event)) {
7569            return true;
7570        }
7571
7572        if (mInputEventConsistencyVerifier != null) {
7573            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7574        }
7575        return false;
7576    }
7577
7578    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7579        //noinspection SimplifiableIfStatement
7580        ListenerInfo li = mListenerInfo;
7581        if (li != null && li.mOnGenericMotionListener != null
7582                && (mViewFlags & ENABLED_MASK) == ENABLED
7583                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7584            return true;
7585        }
7586
7587        if (onGenericMotionEvent(event)) {
7588            return true;
7589        }
7590
7591        if (mInputEventConsistencyVerifier != null) {
7592            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7593        }
7594        return false;
7595    }
7596
7597    /**
7598     * Dispatch a hover event.
7599     * <p>
7600     * Do not call this method directly.
7601     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7602     * </p>
7603     *
7604     * @param event The motion event to be dispatched.
7605     * @return True if the event was handled by the view, false otherwise.
7606     */
7607    protected boolean dispatchHoverEvent(MotionEvent event) {
7608        ListenerInfo li = mListenerInfo;
7609        //noinspection SimplifiableIfStatement
7610        if (li != null && li.mOnHoverListener != null
7611                && (mViewFlags & ENABLED_MASK) == ENABLED
7612                && li.mOnHoverListener.onHover(this, event)) {
7613            return true;
7614        }
7615
7616        return onHoverEvent(event);
7617    }
7618
7619    /**
7620     * Returns true if the view has a child to which it has recently sent
7621     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7622     * it does not have a hovered child, then it must be the innermost hovered view.
7623     * @hide
7624     */
7625    protected boolean hasHoveredChild() {
7626        return false;
7627    }
7628
7629    /**
7630     * Dispatch a generic motion event to the view under the first pointer.
7631     * <p>
7632     * Do not call this method directly.
7633     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7634     * </p>
7635     *
7636     * @param event The motion event to be dispatched.
7637     * @return True if the event was handled by the view, false otherwise.
7638     */
7639    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7640        return false;
7641    }
7642
7643    /**
7644     * Dispatch a generic motion event to the currently focused view.
7645     * <p>
7646     * Do not call this method directly.
7647     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7648     * </p>
7649     *
7650     * @param event The motion event to be dispatched.
7651     * @return True if the event was handled by the view, false otherwise.
7652     */
7653    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7654        return false;
7655    }
7656
7657    /**
7658     * Dispatch a pointer event.
7659     * <p>
7660     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7661     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7662     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7663     * and should not be expected to handle other pointing device features.
7664     * </p>
7665     *
7666     * @param event The motion event to be dispatched.
7667     * @return True if the event was handled by the view, false otherwise.
7668     * @hide
7669     */
7670    public final boolean dispatchPointerEvent(MotionEvent event) {
7671        if (event.isTouchEvent()) {
7672            return dispatchTouchEvent(event);
7673        } else {
7674            return dispatchGenericMotionEvent(event);
7675        }
7676    }
7677
7678    /**
7679     * Called when the window containing this view gains or loses window focus.
7680     * ViewGroups should override to route to their children.
7681     *
7682     * @param hasFocus True if the window containing this view now has focus,
7683     *        false otherwise.
7684     */
7685    public void dispatchWindowFocusChanged(boolean hasFocus) {
7686        onWindowFocusChanged(hasFocus);
7687    }
7688
7689    /**
7690     * Called when the window containing this view gains or loses focus.  Note
7691     * that this is separate from view focus: to receive key events, both
7692     * your view and its window must have focus.  If a window is displayed
7693     * on top of yours that takes input focus, then your own window will lose
7694     * focus but the view focus will remain unchanged.
7695     *
7696     * @param hasWindowFocus True if the window containing this view now has
7697     *        focus, false otherwise.
7698     */
7699    public void onWindowFocusChanged(boolean hasWindowFocus) {
7700        InputMethodManager imm = InputMethodManager.peekInstance();
7701        if (!hasWindowFocus) {
7702            if (isPressed()) {
7703                setPressed(false);
7704            }
7705            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7706                imm.focusOut(this);
7707            }
7708            removeLongPressCallback();
7709            removeTapCallback();
7710            onFocusLost();
7711        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7712            imm.focusIn(this);
7713        }
7714        refreshDrawableState();
7715    }
7716
7717    /**
7718     * Returns true if this view is in a window that currently has window focus.
7719     * Note that this is not the same as the view itself having focus.
7720     *
7721     * @return True if this view is in a window that currently has window focus.
7722     */
7723    public boolean hasWindowFocus() {
7724        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7725    }
7726
7727    /**
7728     * Dispatch a view visibility change down the view hierarchy.
7729     * ViewGroups should override to route to their children.
7730     * @param changedView The view whose visibility changed. Could be 'this' or
7731     * an ancestor view.
7732     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7733     * {@link #INVISIBLE} or {@link #GONE}.
7734     */
7735    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7736        onVisibilityChanged(changedView, visibility);
7737    }
7738
7739    /**
7740     * Called when the visibility of the view or an ancestor of the view is changed.
7741     * @param changedView The view whose visibility changed. Could be 'this' or
7742     * an ancestor view.
7743     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7744     * {@link #INVISIBLE} or {@link #GONE}.
7745     */
7746    protected void onVisibilityChanged(View changedView, int visibility) {
7747        if (visibility == VISIBLE) {
7748            if (mAttachInfo != null) {
7749                initialAwakenScrollBars();
7750            } else {
7751                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7752            }
7753        }
7754    }
7755
7756    /**
7757     * Dispatch a hint about whether this view is displayed. For instance, when
7758     * a View moves out of the screen, it might receives a display hint indicating
7759     * the view is not displayed. Applications should not <em>rely</em> on this hint
7760     * as there is no guarantee that they will receive one.
7761     *
7762     * @param hint A hint about whether or not this view is displayed:
7763     * {@link #VISIBLE} or {@link #INVISIBLE}.
7764     */
7765    public void dispatchDisplayHint(int hint) {
7766        onDisplayHint(hint);
7767    }
7768
7769    /**
7770     * Gives this view a hint about whether is displayed or not. For instance, when
7771     * a View moves out of the screen, it might receives a display hint indicating
7772     * the view is not displayed. Applications should not <em>rely</em> on this hint
7773     * as there is no guarantee that they will receive one.
7774     *
7775     * @param hint A hint about whether or not this view is displayed:
7776     * {@link #VISIBLE} or {@link #INVISIBLE}.
7777     */
7778    protected void onDisplayHint(int hint) {
7779    }
7780
7781    /**
7782     * Dispatch a window visibility change down the view hierarchy.
7783     * ViewGroups should override to route to their children.
7784     *
7785     * @param visibility The new visibility of the window.
7786     *
7787     * @see #onWindowVisibilityChanged(int)
7788     */
7789    public void dispatchWindowVisibilityChanged(int visibility) {
7790        onWindowVisibilityChanged(visibility);
7791    }
7792
7793    /**
7794     * Called when the window containing has change its visibility
7795     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7796     * that this tells you whether or not your window is being made visible
7797     * to the window manager; this does <em>not</em> tell you whether or not
7798     * your window is obscured by other windows on the screen, even if it
7799     * is itself visible.
7800     *
7801     * @param visibility The new visibility of the window.
7802     */
7803    protected void onWindowVisibilityChanged(int visibility) {
7804        if (visibility == VISIBLE) {
7805            initialAwakenScrollBars();
7806        }
7807    }
7808
7809    /**
7810     * Returns the current visibility of the window this view is attached to
7811     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7812     *
7813     * @return Returns the current visibility of the view's window.
7814     */
7815    public int getWindowVisibility() {
7816        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7817    }
7818
7819    /**
7820     * Retrieve the overall visible display size in which the window this view is
7821     * attached to has been positioned in.  This takes into account screen
7822     * decorations above the window, for both cases where the window itself
7823     * is being position inside of them or the window is being placed under
7824     * then and covered insets are used for the window to position its content
7825     * inside.  In effect, this tells you the available area where content can
7826     * be placed and remain visible to users.
7827     *
7828     * <p>This function requires an IPC back to the window manager to retrieve
7829     * the requested information, so should not be used in performance critical
7830     * code like drawing.
7831     *
7832     * @param outRect Filled in with the visible display frame.  If the view
7833     * is not attached to a window, this is simply the raw display size.
7834     */
7835    public void getWindowVisibleDisplayFrame(Rect outRect) {
7836        if (mAttachInfo != null) {
7837            try {
7838                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7839            } catch (RemoteException e) {
7840                return;
7841            }
7842            // XXX This is really broken, and probably all needs to be done
7843            // in the window manager, and we need to know more about whether
7844            // we want the area behind or in front of the IME.
7845            final Rect insets = mAttachInfo.mVisibleInsets;
7846            outRect.left += insets.left;
7847            outRect.top += insets.top;
7848            outRect.right -= insets.right;
7849            outRect.bottom -= insets.bottom;
7850            return;
7851        }
7852        // The view is not attached to a display so we don't have a context.
7853        // Make a best guess about the display size.
7854        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7855        d.getRectSize(outRect);
7856    }
7857
7858    /**
7859     * Dispatch a notification about a resource configuration change down
7860     * the view hierarchy.
7861     * ViewGroups should override to route to their children.
7862     *
7863     * @param newConfig The new resource configuration.
7864     *
7865     * @see #onConfigurationChanged(android.content.res.Configuration)
7866     */
7867    public void dispatchConfigurationChanged(Configuration newConfig) {
7868        onConfigurationChanged(newConfig);
7869    }
7870
7871    /**
7872     * Called when the current configuration of the resources being used
7873     * by the application have changed.  You can use this to decide when
7874     * to reload resources that can changed based on orientation and other
7875     * configuration characterstics.  You only need to use this if you are
7876     * not relying on the normal {@link android.app.Activity} mechanism of
7877     * recreating the activity instance upon a configuration change.
7878     *
7879     * @param newConfig The new resource configuration.
7880     */
7881    protected void onConfigurationChanged(Configuration newConfig) {
7882    }
7883
7884    /**
7885     * Private function to aggregate all per-view attributes in to the view
7886     * root.
7887     */
7888    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7889        performCollectViewAttributes(attachInfo, visibility);
7890    }
7891
7892    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7893        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7894            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7895                attachInfo.mKeepScreenOn = true;
7896            }
7897            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7898            ListenerInfo li = mListenerInfo;
7899            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7900                attachInfo.mHasSystemUiListeners = true;
7901            }
7902        }
7903    }
7904
7905    void needGlobalAttributesUpdate(boolean force) {
7906        final AttachInfo ai = mAttachInfo;
7907        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7908            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7909                    || ai.mHasSystemUiListeners) {
7910                ai.mRecomputeGlobalAttributes = true;
7911            }
7912        }
7913    }
7914
7915    /**
7916     * Returns whether the device is currently in touch mode.  Touch mode is entered
7917     * once the user begins interacting with the device by touch, and affects various
7918     * things like whether focus is always visible to the user.
7919     *
7920     * @return Whether the device is in touch mode.
7921     */
7922    @ViewDebug.ExportedProperty
7923    public boolean isInTouchMode() {
7924        if (mAttachInfo != null) {
7925            return mAttachInfo.mInTouchMode;
7926        } else {
7927            return ViewRootImpl.isInTouchMode();
7928        }
7929    }
7930
7931    /**
7932     * Returns the context the view is running in, through which it can
7933     * access the current theme, resources, etc.
7934     *
7935     * @return The view's Context.
7936     */
7937    @ViewDebug.CapturedViewProperty
7938    public final Context getContext() {
7939        return mContext;
7940    }
7941
7942    /**
7943     * Handle a key event before it is processed by any input method
7944     * associated with the view hierarchy.  This can be used to intercept
7945     * key events in special situations before the IME consumes them; a
7946     * typical example would be handling the BACK key to update the application's
7947     * UI instead of allowing the IME to see it and close itself.
7948     *
7949     * @param keyCode The value in event.getKeyCode().
7950     * @param event Description of the key event.
7951     * @return If you handled the event, return true. If you want to allow the
7952     *         event to be handled by the next receiver, return false.
7953     */
7954    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7955        return false;
7956    }
7957
7958    /**
7959     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7960     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7961     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7962     * is released, if the view is enabled and clickable.
7963     *
7964     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7965     * although some may elect to do so in some situations. Do not rely on this to
7966     * catch software key presses.
7967     *
7968     * @param keyCode A key code that represents the button pressed, from
7969     *                {@link android.view.KeyEvent}.
7970     * @param event   The KeyEvent object that defines the button action.
7971     */
7972    public boolean onKeyDown(int keyCode, KeyEvent event) {
7973        boolean result = false;
7974
7975        if (KeyEvent.isConfirmKey(event.getKeyCode())) {
7976            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7977                return true;
7978            }
7979            // Long clickable items don't necessarily have to be clickable
7980            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7981                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7982                    (event.getRepeatCount() == 0)) {
7983                setPressed(true);
7984                checkForLongClick(0);
7985                return true;
7986            }
7987        }
7988        return result;
7989    }
7990
7991    /**
7992     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7993     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7994     * the event).
7995     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7996     * although some may elect to do so in some situations. Do not rely on this to
7997     * catch software key presses.
7998     */
7999    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8000        return false;
8001    }
8002
8003    /**
8004     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8005     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8006     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8007     * {@link KeyEvent#KEYCODE_ENTER} is released.
8008     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8009     * although some may elect to do so in some situations. Do not rely on this to
8010     * catch software key presses.
8011     *
8012     * @param keyCode A key code that represents the button pressed, from
8013     *                {@link android.view.KeyEvent}.
8014     * @param event   The KeyEvent object that defines the button action.
8015     */
8016    public boolean onKeyUp(int keyCode, KeyEvent event) {
8017        boolean result = false;
8018
8019        switch (keyCode) {
8020            case KeyEvent.KEYCODE_DPAD_CENTER:
8021            case KeyEvent.KEYCODE_ENTER: {
8022                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8023                    return true;
8024                }
8025                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8026                    setPressed(false);
8027
8028                    if (!mHasPerformedLongPress) {
8029                        // This is a tap, so remove the longpress check
8030                        removeLongPressCallback();
8031
8032                        result = performClick();
8033                    }
8034                }
8035                break;
8036            }
8037        }
8038        return result;
8039    }
8040
8041    /**
8042     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8043     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8044     * the event).
8045     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8046     * although some may elect to do so in some situations. Do not rely on this to
8047     * catch software key presses.
8048     *
8049     * @param keyCode     A key code that represents the button pressed, from
8050     *                    {@link android.view.KeyEvent}.
8051     * @param repeatCount The number of times the action was made.
8052     * @param event       The KeyEvent object that defines the button action.
8053     */
8054    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8055        return false;
8056    }
8057
8058    /**
8059     * Called on the focused view when a key shortcut event is not handled.
8060     * Override this method to implement local key shortcuts for the View.
8061     * Key shortcuts can also be implemented by setting the
8062     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8063     *
8064     * @param keyCode The value in event.getKeyCode().
8065     * @param event Description of the key event.
8066     * @return If you handled the event, return true. If you want to allow the
8067     *         event to be handled by the next receiver, return false.
8068     */
8069    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8070        return false;
8071    }
8072
8073    /**
8074     * Check whether the called view is a text editor, in which case it
8075     * would make sense to automatically display a soft input window for
8076     * it.  Subclasses should override this if they implement
8077     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8078     * a call on that method would return a non-null InputConnection, and
8079     * they are really a first-class editor that the user would normally
8080     * start typing on when the go into a window containing your view.
8081     *
8082     * <p>The default implementation always returns false.  This does
8083     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8084     * will not be called or the user can not otherwise perform edits on your
8085     * view; it is just a hint to the system that this is not the primary
8086     * purpose of this view.
8087     *
8088     * @return Returns true if this view is a text editor, else false.
8089     */
8090    public boolean onCheckIsTextEditor() {
8091        return false;
8092    }
8093
8094    /**
8095     * Create a new InputConnection for an InputMethod to interact
8096     * with the view.  The default implementation returns null, since it doesn't
8097     * support input methods.  You can override this to implement such support.
8098     * This is only needed for views that take focus and text input.
8099     *
8100     * <p>When implementing this, you probably also want to implement
8101     * {@link #onCheckIsTextEditor()} to indicate you will return a
8102     * non-null InputConnection.
8103     *
8104     * @param outAttrs Fill in with attribute information about the connection.
8105     */
8106    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8107        return null;
8108    }
8109
8110    /**
8111     * Called by the {@link android.view.inputmethod.InputMethodManager}
8112     * when a view who is not the current
8113     * input connection target is trying to make a call on the manager.  The
8114     * default implementation returns false; you can override this to return
8115     * true for certain views if you are performing InputConnection proxying
8116     * to them.
8117     * @param view The View that is making the InputMethodManager call.
8118     * @return Return true to allow the call, false to reject.
8119     */
8120    public boolean checkInputConnectionProxy(View view) {
8121        return false;
8122    }
8123
8124    /**
8125     * Show the context menu for this view. It is not safe to hold on to the
8126     * menu after returning from this method.
8127     *
8128     * You should normally not overload this method. Overload
8129     * {@link #onCreateContextMenu(ContextMenu)} or define an
8130     * {@link OnCreateContextMenuListener} to add items to the context menu.
8131     *
8132     * @param menu The context menu to populate
8133     */
8134    public void createContextMenu(ContextMenu menu) {
8135        ContextMenuInfo menuInfo = getContextMenuInfo();
8136
8137        // Sets the current menu info so all items added to menu will have
8138        // my extra info set.
8139        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8140
8141        onCreateContextMenu(menu);
8142        ListenerInfo li = mListenerInfo;
8143        if (li != null && li.mOnCreateContextMenuListener != null) {
8144            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8145        }
8146
8147        // Clear the extra information so subsequent items that aren't mine don't
8148        // have my extra info.
8149        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8150
8151        if (mParent != null) {
8152            mParent.createContextMenu(menu);
8153        }
8154    }
8155
8156    /**
8157     * Views should implement this if they have extra information to associate
8158     * with the context menu. The return result is supplied as a parameter to
8159     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8160     * callback.
8161     *
8162     * @return Extra information about the item for which the context menu
8163     *         should be shown. This information will vary across different
8164     *         subclasses of View.
8165     */
8166    protected ContextMenuInfo getContextMenuInfo() {
8167        return null;
8168    }
8169
8170    /**
8171     * Views should implement this if the view itself is going to add items to
8172     * the context menu.
8173     *
8174     * @param menu the context menu to populate
8175     */
8176    protected void onCreateContextMenu(ContextMenu menu) {
8177    }
8178
8179    /**
8180     * Implement this method to handle trackball motion events.  The
8181     * <em>relative</em> movement of the trackball since the last event
8182     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8183     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8184     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8185     * they will often be fractional values, representing the more fine-grained
8186     * movement information available from a trackball).
8187     *
8188     * @param event The motion event.
8189     * @return True if the event was handled, false otherwise.
8190     */
8191    public boolean onTrackballEvent(MotionEvent event) {
8192        return false;
8193    }
8194
8195    /**
8196     * Implement this method to handle generic motion events.
8197     * <p>
8198     * Generic motion events describe joystick movements, mouse hovers, track pad
8199     * touches, scroll wheel movements and other input events.  The
8200     * {@link MotionEvent#getSource() source} of the motion event specifies
8201     * the class of input that was received.  Implementations of this method
8202     * must examine the bits in the source before processing the event.
8203     * The following code example shows how this is done.
8204     * </p><p>
8205     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8206     * are delivered to the view under the pointer.  All other generic motion events are
8207     * delivered to the focused view.
8208     * </p>
8209     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8210     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8211     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8212     *             // process the joystick movement...
8213     *             return true;
8214     *         }
8215     *     }
8216     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8217     *         switch (event.getAction()) {
8218     *             case MotionEvent.ACTION_HOVER_MOVE:
8219     *                 // process the mouse hover movement...
8220     *                 return true;
8221     *             case MotionEvent.ACTION_SCROLL:
8222     *                 // process the scroll wheel movement...
8223     *                 return true;
8224     *         }
8225     *     }
8226     *     return super.onGenericMotionEvent(event);
8227     * }</pre>
8228     *
8229     * @param event The generic motion event being processed.
8230     * @return True if the event was handled, false otherwise.
8231     */
8232    public boolean onGenericMotionEvent(MotionEvent event) {
8233        return false;
8234    }
8235
8236    /**
8237     * Implement this method to handle hover events.
8238     * <p>
8239     * This method is called whenever a pointer is hovering into, over, or out of the
8240     * bounds of a view and the view is not currently being touched.
8241     * Hover events are represented as pointer events with action
8242     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8243     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8244     * </p>
8245     * <ul>
8246     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8247     * when the pointer enters the bounds of the view.</li>
8248     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8249     * when the pointer has already entered the bounds of the view and has moved.</li>
8250     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8251     * when the pointer has exited the bounds of the view or when the pointer is
8252     * about to go down due to a button click, tap, or similar user action that
8253     * causes the view to be touched.</li>
8254     * </ul>
8255     * <p>
8256     * The view should implement this method to return true to indicate that it is
8257     * handling the hover event, such as by changing its drawable state.
8258     * </p><p>
8259     * The default implementation calls {@link #setHovered} to update the hovered state
8260     * of the view when a hover enter or hover exit event is received, if the view
8261     * is enabled and is clickable.  The default implementation also sends hover
8262     * accessibility events.
8263     * </p>
8264     *
8265     * @param event The motion event that describes the hover.
8266     * @return True if the view handled the hover event.
8267     *
8268     * @see #isHovered
8269     * @see #setHovered
8270     * @see #onHoverChanged
8271     */
8272    public boolean onHoverEvent(MotionEvent event) {
8273        // The root view may receive hover (or touch) events that are outside the bounds of
8274        // the window.  This code ensures that we only send accessibility events for
8275        // hovers that are actually within the bounds of the root view.
8276        final int action = event.getActionMasked();
8277        if (!mSendingHoverAccessibilityEvents) {
8278            if ((action == MotionEvent.ACTION_HOVER_ENTER
8279                    || action == MotionEvent.ACTION_HOVER_MOVE)
8280                    && !hasHoveredChild()
8281                    && pointInView(event.getX(), event.getY())) {
8282                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8283                mSendingHoverAccessibilityEvents = true;
8284            }
8285        } else {
8286            if (action == MotionEvent.ACTION_HOVER_EXIT
8287                    || (action == MotionEvent.ACTION_MOVE
8288                            && !pointInView(event.getX(), event.getY()))) {
8289                mSendingHoverAccessibilityEvents = false;
8290                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8291                // If the window does not have input focus we take away accessibility
8292                // focus as soon as the user stop hovering over the view.
8293                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8294                    getViewRootImpl().setAccessibilityFocus(null, null);
8295                }
8296            }
8297        }
8298
8299        if (isHoverable()) {
8300            switch (action) {
8301                case MotionEvent.ACTION_HOVER_ENTER:
8302                    setHovered(true);
8303                    break;
8304                case MotionEvent.ACTION_HOVER_EXIT:
8305                    setHovered(false);
8306                    break;
8307            }
8308
8309            // Dispatch the event to onGenericMotionEvent before returning true.
8310            // This is to provide compatibility with existing applications that
8311            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8312            // break because of the new default handling for hoverable views
8313            // in onHoverEvent.
8314            // Note that onGenericMotionEvent will be called by default when
8315            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8316            dispatchGenericMotionEventInternal(event);
8317            // The event was already handled by calling setHovered(), so always
8318            // return true.
8319            return true;
8320        }
8321
8322        return false;
8323    }
8324
8325    /**
8326     * Returns true if the view should handle {@link #onHoverEvent}
8327     * by calling {@link #setHovered} to change its hovered state.
8328     *
8329     * @return True if the view is hoverable.
8330     */
8331    private boolean isHoverable() {
8332        final int viewFlags = mViewFlags;
8333        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8334            return false;
8335        }
8336
8337        return (viewFlags & CLICKABLE) == CLICKABLE
8338                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8339    }
8340
8341    /**
8342     * Returns true if the view is currently hovered.
8343     *
8344     * @return True if the view is currently hovered.
8345     *
8346     * @see #setHovered
8347     * @see #onHoverChanged
8348     */
8349    @ViewDebug.ExportedProperty
8350    public boolean isHovered() {
8351        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8352    }
8353
8354    /**
8355     * Sets whether the view is currently hovered.
8356     * <p>
8357     * Calling this method also changes the drawable state of the view.  This
8358     * enables the view to react to hover by using different drawable resources
8359     * to change its appearance.
8360     * </p><p>
8361     * The {@link #onHoverChanged} method is called when the hovered state changes.
8362     * </p>
8363     *
8364     * @param hovered True if the view is hovered.
8365     *
8366     * @see #isHovered
8367     * @see #onHoverChanged
8368     */
8369    public void setHovered(boolean hovered) {
8370        if (hovered) {
8371            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8372                mPrivateFlags |= PFLAG_HOVERED;
8373                refreshDrawableState();
8374                onHoverChanged(true);
8375            }
8376        } else {
8377            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8378                mPrivateFlags &= ~PFLAG_HOVERED;
8379                refreshDrawableState();
8380                onHoverChanged(false);
8381            }
8382        }
8383    }
8384
8385    /**
8386     * Implement this method to handle hover state changes.
8387     * <p>
8388     * This method is called whenever the hover state changes as a result of a
8389     * call to {@link #setHovered}.
8390     * </p>
8391     *
8392     * @param hovered The current hover state, as returned by {@link #isHovered}.
8393     *
8394     * @see #isHovered
8395     * @see #setHovered
8396     */
8397    public void onHoverChanged(boolean hovered) {
8398    }
8399
8400    /**
8401     * Implement this method to handle touch screen motion events.
8402     *
8403     * @param event The motion event.
8404     * @return True if the event was handled, false otherwise.
8405     */
8406    public boolean onTouchEvent(MotionEvent event) {
8407        final int viewFlags = mViewFlags;
8408
8409        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8410            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8411                setPressed(false);
8412            }
8413            // A disabled view that is clickable still consumes the touch
8414            // events, it just doesn't respond to them.
8415            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8416                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8417        }
8418
8419        if (mTouchDelegate != null) {
8420            if (mTouchDelegate.onTouchEvent(event)) {
8421                return true;
8422            }
8423        }
8424
8425        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8426                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8427            switch (event.getAction()) {
8428                case MotionEvent.ACTION_UP:
8429                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8430                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8431                        // take focus if we don't have it already and we should in
8432                        // touch mode.
8433                        boolean focusTaken = false;
8434                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8435                            focusTaken = requestFocus();
8436                        }
8437
8438                        if (prepressed) {
8439                            // The button is being released before we actually
8440                            // showed it as pressed.  Make it show the pressed
8441                            // state now (before scheduling the click) to ensure
8442                            // the user sees it.
8443                            setPressed(true);
8444                       }
8445
8446                        if (!mHasPerformedLongPress) {
8447                            // This is a tap, so remove the longpress check
8448                            removeLongPressCallback();
8449
8450                            // Only perform take click actions if we were in the pressed state
8451                            if (!focusTaken) {
8452                                // Use a Runnable and post this rather than calling
8453                                // performClick directly. This lets other visual state
8454                                // of the view update before click actions start.
8455                                if (mPerformClick == null) {
8456                                    mPerformClick = new PerformClick();
8457                                }
8458                                if (!post(mPerformClick)) {
8459                                    performClick();
8460                                }
8461                            }
8462                        }
8463
8464                        if (mUnsetPressedState == null) {
8465                            mUnsetPressedState = new UnsetPressedState();
8466                        }
8467
8468                        if (prepressed) {
8469                            postDelayed(mUnsetPressedState,
8470                                    ViewConfiguration.getPressedStateDuration());
8471                        } else if (!post(mUnsetPressedState)) {
8472                            // If the post failed, unpress right now
8473                            mUnsetPressedState.run();
8474                        }
8475                        removeTapCallback();
8476                    }
8477                    break;
8478
8479                case MotionEvent.ACTION_DOWN:
8480                    mHasPerformedLongPress = false;
8481
8482                    if (performButtonActionOnTouchDown(event)) {
8483                        break;
8484                    }
8485
8486                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8487                    boolean isInScrollingContainer = isInScrollingContainer();
8488
8489                    // For views inside a scrolling container, delay the pressed feedback for
8490                    // a short period in case this is a scroll.
8491                    if (isInScrollingContainer) {
8492                        mPrivateFlags |= PFLAG_PREPRESSED;
8493                        if (mPendingCheckForTap == null) {
8494                            mPendingCheckForTap = new CheckForTap();
8495                        }
8496                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8497                    } else {
8498                        // Not inside a scrolling container, so show the feedback right away
8499                        setPressed(true);
8500                        checkForLongClick(0);
8501                    }
8502                    break;
8503
8504                case MotionEvent.ACTION_CANCEL:
8505                    setPressed(false);
8506                    removeTapCallback();
8507                    removeLongPressCallback();
8508                    break;
8509
8510                case MotionEvent.ACTION_MOVE:
8511                    final int x = (int) event.getX();
8512                    final int y = (int) event.getY();
8513
8514                    // Be lenient about moving outside of buttons
8515                    if (!pointInView(x, y, mTouchSlop)) {
8516                        // Outside button
8517                        removeTapCallback();
8518                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8519                            // Remove any future long press/tap checks
8520                            removeLongPressCallback();
8521
8522                            setPressed(false);
8523                        }
8524                    }
8525                    break;
8526            }
8527            return true;
8528        }
8529
8530        return false;
8531    }
8532
8533    /**
8534     * @hide
8535     */
8536    public boolean isInScrollingContainer() {
8537        ViewParent p = getParent();
8538        while (p != null && p instanceof ViewGroup) {
8539            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8540                return true;
8541            }
8542            p = p.getParent();
8543        }
8544        return false;
8545    }
8546
8547    /**
8548     * Remove the longpress detection timer.
8549     */
8550    private void removeLongPressCallback() {
8551        if (mPendingCheckForLongPress != null) {
8552          removeCallbacks(mPendingCheckForLongPress);
8553        }
8554    }
8555
8556    /**
8557     * Remove the pending click action
8558     */
8559    private void removePerformClickCallback() {
8560        if (mPerformClick != null) {
8561            removeCallbacks(mPerformClick);
8562        }
8563    }
8564
8565    /**
8566     * Remove the prepress detection timer.
8567     */
8568    private void removeUnsetPressCallback() {
8569        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8570            setPressed(false);
8571            removeCallbacks(mUnsetPressedState);
8572        }
8573    }
8574
8575    /**
8576     * Remove the tap detection timer.
8577     */
8578    private void removeTapCallback() {
8579        if (mPendingCheckForTap != null) {
8580            mPrivateFlags &= ~PFLAG_PREPRESSED;
8581            removeCallbacks(mPendingCheckForTap);
8582        }
8583    }
8584
8585    /**
8586     * Cancels a pending long press.  Your subclass can use this if you
8587     * want the context menu to come up if the user presses and holds
8588     * at the same place, but you don't want it to come up if they press
8589     * and then move around enough to cause scrolling.
8590     */
8591    public void cancelLongPress() {
8592        removeLongPressCallback();
8593
8594        /*
8595         * The prepressed state handled by the tap callback is a display
8596         * construct, but the tap callback will post a long press callback
8597         * less its own timeout. Remove it here.
8598         */
8599        removeTapCallback();
8600    }
8601
8602    /**
8603     * Remove the pending callback for sending a
8604     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8605     */
8606    private void removeSendViewScrolledAccessibilityEventCallback() {
8607        if (mSendViewScrolledAccessibilityEvent != null) {
8608            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8609            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8610        }
8611    }
8612
8613    /**
8614     * Sets the TouchDelegate for this View.
8615     */
8616    public void setTouchDelegate(TouchDelegate delegate) {
8617        mTouchDelegate = delegate;
8618    }
8619
8620    /**
8621     * Gets the TouchDelegate for this View.
8622     */
8623    public TouchDelegate getTouchDelegate() {
8624        return mTouchDelegate;
8625    }
8626
8627    /**
8628     * Set flags controlling behavior of this view.
8629     *
8630     * @param flags Constant indicating the value which should be set
8631     * @param mask Constant indicating the bit range that should be changed
8632     */
8633    void setFlags(int flags, int mask) {
8634        final boolean accessibilityEnabled =
8635                AccessibilityManager.getInstance(mContext).isEnabled();
8636        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8637
8638        int old = mViewFlags;
8639        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8640
8641        int changed = mViewFlags ^ old;
8642        if (changed == 0) {
8643            return;
8644        }
8645        int privateFlags = mPrivateFlags;
8646
8647        /* Check if the FOCUSABLE bit has changed */
8648        if (((changed & FOCUSABLE_MASK) != 0) &&
8649                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8650            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8651                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8652                /* Give up focus if we are no longer focusable */
8653                clearFocus();
8654            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8655                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8656                /*
8657                 * Tell the view system that we are now available to take focus
8658                 * if no one else already has it.
8659                 */
8660                if (mParent != null) mParent.focusableViewAvailable(this);
8661            }
8662        }
8663
8664        final int newVisibility = flags & VISIBILITY_MASK;
8665        if (newVisibility == VISIBLE) {
8666            if ((changed & VISIBILITY_MASK) != 0) {
8667                /*
8668                 * If this view is becoming visible, invalidate it in case it changed while
8669                 * it was not visible. Marking it drawn ensures that the invalidation will
8670                 * go through.
8671                 */
8672                mPrivateFlags |= PFLAG_DRAWN;
8673                invalidate(true);
8674
8675                needGlobalAttributesUpdate(true);
8676
8677                // a view becoming visible is worth notifying the parent
8678                // about in case nothing has focus.  even if this specific view
8679                // isn't focusable, it may contain something that is, so let
8680                // the root view try to give this focus if nothing else does.
8681                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8682                    mParent.focusableViewAvailable(this);
8683                }
8684            }
8685        }
8686
8687        /* Check if the GONE bit has changed */
8688        if ((changed & GONE) != 0) {
8689            needGlobalAttributesUpdate(false);
8690            requestLayout();
8691
8692            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8693                if (hasFocus()) clearFocus();
8694                clearAccessibilityFocus();
8695                destroyDrawingCache();
8696                if (mParent instanceof View) {
8697                    // GONE views noop invalidation, so invalidate the parent
8698                    ((View) mParent).invalidate(true);
8699                }
8700                // Mark the view drawn to ensure that it gets invalidated properly the next
8701                // time it is visible and gets invalidated
8702                mPrivateFlags |= PFLAG_DRAWN;
8703            }
8704            if (mAttachInfo != null) {
8705                mAttachInfo.mViewVisibilityChanged = true;
8706            }
8707        }
8708
8709        /* Check if the VISIBLE bit has changed */
8710        if ((changed & INVISIBLE) != 0) {
8711            needGlobalAttributesUpdate(false);
8712            /*
8713             * If this view is becoming invisible, set the DRAWN flag so that
8714             * the next invalidate() will not be skipped.
8715             */
8716            mPrivateFlags |= PFLAG_DRAWN;
8717
8718            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8719                // root view becoming invisible shouldn't clear focus and accessibility focus
8720                if (getRootView() != this) {
8721                    clearFocus();
8722                    clearAccessibilityFocus();
8723                }
8724            }
8725            if (mAttachInfo != null) {
8726                mAttachInfo.mViewVisibilityChanged = true;
8727            }
8728        }
8729
8730        if ((changed & VISIBILITY_MASK) != 0) {
8731            // If the view is invisible, cleanup its display list to free up resources
8732            if (newVisibility != VISIBLE) {
8733                cleanupDraw();
8734            }
8735
8736            if (mParent instanceof ViewGroup) {
8737                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8738                        (changed & VISIBILITY_MASK), newVisibility);
8739                ((View) mParent).invalidate(true);
8740            } else if (mParent != null) {
8741                mParent.invalidateChild(this, null);
8742            }
8743            dispatchVisibilityChanged(this, newVisibility);
8744        }
8745
8746        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8747            destroyDrawingCache();
8748        }
8749
8750        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8751            destroyDrawingCache();
8752            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8753            invalidateParentCaches();
8754        }
8755
8756        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8757            destroyDrawingCache();
8758            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8759        }
8760
8761        if ((changed & DRAW_MASK) != 0) {
8762            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8763                if (mBackground != null) {
8764                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8765                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8766                } else {
8767                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8768                }
8769            } else {
8770                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8771            }
8772            requestLayout();
8773            invalidate(true);
8774        }
8775
8776        if ((changed & KEEP_SCREEN_ON) != 0) {
8777            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8778                mParent.recomputeViewAttributes(this);
8779            }
8780        }
8781
8782        if (accessibilityEnabled) {
8783            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
8784                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
8785                if (oldIncludeForAccessibility != includeForAccessibility()) {
8786                    notifySubtreeAccessibilityStateChangedIfNeeded();
8787                } else {
8788                    notifyViewAccessibilityStateChangedIfNeeded();
8789                }
8790            }
8791            if ((changed & ENABLED_MASK) != 0) {
8792                notifyViewAccessibilityStateChangedIfNeeded();
8793            }
8794        }
8795    }
8796
8797    /**
8798     * Change the view's z order in the tree, so it's on top of other sibling
8799     * views. This ordering change may affect layout, if the parent container
8800     * uses an order-dependent layout scheme (e.g., LinearLayout). This
8801     * method should be followed by calls to {@link #requestLayout()} and
8802     * {@link View#invalidate()} on the parent.
8803     *
8804     * @see ViewGroup#bringChildToFront(View)
8805     */
8806    public void bringToFront() {
8807        if (mParent != null) {
8808            mParent.bringChildToFront(this);
8809        }
8810    }
8811
8812    /**
8813     * This is called in response to an internal scroll in this view (i.e., the
8814     * view scrolled its own contents). This is typically as a result of
8815     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8816     * called.
8817     *
8818     * @param l Current horizontal scroll origin.
8819     * @param t Current vertical scroll origin.
8820     * @param oldl Previous horizontal scroll origin.
8821     * @param oldt Previous vertical scroll origin.
8822     */
8823    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8824        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8825            postSendViewScrolledAccessibilityEventCallback();
8826        }
8827
8828        mBackgroundSizeChanged = true;
8829
8830        final AttachInfo ai = mAttachInfo;
8831        if (ai != null) {
8832            ai.mViewScrollChanged = true;
8833        }
8834    }
8835
8836    /**
8837     * Interface definition for a callback to be invoked when the layout bounds of a view
8838     * changes due to layout processing.
8839     */
8840    public interface OnLayoutChangeListener {
8841        /**
8842         * Called when the focus state of a view has changed.
8843         *
8844         * @param v The view whose state has changed.
8845         * @param left The new value of the view's left property.
8846         * @param top The new value of the view's top property.
8847         * @param right The new value of the view's right property.
8848         * @param bottom The new value of the view's bottom property.
8849         * @param oldLeft The previous value of the view's left property.
8850         * @param oldTop The previous value of the view's top property.
8851         * @param oldRight The previous value of the view's right property.
8852         * @param oldBottom The previous value of the view's bottom property.
8853         */
8854        void onLayoutChange(View v, int left, int top, int right, int bottom,
8855            int oldLeft, int oldTop, int oldRight, int oldBottom);
8856    }
8857
8858    /**
8859     * This is called during layout when the size of this view has changed. If
8860     * you were just added to the view hierarchy, you're called with the old
8861     * values of 0.
8862     *
8863     * @param w Current width of this view.
8864     * @param h Current height of this view.
8865     * @param oldw Old width of this view.
8866     * @param oldh Old height of this view.
8867     */
8868    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8869    }
8870
8871    /**
8872     * Called by draw to draw the child views. This may be overridden
8873     * by derived classes to gain control just before its children are drawn
8874     * (but after its own view has been drawn).
8875     * @param canvas the canvas on which to draw the view
8876     */
8877    protected void dispatchDraw(Canvas canvas) {
8878
8879    }
8880
8881    /**
8882     * Gets the parent of this view. Note that the parent is a
8883     * ViewParent and not necessarily a View.
8884     *
8885     * @return Parent of this view.
8886     */
8887    public final ViewParent getParent() {
8888        return mParent;
8889    }
8890
8891    /**
8892     * Set the horizontal scrolled position of your view. This will cause a call to
8893     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8894     * invalidated.
8895     * @param value the x position to scroll to
8896     */
8897    public void setScrollX(int value) {
8898        scrollTo(value, mScrollY);
8899    }
8900
8901    /**
8902     * Set the vertical scrolled position of your view. This will cause a call to
8903     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8904     * invalidated.
8905     * @param value the y position to scroll to
8906     */
8907    public void setScrollY(int value) {
8908        scrollTo(mScrollX, value);
8909    }
8910
8911    /**
8912     * Return the scrolled left position of this view. This is the left edge of
8913     * the displayed part of your view. You do not need to draw any pixels
8914     * farther left, since those are outside of the frame of your view on
8915     * screen.
8916     *
8917     * @return The left edge of the displayed part of your view, in pixels.
8918     */
8919    public final int getScrollX() {
8920        return mScrollX;
8921    }
8922
8923    /**
8924     * Return the scrolled top position of this view. This is the top edge of
8925     * the displayed part of your view. You do not need to draw any pixels above
8926     * it, since those are outside of the frame of your view on screen.
8927     *
8928     * @return The top edge of the displayed part of your view, in pixels.
8929     */
8930    public final int getScrollY() {
8931        return mScrollY;
8932    }
8933
8934    /**
8935     * Return the width of the your view.
8936     *
8937     * @return The width of your view, in pixels.
8938     */
8939    @ViewDebug.ExportedProperty(category = "layout")
8940    public final int getWidth() {
8941        return mRight - mLeft;
8942    }
8943
8944    /**
8945     * Return the height of your view.
8946     *
8947     * @return The height of your view, in pixels.
8948     */
8949    @ViewDebug.ExportedProperty(category = "layout")
8950    public final int getHeight() {
8951        return mBottom - mTop;
8952    }
8953
8954    /**
8955     * Return the visible drawing bounds of your view. Fills in the output
8956     * rectangle with the values from getScrollX(), getScrollY(),
8957     * getWidth(), and getHeight(). These bounds do not account for any
8958     * transformation properties currently set on the view, such as
8959     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8960     *
8961     * @param outRect The (scrolled) drawing bounds of the view.
8962     */
8963    public void getDrawingRect(Rect outRect) {
8964        outRect.left = mScrollX;
8965        outRect.top = mScrollY;
8966        outRect.right = mScrollX + (mRight - mLeft);
8967        outRect.bottom = mScrollY + (mBottom - mTop);
8968    }
8969
8970    /**
8971     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8972     * raw width component (that is the result is masked by
8973     * {@link #MEASURED_SIZE_MASK}).
8974     *
8975     * @return The raw measured width of this view.
8976     */
8977    public final int getMeasuredWidth() {
8978        return mMeasuredWidth & MEASURED_SIZE_MASK;
8979    }
8980
8981    /**
8982     * Return the full width measurement information for this view as computed
8983     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8984     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8985     * This should be used during measurement and layout calculations only. Use
8986     * {@link #getWidth()} to see how wide a view is after layout.
8987     *
8988     * @return The measured width of this view as a bit mask.
8989     */
8990    public final int getMeasuredWidthAndState() {
8991        return mMeasuredWidth;
8992    }
8993
8994    /**
8995     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8996     * raw width component (that is the result is masked by
8997     * {@link #MEASURED_SIZE_MASK}).
8998     *
8999     * @return The raw measured height of this view.
9000     */
9001    public final int getMeasuredHeight() {
9002        return mMeasuredHeight & MEASURED_SIZE_MASK;
9003    }
9004
9005    /**
9006     * Return the full height measurement information for this view as computed
9007     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9008     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9009     * This should be used during measurement and layout calculations only. Use
9010     * {@link #getHeight()} to see how wide a view is after layout.
9011     *
9012     * @return The measured width of this view as a bit mask.
9013     */
9014    public final int getMeasuredHeightAndState() {
9015        return mMeasuredHeight;
9016    }
9017
9018    /**
9019     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9020     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9021     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9022     * and the height component is at the shifted bits
9023     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9024     */
9025    public final int getMeasuredState() {
9026        return (mMeasuredWidth&MEASURED_STATE_MASK)
9027                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9028                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9029    }
9030
9031    /**
9032     * The transform matrix of this view, which is calculated based on the current
9033     * roation, scale, and pivot properties.
9034     *
9035     * @see #getRotation()
9036     * @see #getScaleX()
9037     * @see #getScaleY()
9038     * @see #getPivotX()
9039     * @see #getPivotY()
9040     * @return The current transform matrix for the view
9041     */
9042    public Matrix getMatrix() {
9043        if (mTransformationInfo != null) {
9044            updateMatrix();
9045            return mTransformationInfo.mMatrix;
9046        }
9047        return Matrix.IDENTITY_MATRIX;
9048    }
9049
9050    /**
9051     * Utility function to determine if the value is far enough away from zero to be
9052     * considered non-zero.
9053     * @param value A floating point value to check for zero-ness
9054     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9055     */
9056    private static boolean nonzero(float value) {
9057        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9058    }
9059
9060    /**
9061     * Returns true if the transform matrix is the identity matrix.
9062     * Recomputes the matrix if necessary.
9063     *
9064     * @return True if the transform matrix is the identity matrix, false otherwise.
9065     */
9066    final boolean hasIdentityMatrix() {
9067        if (mTransformationInfo != null) {
9068            updateMatrix();
9069            return mTransformationInfo.mMatrixIsIdentity;
9070        }
9071        return true;
9072    }
9073
9074    void ensureTransformationInfo() {
9075        if (mTransformationInfo == null) {
9076            mTransformationInfo = new TransformationInfo();
9077        }
9078    }
9079
9080    /**
9081     * Recomputes the transform matrix if necessary.
9082     */
9083    private void updateMatrix() {
9084        final TransformationInfo info = mTransformationInfo;
9085        if (info == null) {
9086            return;
9087        }
9088        if (info.mMatrixDirty) {
9089            // transform-related properties have changed since the last time someone
9090            // asked for the matrix; recalculate it with the current values
9091
9092            // Figure out if we need to update the pivot point
9093            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9094                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9095                    info.mPrevWidth = mRight - mLeft;
9096                    info.mPrevHeight = mBottom - mTop;
9097                    info.mPivotX = info.mPrevWidth / 2f;
9098                    info.mPivotY = info.mPrevHeight / 2f;
9099                }
9100            }
9101            info.mMatrix.reset();
9102            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9103                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9104                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9105                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9106            } else {
9107                if (info.mCamera == null) {
9108                    info.mCamera = new Camera();
9109                    info.matrix3D = new Matrix();
9110                }
9111                info.mCamera.save();
9112                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9113                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9114                info.mCamera.getMatrix(info.matrix3D);
9115                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9116                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9117                        info.mPivotY + info.mTranslationY);
9118                info.mMatrix.postConcat(info.matrix3D);
9119                info.mCamera.restore();
9120            }
9121            info.mMatrixDirty = false;
9122            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9123            info.mInverseMatrixDirty = true;
9124        }
9125    }
9126
9127   /**
9128     * Utility method to retrieve the inverse of the current mMatrix property.
9129     * We cache the matrix to avoid recalculating it when transform properties
9130     * have not changed.
9131     *
9132     * @return The inverse of the current matrix of this view.
9133     */
9134    final Matrix getInverseMatrix() {
9135        final TransformationInfo info = mTransformationInfo;
9136        if (info != null) {
9137            updateMatrix();
9138            if (info.mInverseMatrixDirty) {
9139                if (info.mInverseMatrix == null) {
9140                    info.mInverseMatrix = new Matrix();
9141                }
9142                info.mMatrix.invert(info.mInverseMatrix);
9143                info.mInverseMatrixDirty = false;
9144            }
9145            return info.mInverseMatrix;
9146        }
9147        return Matrix.IDENTITY_MATRIX;
9148    }
9149
9150    /**
9151     * Gets the distance along the Z axis from the camera to this view.
9152     *
9153     * @see #setCameraDistance(float)
9154     *
9155     * @return The distance along the Z axis.
9156     */
9157    public float getCameraDistance() {
9158        ensureTransformationInfo();
9159        final float dpi = mResources.getDisplayMetrics().densityDpi;
9160        final TransformationInfo info = mTransformationInfo;
9161        if (info.mCamera == null) {
9162            info.mCamera = new Camera();
9163            info.matrix3D = new Matrix();
9164        }
9165        return -(info.mCamera.getLocationZ() * dpi);
9166    }
9167
9168    /**
9169     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9170     * views are drawn) from the camera to this view. The camera's distance
9171     * affects 3D transformations, for instance rotations around the X and Y
9172     * axis. If the rotationX or rotationY properties are changed and this view is
9173     * large (more than half the size of the screen), it is recommended to always
9174     * use a camera distance that's greater than the height (X axis rotation) or
9175     * the width (Y axis rotation) of this view.</p>
9176     *
9177     * <p>The distance of the camera from the view plane can have an affect on the
9178     * perspective distortion of the view when it is rotated around the x or y axis.
9179     * For example, a large distance will result in a large viewing angle, and there
9180     * will not be much perspective distortion of the view as it rotates. A short
9181     * distance may cause much more perspective distortion upon rotation, and can
9182     * also result in some drawing artifacts if the rotated view ends up partially
9183     * behind the camera (which is why the recommendation is to use a distance at
9184     * least as far as the size of the view, if the view is to be rotated.)</p>
9185     *
9186     * <p>The distance is expressed in "depth pixels." The default distance depends
9187     * on the screen density. For instance, on a medium density display, the
9188     * default distance is 1280. On a high density display, the default distance
9189     * is 1920.</p>
9190     *
9191     * <p>If you want to specify a distance that leads to visually consistent
9192     * results across various densities, use the following formula:</p>
9193     * <pre>
9194     * float scale = context.getResources().getDisplayMetrics().density;
9195     * view.setCameraDistance(distance * scale);
9196     * </pre>
9197     *
9198     * <p>The density scale factor of a high density display is 1.5,
9199     * and 1920 = 1280 * 1.5.</p>
9200     *
9201     * @param distance The distance in "depth pixels", if negative the opposite
9202     *        value is used
9203     *
9204     * @see #setRotationX(float)
9205     * @see #setRotationY(float)
9206     */
9207    public void setCameraDistance(float distance) {
9208        invalidateViewProperty(true, false);
9209
9210        ensureTransformationInfo();
9211        final float dpi = mResources.getDisplayMetrics().densityDpi;
9212        final TransformationInfo info = mTransformationInfo;
9213        if (info.mCamera == null) {
9214            info.mCamera = new Camera();
9215            info.matrix3D = new Matrix();
9216        }
9217
9218        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9219        info.mMatrixDirty = true;
9220
9221        invalidateViewProperty(false, false);
9222        if (mDisplayList != null) {
9223            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9224        }
9225        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9226            // View was rejected last time it was drawn by its parent; this may have changed
9227            invalidateParentIfNeeded();
9228        }
9229    }
9230
9231    /**
9232     * The degrees that the view is rotated around the pivot point.
9233     *
9234     * @see #setRotation(float)
9235     * @see #getPivotX()
9236     * @see #getPivotY()
9237     *
9238     * @return The degrees of rotation.
9239     */
9240    @ViewDebug.ExportedProperty(category = "drawing")
9241    public float getRotation() {
9242        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9243    }
9244
9245    /**
9246     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9247     * result in clockwise rotation.
9248     *
9249     * @param rotation The degrees of rotation.
9250     *
9251     * @see #getRotation()
9252     * @see #getPivotX()
9253     * @see #getPivotY()
9254     * @see #setRotationX(float)
9255     * @see #setRotationY(float)
9256     *
9257     * @attr ref android.R.styleable#View_rotation
9258     */
9259    public void setRotation(float rotation) {
9260        ensureTransformationInfo();
9261        final TransformationInfo info = mTransformationInfo;
9262        if (info.mRotation != rotation) {
9263            // Double-invalidation is necessary to capture view's old and new areas
9264            invalidateViewProperty(true, false);
9265            info.mRotation = rotation;
9266            info.mMatrixDirty = true;
9267            invalidateViewProperty(false, true);
9268            if (mDisplayList != null) {
9269                mDisplayList.setRotation(rotation);
9270            }
9271            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9272                // View was rejected last time it was drawn by its parent; this may have changed
9273                invalidateParentIfNeeded();
9274            }
9275        }
9276    }
9277
9278    /**
9279     * The degrees that the view is rotated around the vertical axis through the pivot point.
9280     *
9281     * @see #getPivotX()
9282     * @see #getPivotY()
9283     * @see #setRotationY(float)
9284     *
9285     * @return The degrees of Y rotation.
9286     */
9287    @ViewDebug.ExportedProperty(category = "drawing")
9288    public float getRotationY() {
9289        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9290    }
9291
9292    /**
9293     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9294     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9295     * down the y axis.
9296     *
9297     * When rotating large views, it is recommended to adjust the camera distance
9298     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9299     *
9300     * @param rotationY The degrees of Y rotation.
9301     *
9302     * @see #getRotationY()
9303     * @see #getPivotX()
9304     * @see #getPivotY()
9305     * @see #setRotation(float)
9306     * @see #setRotationX(float)
9307     * @see #setCameraDistance(float)
9308     *
9309     * @attr ref android.R.styleable#View_rotationY
9310     */
9311    public void setRotationY(float rotationY) {
9312        ensureTransformationInfo();
9313        final TransformationInfo info = mTransformationInfo;
9314        if (info.mRotationY != rotationY) {
9315            invalidateViewProperty(true, false);
9316            info.mRotationY = rotationY;
9317            info.mMatrixDirty = true;
9318            invalidateViewProperty(false, true);
9319            if (mDisplayList != null) {
9320                mDisplayList.setRotationY(rotationY);
9321            }
9322            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9323                // View was rejected last time it was drawn by its parent; this may have changed
9324                invalidateParentIfNeeded();
9325            }
9326        }
9327    }
9328
9329    /**
9330     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9331     *
9332     * @see #getPivotX()
9333     * @see #getPivotY()
9334     * @see #setRotationX(float)
9335     *
9336     * @return The degrees of X rotation.
9337     */
9338    @ViewDebug.ExportedProperty(category = "drawing")
9339    public float getRotationX() {
9340        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9341    }
9342
9343    /**
9344     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9345     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9346     * x axis.
9347     *
9348     * When rotating large views, it is recommended to adjust the camera distance
9349     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9350     *
9351     * @param rotationX The degrees of X rotation.
9352     *
9353     * @see #getRotationX()
9354     * @see #getPivotX()
9355     * @see #getPivotY()
9356     * @see #setRotation(float)
9357     * @see #setRotationY(float)
9358     * @see #setCameraDistance(float)
9359     *
9360     * @attr ref android.R.styleable#View_rotationX
9361     */
9362    public void setRotationX(float rotationX) {
9363        ensureTransformationInfo();
9364        final TransformationInfo info = mTransformationInfo;
9365        if (info.mRotationX != rotationX) {
9366            invalidateViewProperty(true, false);
9367            info.mRotationX = rotationX;
9368            info.mMatrixDirty = true;
9369            invalidateViewProperty(false, true);
9370            if (mDisplayList != null) {
9371                mDisplayList.setRotationX(rotationX);
9372            }
9373            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9374                // View was rejected last time it was drawn by its parent; this may have changed
9375                invalidateParentIfNeeded();
9376            }
9377        }
9378    }
9379
9380    /**
9381     * The amount that the view is scaled in x around the pivot point, as a proportion of
9382     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9383     *
9384     * <p>By default, this is 1.0f.
9385     *
9386     * @see #getPivotX()
9387     * @see #getPivotY()
9388     * @return The scaling factor.
9389     */
9390    @ViewDebug.ExportedProperty(category = "drawing")
9391    public float getScaleX() {
9392        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9393    }
9394
9395    /**
9396     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9397     * the view's unscaled width. A value of 1 means that no scaling is applied.
9398     *
9399     * @param scaleX The scaling factor.
9400     * @see #getPivotX()
9401     * @see #getPivotY()
9402     *
9403     * @attr ref android.R.styleable#View_scaleX
9404     */
9405    public void setScaleX(float scaleX) {
9406        ensureTransformationInfo();
9407        final TransformationInfo info = mTransformationInfo;
9408        if (info.mScaleX != scaleX) {
9409            invalidateViewProperty(true, false);
9410            info.mScaleX = scaleX;
9411            info.mMatrixDirty = true;
9412            invalidateViewProperty(false, true);
9413            if (mDisplayList != null) {
9414                mDisplayList.setScaleX(scaleX);
9415            }
9416            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9417                // View was rejected last time it was drawn by its parent; this may have changed
9418                invalidateParentIfNeeded();
9419            }
9420        }
9421    }
9422
9423    /**
9424     * The amount that the view is scaled in y around the pivot point, as a proportion of
9425     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9426     *
9427     * <p>By default, this is 1.0f.
9428     *
9429     * @see #getPivotX()
9430     * @see #getPivotY()
9431     * @return The scaling factor.
9432     */
9433    @ViewDebug.ExportedProperty(category = "drawing")
9434    public float getScaleY() {
9435        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9436    }
9437
9438    /**
9439     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9440     * the view's unscaled width. A value of 1 means that no scaling is applied.
9441     *
9442     * @param scaleY The scaling factor.
9443     * @see #getPivotX()
9444     * @see #getPivotY()
9445     *
9446     * @attr ref android.R.styleable#View_scaleY
9447     */
9448    public void setScaleY(float scaleY) {
9449        ensureTransformationInfo();
9450        final TransformationInfo info = mTransformationInfo;
9451        if (info.mScaleY != scaleY) {
9452            invalidateViewProperty(true, false);
9453            info.mScaleY = scaleY;
9454            info.mMatrixDirty = true;
9455            invalidateViewProperty(false, true);
9456            if (mDisplayList != null) {
9457                mDisplayList.setScaleY(scaleY);
9458            }
9459            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9460                // View was rejected last time it was drawn by its parent; this may have changed
9461                invalidateParentIfNeeded();
9462            }
9463        }
9464    }
9465
9466    /**
9467     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9468     * and {@link #setScaleX(float) scaled}.
9469     *
9470     * @see #getRotation()
9471     * @see #getScaleX()
9472     * @see #getScaleY()
9473     * @see #getPivotY()
9474     * @return The x location of the pivot point.
9475     *
9476     * @attr ref android.R.styleable#View_transformPivotX
9477     */
9478    @ViewDebug.ExportedProperty(category = "drawing")
9479    public float getPivotX() {
9480        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9481    }
9482
9483    /**
9484     * Sets the x location of the point around which the view is
9485     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9486     * By default, the pivot point is centered on the object.
9487     * Setting this property disables this behavior and causes the view to use only the
9488     * explicitly set pivotX and pivotY values.
9489     *
9490     * @param pivotX The x location of the pivot point.
9491     * @see #getRotation()
9492     * @see #getScaleX()
9493     * @see #getScaleY()
9494     * @see #getPivotY()
9495     *
9496     * @attr ref android.R.styleable#View_transformPivotX
9497     */
9498    public void setPivotX(float pivotX) {
9499        ensureTransformationInfo();
9500        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9501        final TransformationInfo info = mTransformationInfo;
9502        if (info.mPivotX != pivotX) {
9503            invalidateViewProperty(true, false);
9504            info.mPivotX = pivotX;
9505            info.mMatrixDirty = true;
9506            invalidateViewProperty(false, true);
9507            if (mDisplayList != null) {
9508                mDisplayList.setPivotX(pivotX);
9509            }
9510            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9511                // View was rejected last time it was drawn by its parent; this may have changed
9512                invalidateParentIfNeeded();
9513            }
9514        }
9515    }
9516
9517    /**
9518     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9519     * and {@link #setScaleY(float) scaled}.
9520     *
9521     * @see #getRotation()
9522     * @see #getScaleX()
9523     * @see #getScaleY()
9524     * @see #getPivotY()
9525     * @return The y location of the pivot point.
9526     *
9527     * @attr ref android.R.styleable#View_transformPivotY
9528     */
9529    @ViewDebug.ExportedProperty(category = "drawing")
9530    public float getPivotY() {
9531        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9532    }
9533
9534    /**
9535     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9536     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9537     * Setting this property disables this behavior and causes the view to use only the
9538     * explicitly set pivotX and pivotY values.
9539     *
9540     * @param pivotY The y location of the pivot point.
9541     * @see #getRotation()
9542     * @see #getScaleX()
9543     * @see #getScaleY()
9544     * @see #getPivotY()
9545     *
9546     * @attr ref android.R.styleable#View_transformPivotY
9547     */
9548    public void setPivotY(float pivotY) {
9549        ensureTransformationInfo();
9550        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9551        final TransformationInfo info = mTransformationInfo;
9552        if (info.mPivotY != pivotY) {
9553            invalidateViewProperty(true, false);
9554            info.mPivotY = pivotY;
9555            info.mMatrixDirty = true;
9556            invalidateViewProperty(false, true);
9557            if (mDisplayList != null) {
9558                mDisplayList.setPivotY(pivotY);
9559            }
9560            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9561                // View was rejected last time it was drawn by its parent; this may have changed
9562                invalidateParentIfNeeded();
9563            }
9564        }
9565    }
9566
9567    /**
9568     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9569     * completely transparent and 1 means the view is completely opaque.
9570     *
9571     * <p>By default this is 1.0f.
9572     * @return The opacity of the view.
9573     */
9574    @ViewDebug.ExportedProperty(category = "drawing")
9575    public float getAlpha() {
9576        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9577    }
9578
9579    /**
9580     * Returns whether this View has content which overlaps. This function, intended to be
9581     * overridden by specific View types, is an optimization when alpha is set on a view. If
9582     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9583     * and then composited it into place, which can be expensive. If the view has no overlapping
9584     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9585     * An example of overlapping rendering is a TextView with a background image, such as a
9586     * Button. An example of non-overlapping rendering is a TextView with no background, or
9587     * an ImageView with only the foreground image. The default implementation returns true;
9588     * subclasses should override if they have cases which can be optimized.
9589     *
9590     * @return true if the content in this view might overlap, false otherwise.
9591     */
9592    public boolean hasOverlappingRendering() {
9593        return true;
9594    }
9595
9596    /**
9597     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9598     * completely transparent and 1 means the view is completely opaque.</p>
9599     *
9600     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9601     * performance implications, especially for large views. It is best to use the alpha property
9602     * sparingly and transiently, as in the case of fading animations.</p>
9603     *
9604     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9605     * strongly recommended for performance reasons to either override
9606     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9607     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9608     *
9609     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9610     * responsible for applying the opacity itself.</p>
9611     *
9612     * <p>Note that if the view is backed by a
9613     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9614     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9615     * 1.0 will supercede the alpha of the layer paint.</p>
9616     *
9617     * @param alpha The opacity of the view.
9618     *
9619     * @see #hasOverlappingRendering()
9620     * @see #setLayerType(int, android.graphics.Paint)
9621     *
9622     * @attr ref android.R.styleable#View_alpha
9623     */
9624    public void setAlpha(float alpha) {
9625        ensureTransformationInfo();
9626        if (mTransformationInfo.mAlpha != alpha) {
9627            mTransformationInfo.mAlpha = alpha;
9628            if (onSetAlpha((int) (alpha * 255))) {
9629                mPrivateFlags |= PFLAG_ALPHA_SET;
9630                // subclass is handling alpha - don't optimize rendering cache invalidation
9631                invalidateParentCaches();
9632                invalidate(true);
9633            } else {
9634                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9635                invalidateViewProperty(true, false);
9636                if (mDisplayList != null) {
9637                    mDisplayList.setAlpha(alpha);
9638                }
9639            }
9640        }
9641    }
9642
9643    /**
9644     * Faster version of setAlpha() which performs the same steps except there are
9645     * no calls to invalidate(). The caller of this function should perform proper invalidation
9646     * on the parent and this object. The return value indicates whether the subclass handles
9647     * alpha (the return value for onSetAlpha()).
9648     *
9649     * @param alpha The new value for the alpha property
9650     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9651     *         the new value for the alpha property is different from the old value
9652     */
9653    boolean setAlphaNoInvalidation(float alpha) {
9654        ensureTransformationInfo();
9655        if (mTransformationInfo.mAlpha != alpha) {
9656            mTransformationInfo.mAlpha = alpha;
9657            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9658            if (subclassHandlesAlpha) {
9659                mPrivateFlags |= PFLAG_ALPHA_SET;
9660                return true;
9661            } else {
9662                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9663                if (mDisplayList != null) {
9664                    mDisplayList.setAlpha(alpha);
9665                }
9666            }
9667        }
9668        return false;
9669    }
9670
9671    /**
9672     * Top position of this view relative to its parent.
9673     *
9674     * @return The top of this view, in pixels.
9675     */
9676    @ViewDebug.CapturedViewProperty
9677    public final int getTop() {
9678        return mTop;
9679    }
9680
9681    /**
9682     * Sets the top position of this view relative to its parent. This method is meant to be called
9683     * by the layout system and should not generally be called otherwise, because the property
9684     * may be changed at any time by the layout.
9685     *
9686     * @param top The top of this view, in pixels.
9687     */
9688    public final void setTop(int top) {
9689        if (top != mTop) {
9690            updateMatrix();
9691            final boolean matrixIsIdentity = mTransformationInfo == null
9692                    || mTransformationInfo.mMatrixIsIdentity;
9693            if (matrixIsIdentity) {
9694                if (mAttachInfo != null) {
9695                    int minTop;
9696                    int yLoc;
9697                    if (top < mTop) {
9698                        minTop = top;
9699                        yLoc = top - mTop;
9700                    } else {
9701                        minTop = mTop;
9702                        yLoc = 0;
9703                    }
9704                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9705                }
9706            } else {
9707                // Double-invalidation is necessary to capture view's old and new areas
9708                invalidate(true);
9709            }
9710
9711            int width = mRight - mLeft;
9712            int oldHeight = mBottom - mTop;
9713
9714            mTop = top;
9715            if (mDisplayList != null) {
9716                mDisplayList.setTop(mTop);
9717            }
9718
9719            sizeChange(width, mBottom - mTop, width, oldHeight);
9720
9721            if (!matrixIsIdentity) {
9722                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9723                    // A change in dimension means an auto-centered pivot point changes, too
9724                    mTransformationInfo.mMatrixDirty = true;
9725                }
9726                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9727                invalidate(true);
9728            }
9729            mBackgroundSizeChanged = true;
9730            invalidateParentIfNeeded();
9731            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9732                // View was rejected last time it was drawn by its parent; this may have changed
9733                invalidateParentIfNeeded();
9734            }
9735        }
9736    }
9737
9738    /**
9739     * Bottom position of this view relative to its parent.
9740     *
9741     * @return The bottom of this view, in pixels.
9742     */
9743    @ViewDebug.CapturedViewProperty
9744    public final int getBottom() {
9745        return mBottom;
9746    }
9747
9748    /**
9749     * True if this view has changed since the last time being drawn.
9750     *
9751     * @return The dirty state of this view.
9752     */
9753    public boolean isDirty() {
9754        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9755    }
9756
9757    /**
9758     * Sets the bottom position of this view relative to its parent. This method is meant to be
9759     * called by the layout system and should not generally be called otherwise, because the
9760     * property may be changed at any time by the layout.
9761     *
9762     * @param bottom The bottom of this view, in pixels.
9763     */
9764    public final void setBottom(int bottom) {
9765        if (bottom != mBottom) {
9766            updateMatrix();
9767            final boolean matrixIsIdentity = mTransformationInfo == null
9768                    || mTransformationInfo.mMatrixIsIdentity;
9769            if (matrixIsIdentity) {
9770                if (mAttachInfo != null) {
9771                    int maxBottom;
9772                    if (bottom < mBottom) {
9773                        maxBottom = mBottom;
9774                    } else {
9775                        maxBottom = bottom;
9776                    }
9777                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9778                }
9779            } else {
9780                // Double-invalidation is necessary to capture view's old and new areas
9781                invalidate(true);
9782            }
9783
9784            int width = mRight - mLeft;
9785            int oldHeight = mBottom - mTop;
9786
9787            mBottom = bottom;
9788            if (mDisplayList != null) {
9789                mDisplayList.setBottom(mBottom);
9790            }
9791
9792            sizeChange(width, mBottom - mTop, width, oldHeight);
9793
9794            if (!matrixIsIdentity) {
9795                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9796                    // A change in dimension means an auto-centered pivot point changes, too
9797                    mTransformationInfo.mMatrixDirty = true;
9798                }
9799                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9800                invalidate(true);
9801            }
9802            mBackgroundSizeChanged = true;
9803            invalidateParentIfNeeded();
9804            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9805                // View was rejected last time it was drawn by its parent; this may have changed
9806                invalidateParentIfNeeded();
9807            }
9808        }
9809    }
9810
9811    /**
9812     * Left position of this view relative to its parent.
9813     *
9814     * @return The left edge of this view, in pixels.
9815     */
9816    @ViewDebug.CapturedViewProperty
9817    public final int getLeft() {
9818        return mLeft;
9819    }
9820
9821    /**
9822     * Sets the left position of this view relative to its parent. This method is meant to be called
9823     * by the layout system and should not generally be called otherwise, because the property
9824     * may be changed at any time by the layout.
9825     *
9826     * @param left The bottom of this view, in pixels.
9827     */
9828    public final void setLeft(int left) {
9829        if (left != mLeft) {
9830            updateMatrix();
9831            final boolean matrixIsIdentity = mTransformationInfo == null
9832                    || mTransformationInfo.mMatrixIsIdentity;
9833            if (matrixIsIdentity) {
9834                if (mAttachInfo != null) {
9835                    int minLeft;
9836                    int xLoc;
9837                    if (left < mLeft) {
9838                        minLeft = left;
9839                        xLoc = left - mLeft;
9840                    } else {
9841                        minLeft = mLeft;
9842                        xLoc = 0;
9843                    }
9844                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9845                }
9846            } else {
9847                // Double-invalidation is necessary to capture view's old and new areas
9848                invalidate(true);
9849            }
9850
9851            int oldWidth = mRight - mLeft;
9852            int height = mBottom - mTop;
9853
9854            mLeft = left;
9855            if (mDisplayList != null) {
9856                mDisplayList.setLeft(left);
9857            }
9858
9859            sizeChange(mRight - mLeft, height, oldWidth, height);
9860
9861            if (!matrixIsIdentity) {
9862                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9863                    // A change in dimension means an auto-centered pivot point changes, too
9864                    mTransformationInfo.mMatrixDirty = true;
9865                }
9866                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9867                invalidate(true);
9868            }
9869            mBackgroundSizeChanged = true;
9870            invalidateParentIfNeeded();
9871            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9872                // View was rejected last time it was drawn by its parent; this may have changed
9873                invalidateParentIfNeeded();
9874            }
9875        }
9876    }
9877
9878    /**
9879     * Right position of this view relative to its parent.
9880     *
9881     * @return The right edge of this view, in pixels.
9882     */
9883    @ViewDebug.CapturedViewProperty
9884    public final int getRight() {
9885        return mRight;
9886    }
9887
9888    /**
9889     * Sets the right position of this view relative to its parent. This method is meant to be called
9890     * by the layout system and should not generally be called otherwise, because the property
9891     * may be changed at any time by the layout.
9892     *
9893     * @param right The bottom of this view, in pixels.
9894     */
9895    public final void setRight(int right) {
9896        if (right != mRight) {
9897            updateMatrix();
9898            final boolean matrixIsIdentity = mTransformationInfo == null
9899                    || mTransformationInfo.mMatrixIsIdentity;
9900            if (matrixIsIdentity) {
9901                if (mAttachInfo != null) {
9902                    int maxRight;
9903                    if (right < mRight) {
9904                        maxRight = mRight;
9905                    } else {
9906                        maxRight = right;
9907                    }
9908                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9909                }
9910            } else {
9911                // Double-invalidation is necessary to capture view's old and new areas
9912                invalidate(true);
9913            }
9914
9915            int oldWidth = mRight - mLeft;
9916            int height = mBottom - mTop;
9917
9918            mRight = right;
9919            if (mDisplayList != null) {
9920                mDisplayList.setRight(mRight);
9921            }
9922
9923            sizeChange(mRight - mLeft, height, oldWidth, height);
9924
9925            if (!matrixIsIdentity) {
9926                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9927                    // A change in dimension means an auto-centered pivot point changes, too
9928                    mTransformationInfo.mMatrixDirty = true;
9929                }
9930                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9931                invalidate(true);
9932            }
9933            mBackgroundSizeChanged = true;
9934            invalidateParentIfNeeded();
9935            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9936                // View was rejected last time it was drawn by its parent; this may have changed
9937                invalidateParentIfNeeded();
9938            }
9939        }
9940    }
9941
9942    /**
9943     * The visual x position of this view, in pixels. This is equivalent to the
9944     * {@link #setTranslationX(float) translationX} property plus the current
9945     * {@link #getLeft() left} property.
9946     *
9947     * @return The visual x position of this view, in pixels.
9948     */
9949    @ViewDebug.ExportedProperty(category = "drawing")
9950    public float getX() {
9951        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9952    }
9953
9954    /**
9955     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9956     * {@link #setTranslationX(float) translationX} property to be the difference between
9957     * the x value passed in and the current {@link #getLeft() left} property.
9958     *
9959     * @param x The visual x position of this view, in pixels.
9960     */
9961    public void setX(float x) {
9962        setTranslationX(x - mLeft);
9963    }
9964
9965    /**
9966     * The visual y position of this view, in pixels. This is equivalent to the
9967     * {@link #setTranslationY(float) translationY} property plus the current
9968     * {@link #getTop() top} property.
9969     *
9970     * @return The visual y position of this view, in pixels.
9971     */
9972    @ViewDebug.ExportedProperty(category = "drawing")
9973    public float getY() {
9974        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9975    }
9976
9977    /**
9978     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9979     * {@link #setTranslationY(float) translationY} property to be the difference between
9980     * the y value passed in and the current {@link #getTop() top} property.
9981     *
9982     * @param y The visual y position of this view, in pixels.
9983     */
9984    public void setY(float y) {
9985        setTranslationY(y - mTop);
9986    }
9987
9988
9989    /**
9990     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9991     * This position is post-layout, in addition to wherever the object's
9992     * layout placed it.
9993     *
9994     * @return The horizontal position of this view relative to its left position, in pixels.
9995     */
9996    @ViewDebug.ExportedProperty(category = "drawing")
9997    public float getTranslationX() {
9998        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9999    }
10000
10001    /**
10002     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10003     * This effectively positions the object post-layout, in addition to wherever the object's
10004     * layout placed it.
10005     *
10006     * @param translationX The horizontal position of this view relative to its left position,
10007     * in pixels.
10008     *
10009     * @attr ref android.R.styleable#View_translationX
10010     */
10011    public void setTranslationX(float translationX) {
10012        ensureTransformationInfo();
10013        final TransformationInfo info = mTransformationInfo;
10014        if (info.mTranslationX != translationX) {
10015            // Double-invalidation is necessary to capture view's old and new areas
10016            invalidateViewProperty(true, false);
10017            info.mTranslationX = translationX;
10018            info.mMatrixDirty = true;
10019            invalidateViewProperty(false, true);
10020            if (mDisplayList != null) {
10021                mDisplayList.setTranslationX(translationX);
10022            }
10023            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10024                // View was rejected last time it was drawn by its parent; this may have changed
10025                invalidateParentIfNeeded();
10026            }
10027        }
10028    }
10029
10030    /**
10031     * The horizontal location of this view relative to its {@link #getTop() top} position.
10032     * This position is post-layout, in addition to wherever the object's
10033     * layout placed it.
10034     *
10035     * @return The vertical position of this view relative to its top position,
10036     * in pixels.
10037     */
10038    @ViewDebug.ExportedProperty(category = "drawing")
10039    public float getTranslationY() {
10040        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10041    }
10042
10043    /**
10044     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10045     * This effectively positions the object post-layout, in addition to wherever the object's
10046     * layout placed it.
10047     *
10048     * @param translationY The vertical position of this view relative to its top position,
10049     * in pixels.
10050     *
10051     * @attr ref android.R.styleable#View_translationY
10052     */
10053    public void setTranslationY(float translationY) {
10054        ensureTransformationInfo();
10055        final TransformationInfo info = mTransformationInfo;
10056        if (info.mTranslationY != translationY) {
10057            invalidateViewProperty(true, false);
10058            info.mTranslationY = translationY;
10059            info.mMatrixDirty = true;
10060            invalidateViewProperty(false, true);
10061            if (mDisplayList != null) {
10062                mDisplayList.setTranslationY(translationY);
10063            }
10064            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10065                // View was rejected last time it was drawn by its parent; this may have changed
10066                invalidateParentIfNeeded();
10067            }
10068        }
10069    }
10070
10071    /**
10072     * Hit rectangle in parent's coordinates
10073     *
10074     * @param outRect The hit rectangle of the view.
10075     */
10076    public void getHitRect(Rect outRect) {
10077        updateMatrix();
10078        final TransformationInfo info = mTransformationInfo;
10079        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10080            outRect.set(mLeft, mTop, mRight, mBottom);
10081        } else {
10082            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10083            tmpRect.set(0, 0, getWidth(), getHeight());
10084            info.mMatrix.mapRect(tmpRect);
10085            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10086                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10087        }
10088    }
10089
10090    /**
10091     * Determines whether the given point, in local coordinates is inside the view.
10092     */
10093    /*package*/ final boolean pointInView(float localX, float localY) {
10094        return localX >= 0 && localX < (mRight - mLeft)
10095                && localY >= 0 && localY < (mBottom - mTop);
10096    }
10097
10098    /**
10099     * Utility method to determine whether the given point, in local coordinates,
10100     * is inside the view, where the area of the view is expanded by the slop factor.
10101     * This method is called while processing touch-move events to determine if the event
10102     * is still within the view.
10103     *
10104     * @hide
10105     */
10106    public boolean pointInView(float localX, float localY, float slop) {
10107        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10108                localY < ((mBottom - mTop) + slop);
10109    }
10110
10111    /**
10112     * When a view has focus and the user navigates away from it, the next view is searched for
10113     * starting from the rectangle filled in by this method.
10114     *
10115     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10116     * of the view.  However, if your view maintains some idea of internal selection,
10117     * such as a cursor, or a selected row or column, you should override this method and
10118     * fill in a more specific rectangle.
10119     *
10120     * @param r The rectangle to fill in, in this view's coordinates.
10121     */
10122    public void getFocusedRect(Rect r) {
10123        getDrawingRect(r);
10124    }
10125
10126    /**
10127     * If some part of this view is not clipped by any of its parents, then
10128     * return that area in r in global (root) coordinates. To convert r to local
10129     * coordinates (without taking possible View rotations into account), offset
10130     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10131     * If the view is completely clipped or translated out, return false.
10132     *
10133     * @param r If true is returned, r holds the global coordinates of the
10134     *        visible portion of this view.
10135     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10136     *        between this view and its root. globalOffet may be null.
10137     * @return true if r is non-empty (i.e. part of the view is visible at the
10138     *         root level.
10139     */
10140    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10141        int width = mRight - mLeft;
10142        int height = mBottom - mTop;
10143        if (width > 0 && height > 0) {
10144            r.set(0, 0, width, height);
10145            if (globalOffset != null) {
10146                globalOffset.set(-mScrollX, -mScrollY);
10147            }
10148            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10149        }
10150        return false;
10151    }
10152
10153    public final boolean getGlobalVisibleRect(Rect r) {
10154        return getGlobalVisibleRect(r, null);
10155    }
10156
10157    public final boolean getLocalVisibleRect(Rect r) {
10158        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10159        if (getGlobalVisibleRect(r, offset)) {
10160            r.offset(-offset.x, -offset.y); // make r local
10161            return true;
10162        }
10163        return false;
10164    }
10165
10166    /**
10167     * Offset this view's vertical location by the specified number of pixels.
10168     *
10169     * @param offset the number of pixels to offset the view by
10170     */
10171    public void offsetTopAndBottom(int offset) {
10172        if (offset != 0) {
10173            updateMatrix();
10174            final boolean matrixIsIdentity = mTransformationInfo == null
10175                    || mTransformationInfo.mMatrixIsIdentity;
10176            if (matrixIsIdentity) {
10177                if (mDisplayList != null) {
10178                    invalidateViewProperty(false, false);
10179                } else {
10180                    final ViewParent p = mParent;
10181                    if (p != null && mAttachInfo != null) {
10182                        final Rect r = mAttachInfo.mTmpInvalRect;
10183                        int minTop;
10184                        int maxBottom;
10185                        int yLoc;
10186                        if (offset < 0) {
10187                            minTop = mTop + offset;
10188                            maxBottom = mBottom;
10189                            yLoc = offset;
10190                        } else {
10191                            minTop = mTop;
10192                            maxBottom = mBottom + offset;
10193                            yLoc = 0;
10194                        }
10195                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10196                        p.invalidateChild(this, r);
10197                    }
10198                }
10199            } else {
10200                invalidateViewProperty(false, false);
10201            }
10202
10203            mTop += offset;
10204            mBottom += offset;
10205            if (mDisplayList != null) {
10206                mDisplayList.offsetTopAndBottom(offset);
10207                invalidateViewProperty(false, false);
10208            } else {
10209                if (!matrixIsIdentity) {
10210                    invalidateViewProperty(false, true);
10211                }
10212                invalidateParentIfNeeded();
10213            }
10214        }
10215    }
10216
10217    /**
10218     * Offset this view's horizontal location by the specified amount of pixels.
10219     *
10220     * @param offset the number of pixels to offset the view by
10221     */
10222    public void offsetLeftAndRight(int offset) {
10223        if (offset != 0) {
10224            updateMatrix();
10225            final boolean matrixIsIdentity = mTransformationInfo == null
10226                    || mTransformationInfo.mMatrixIsIdentity;
10227            if (matrixIsIdentity) {
10228                if (mDisplayList != null) {
10229                    invalidateViewProperty(false, false);
10230                } else {
10231                    final ViewParent p = mParent;
10232                    if (p != null && mAttachInfo != null) {
10233                        final Rect r = mAttachInfo.mTmpInvalRect;
10234                        int minLeft;
10235                        int maxRight;
10236                        if (offset < 0) {
10237                            minLeft = mLeft + offset;
10238                            maxRight = mRight;
10239                        } else {
10240                            minLeft = mLeft;
10241                            maxRight = mRight + offset;
10242                        }
10243                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10244                        p.invalidateChild(this, r);
10245                    }
10246                }
10247            } else {
10248                invalidateViewProperty(false, false);
10249            }
10250
10251            mLeft += offset;
10252            mRight += offset;
10253            if (mDisplayList != null) {
10254                mDisplayList.offsetLeftAndRight(offset);
10255                invalidateViewProperty(false, false);
10256            } else {
10257                if (!matrixIsIdentity) {
10258                    invalidateViewProperty(false, true);
10259                }
10260                invalidateParentIfNeeded();
10261            }
10262        }
10263    }
10264
10265    /**
10266     * Get the LayoutParams associated with this view. All views should have
10267     * layout parameters. These supply parameters to the <i>parent</i> of this
10268     * view specifying how it should be arranged. There are many subclasses of
10269     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10270     * of ViewGroup that are responsible for arranging their children.
10271     *
10272     * This method may return null if this View is not attached to a parent
10273     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10274     * was not invoked successfully. When a View is attached to a parent
10275     * ViewGroup, this method must not return null.
10276     *
10277     * @return The LayoutParams associated with this view, or null if no
10278     *         parameters have been set yet
10279     */
10280    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10281    public ViewGroup.LayoutParams getLayoutParams() {
10282        return mLayoutParams;
10283    }
10284
10285    /**
10286     * Set the layout parameters associated with this view. These supply
10287     * parameters to the <i>parent</i> of this view specifying how it should be
10288     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10289     * correspond to the different subclasses of ViewGroup that are responsible
10290     * for arranging their children.
10291     *
10292     * @param params The layout parameters for this view, cannot be null
10293     */
10294    public void setLayoutParams(ViewGroup.LayoutParams params) {
10295        if (params == null) {
10296            throw new NullPointerException("Layout parameters cannot be null");
10297        }
10298        mLayoutParams = params;
10299        resolveLayoutParams();
10300        if (mParent instanceof ViewGroup) {
10301            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10302        }
10303        requestLayout();
10304    }
10305
10306    /**
10307     * Resolve the layout parameters depending on the resolved layout direction
10308     *
10309     * @hide
10310     */
10311    public void resolveLayoutParams() {
10312        if (mLayoutParams != null) {
10313            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10314        }
10315    }
10316
10317    /**
10318     * Set the scrolled position of your view. This will cause a call to
10319     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10320     * invalidated.
10321     * @param x the x position to scroll to
10322     * @param y the y position to scroll to
10323     */
10324    public void scrollTo(int x, int y) {
10325        if (mScrollX != x || mScrollY != y) {
10326            int oldX = mScrollX;
10327            int oldY = mScrollY;
10328            mScrollX = x;
10329            mScrollY = y;
10330            invalidateParentCaches();
10331            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10332            if (!awakenScrollBars()) {
10333                postInvalidateOnAnimation();
10334            }
10335        }
10336    }
10337
10338    /**
10339     * Move the scrolled position of your view. This will cause a call to
10340     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10341     * invalidated.
10342     * @param x the amount of pixels to scroll by horizontally
10343     * @param y the amount of pixels to scroll by vertically
10344     */
10345    public void scrollBy(int x, int y) {
10346        scrollTo(mScrollX + x, mScrollY + y);
10347    }
10348
10349    /**
10350     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10351     * animation to fade the scrollbars out after a default delay. If a subclass
10352     * provides animated scrolling, the start delay should equal the duration
10353     * of the scrolling animation.</p>
10354     *
10355     * <p>The animation starts only if at least one of the scrollbars is
10356     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10357     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10358     * this method returns true, and false otherwise. If the animation is
10359     * started, this method calls {@link #invalidate()}; in that case the
10360     * caller should not call {@link #invalidate()}.</p>
10361     *
10362     * <p>This method should be invoked every time a subclass directly updates
10363     * the scroll parameters.</p>
10364     *
10365     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10366     * and {@link #scrollTo(int, int)}.</p>
10367     *
10368     * @return true if the animation is played, false otherwise
10369     *
10370     * @see #awakenScrollBars(int)
10371     * @see #scrollBy(int, int)
10372     * @see #scrollTo(int, int)
10373     * @see #isHorizontalScrollBarEnabled()
10374     * @see #isVerticalScrollBarEnabled()
10375     * @see #setHorizontalScrollBarEnabled(boolean)
10376     * @see #setVerticalScrollBarEnabled(boolean)
10377     */
10378    protected boolean awakenScrollBars() {
10379        return mScrollCache != null &&
10380                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10381    }
10382
10383    /**
10384     * Trigger the scrollbars to draw.
10385     * This method differs from awakenScrollBars() only in its default duration.
10386     * initialAwakenScrollBars() will show the scroll bars for longer than
10387     * usual to give the user more of a chance to notice them.
10388     *
10389     * @return true if the animation is played, false otherwise.
10390     */
10391    private boolean initialAwakenScrollBars() {
10392        return mScrollCache != null &&
10393                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10394    }
10395
10396    /**
10397     * <p>
10398     * Trigger the scrollbars to draw. When invoked this method starts an
10399     * animation to fade the scrollbars out after a fixed delay. If a subclass
10400     * provides animated scrolling, the start delay should equal the duration of
10401     * the scrolling animation.
10402     * </p>
10403     *
10404     * <p>
10405     * The animation starts only if at least one of the scrollbars is enabled,
10406     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10407     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10408     * this method returns true, and false otherwise. If the animation is
10409     * started, this method calls {@link #invalidate()}; in that case the caller
10410     * should not call {@link #invalidate()}.
10411     * </p>
10412     *
10413     * <p>
10414     * This method should be invoked everytime a subclass directly updates the
10415     * scroll parameters.
10416     * </p>
10417     *
10418     * @param startDelay the delay, in milliseconds, after which the animation
10419     *        should start; when the delay is 0, the animation starts
10420     *        immediately
10421     * @return true if the animation is played, false otherwise
10422     *
10423     * @see #scrollBy(int, int)
10424     * @see #scrollTo(int, int)
10425     * @see #isHorizontalScrollBarEnabled()
10426     * @see #isVerticalScrollBarEnabled()
10427     * @see #setHorizontalScrollBarEnabled(boolean)
10428     * @see #setVerticalScrollBarEnabled(boolean)
10429     */
10430    protected boolean awakenScrollBars(int startDelay) {
10431        return awakenScrollBars(startDelay, true);
10432    }
10433
10434    /**
10435     * <p>
10436     * Trigger the scrollbars to draw. When invoked this method starts an
10437     * animation to fade the scrollbars out after a fixed delay. If a subclass
10438     * provides animated scrolling, the start delay should equal the duration of
10439     * the scrolling animation.
10440     * </p>
10441     *
10442     * <p>
10443     * The animation starts only if at least one of the scrollbars is enabled,
10444     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10445     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10446     * this method returns true, and false otherwise. If the animation is
10447     * started, this method calls {@link #invalidate()} if the invalidate parameter
10448     * is set to true; in that case the caller
10449     * should not call {@link #invalidate()}.
10450     * </p>
10451     *
10452     * <p>
10453     * This method should be invoked everytime a subclass directly updates the
10454     * scroll parameters.
10455     * </p>
10456     *
10457     * @param startDelay the delay, in milliseconds, after which the animation
10458     *        should start; when the delay is 0, the animation starts
10459     *        immediately
10460     *
10461     * @param invalidate Wheter this method should call invalidate
10462     *
10463     * @return true if the animation is played, false otherwise
10464     *
10465     * @see #scrollBy(int, int)
10466     * @see #scrollTo(int, int)
10467     * @see #isHorizontalScrollBarEnabled()
10468     * @see #isVerticalScrollBarEnabled()
10469     * @see #setHorizontalScrollBarEnabled(boolean)
10470     * @see #setVerticalScrollBarEnabled(boolean)
10471     */
10472    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10473        final ScrollabilityCache scrollCache = mScrollCache;
10474
10475        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10476            return false;
10477        }
10478
10479        if (scrollCache.scrollBar == null) {
10480            scrollCache.scrollBar = new ScrollBarDrawable();
10481        }
10482
10483        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10484
10485            if (invalidate) {
10486                // Invalidate to show the scrollbars
10487                postInvalidateOnAnimation();
10488            }
10489
10490            if (scrollCache.state == ScrollabilityCache.OFF) {
10491                // FIXME: this is copied from WindowManagerService.
10492                // We should get this value from the system when it
10493                // is possible to do so.
10494                final int KEY_REPEAT_FIRST_DELAY = 750;
10495                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10496            }
10497
10498            // Tell mScrollCache when we should start fading. This may
10499            // extend the fade start time if one was already scheduled
10500            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10501            scrollCache.fadeStartTime = fadeStartTime;
10502            scrollCache.state = ScrollabilityCache.ON;
10503
10504            // Schedule our fader to run, unscheduling any old ones first
10505            if (mAttachInfo != null) {
10506                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10507                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10508            }
10509
10510            return true;
10511        }
10512
10513        return false;
10514    }
10515
10516    /**
10517     * Do not invalidate views which are not visible and which are not running an animation. They
10518     * will not get drawn and they should not set dirty flags as if they will be drawn
10519     */
10520    private boolean skipInvalidate() {
10521        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10522                (!(mParent instanceof ViewGroup) ||
10523                        !((ViewGroup) mParent).isViewTransitioning(this));
10524    }
10525    /**
10526     * Mark the area defined by dirty as needing to be drawn. If the view is
10527     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10528     * in the future. This must be called from a UI thread. To call from a non-UI
10529     * thread, call {@link #postInvalidate()}.
10530     *
10531     * WARNING: This method is destructive to dirty.
10532     * @param dirty the rectangle representing the bounds of the dirty region
10533     */
10534    public void invalidate(Rect dirty) {
10535        if (skipInvalidate()) {
10536            return;
10537        }
10538        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10539                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10540                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10541            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10542            mPrivateFlags |= PFLAG_INVALIDATED;
10543            mPrivateFlags |= PFLAG_DIRTY;
10544            final ViewParent p = mParent;
10545            final AttachInfo ai = mAttachInfo;
10546            //noinspection PointlessBooleanExpression,ConstantConditions
10547            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10548                if (p != null && ai != null && ai.mHardwareAccelerated) {
10549                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10550                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10551                    p.invalidateChild(this, null);
10552                    return;
10553                }
10554            }
10555            if (p != null && ai != null) {
10556                final int scrollX = mScrollX;
10557                final int scrollY = mScrollY;
10558                final Rect r = ai.mTmpInvalRect;
10559                r.set(dirty.left - scrollX, dirty.top - scrollY,
10560                        dirty.right - scrollX, dirty.bottom - scrollY);
10561                mParent.invalidateChild(this, r);
10562            }
10563        }
10564    }
10565
10566    /**
10567     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10568     * The coordinates of the dirty rect are relative to the view.
10569     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10570     * will be called at some point in the future. This must be called from
10571     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10572     * @param l the left position of the dirty region
10573     * @param t the top position of the dirty region
10574     * @param r the right position of the dirty region
10575     * @param b the bottom position of the dirty region
10576     */
10577    public void invalidate(int l, int t, int r, int b) {
10578        if (skipInvalidate()) {
10579            return;
10580        }
10581        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10582                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10583                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10584            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10585            mPrivateFlags |= PFLAG_INVALIDATED;
10586            mPrivateFlags |= PFLAG_DIRTY;
10587            final ViewParent p = mParent;
10588            final AttachInfo ai = mAttachInfo;
10589            //noinspection PointlessBooleanExpression,ConstantConditions
10590            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10591                if (p != null && ai != null && ai.mHardwareAccelerated) {
10592                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10593                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10594                    p.invalidateChild(this, null);
10595                    return;
10596                }
10597            }
10598            if (p != null && ai != null && l < r && t < b) {
10599                final int scrollX = mScrollX;
10600                final int scrollY = mScrollY;
10601                final Rect tmpr = ai.mTmpInvalRect;
10602                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10603                p.invalidateChild(this, tmpr);
10604            }
10605        }
10606    }
10607
10608    /**
10609     * Invalidate the whole view. If the view is visible,
10610     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10611     * the future. This must be called from a UI thread. To call from a non-UI thread,
10612     * call {@link #postInvalidate()}.
10613     */
10614    public void invalidate() {
10615        invalidate(true);
10616    }
10617
10618    /**
10619     * This is where the invalidate() work actually happens. A full invalidate()
10620     * causes the drawing cache to be invalidated, but this function can be called with
10621     * invalidateCache set to false to skip that invalidation step for cases that do not
10622     * need it (for example, a component that remains at the same dimensions with the same
10623     * content).
10624     *
10625     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10626     * well. This is usually true for a full invalidate, but may be set to false if the
10627     * View's contents or dimensions have not changed.
10628     */
10629    void invalidate(boolean invalidateCache) {
10630        if (skipInvalidate()) {
10631            return;
10632        }
10633        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10634                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10635                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10636            mLastIsOpaque = isOpaque();
10637            mPrivateFlags &= ~PFLAG_DRAWN;
10638            mPrivateFlags |= PFLAG_DIRTY;
10639            if (invalidateCache) {
10640                mPrivateFlags |= PFLAG_INVALIDATED;
10641                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10642            }
10643            final AttachInfo ai = mAttachInfo;
10644            final ViewParent p = mParent;
10645            //noinspection PointlessBooleanExpression,ConstantConditions
10646            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10647                if (p != null && ai != null && ai.mHardwareAccelerated) {
10648                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10649                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10650                    p.invalidateChild(this, null);
10651                    return;
10652                }
10653            }
10654
10655            if (p != null && ai != null) {
10656                final Rect r = ai.mTmpInvalRect;
10657                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10658                // Don't call invalidate -- we don't want to internally scroll
10659                // our own bounds
10660                p.invalidateChild(this, r);
10661            }
10662        }
10663    }
10664
10665    /**
10666     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10667     * set any flags or handle all of the cases handled by the default invalidation methods.
10668     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10669     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10670     * walk up the hierarchy, transforming the dirty rect as necessary.
10671     *
10672     * The method also handles normal invalidation logic if display list properties are not
10673     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10674     * backup approach, to handle these cases used in the various property-setting methods.
10675     *
10676     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10677     * are not being used in this view
10678     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10679     * list properties are not being used in this view
10680     */
10681    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10682        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10683            if (invalidateParent) {
10684                invalidateParentCaches();
10685            }
10686            if (forceRedraw) {
10687                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10688            }
10689            invalidate(false);
10690        } else {
10691            final AttachInfo ai = mAttachInfo;
10692            final ViewParent p = mParent;
10693            if (p != null && ai != null) {
10694                final Rect r = ai.mTmpInvalRect;
10695                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10696                if (mParent instanceof ViewGroup) {
10697                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10698                } else {
10699                    mParent.invalidateChild(this, r);
10700                }
10701            }
10702        }
10703    }
10704
10705    /**
10706     * Utility method to transform a given Rect by the current matrix of this view.
10707     */
10708    void transformRect(final Rect rect) {
10709        if (!getMatrix().isIdentity()) {
10710            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10711            boundingRect.set(rect);
10712            getMatrix().mapRect(boundingRect);
10713            rect.set((int) Math.floor(boundingRect.left),
10714                    (int) Math.floor(boundingRect.top),
10715                    (int) Math.ceil(boundingRect.right),
10716                    (int) Math.ceil(boundingRect.bottom));
10717        }
10718    }
10719
10720    /**
10721     * Used to indicate that the parent of this view should clear its caches. This functionality
10722     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10723     * which is necessary when various parent-managed properties of the view change, such as
10724     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10725     * clears the parent caches and does not causes an invalidate event.
10726     *
10727     * @hide
10728     */
10729    protected void invalidateParentCaches() {
10730        if (mParent instanceof View) {
10731            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10732        }
10733    }
10734
10735    /**
10736     * Used to indicate that the parent of this view should be invalidated. This functionality
10737     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10738     * which is necessary when various parent-managed properties of the view change, such as
10739     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10740     * an invalidation event to the parent.
10741     *
10742     * @hide
10743     */
10744    protected void invalidateParentIfNeeded() {
10745        if (isHardwareAccelerated() && mParent instanceof View) {
10746            ((View) mParent).invalidate(true);
10747        }
10748    }
10749
10750    /**
10751     * Indicates whether this View is opaque. An opaque View guarantees that it will
10752     * draw all the pixels overlapping its bounds using a fully opaque color.
10753     *
10754     * Subclasses of View should override this method whenever possible to indicate
10755     * whether an instance is opaque. Opaque Views are treated in a special way by
10756     * the View hierarchy, possibly allowing it to perform optimizations during
10757     * invalidate/draw passes.
10758     *
10759     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10760     */
10761    @ViewDebug.ExportedProperty(category = "drawing")
10762    public boolean isOpaque() {
10763        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10764                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10765    }
10766
10767    /**
10768     * @hide
10769     */
10770    protected void computeOpaqueFlags() {
10771        // Opaque if:
10772        //   - Has a background
10773        //   - Background is opaque
10774        //   - Doesn't have scrollbars or scrollbars overlay
10775
10776        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10777            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10778        } else {
10779            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10780        }
10781
10782        final int flags = mViewFlags;
10783        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10784                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10785                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10786            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10787        } else {
10788            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10789        }
10790    }
10791
10792    /**
10793     * @hide
10794     */
10795    protected boolean hasOpaqueScrollbars() {
10796        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10797    }
10798
10799    /**
10800     * @return A handler associated with the thread running the View. This
10801     * handler can be used to pump events in the UI events queue.
10802     */
10803    public Handler getHandler() {
10804        final AttachInfo attachInfo = mAttachInfo;
10805        if (attachInfo != null) {
10806            return attachInfo.mHandler;
10807        }
10808        return null;
10809    }
10810
10811    /**
10812     * Gets the view root associated with the View.
10813     * @return The view root, or null if none.
10814     * @hide
10815     */
10816    public ViewRootImpl getViewRootImpl() {
10817        if (mAttachInfo != null) {
10818            return mAttachInfo.mViewRootImpl;
10819        }
10820        return null;
10821    }
10822
10823    /**
10824     * <p>Causes the Runnable to be added to the message queue.
10825     * The runnable will be run on the user interface thread.</p>
10826     *
10827     * @param action The Runnable that will be executed.
10828     *
10829     * @return Returns true if the Runnable was successfully placed in to the
10830     *         message queue.  Returns false on failure, usually because the
10831     *         looper processing the message queue is exiting.
10832     *
10833     * @see #postDelayed
10834     * @see #removeCallbacks
10835     */
10836    public boolean post(Runnable action) {
10837        final AttachInfo attachInfo = mAttachInfo;
10838        if (attachInfo != null) {
10839            return attachInfo.mHandler.post(action);
10840        }
10841        // Assume that post will succeed later
10842        ViewRootImpl.getRunQueue().post(action);
10843        return true;
10844    }
10845
10846    /**
10847     * <p>Causes the Runnable to be added to the message queue, to be run
10848     * after the specified amount of time elapses.
10849     * The runnable will be run on the user interface thread.</p>
10850     *
10851     * @param action The Runnable that will be executed.
10852     * @param delayMillis The delay (in milliseconds) until the Runnable
10853     *        will be executed.
10854     *
10855     * @return true if the Runnable was successfully placed in to the
10856     *         message queue.  Returns false on failure, usually because the
10857     *         looper processing the message queue is exiting.  Note that a
10858     *         result of true does not mean the Runnable will be processed --
10859     *         if the looper is quit before the delivery time of the message
10860     *         occurs then the message will be dropped.
10861     *
10862     * @see #post
10863     * @see #removeCallbacks
10864     */
10865    public boolean postDelayed(Runnable action, long delayMillis) {
10866        final AttachInfo attachInfo = mAttachInfo;
10867        if (attachInfo != null) {
10868            return attachInfo.mHandler.postDelayed(action, delayMillis);
10869        }
10870        // Assume that post will succeed later
10871        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10872        return true;
10873    }
10874
10875    /**
10876     * <p>Causes the Runnable to execute on the next animation time step.
10877     * The runnable will be run on the user interface thread.</p>
10878     *
10879     * @param action The Runnable that will be executed.
10880     *
10881     * @see #postOnAnimationDelayed
10882     * @see #removeCallbacks
10883     */
10884    public void postOnAnimation(Runnable action) {
10885        final AttachInfo attachInfo = mAttachInfo;
10886        if (attachInfo != null) {
10887            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10888                    Choreographer.CALLBACK_ANIMATION, action, null);
10889        } else {
10890            // Assume that post will succeed later
10891            ViewRootImpl.getRunQueue().post(action);
10892        }
10893    }
10894
10895    /**
10896     * <p>Causes the Runnable to execute on the next animation time step,
10897     * after the specified amount of time elapses.
10898     * The runnable will be run on the user interface thread.</p>
10899     *
10900     * @param action The Runnable that will be executed.
10901     * @param delayMillis The delay (in milliseconds) until the Runnable
10902     *        will be executed.
10903     *
10904     * @see #postOnAnimation
10905     * @see #removeCallbacks
10906     */
10907    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10908        final AttachInfo attachInfo = mAttachInfo;
10909        if (attachInfo != null) {
10910            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10911                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10912        } else {
10913            // Assume that post will succeed later
10914            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10915        }
10916    }
10917
10918    /**
10919     * <p>Removes the specified Runnable from the message queue.</p>
10920     *
10921     * @param action The Runnable to remove from the message handling queue
10922     *
10923     * @return true if this view could ask the Handler to remove the Runnable,
10924     *         false otherwise. When the returned value is true, the Runnable
10925     *         may or may not have been actually removed from the message queue
10926     *         (for instance, if the Runnable was not in the queue already.)
10927     *
10928     * @see #post
10929     * @see #postDelayed
10930     * @see #postOnAnimation
10931     * @see #postOnAnimationDelayed
10932     */
10933    public boolean removeCallbacks(Runnable action) {
10934        if (action != null) {
10935            final AttachInfo attachInfo = mAttachInfo;
10936            if (attachInfo != null) {
10937                attachInfo.mHandler.removeCallbacks(action);
10938                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10939                        Choreographer.CALLBACK_ANIMATION, action, null);
10940            } else {
10941                // Assume that post will succeed later
10942                ViewRootImpl.getRunQueue().removeCallbacks(action);
10943            }
10944        }
10945        return true;
10946    }
10947
10948    /**
10949     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10950     * Use this to invalidate the View from a non-UI thread.</p>
10951     *
10952     * <p>This method can be invoked from outside of the UI thread
10953     * only when this View is attached to a window.</p>
10954     *
10955     * @see #invalidate()
10956     * @see #postInvalidateDelayed(long)
10957     */
10958    public void postInvalidate() {
10959        postInvalidateDelayed(0);
10960    }
10961
10962    /**
10963     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10964     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10965     *
10966     * <p>This method can be invoked from outside of the UI thread
10967     * only when this View is attached to a window.</p>
10968     *
10969     * @param left The left coordinate of the rectangle to invalidate.
10970     * @param top The top coordinate of the rectangle to invalidate.
10971     * @param right The right coordinate of the rectangle to invalidate.
10972     * @param bottom The bottom coordinate of the rectangle to invalidate.
10973     *
10974     * @see #invalidate(int, int, int, int)
10975     * @see #invalidate(Rect)
10976     * @see #postInvalidateDelayed(long, int, int, int, int)
10977     */
10978    public void postInvalidate(int left, int top, int right, int bottom) {
10979        postInvalidateDelayed(0, left, top, right, bottom);
10980    }
10981
10982    /**
10983     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10984     * loop. Waits for the specified amount of time.</p>
10985     *
10986     * <p>This method can be invoked from outside of the UI thread
10987     * only when this View is attached to a window.</p>
10988     *
10989     * @param delayMilliseconds the duration in milliseconds to delay the
10990     *         invalidation by
10991     *
10992     * @see #invalidate()
10993     * @see #postInvalidate()
10994     */
10995    public void postInvalidateDelayed(long delayMilliseconds) {
10996        // We try only with the AttachInfo because there's no point in invalidating
10997        // if we are not attached to our window
10998        final AttachInfo attachInfo = mAttachInfo;
10999        if (attachInfo != null) {
11000            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11001        }
11002    }
11003
11004    /**
11005     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11006     * through the event loop. Waits for the specified amount of time.</p>
11007     *
11008     * <p>This method can be invoked from outside of the UI thread
11009     * only when this View is attached to a window.</p>
11010     *
11011     * @param delayMilliseconds the duration in milliseconds to delay the
11012     *         invalidation by
11013     * @param left The left coordinate of the rectangle to invalidate.
11014     * @param top The top coordinate of the rectangle to invalidate.
11015     * @param right The right coordinate of the rectangle to invalidate.
11016     * @param bottom The bottom coordinate of the rectangle to invalidate.
11017     *
11018     * @see #invalidate(int, int, int, int)
11019     * @see #invalidate(Rect)
11020     * @see #postInvalidate(int, int, int, int)
11021     */
11022    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11023            int right, int bottom) {
11024
11025        // We try only with the AttachInfo because there's no point in invalidating
11026        // if we are not attached to our window
11027        final AttachInfo attachInfo = mAttachInfo;
11028        if (attachInfo != null) {
11029            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11030            info.target = this;
11031            info.left = left;
11032            info.top = top;
11033            info.right = right;
11034            info.bottom = bottom;
11035
11036            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11037        }
11038    }
11039
11040    /**
11041     * <p>Cause an invalidate to happen on the next animation time step, typically the
11042     * next display frame.</p>
11043     *
11044     * <p>This method can be invoked from outside of the UI thread
11045     * only when this View is attached to a window.</p>
11046     *
11047     * @see #invalidate()
11048     */
11049    public void postInvalidateOnAnimation() {
11050        // We try only with the AttachInfo because there's no point in invalidating
11051        // if we are not attached to our window
11052        final AttachInfo attachInfo = mAttachInfo;
11053        if (attachInfo != null) {
11054            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11055        }
11056    }
11057
11058    /**
11059     * <p>Cause an invalidate of the specified area to happen on the next animation
11060     * time step, typically the next display frame.</p>
11061     *
11062     * <p>This method can be invoked from outside of the UI thread
11063     * only when this View is attached to a window.</p>
11064     *
11065     * @param left The left coordinate of the rectangle to invalidate.
11066     * @param top The top coordinate of the rectangle to invalidate.
11067     * @param right The right coordinate of the rectangle to invalidate.
11068     * @param bottom The bottom coordinate of the rectangle to invalidate.
11069     *
11070     * @see #invalidate(int, int, int, int)
11071     * @see #invalidate(Rect)
11072     */
11073    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11074        // We try only with the AttachInfo because there's no point in invalidating
11075        // if we are not attached to our window
11076        final AttachInfo attachInfo = mAttachInfo;
11077        if (attachInfo != null) {
11078            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11079            info.target = this;
11080            info.left = left;
11081            info.top = top;
11082            info.right = right;
11083            info.bottom = bottom;
11084
11085            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11086        }
11087    }
11088
11089    /**
11090     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11091     * This event is sent at most once every
11092     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11093     */
11094    private void postSendViewScrolledAccessibilityEventCallback() {
11095        if (mSendViewScrolledAccessibilityEvent == null) {
11096            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11097        }
11098        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11099            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11100            postDelayed(mSendViewScrolledAccessibilityEvent,
11101                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11102        }
11103    }
11104
11105    /**
11106     * Called by a parent to request that a child update its values for mScrollX
11107     * and mScrollY if necessary. This will typically be done if the child is
11108     * animating a scroll using a {@link android.widget.Scroller Scroller}
11109     * object.
11110     */
11111    public void computeScroll() {
11112    }
11113
11114    /**
11115     * <p>Indicate whether the horizontal edges are faded when the view is
11116     * scrolled horizontally.</p>
11117     *
11118     * @return true if the horizontal edges should are faded on scroll, false
11119     *         otherwise
11120     *
11121     * @see #setHorizontalFadingEdgeEnabled(boolean)
11122     *
11123     * @attr ref android.R.styleable#View_requiresFadingEdge
11124     */
11125    public boolean isHorizontalFadingEdgeEnabled() {
11126        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11127    }
11128
11129    /**
11130     * <p>Define whether the horizontal edges should be faded when this view
11131     * is scrolled horizontally.</p>
11132     *
11133     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11134     *                                    be faded when the view is scrolled
11135     *                                    horizontally
11136     *
11137     * @see #isHorizontalFadingEdgeEnabled()
11138     *
11139     * @attr ref android.R.styleable#View_requiresFadingEdge
11140     */
11141    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11142        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11143            if (horizontalFadingEdgeEnabled) {
11144                initScrollCache();
11145            }
11146
11147            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11148        }
11149    }
11150
11151    /**
11152     * <p>Indicate whether the vertical edges are faded when the view is
11153     * scrolled horizontally.</p>
11154     *
11155     * @return true if the vertical edges should are faded on scroll, false
11156     *         otherwise
11157     *
11158     * @see #setVerticalFadingEdgeEnabled(boolean)
11159     *
11160     * @attr ref android.R.styleable#View_requiresFadingEdge
11161     */
11162    public boolean isVerticalFadingEdgeEnabled() {
11163        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11164    }
11165
11166    /**
11167     * <p>Define whether the vertical edges should be faded when this view
11168     * is scrolled vertically.</p>
11169     *
11170     * @param verticalFadingEdgeEnabled true if the vertical edges should
11171     *                                  be faded when the view is scrolled
11172     *                                  vertically
11173     *
11174     * @see #isVerticalFadingEdgeEnabled()
11175     *
11176     * @attr ref android.R.styleable#View_requiresFadingEdge
11177     */
11178    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11179        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11180            if (verticalFadingEdgeEnabled) {
11181                initScrollCache();
11182            }
11183
11184            mViewFlags ^= FADING_EDGE_VERTICAL;
11185        }
11186    }
11187
11188    /**
11189     * Returns the strength, or intensity, of the top faded edge. The strength is
11190     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11191     * returns 0.0 or 1.0 but no value in between.
11192     *
11193     * Subclasses should override this method to provide a smoother fade transition
11194     * when scrolling occurs.
11195     *
11196     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11197     */
11198    protected float getTopFadingEdgeStrength() {
11199        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11200    }
11201
11202    /**
11203     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11204     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11205     * returns 0.0 or 1.0 but no value in between.
11206     *
11207     * Subclasses should override this method to provide a smoother fade transition
11208     * when scrolling occurs.
11209     *
11210     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11211     */
11212    protected float getBottomFadingEdgeStrength() {
11213        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11214                computeVerticalScrollRange() ? 1.0f : 0.0f;
11215    }
11216
11217    /**
11218     * Returns the strength, or intensity, of the left faded edge. The strength is
11219     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11220     * returns 0.0 or 1.0 but no value in between.
11221     *
11222     * Subclasses should override this method to provide a smoother fade transition
11223     * when scrolling occurs.
11224     *
11225     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11226     */
11227    protected float getLeftFadingEdgeStrength() {
11228        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11229    }
11230
11231    /**
11232     * Returns the strength, or intensity, of the right faded edge. The strength is
11233     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11234     * returns 0.0 or 1.0 but no value in between.
11235     *
11236     * Subclasses should override this method to provide a smoother fade transition
11237     * when scrolling occurs.
11238     *
11239     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11240     */
11241    protected float getRightFadingEdgeStrength() {
11242        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11243                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11244    }
11245
11246    /**
11247     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11248     * scrollbar is not drawn by default.</p>
11249     *
11250     * @return true if the horizontal scrollbar should be painted, false
11251     *         otherwise
11252     *
11253     * @see #setHorizontalScrollBarEnabled(boolean)
11254     */
11255    public boolean isHorizontalScrollBarEnabled() {
11256        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11257    }
11258
11259    /**
11260     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11261     * scrollbar is not drawn by default.</p>
11262     *
11263     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11264     *                                   be painted
11265     *
11266     * @see #isHorizontalScrollBarEnabled()
11267     */
11268    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11269        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11270            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11271            computeOpaqueFlags();
11272            resolvePadding();
11273        }
11274    }
11275
11276    /**
11277     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11278     * scrollbar is not drawn by default.</p>
11279     *
11280     * @return true if the vertical scrollbar should be painted, false
11281     *         otherwise
11282     *
11283     * @see #setVerticalScrollBarEnabled(boolean)
11284     */
11285    public boolean isVerticalScrollBarEnabled() {
11286        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11287    }
11288
11289    /**
11290     * <p>Define whether the vertical scrollbar should be drawn or not. The
11291     * scrollbar is not drawn by default.</p>
11292     *
11293     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11294     *                                 be painted
11295     *
11296     * @see #isVerticalScrollBarEnabled()
11297     */
11298    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11299        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11300            mViewFlags ^= SCROLLBARS_VERTICAL;
11301            computeOpaqueFlags();
11302            resolvePadding();
11303        }
11304    }
11305
11306    /**
11307     * @hide
11308     */
11309    protected void recomputePadding() {
11310        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11311    }
11312
11313    /**
11314     * Define whether scrollbars will fade when the view is not scrolling.
11315     *
11316     * @param fadeScrollbars wheter to enable fading
11317     *
11318     * @attr ref android.R.styleable#View_fadeScrollbars
11319     */
11320    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11321        initScrollCache();
11322        final ScrollabilityCache scrollabilityCache = mScrollCache;
11323        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11324        if (fadeScrollbars) {
11325            scrollabilityCache.state = ScrollabilityCache.OFF;
11326        } else {
11327            scrollabilityCache.state = ScrollabilityCache.ON;
11328        }
11329    }
11330
11331    /**
11332     *
11333     * Returns true if scrollbars will fade when this view is not scrolling
11334     *
11335     * @return true if scrollbar fading is enabled
11336     *
11337     * @attr ref android.R.styleable#View_fadeScrollbars
11338     */
11339    public boolean isScrollbarFadingEnabled() {
11340        return mScrollCache != null && mScrollCache.fadeScrollBars;
11341    }
11342
11343    /**
11344     *
11345     * Returns the delay before scrollbars fade.
11346     *
11347     * @return the delay before scrollbars fade
11348     *
11349     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11350     */
11351    public int getScrollBarDefaultDelayBeforeFade() {
11352        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11353                mScrollCache.scrollBarDefaultDelayBeforeFade;
11354    }
11355
11356    /**
11357     * Define the delay before scrollbars fade.
11358     *
11359     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11360     *
11361     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11362     */
11363    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11364        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11365    }
11366
11367    /**
11368     *
11369     * Returns the scrollbar fade duration.
11370     *
11371     * @return the scrollbar fade duration
11372     *
11373     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11374     */
11375    public int getScrollBarFadeDuration() {
11376        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11377                mScrollCache.scrollBarFadeDuration;
11378    }
11379
11380    /**
11381     * Define the scrollbar fade duration.
11382     *
11383     * @param scrollBarFadeDuration - the scrollbar fade duration
11384     *
11385     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11386     */
11387    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11388        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11389    }
11390
11391    /**
11392     *
11393     * Returns the scrollbar size.
11394     *
11395     * @return the scrollbar size
11396     *
11397     * @attr ref android.R.styleable#View_scrollbarSize
11398     */
11399    public int getScrollBarSize() {
11400        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11401                mScrollCache.scrollBarSize;
11402    }
11403
11404    /**
11405     * Define the scrollbar size.
11406     *
11407     * @param scrollBarSize - the scrollbar size
11408     *
11409     * @attr ref android.R.styleable#View_scrollbarSize
11410     */
11411    public void setScrollBarSize(int scrollBarSize) {
11412        getScrollCache().scrollBarSize = scrollBarSize;
11413    }
11414
11415    /**
11416     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11417     * inset. When inset, they add to the padding of the view. And the scrollbars
11418     * can be drawn inside the padding area or on the edge of the view. For example,
11419     * if a view has a background drawable and you want to draw the scrollbars
11420     * inside the padding specified by the drawable, you can use
11421     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11422     * appear at the edge of the view, ignoring the padding, then you can use
11423     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11424     * @param style the style of the scrollbars. Should be one of
11425     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11426     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11427     * @see #SCROLLBARS_INSIDE_OVERLAY
11428     * @see #SCROLLBARS_INSIDE_INSET
11429     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11430     * @see #SCROLLBARS_OUTSIDE_INSET
11431     *
11432     * @attr ref android.R.styleable#View_scrollbarStyle
11433     */
11434    public void setScrollBarStyle(int style) {
11435        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11436            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11437            computeOpaqueFlags();
11438            resolvePadding();
11439        }
11440    }
11441
11442    /**
11443     * <p>Returns the current scrollbar style.</p>
11444     * @return the current scrollbar style
11445     * @see #SCROLLBARS_INSIDE_OVERLAY
11446     * @see #SCROLLBARS_INSIDE_INSET
11447     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11448     * @see #SCROLLBARS_OUTSIDE_INSET
11449     *
11450     * @attr ref android.R.styleable#View_scrollbarStyle
11451     */
11452    @ViewDebug.ExportedProperty(mapping = {
11453            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11454            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11455            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11456            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11457    })
11458    public int getScrollBarStyle() {
11459        return mViewFlags & SCROLLBARS_STYLE_MASK;
11460    }
11461
11462    /**
11463     * <p>Compute the horizontal range that the horizontal scrollbar
11464     * represents.</p>
11465     *
11466     * <p>The range is expressed in arbitrary units that must be the same as the
11467     * units used by {@link #computeHorizontalScrollExtent()} and
11468     * {@link #computeHorizontalScrollOffset()}.</p>
11469     *
11470     * <p>The default range is the drawing width of this view.</p>
11471     *
11472     * @return the total horizontal range represented by the horizontal
11473     *         scrollbar
11474     *
11475     * @see #computeHorizontalScrollExtent()
11476     * @see #computeHorizontalScrollOffset()
11477     * @see android.widget.ScrollBarDrawable
11478     */
11479    protected int computeHorizontalScrollRange() {
11480        return getWidth();
11481    }
11482
11483    /**
11484     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11485     * within the horizontal range. This value is used to compute the position
11486     * of the thumb within the scrollbar's track.</p>
11487     *
11488     * <p>The range is expressed in arbitrary units that must be the same as the
11489     * units used by {@link #computeHorizontalScrollRange()} and
11490     * {@link #computeHorizontalScrollExtent()}.</p>
11491     *
11492     * <p>The default offset is the scroll offset of this view.</p>
11493     *
11494     * @return the horizontal offset of the scrollbar's thumb
11495     *
11496     * @see #computeHorizontalScrollRange()
11497     * @see #computeHorizontalScrollExtent()
11498     * @see android.widget.ScrollBarDrawable
11499     */
11500    protected int computeHorizontalScrollOffset() {
11501        return mScrollX;
11502    }
11503
11504    /**
11505     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11506     * within the horizontal range. This value is used to compute the length
11507     * of the thumb within the scrollbar's track.</p>
11508     *
11509     * <p>The range is expressed in arbitrary units that must be the same as the
11510     * units used by {@link #computeHorizontalScrollRange()} and
11511     * {@link #computeHorizontalScrollOffset()}.</p>
11512     *
11513     * <p>The default extent is the drawing width of this view.</p>
11514     *
11515     * @return the horizontal extent of the scrollbar's thumb
11516     *
11517     * @see #computeHorizontalScrollRange()
11518     * @see #computeHorizontalScrollOffset()
11519     * @see android.widget.ScrollBarDrawable
11520     */
11521    protected int computeHorizontalScrollExtent() {
11522        return getWidth();
11523    }
11524
11525    /**
11526     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11527     *
11528     * <p>The range is expressed in arbitrary units that must be the same as the
11529     * units used by {@link #computeVerticalScrollExtent()} and
11530     * {@link #computeVerticalScrollOffset()}.</p>
11531     *
11532     * @return the total vertical range represented by the vertical scrollbar
11533     *
11534     * <p>The default range is the drawing height of this view.</p>
11535     *
11536     * @see #computeVerticalScrollExtent()
11537     * @see #computeVerticalScrollOffset()
11538     * @see android.widget.ScrollBarDrawable
11539     */
11540    protected int computeVerticalScrollRange() {
11541        return getHeight();
11542    }
11543
11544    /**
11545     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11546     * within the horizontal range. This value is used to compute the position
11547     * of the thumb within the scrollbar's track.</p>
11548     *
11549     * <p>The range is expressed in arbitrary units that must be the same as the
11550     * units used by {@link #computeVerticalScrollRange()} and
11551     * {@link #computeVerticalScrollExtent()}.</p>
11552     *
11553     * <p>The default offset is the scroll offset of this view.</p>
11554     *
11555     * @return the vertical offset of the scrollbar's thumb
11556     *
11557     * @see #computeVerticalScrollRange()
11558     * @see #computeVerticalScrollExtent()
11559     * @see android.widget.ScrollBarDrawable
11560     */
11561    protected int computeVerticalScrollOffset() {
11562        return mScrollY;
11563    }
11564
11565    /**
11566     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11567     * within the vertical range. This value is used to compute the length
11568     * of the thumb within the scrollbar's track.</p>
11569     *
11570     * <p>The range is expressed in arbitrary units that must be the same as the
11571     * units used by {@link #computeVerticalScrollRange()} and
11572     * {@link #computeVerticalScrollOffset()}.</p>
11573     *
11574     * <p>The default extent is the drawing height of this view.</p>
11575     *
11576     * @return the vertical extent of the scrollbar's thumb
11577     *
11578     * @see #computeVerticalScrollRange()
11579     * @see #computeVerticalScrollOffset()
11580     * @see android.widget.ScrollBarDrawable
11581     */
11582    protected int computeVerticalScrollExtent() {
11583        return getHeight();
11584    }
11585
11586    /**
11587     * Check if this view can be scrolled horizontally in a certain direction.
11588     *
11589     * @param direction Negative to check scrolling left, positive to check scrolling right.
11590     * @return true if this view can be scrolled in the specified direction, false otherwise.
11591     */
11592    public boolean canScrollHorizontally(int direction) {
11593        final int offset = computeHorizontalScrollOffset();
11594        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11595        if (range == 0) return false;
11596        if (direction < 0) {
11597            return offset > 0;
11598        } else {
11599            return offset < range - 1;
11600        }
11601    }
11602
11603    /**
11604     * Check if this view can be scrolled vertically in a certain direction.
11605     *
11606     * @param direction Negative to check scrolling up, positive to check scrolling down.
11607     * @return true if this view can be scrolled in the specified direction, false otherwise.
11608     */
11609    public boolean canScrollVertically(int direction) {
11610        final int offset = computeVerticalScrollOffset();
11611        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11612        if (range == 0) return false;
11613        if (direction < 0) {
11614            return offset > 0;
11615        } else {
11616            return offset < range - 1;
11617        }
11618    }
11619
11620    /**
11621     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11622     * scrollbars are painted only if they have been awakened first.</p>
11623     *
11624     * @param canvas the canvas on which to draw the scrollbars
11625     *
11626     * @see #awakenScrollBars(int)
11627     */
11628    protected final void onDrawScrollBars(Canvas canvas) {
11629        // scrollbars are drawn only when the animation is running
11630        final ScrollabilityCache cache = mScrollCache;
11631        if (cache != null) {
11632
11633            int state = cache.state;
11634
11635            if (state == ScrollabilityCache.OFF) {
11636                return;
11637            }
11638
11639            boolean invalidate = false;
11640
11641            if (state == ScrollabilityCache.FADING) {
11642                // We're fading -- get our fade interpolation
11643                if (cache.interpolatorValues == null) {
11644                    cache.interpolatorValues = new float[1];
11645                }
11646
11647                float[] values = cache.interpolatorValues;
11648
11649                // Stops the animation if we're done
11650                if (cache.scrollBarInterpolator.timeToValues(values) ==
11651                        Interpolator.Result.FREEZE_END) {
11652                    cache.state = ScrollabilityCache.OFF;
11653                } else {
11654                    cache.scrollBar.setAlpha(Math.round(values[0]));
11655                }
11656
11657                // This will make the scroll bars inval themselves after
11658                // drawing. We only want this when we're fading so that
11659                // we prevent excessive redraws
11660                invalidate = true;
11661            } else {
11662                // We're just on -- but we may have been fading before so
11663                // reset alpha
11664                cache.scrollBar.setAlpha(255);
11665            }
11666
11667
11668            final int viewFlags = mViewFlags;
11669
11670            final boolean drawHorizontalScrollBar =
11671                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11672            final boolean drawVerticalScrollBar =
11673                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11674                && !isVerticalScrollBarHidden();
11675
11676            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11677                final int width = mRight - mLeft;
11678                final int height = mBottom - mTop;
11679
11680                final ScrollBarDrawable scrollBar = cache.scrollBar;
11681
11682                final int scrollX = mScrollX;
11683                final int scrollY = mScrollY;
11684                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11685
11686                int left;
11687                int top;
11688                int right;
11689                int bottom;
11690
11691                if (drawHorizontalScrollBar) {
11692                    int size = scrollBar.getSize(false);
11693                    if (size <= 0) {
11694                        size = cache.scrollBarSize;
11695                    }
11696
11697                    scrollBar.setParameters(computeHorizontalScrollRange(),
11698                                            computeHorizontalScrollOffset(),
11699                                            computeHorizontalScrollExtent(), false);
11700                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11701                            getVerticalScrollbarWidth() : 0;
11702                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11703                    left = scrollX + (mPaddingLeft & inside);
11704                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11705                    bottom = top + size;
11706                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11707                    if (invalidate) {
11708                        invalidate(left, top, right, bottom);
11709                    }
11710                }
11711
11712                if (drawVerticalScrollBar) {
11713                    int size = scrollBar.getSize(true);
11714                    if (size <= 0) {
11715                        size = cache.scrollBarSize;
11716                    }
11717
11718                    scrollBar.setParameters(computeVerticalScrollRange(),
11719                                            computeVerticalScrollOffset(),
11720                                            computeVerticalScrollExtent(), true);
11721                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11722                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11723                        verticalScrollbarPosition = isLayoutRtl() ?
11724                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11725                    }
11726                    switch (verticalScrollbarPosition) {
11727                        default:
11728                        case SCROLLBAR_POSITION_RIGHT:
11729                            left = scrollX + width - size - (mUserPaddingRight & inside);
11730                            break;
11731                        case SCROLLBAR_POSITION_LEFT:
11732                            left = scrollX + (mUserPaddingLeft & inside);
11733                            break;
11734                    }
11735                    top = scrollY + (mPaddingTop & inside);
11736                    right = left + size;
11737                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11738                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11739                    if (invalidate) {
11740                        invalidate(left, top, right, bottom);
11741                    }
11742                }
11743            }
11744        }
11745    }
11746
11747    /**
11748     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11749     * FastScroller is visible.
11750     * @return whether to temporarily hide the vertical scrollbar
11751     * @hide
11752     */
11753    protected boolean isVerticalScrollBarHidden() {
11754        return false;
11755    }
11756
11757    /**
11758     * <p>Draw the horizontal scrollbar if
11759     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11760     *
11761     * @param canvas the canvas on which to draw the scrollbar
11762     * @param scrollBar the scrollbar's drawable
11763     *
11764     * @see #isHorizontalScrollBarEnabled()
11765     * @see #computeHorizontalScrollRange()
11766     * @see #computeHorizontalScrollExtent()
11767     * @see #computeHorizontalScrollOffset()
11768     * @see android.widget.ScrollBarDrawable
11769     * @hide
11770     */
11771    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11772            int l, int t, int r, int b) {
11773        scrollBar.setBounds(l, t, r, b);
11774        scrollBar.draw(canvas);
11775    }
11776
11777    /**
11778     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11779     * returns true.</p>
11780     *
11781     * @param canvas the canvas on which to draw the scrollbar
11782     * @param scrollBar the scrollbar's drawable
11783     *
11784     * @see #isVerticalScrollBarEnabled()
11785     * @see #computeVerticalScrollRange()
11786     * @see #computeVerticalScrollExtent()
11787     * @see #computeVerticalScrollOffset()
11788     * @see android.widget.ScrollBarDrawable
11789     * @hide
11790     */
11791    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11792            int l, int t, int r, int b) {
11793        scrollBar.setBounds(l, t, r, b);
11794        scrollBar.draw(canvas);
11795    }
11796
11797    /**
11798     * Implement this to do your drawing.
11799     *
11800     * @param canvas the canvas on which the background will be drawn
11801     */
11802    protected void onDraw(Canvas canvas) {
11803    }
11804
11805    /*
11806     * Caller is responsible for calling requestLayout if necessary.
11807     * (This allows addViewInLayout to not request a new layout.)
11808     */
11809    void assignParent(ViewParent parent) {
11810        if (mParent == null) {
11811            mParent = parent;
11812        } else if (parent == null) {
11813            mParent = null;
11814        } else {
11815            throw new RuntimeException("view " + this + " being added, but"
11816                    + " it already has a parent");
11817        }
11818    }
11819
11820    /**
11821     * This is called when the view is attached to a window.  At this point it
11822     * has a Surface and will start drawing.  Note that this function is
11823     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11824     * however it may be called any time before the first onDraw -- including
11825     * before or after {@link #onMeasure(int, int)}.
11826     *
11827     * @see #onDetachedFromWindow()
11828     */
11829    protected void onAttachedToWindow() {
11830        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11831            mParent.requestTransparentRegion(this);
11832        }
11833
11834        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11835            initialAwakenScrollBars();
11836            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11837        }
11838
11839        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
11840
11841        jumpDrawablesToCurrentState();
11842
11843        clearAccessibilityFocus();
11844        resetSubtreeAccessibilityStateChanged();
11845
11846        if (isFocused()) {
11847            InputMethodManager imm = InputMethodManager.peekInstance();
11848            imm.focusIn(this);
11849        }
11850
11851        if (mDisplayList != null) {
11852            mDisplayList.clearDirty();
11853        }
11854    }
11855
11856    /**
11857     * Resolve all RTL related properties.
11858     *
11859     * @return true if resolution of RTL properties has been done
11860     *
11861     * @hide
11862     */
11863    public boolean resolveRtlPropertiesIfNeeded() {
11864        if (!needRtlPropertiesResolution()) return false;
11865
11866        // Order is important here: LayoutDirection MUST be resolved first
11867        if (!isLayoutDirectionResolved()) {
11868            resolveLayoutDirection();
11869            resolveLayoutParams();
11870        }
11871        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11872        if (!isTextDirectionResolved()) {
11873            resolveTextDirection();
11874        }
11875        if (!isTextAlignmentResolved()) {
11876            resolveTextAlignment();
11877        }
11878        if (!isPaddingResolved()) {
11879            resolvePadding();
11880        }
11881        if (!isDrawablesResolved()) {
11882            resolveDrawables();
11883        }
11884        onRtlPropertiesChanged(getLayoutDirection());
11885        return true;
11886    }
11887
11888    /**
11889     * Reset resolution of all RTL related properties.
11890     *
11891     * @hide
11892     */
11893    public void resetRtlProperties() {
11894        resetResolvedLayoutDirection();
11895        resetResolvedTextDirection();
11896        resetResolvedTextAlignment();
11897        resetResolvedPadding();
11898        resetResolvedDrawables();
11899    }
11900
11901    /**
11902     * @see #onScreenStateChanged(int)
11903     */
11904    void dispatchScreenStateChanged(int screenState) {
11905        onScreenStateChanged(screenState);
11906    }
11907
11908    /**
11909     * This method is called whenever the state of the screen this view is
11910     * attached to changes. A state change will usually occurs when the screen
11911     * turns on or off (whether it happens automatically or the user does it
11912     * manually.)
11913     *
11914     * @param screenState The new state of the screen. Can be either
11915     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11916     */
11917    public void onScreenStateChanged(int screenState) {
11918    }
11919
11920    /**
11921     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11922     */
11923    private boolean hasRtlSupport() {
11924        return mContext.getApplicationInfo().hasRtlSupport();
11925    }
11926
11927    /**
11928     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11929     * RTL not supported)
11930     */
11931    private boolean isRtlCompatibilityMode() {
11932        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11933        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11934    }
11935
11936    /**
11937     * @return true if RTL properties need resolution.
11938     *
11939     */
11940    private boolean needRtlPropertiesResolution() {
11941        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11942    }
11943
11944    /**
11945     * Called when any RTL property (layout direction or text direction or text alignment) has
11946     * been changed.
11947     *
11948     * Subclasses need to override this method to take care of cached information that depends on the
11949     * resolved layout direction, or to inform child views that inherit their layout direction.
11950     *
11951     * The default implementation does nothing.
11952     *
11953     * @param layoutDirection the direction of the layout
11954     *
11955     * @see #LAYOUT_DIRECTION_LTR
11956     * @see #LAYOUT_DIRECTION_RTL
11957     */
11958    public void onRtlPropertiesChanged(int layoutDirection) {
11959    }
11960
11961    /**
11962     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11963     * that the parent directionality can and will be resolved before its children.
11964     *
11965     * @return true if resolution has been done, false otherwise.
11966     *
11967     * @hide
11968     */
11969    public boolean resolveLayoutDirection() {
11970        // Clear any previous layout direction resolution
11971        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11972
11973        if (hasRtlSupport()) {
11974            // Set resolved depending on layout direction
11975            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11976                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11977                case LAYOUT_DIRECTION_INHERIT:
11978                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11979                    // later to get the correct resolved value
11980                    if (!canResolveLayoutDirection()) return false;
11981
11982                    // Parent has not yet resolved, LTR is still the default
11983                    try {
11984                        if (!mParent.isLayoutDirectionResolved()) return false;
11985
11986                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11987                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11988                        }
11989                    } catch (AbstractMethodError e) {
11990                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
11991                                " does not fully implement ViewParent", e);
11992                    }
11993                    break;
11994                case LAYOUT_DIRECTION_RTL:
11995                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11996                    break;
11997                case LAYOUT_DIRECTION_LOCALE:
11998                    if((LAYOUT_DIRECTION_RTL ==
11999                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12000                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12001                    }
12002                    break;
12003                default:
12004                    // Nothing to do, LTR by default
12005            }
12006        }
12007
12008        // Set to resolved
12009        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12010        return true;
12011    }
12012
12013    /**
12014     * Check if layout direction resolution can be done.
12015     *
12016     * @return true if layout direction resolution can be done otherwise return false.
12017     */
12018    public boolean canResolveLayoutDirection() {
12019        switch (getRawLayoutDirection()) {
12020            case LAYOUT_DIRECTION_INHERIT:
12021                if (mParent != null) {
12022                    try {
12023                        return mParent.canResolveLayoutDirection();
12024                    } catch (AbstractMethodError e) {
12025                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12026                                " does not fully implement ViewParent", e);
12027                    }
12028                }
12029                return false;
12030
12031            default:
12032                return true;
12033        }
12034    }
12035
12036    /**
12037     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12038     * {@link #onMeasure(int, int)}.
12039     *
12040     * @hide
12041     */
12042    public void resetResolvedLayoutDirection() {
12043        // Reset the current resolved bits
12044        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12045    }
12046
12047    /**
12048     * @return true if the layout direction is inherited.
12049     *
12050     * @hide
12051     */
12052    public boolean isLayoutDirectionInherited() {
12053        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12054    }
12055
12056    /**
12057     * @return true if layout direction has been resolved.
12058     */
12059    public boolean isLayoutDirectionResolved() {
12060        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12061    }
12062
12063    /**
12064     * Return if padding has been resolved
12065     *
12066     * @hide
12067     */
12068    boolean isPaddingResolved() {
12069        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12070    }
12071
12072    /**
12073     * Resolves padding depending on layout direction, if applicable, and
12074     * recomputes internal padding values to adjust for scroll bars.
12075     *
12076     * @hide
12077     */
12078    public void resolvePadding() {
12079        if (!isRtlCompatibilityMode()) {
12080            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12081            // If start / end padding are defined, they will be resolved (hence overriding) to
12082            // left / right or right / left depending on the resolved layout direction.
12083            // If start / end padding are not defined, use the left / right ones.
12084            int resolvedLayoutDirection = getLayoutDirection();
12085            switch (resolvedLayoutDirection) {
12086                case LAYOUT_DIRECTION_RTL:
12087                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12088                        mUserPaddingRight = mUserPaddingStart;
12089                    } else {
12090                        mUserPaddingRight = mUserPaddingRightInitial;
12091                    }
12092                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12093                        mUserPaddingLeft = mUserPaddingEnd;
12094                    } else {
12095                        mUserPaddingLeft = mUserPaddingLeftInitial;
12096                    }
12097                    break;
12098                case LAYOUT_DIRECTION_LTR:
12099                default:
12100                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12101                        mUserPaddingLeft = mUserPaddingStart;
12102                    } else {
12103                        mUserPaddingLeft = mUserPaddingLeftInitial;
12104                    }
12105                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12106                        mUserPaddingRight = mUserPaddingEnd;
12107                    } else {
12108                        mUserPaddingRight = mUserPaddingRightInitial;
12109                    }
12110            }
12111
12112            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12113
12114            onRtlPropertiesChanged(resolvedLayoutDirection);
12115        }
12116
12117        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12118
12119        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12120    }
12121
12122    /**
12123     * Reset the resolved layout direction.
12124     *
12125     * @hide
12126     */
12127    public void resetResolvedPadding() {
12128        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12129    }
12130
12131    /**
12132     * This is called when the view is detached from a window.  At this point it
12133     * no longer has a surface for drawing.
12134     *
12135     * @see #onAttachedToWindow()
12136     */
12137    protected void onDetachedFromWindow() {
12138        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12139        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12140
12141        removeUnsetPressCallback();
12142        removeLongPressCallback();
12143        removePerformClickCallback();
12144        removeSendViewScrolledAccessibilityEventCallback();
12145
12146        destroyDrawingCache();
12147        destroyLayer(false);
12148
12149        cleanupDraw();
12150
12151        mCurrentAnimation = null;
12152        mCurrentScene = null;
12153    }
12154
12155    private void cleanupDraw() {
12156        if (mAttachInfo != null) {
12157            if (mDisplayList != null) {
12158                mDisplayList.markDirty();
12159                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12160            }
12161            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12162        } else {
12163            // Should never happen
12164            resetDisplayList();
12165        }
12166    }
12167
12168    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12169    }
12170
12171    /**
12172     * @return The number of times this view has been attached to a window
12173     */
12174    protected int getWindowAttachCount() {
12175        return mWindowAttachCount;
12176    }
12177
12178    /**
12179     * Retrieve a unique token identifying the window this view is attached to.
12180     * @return Return the window's token for use in
12181     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12182     */
12183    public IBinder getWindowToken() {
12184        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12185    }
12186
12187    /**
12188     * Retrieve the {@link WindowId} for the window this view is
12189     * currently attached to.
12190     */
12191    public WindowId getWindowId() {
12192        if (mAttachInfo == null) {
12193            return null;
12194        }
12195        if (mAttachInfo.mWindowId == null) {
12196            try {
12197                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12198                        mAttachInfo.mWindowToken);
12199                mAttachInfo.mWindowId = new WindowId(
12200                        mAttachInfo.mIWindowId);
12201            } catch (RemoteException e) {
12202            }
12203        }
12204        return mAttachInfo.mWindowId;
12205    }
12206
12207    /**
12208     * Retrieve a unique token identifying the top-level "real" window of
12209     * the window that this view is attached to.  That is, this is like
12210     * {@link #getWindowToken}, except if the window this view in is a panel
12211     * window (attached to another containing window), then the token of
12212     * the containing window is returned instead.
12213     *
12214     * @return Returns the associated window token, either
12215     * {@link #getWindowToken()} or the containing window's token.
12216     */
12217    public IBinder getApplicationWindowToken() {
12218        AttachInfo ai = mAttachInfo;
12219        if (ai != null) {
12220            IBinder appWindowToken = ai.mPanelParentWindowToken;
12221            if (appWindowToken == null) {
12222                appWindowToken = ai.mWindowToken;
12223            }
12224            return appWindowToken;
12225        }
12226        return null;
12227    }
12228
12229    /**
12230     * Gets the logical display to which the view's window has been attached.
12231     *
12232     * @return The logical display, or null if the view is not currently attached to a window.
12233     */
12234    public Display getDisplay() {
12235        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12236    }
12237
12238    /**
12239     * Retrieve private session object this view hierarchy is using to
12240     * communicate with the window manager.
12241     * @return the session object to communicate with the window manager
12242     */
12243    /*package*/ IWindowSession getWindowSession() {
12244        return mAttachInfo != null ? mAttachInfo.mSession : null;
12245    }
12246
12247    /**
12248     * @param info the {@link android.view.View.AttachInfo} to associated with
12249     *        this view
12250     */
12251    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12252        //System.out.println("Attached! " + this);
12253        mAttachInfo = info;
12254        if (mOverlay != null) {
12255            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12256        }
12257        mWindowAttachCount++;
12258        // We will need to evaluate the drawable state at least once.
12259        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12260        if (mFloatingTreeObserver != null) {
12261            info.mTreeObserver.merge(mFloatingTreeObserver);
12262            mFloatingTreeObserver = null;
12263        }
12264        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12265            mAttachInfo.mScrollContainers.add(this);
12266            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12267        }
12268        performCollectViewAttributes(mAttachInfo, visibility);
12269        onAttachedToWindow();
12270
12271        ListenerInfo li = mListenerInfo;
12272        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12273                li != null ? li.mOnAttachStateChangeListeners : null;
12274        if (listeners != null && listeners.size() > 0) {
12275            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12276            // perform the dispatching. The iterator is a safe guard against listeners that
12277            // could mutate the list by calling the various add/remove methods. This prevents
12278            // the array from being modified while we iterate it.
12279            for (OnAttachStateChangeListener listener : listeners) {
12280                listener.onViewAttachedToWindow(this);
12281            }
12282        }
12283
12284        int vis = info.mWindowVisibility;
12285        if (vis != GONE) {
12286            onWindowVisibilityChanged(vis);
12287        }
12288        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12289            // If nobody has evaluated the drawable state yet, then do it now.
12290            refreshDrawableState();
12291        }
12292        needGlobalAttributesUpdate(false);
12293    }
12294
12295    void dispatchDetachedFromWindow() {
12296        AttachInfo info = mAttachInfo;
12297        if (info != null) {
12298            int vis = info.mWindowVisibility;
12299            if (vis != GONE) {
12300                onWindowVisibilityChanged(GONE);
12301            }
12302        }
12303
12304        onDetachedFromWindow();
12305
12306        ListenerInfo li = mListenerInfo;
12307        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12308                li != null ? li.mOnAttachStateChangeListeners : null;
12309        if (listeners != null && listeners.size() > 0) {
12310            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12311            // perform the dispatching. The iterator is a safe guard against listeners that
12312            // could mutate the list by calling the various add/remove methods. This prevents
12313            // the array from being modified while we iterate it.
12314            for (OnAttachStateChangeListener listener : listeners) {
12315                listener.onViewDetachedFromWindow(this);
12316            }
12317        }
12318
12319        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12320            mAttachInfo.mScrollContainers.remove(this);
12321            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12322        }
12323
12324        mAttachInfo = null;
12325        if (mOverlay != null) {
12326            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12327        }
12328    }
12329
12330    /**
12331     * Store this view hierarchy's frozen state into the given container.
12332     *
12333     * @param container The SparseArray in which to save the view's state.
12334     *
12335     * @see #restoreHierarchyState(android.util.SparseArray)
12336     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12337     * @see #onSaveInstanceState()
12338     */
12339    public void saveHierarchyState(SparseArray<Parcelable> container) {
12340        dispatchSaveInstanceState(container);
12341    }
12342
12343    /**
12344     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12345     * this view and its children. May be overridden to modify how freezing happens to a
12346     * view's children; for example, some views may want to not store state for their children.
12347     *
12348     * @param container The SparseArray in which to save the view's state.
12349     *
12350     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12351     * @see #saveHierarchyState(android.util.SparseArray)
12352     * @see #onSaveInstanceState()
12353     */
12354    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12355        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12356            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12357            Parcelable state = onSaveInstanceState();
12358            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12359                throw new IllegalStateException(
12360                        "Derived class did not call super.onSaveInstanceState()");
12361            }
12362            if (state != null) {
12363                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12364                // + ": " + state);
12365                container.put(mID, state);
12366            }
12367        }
12368    }
12369
12370    /**
12371     * Hook allowing a view to generate a representation of its internal state
12372     * that can later be used to create a new instance with that same state.
12373     * This state should only contain information that is not persistent or can
12374     * not be reconstructed later. For example, you will never store your
12375     * current position on screen because that will be computed again when a
12376     * new instance of the view is placed in its view hierarchy.
12377     * <p>
12378     * Some examples of things you may store here: the current cursor position
12379     * in a text view (but usually not the text itself since that is stored in a
12380     * content provider or other persistent storage), the currently selected
12381     * item in a list view.
12382     *
12383     * @return Returns a Parcelable object containing the view's current dynamic
12384     *         state, or null if there is nothing interesting to save. The
12385     *         default implementation returns null.
12386     * @see #onRestoreInstanceState(android.os.Parcelable)
12387     * @see #saveHierarchyState(android.util.SparseArray)
12388     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12389     * @see #setSaveEnabled(boolean)
12390     */
12391    protected Parcelable onSaveInstanceState() {
12392        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12393        return BaseSavedState.EMPTY_STATE;
12394    }
12395
12396    /**
12397     * Restore this view hierarchy's frozen state from the given container.
12398     *
12399     * @param container The SparseArray which holds previously frozen states.
12400     *
12401     * @see #saveHierarchyState(android.util.SparseArray)
12402     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12403     * @see #onRestoreInstanceState(android.os.Parcelable)
12404     */
12405    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12406        dispatchRestoreInstanceState(container);
12407    }
12408
12409    /**
12410     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12411     * state for this view and its children. May be overridden to modify how restoring
12412     * happens to a view's children; for example, some views may want to not store state
12413     * for their children.
12414     *
12415     * @param container The SparseArray which holds previously saved state.
12416     *
12417     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12418     * @see #restoreHierarchyState(android.util.SparseArray)
12419     * @see #onRestoreInstanceState(android.os.Parcelable)
12420     */
12421    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12422        if (mID != NO_ID) {
12423            Parcelable state = container.get(mID);
12424            if (state != null) {
12425                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12426                // + ": " + state);
12427                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12428                onRestoreInstanceState(state);
12429                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12430                    throw new IllegalStateException(
12431                            "Derived class did not call super.onRestoreInstanceState()");
12432                }
12433            }
12434        }
12435    }
12436
12437    /**
12438     * Hook allowing a view to re-apply a representation of its internal state that had previously
12439     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12440     * null state.
12441     *
12442     * @param state The frozen state that had previously been returned by
12443     *        {@link #onSaveInstanceState}.
12444     *
12445     * @see #onSaveInstanceState()
12446     * @see #restoreHierarchyState(android.util.SparseArray)
12447     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12448     */
12449    protected void onRestoreInstanceState(Parcelable state) {
12450        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12451        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12452            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12453                    + "received " + state.getClass().toString() + " instead. This usually happens "
12454                    + "when two views of different type have the same id in the same hierarchy. "
12455                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12456                    + "other views do not use the same id.");
12457        }
12458    }
12459
12460    /**
12461     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12462     *
12463     * @return the drawing start time in milliseconds
12464     */
12465    public long getDrawingTime() {
12466        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12467    }
12468
12469    /**
12470     * <p>Enables or disables the duplication of the parent's state into this view. When
12471     * duplication is enabled, this view gets its drawable state from its parent rather
12472     * than from its own internal properties.</p>
12473     *
12474     * <p>Note: in the current implementation, setting this property to true after the
12475     * view was added to a ViewGroup might have no effect at all. This property should
12476     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12477     *
12478     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12479     * property is enabled, an exception will be thrown.</p>
12480     *
12481     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12482     * parent, these states should not be affected by this method.</p>
12483     *
12484     * @param enabled True to enable duplication of the parent's drawable state, false
12485     *                to disable it.
12486     *
12487     * @see #getDrawableState()
12488     * @see #isDuplicateParentStateEnabled()
12489     */
12490    public void setDuplicateParentStateEnabled(boolean enabled) {
12491        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12492    }
12493
12494    /**
12495     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12496     *
12497     * @return True if this view's drawable state is duplicated from the parent,
12498     *         false otherwise
12499     *
12500     * @see #getDrawableState()
12501     * @see #setDuplicateParentStateEnabled(boolean)
12502     */
12503    public boolean isDuplicateParentStateEnabled() {
12504        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12505    }
12506
12507    /**
12508     * <p>Specifies the type of layer backing this view. The layer can be
12509     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12510     * {@link #LAYER_TYPE_HARDWARE}.</p>
12511     *
12512     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12513     * instance that controls how the layer is composed on screen. The following
12514     * properties of the paint are taken into account when composing the layer:</p>
12515     * <ul>
12516     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12517     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12518     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12519     * </ul>
12520     *
12521     * <p>If this view has an alpha value set to < 1.0 by calling
12522     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12523     * by this view's alpha value.</p>
12524     *
12525     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12526     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12527     * for more information on when and how to use layers.</p>
12528     *
12529     * @param layerType The type of layer to use with this view, must be one of
12530     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12531     *        {@link #LAYER_TYPE_HARDWARE}
12532     * @param paint The paint used to compose the layer. This argument is optional
12533     *        and can be null. It is ignored when the layer type is
12534     *        {@link #LAYER_TYPE_NONE}
12535     *
12536     * @see #getLayerType()
12537     * @see #LAYER_TYPE_NONE
12538     * @see #LAYER_TYPE_SOFTWARE
12539     * @see #LAYER_TYPE_HARDWARE
12540     * @see #setAlpha(float)
12541     *
12542     * @attr ref android.R.styleable#View_layerType
12543     */
12544    public void setLayerType(int layerType, Paint paint) {
12545        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12546            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12547                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12548        }
12549
12550        if (layerType == mLayerType) {
12551            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12552                mLayerPaint = paint == null ? new Paint() : paint;
12553                invalidateParentCaches();
12554                invalidate(true);
12555            }
12556            return;
12557        }
12558
12559        // Destroy any previous software drawing cache if needed
12560        switch (mLayerType) {
12561            case LAYER_TYPE_HARDWARE:
12562                destroyLayer(false);
12563                // fall through - non-accelerated views may use software layer mechanism instead
12564            case LAYER_TYPE_SOFTWARE:
12565                destroyDrawingCache();
12566                break;
12567            default:
12568                break;
12569        }
12570
12571        mLayerType = layerType;
12572        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12573        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12574        mLocalDirtyRect = layerDisabled ? null : new Rect();
12575
12576        invalidateParentCaches();
12577        invalidate(true);
12578    }
12579
12580    /**
12581     * Updates the {@link Paint} object used with the current layer (used only if the current
12582     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12583     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12584     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12585     * ensure that the view gets redrawn immediately.
12586     *
12587     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12588     * instance that controls how the layer is composed on screen. The following
12589     * properties of the paint are taken into account when composing the layer:</p>
12590     * <ul>
12591     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12592     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12593     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12594     * </ul>
12595     *
12596     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12597     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12598     *
12599     * @param paint The paint used to compose the layer. This argument is optional
12600     *        and can be null. It is ignored when the layer type is
12601     *        {@link #LAYER_TYPE_NONE}
12602     *
12603     * @see #setLayerType(int, android.graphics.Paint)
12604     */
12605    public void setLayerPaint(Paint paint) {
12606        int layerType = getLayerType();
12607        if (layerType != LAYER_TYPE_NONE) {
12608            mLayerPaint = paint == null ? new Paint() : paint;
12609            if (layerType == LAYER_TYPE_HARDWARE) {
12610                HardwareLayer layer = getHardwareLayer();
12611                if (layer != null) {
12612                    layer.setLayerPaint(paint);
12613                }
12614                invalidateViewProperty(false, false);
12615            } else {
12616                invalidate();
12617            }
12618        }
12619    }
12620
12621    /**
12622     * Indicates whether this view has a static layer. A view with layer type
12623     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12624     * dynamic.
12625     */
12626    boolean hasStaticLayer() {
12627        return true;
12628    }
12629
12630    /**
12631     * Indicates what type of layer is currently associated with this view. By default
12632     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12633     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12634     * for more information on the different types of layers.
12635     *
12636     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12637     *         {@link #LAYER_TYPE_HARDWARE}
12638     *
12639     * @see #setLayerType(int, android.graphics.Paint)
12640     * @see #buildLayer()
12641     * @see #LAYER_TYPE_NONE
12642     * @see #LAYER_TYPE_SOFTWARE
12643     * @see #LAYER_TYPE_HARDWARE
12644     */
12645    public int getLayerType() {
12646        return mLayerType;
12647    }
12648
12649    /**
12650     * Forces this view's layer to be created and this view to be rendered
12651     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12652     * invoking this method will have no effect.
12653     *
12654     * This method can for instance be used to render a view into its layer before
12655     * starting an animation. If this view is complex, rendering into the layer
12656     * before starting the animation will avoid skipping frames.
12657     *
12658     * @throws IllegalStateException If this view is not attached to a window
12659     *
12660     * @see #setLayerType(int, android.graphics.Paint)
12661     */
12662    public void buildLayer() {
12663        if (mLayerType == LAYER_TYPE_NONE) return;
12664
12665        final AttachInfo attachInfo = mAttachInfo;
12666        if (attachInfo == null) {
12667            throw new IllegalStateException("This view must be attached to a window first");
12668        }
12669
12670        switch (mLayerType) {
12671            case LAYER_TYPE_HARDWARE:
12672                if (attachInfo.mHardwareRenderer != null &&
12673                        attachInfo.mHardwareRenderer.isEnabled() &&
12674                        attachInfo.mHardwareRenderer.validate()) {
12675                    getHardwareLayer();
12676                    // TODO: We need a better way to handle this case
12677                    // If views have registered pre-draw listeners they need
12678                    // to be notified before we build the layer. Those listeners
12679                    // may however rely on other events to happen first so we
12680                    // cannot just invoke them here until they don't cancel the
12681                    // current frame
12682                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
12683                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
12684                    }
12685                }
12686                break;
12687            case LAYER_TYPE_SOFTWARE:
12688                buildDrawingCache(true);
12689                break;
12690        }
12691    }
12692
12693    /**
12694     * <p>Returns a hardware layer that can be used to draw this view again
12695     * without executing its draw method.</p>
12696     *
12697     * @return A HardwareLayer ready to render, or null if an error occurred.
12698     */
12699    HardwareLayer getHardwareLayer() {
12700        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12701                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12702            return null;
12703        }
12704
12705        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12706
12707        final int width = mRight - mLeft;
12708        final int height = mBottom - mTop;
12709
12710        if (width == 0 || height == 0) {
12711            return null;
12712        }
12713
12714        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12715            if (mHardwareLayer == null) {
12716                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12717                        width, height, isOpaque());
12718                mLocalDirtyRect.set(0, 0, width, height);
12719            } else {
12720                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12721                    if (mHardwareLayer.resize(width, height)) {
12722                        mLocalDirtyRect.set(0, 0, width, height);
12723                    }
12724                }
12725
12726                // This should not be necessary but applications that change
12727                // the parameters of their background drawable without calling
12728                // this.setBackground(Drawable) can leave the view in a bad state
12729                // (for instance isOpaque() returns true, but the background is
12730                // not opaque.)
12731                computeOpaqueFlags();
12732
12733                final boolean opaque = isOpaque();
12734                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12735                    mHardwareLayer.setOpaque(opaque);
12736                    mLocalDirtyRect.set(0, 0, width, height);
12737                }
12738            }
12739
12740            // The layer is not valid if the underlying GPU resources cannot be allocated
12741            if (!mHardwareLayer.isValid()) {
12742                return null;
12743            }
12744
12745            mHardwareLayer.setLayerPaint(mLayerPaint);
12746            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12747            ViewRootImpl viewRoot = getViewRootImpl();
12748            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12749
12750            mLocalDirtyRect.setEmpty();
12751        }
12752
12753        return mHardwareLayer;
12754    }
12755
12756    /**
12757     * Destroys this View's hardware layer if possible.
12758     *
12759     * @return True if the layer was destroyed, false otherwise.
12760     *
12761     * @see #setLayerType(int, android.graphics.Paint)
12762     * @see #LAYER_TYPE_HARDWARE
12763     */
12764    boolean destroyLayer(boolean valid) {
12765        if (mHardwareLayer != null) {
12766            AttachInfo info = mAttachInfo;
12767            if (info != null && info.mHardwareRenderer != null &&
12768                    info.mHardwareRenderer.isEnabled() &&
12769                    (valid || info.mHardwareRenderer.validate())) {
12770
12771                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
12772                mHardwareLayer.destroy();
12773                mHardwareLayer = null;
12774
12775                invalidate(true);
12776                invalidateParentCaches();
12777            }
12778            return true;
12779        }
12780        return false;
12781    }
12782
12783    /**
12784     * Destroys all hardware rendering resources. This method is invoked
12785     * when the system needs to reclaim resources. Upon execution of this
12786     * method, you should free any OpenGL resources created by the view.
12787     *
12788     * Note: you <strong>must</strong> call
12789     * <code>super.destroyHardwareResources()</code> when overriding
12790     * this method.
12791     *
12792     * @hide
12793     */
12794    protected void destroyHardwareResources() {
12795        resetDisplayList();
12796        destroyLayer(true);
12797    }
12798
12799    /**
12800     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12801     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12802     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12803     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12804     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12805     * null.</p>
12806     *
12807     * <p>Enabling the drawing cache is similar to
12808     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12809     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12810     * drawing cache has no effect on rendering because the system uses a different mechanism
12811     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12812     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12813     * for information on how to enable software and hardware layers.</p>
12814     *
12815     * <p>This API can be used to manually generate
12816     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12817     * {@link #getDrawingCache()}.</p>
12818     *
12819     * @param enabled true to enable the drawing cache, false otherwise
12820     *
12821     * @see #isDrawingCacheEnabled()
12822     * @see #getDrawingCache()
12823     * @see #buildDrawingCache()
12824     * @see #setLayerType(int, android.graphics.Paint)
12825     */
12826    public void setDrawingCacheEnabled(boolean enabled) {
12827        mCachingFailed = false;
12828        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12829    }
12830
12831    /**
12832     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12833     *
12834     * @return true if the drawing cache is enabled
12835     *
12836     * @see #setDrawingCacheEnabled(boolean)
12837     * @see #getDrawingCache()
12838     */
12839    @ViewDebug.ExportedProperty(category = "drawing")
12840    public boolean isDrawingCacheEnabled() {
12841        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12842    }
12843
12844    /**
12845     * Debugging utility which recursively outputs the dirty state of a view and its
12846     * descendants.
12847     *
12848     * @hide
12849     */
12850    @SuppressWarnings({"UnusedDeclaration"})
12851    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12852        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12853                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12854                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12855                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12856        if (clear) {
12857            mPrivateFlags &= clearMask;
12858        }
12859        if (this instanceof ViewGroup) {
12860            ViewGroup parent = (ViewGroup) this;
12861            final int count = parent.getChildCount();
12862            for (int i = 0; i < count; i++) {
12863                final View child = parent.getChildAt(i);
12864                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12865            }
12866        }
12867    }
12868
12869    /**
12870     * This method is used by ViewGroup to cause its children to restore or recreate their
12871     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12872     * to recreate its own display list, which would happen if it went through the normal
12873     * draw/dispatchDraw mechanisms.
12874     *
12875     * @hide
12876     */
12877    protected void dispatchGetDisplayList() {}
12878
12879    /**
12880     * A view that is not attached or hardware accelerated cannot create a display list.
12881     * This method checks these conditions and returns the appropriate result.
12882     *
12883     * @return true if view has the ability to create a display list, false otherwise.
12884     *
12885     * @hide
12886     */
12887    public boolean canHaveDisplayList() {
12888        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12889    }
12890
12891    /**
12892     * @return The {@link HardwareRenderer} associated with that view or null if
12893     *         hardware rendering is not supported or this view is not attached
12894     *         to a window.
12895     *
12896     * @hide
12897     */
12898    public HardwareRenderer getHardwareRenderer() {
12899        if (mAttachInfo != null) {
12900            return mAttachInfo.mHardwareRenderer;
12901        }
12902        return null;
12903    }
12904
12905    /**
12906     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12907     * Otherwise, the same display list will be returned (after having been rendered into
12908     * along the way, depending on the invalidation state of the view).
12909     *
12910     * @param displayList The previous version of this displayList, could be null.
12911     * @param isLayer Whether the requester of the display list is a layer. If so,
12912     * the view will avoid creating a layer inside the resulting display list.
12913     * @return A new or reused DisplayList object.
12914     */
12915    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12916        if (!canHaveDisplayList()) {
12917            return null;
12918        }
12919
12920        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12921                displayList == null || !displayList.isValid() ||
12922                (!isLayer && mRecreateDisplayList))) {
12923            // Don't need to recreate the display list, just need to tell our
12924            // children to restore/recreate theirs
12925            if (displayList != null && displayList.isValid() &&
12926                    !isLayer && !mRecreateDisplayList) {
12927                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12928                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12929                dispatchGetDisplayList();
12930
12931                return displayList;
12932            }
12933
12934            if (!isLayer) {
12935                // If we got here, we're recreating it. Mark it as such to ensure that
12936                // we copy in child display lists into ours in drawChild()
12937                mRecreateDisplayList = true;
12938            }
12939            if (displayList == null) {
12940                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
12941                // If we're creating a new display list, make sure our parent gets invalidated
12942                // since they will need to recreate their display list to account for this
12943                // new child display list.
12944                invalidateParentCaches();
12945            }
12946
12947            boolean caching = false;
12948            int width = mRight - mLeft;
12949            int height = mBottom - mTop;
12950            int layerType = getLayerType();
12951
12952            final HardwareCanvas canvas = displayList.start(width, height);
12953
12954            try {
12955                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12956                    if (layerType == LAYER_TYPE_HARDWARE) {
12957                        final HardwareLayer layer = getHardwareLayer();
12958                        if (layer != null && layer.isValid()) {
12959                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12960                        } else {
12961                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12962                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12963                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12964                        }
12965                        caching = true;
12966                    } else {
12967                        buildDrawingCache(true);
12968                        Bitmap cache = getDrawingCache(true);
12969                        if (cache != null) {
12970                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12971                            caching = true;
12972                        }
12973                    }
12974                } else {
12975
12976                    computeScroll();
12977
12978                    canvas.translate(-mScrollX, -mScrollY);
12979                    if (!isLayer) {
12980                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12981                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12982                    }
12983
12984                    // Fast path for layouts with no backgrounds
12985                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12986                        dispatchDraw(canvas);
12987                        if (mOverlay != null && !mOverlay.isEmpty()) {
12988                            mOverlay.getOverlayView().draw(canvas);
12989                        }
12990                    } else {
12991                        draw(canvas);
12992                    }
12993                }
12994            } finally {
12995                displayList.end();
12996                displayList.setCaching(caching);
12997                if (isLayer) {
12998                    displayList.setLeftTopRightBottom(0, 0, width, height);
12999                } else {
13000                    setDisplayListProperties(displayList);
13001                }
13002            }
13003        } else if (!isLayer) {
13004            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13005            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13006        }
13007
13008        return displayList;
13009    }
13010
13011    /**
13012     * Get the DisplayList for the HardwareLayer
13013     *
13014     * @param layer The HardwareLayer whose DisplayList we want
13015     * @return A DisplayList fopr the specified HardwareLayer
13016     */
13017    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
13018        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
13019        layer.setDisplayList(displayList);
13020        return displayList;
13021    }
13022
13023
13024    /**
13025     * <p>Returns a display list that can be used to draw this view again
13026     * without executing its draw method.</p>
13027     *
13028     * @return A DisplayList ready to replay, or null if caching is not enabled.
13029     *
13030     * @hide
13031     */
13032    public DisplayList getDisplayList() {
13033        mDisplayList = getDisplayList(mDisplayList, false);
13034        return mDisplayList;
13035    }
13036
13037    private void clearDisplayList() {
13038        if (mDisplayList != null) {
13039            mDisplayList.clear();
13040        }
13041    }
13042
13043    private void resetDisplayList() {
13044        if (mDisplayList != null) {
13045            mDisplayList.reset();
13046        }
13047    }
13048
13049    /**
13050     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13051     *
13052     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13053     *
13054     * @see #getDrawingCache(boolean)
13055     */
13056    public Bitmap getDrawingCache() {
13057        return getDrawingCache(false);
13058    }
13059
13060    /**
13061     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13062     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13063     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13064     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13065     * request the drawing cache by calling this method and draw it on screen if the
13066     * returned bitmap is not null.</p>
13067     *
13068     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13069     * this method will create a bitmap of the same size as this view. Because this bitmap
13070     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13071     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13072     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13073     * size than the view. This implies that your application must be able to handle this
13074     * size.</p>
13075     *
13076     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13077     *        the current density of the screen when the application is in compatibility
13078     *        mode.
13079     *
13080     * @return A bitmap representing this view or null if cache is disabled.
13081     *
13082     * @see #setDrawingCacheEnabled(boolean)
13083     * @see #isDrawingCacheEnabled()
13084     * @see #buildDrawingCache(boolean)
13085     * @see #destroyDrawingCache()
13086     */
13087    public Bitmap getDrawingCache(boolean autoScale) {
13088        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13089            return null;
13090        }
13091        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13092            buildDrawingCache(autoScale);
13093        }
13094        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13095    }
13096
13097    /**
13098     * <p>Frees the resources used by the drawing cache. If you call
13099     * {@link #buildDrawingCache()} manually without calling
13100     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13101     * should cleanup the cache with this method afterwards.</p>
13102     *
13103     * @see #setDrawingCacheEnabled(boolean)
13104     * @see #buildDrawingCache()
13105     * @see #getDrawingCache()
13106     */
13107    public void destroyDrawingCache() {
13108        if (mDrawingCache != null) {
13109            mDrawingCache.recycle();
13110            mDrawingCache = null;
13111        }
13112        if (mUnscaledDrawingCache != null) {
13113            mUnscaledDrawingCache.recycle();
13114            mUnscaledDrawingCache = null;
13115        }
13116    }
13117
13118    /**
13119     * Setting a solid background color for the drawing cache's bitmaps will improve
13120     * performance and memory usage. Note, though that this should only be used if this
13121     * view will always be drawn on top of a solid color.
13122     *
13123     * @param color The background color to use for the drawing cache's bitmap
13124     *
13125     * @see #setDrawingCacheEnabled(boolean)
13126     * @see #buildDrawingCache()
13127     * @see #getDrawingCache()
13128     */
13129    public void setDrawingCacheBackgroundColor(int color) {
13130        if (color != mDrawingCacheBackgroundColor) {
13131            mDrawingCacheBackgroundColor = color;
13132            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13133        }
13134    }
13135
13136    /**
13137     * @see #setDrawingCacheBackgroundColor(int)
13138     *
13139     * @return The background color to used for the drawing cache's bitmap
13140     */
13141    public int getDrawingCacheBackgroundColor() {
13142        return mDrawingCacheBackgroundColor;
13143    }
13144
13145    /**
13146     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13147     *
13148     * @see #buildDrawingCache(boolean)
13149     */
13150    public void buildDrawingCache() {
13151        buildDrawingCache(false);
13152    }
13153
13154    /**
13155     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13156     *
13157     * <p>If you call {@link #buildDrawingCache()} manually without calling
13158     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13159     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13160     *
13161     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13162     * this method will create a bitmap of the same size as this view. Because this bitmap
13163     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13164     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13165     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13166     * size than the view. This implies that your application must be able to handle this
13167     * size.</p>
13168     *
13169     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13170     * you do not need the drawing cache bitmap, calling this method will increase memory
13171     * usage and cause the view to be rendered in software once, thus negatively impacting
13172     * performance.</p>
13173     *
13174     * @see #getDrawingCache()
13175     * @see #destroyDrawingCache()
13176     */
13177    public void buildDrawingCache(boolean autoScale) {
13178        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13179                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13180            mCachingFailed = false;
13181
13182            int width = mRight - mLeft;
13183            int height = mBottom - mTop;
13184
13185            final AttachInfo attachInfo = mAttachInfo;
13186            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13187
13188            if (autoScale && scalingRequired) {
13189                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13190                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13191            }
13192
13193            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13194            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13195            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13196
13197            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13198            final long drawingCacheSize =
13199                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13200            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13201                if (width > 0 && height > 0) {
13202                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13203                            + projectedBitmapSize + " bytes, only "
13204                            + drawingCacheSize + " available");
13205                }
13206                destroyDrawingCache();
13207                mCachingFailed = true;
13208                return;
13209            }
13210
13211            boolean clear = true;
13212            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13213
13214            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13215                Bitmap.Config quality;
13216                if (!opaque) {
13217                    // Never pick ARGB_4444 because it looks awful
13218                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13219                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13220                        case DRAWING_CACHE_QUALITY_AUTO:
13221                            quality = Bitmap.Config.ARGB_8888;
13222                            break;
13223                        case DRAWING_CACHE_QUALITY_LOW:
13224                            quality = Bitmap.Config.ARGB_8888;
13225                            break;
13226                        case DRAWING_CACHE_QUALITY_HIGH:
13227                            quality = Bitmap.Config.ARGB_8888;
13228                            break;
13229                        default:
13230                            quality = Bitmap.Config.ARGB_8888;
13231                            break;
13232                    }
13233                } else {
13234                    // Optimization for translucent windows
13235                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13236                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13237                }
13238
13239                // Try to cleanup memory
13240                if (bitmap != null) bitmap.recycle();
13241
13242                try {
13243                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13244                            width, height, quality);
13245                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13246                    if (autoScale) {
13247                        mDrawingCache = bitmap;
13248                    } else {
13249                        mUnscaledDrawingCache = bitmap;
13250                    }
13251                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13252                } catch (OutOfMemoryError e) {
13253                    // If there is not enough memory to create the bitmap cache, just
13254                    // ignore the issue as bitmap caches are not required to draw the
13255                    // view hierarchy
13256                    if (autoScale) {
13257                        mDrawingCache = null;
13258                    } else {
13259                        mUnscaledDrawingCache = null;
13260                    }
13261                    mCachingFailed = true;
13262                    return;
13263                }
13264
13265                clear = drawingCacheBackgroundColor != 0;
13266            }
13267
13268            Canvas canvas;
13269            if (attachInfo != null) {
13270                canvas = attachInfo.mCanvas;
13271                if (canvas == null) {
13272                    canvas = new Canvas();
13273                }
13274                canvas.setBitmap(bitmap);
13275                // Temporarily clobber the cached Canvas in case one of our children
13276                // is also using a drawing cache. Without this, the children would
13277                // steal the canvas by attaching their own bitmap to it and bad, bad
13278                // thing would happen (invisible views, corrupted drawings, etc.)
13279                attachInfo.mCanvas = null;
13280            } else {
13281                // This case should hopefully never or seldom happen
13282                canvas = new Canvas(bitmap);
13283            }
13284
13285            if (clear) {
13286                bitmap.eraseColor(drawingCacheBackgroundColor);
13287            }
13288
13289            computeScroll();
13290            final int restoreCount = canvas.save();
13291
13292            if (autoScale && scalingRequired) {
13293                final float scale = attachInfo.mApplicationScale;
13294                canvas.scale(scale, scale);
13295            }
13296
13297            canvas.translate(-mScrollX, -mScrollY);
13298
13299            mPrivateFlags |= PFLAG_DRAWN;
13300            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13301                    mLayerType != LAYER_TYPE_NONE) {
13302                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13303            }
13304
13305            // Fast path for layouts with no backgrounds
13306            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13307                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13308                dispatchDraw(canvas);
13309                if (mOverlay != null && !mOverlay.isEmpty()) {
13310                    mOverlay.getOverlayView().draw(canvas);
13311                }
13312            } else {
13313                draw(canvas);
13314            }
13315
13316            canvas.restoreToCount(restoreCount);
13317            canvas.setBitmap(null);
13318
13319            if (attachInfo != null) {
13320                // Restore the cached Canvas for our siblings
13321                attachInfo.mCanvas = canvas;
13322            }
13323        }
13324    }
13325
13326    /**
13327     * Create a snapshot of the view into a bitmap.  We should probably make
13328     * some form of this public, but should think about the API.
13329     */
13330    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13331        int width = mRight - mLeft;
13332        int height = mBottom - mTop;
13333
13334        final AttachInfo attachInfo = mAttachInfo;
13335        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13336        width = (int) ((width * scale) + 0.5f);
13337        height = (int) ((height * scale) + 0.5f);
13338
13339        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13340                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13341        if (bitmap == null) {
13342            throw new OutOfMemoryError();
13343        }
13344
13345        Resources resources = getResources();
13346        if (resources != null) {
13347            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13348        }
13349
13350        Canvas canvas;
13351        if (attachInfo != null) {
13352            canvas = attachInfo.mCanvas;
13353            if (canvas == null) {
13354                canvas = new Canvas();
13355            }
13356            canvas.setBitmap(bitmap);
13357            // Temporarily clobber the cached Canvas in case one of our children
13358            // is also using a drawing cache. Without this, the children would
13359            // steal the canvas by attaching their own bitmap to it and bad, bad
13360            // things would happen (invisible views, corrupted drawings, etc.)
13361            attachInfo.mCanvas = null;
13362        } else {
13363            // This case should hopefully never or seldom happen
13364            canvas = new Canvas(bitmap);
13365        }
13366
13367        if ((backgroundColor & 0xff000000) != 0) {
13368            bitmap.eraseColor(backgroundColor);
13369        }
13370
13371        computeScroll();
13372        final int restoreCount = canvas.save();
13373        canvas.scale(scale, scale);
13374        canvas.translate(-mScrollX, -mScrollY);
13375
13376        // Temporarily remove the dirty mask
13377        int flags = mPrivateFlags;
13378        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13379
13380        // Fast path for layouts with no backgrounds
13381        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13382            dispatchDraw(canvas);
13383        } else {
13384            draw(canvas);
13385        }
13386
13387        mPrivateFlags = flags;
13388
13389        canvas.restoreToCount(restoreCount);
13390        canvas.setBitmap(null);
13391
13392        if (attachInfo != null) {
13393            // Restore the cached Canvas for our siblings
13394            attachInfo.mCanvas = canvas;
13395        }
13396
13397        return bitmap;
13398    }
13399
13400    /**
13401     * Indicates whether this View is currently in edit mode. A View is usually
13402     * in edit mode when displayed within a developer tool. For instance, if
13403     * this View is being drawn by a visual user interface builder, this method
13404     * should return true.
13405     *
13406     * Subclasses should check the return value of this method to provide
13407     * different behaviors if their normal behavior might interfere with the
13408     * host environment. For instance: the class spawns a thread in its
13409     * constructor, the drawing code relies on device-specific features, etc.
13410     *
13411     * This method is usually checked in the drawing code of custom widgets.
13412     *
13413     * @return True if this View is in edit mode, false otherwise.
13414     */
13415    public boolean isInEditMode() {
13416        return false;
13417    }
13418
13419    /**
13420     * If the View draws content inside its padding and enables fading edges,
13421     * it needs to support padding offsets. Padding offsets are added to the
13422     * fading edges to extend the length of the fade so that it covers pixels
13423     * drawn inside the padding.
13424     *
13425     * Subclasses of this class should override this method if they need
13426     * to draw content inside the padding.
13427     *
13428     * @return True if padding offset must be applied, false otherwise.
13429     *
13430     * @see #getLeftPaddingOffset()
13431     * @see #getRightPaddingOffset()
13432     * @see #getTopPaddingOffset()
13433     * @see #getBottomPaddingOffset()
13434     *
13435     * @since CURRENT
13436     */
13437    protected boolean isPaddingOffsetRequired() {
13438        return false;
13439    }
13440
13441    /**
13442     * Amount by which to extend the left fading region. Called only when
13443     * {@link #isPaddingOffsetRequired()} returns true.
13444     *
13445     * @return The left padding offset in pixels.
13446     *
13447     * @see #isPaddingOffsetRequired()
13448     *
13449     * @since CURRENT
13450     */
13451    protected int getLeftPaddingOffset() {
13452        return 0;
13453    }
13454
13455    /**
13456     * Amount by which to extend the right fading region. Called only when
13457     * {@link #isPaddingOffsetRequired()} returns true.
13458     *
13459     * @return The right padding offset in pixels.
13460     *
13461     * @see #isPaddingOffsetRequired()
13462     *
13463     * @since CURRENT
13464     */
13465    protected int getRightPaddingOffset() {
13466        return 0;
13467    }
13468
13469    /**
13470     * Amount by which to extend the top fading region. Called only when
13471     * {@link #isPaddingOffsetRequired()} returns true.
13472     *
13473     * @return The top padding offset in pixels.
13474     *
13475     * @see #isPaddingOffsetRequired()
13476     *
13477     * @since CURRENT
13478     */
13479    protected int getTopPaddingOffset() {
13480        return 0;
13481    }
13482
13483    /**
13484     * Amount by which to extend the bottom fading region. Called only when
13485     * {@link #isPaddingOffsetRequired()} returns true.
13486     *
13487     * @return The bottom padding offset in pixels.
13488     *
13489     * @see #isPaddingOffsetRequired()
13490     *
13491     * @since CURRENT
13492     */
13493    protected int getBottomPaddingOffset() {
13494        return 0;
13495    }
13496
13497    /**
13498     * @hide
13499     * @param offsetRequired
13500     */
13501    protected int getFadeTop(boolean offsetRequired) {
13502        int top = mPaddingTop;
13503        if (offsetRequired) top += getTopPaddingOffset();
13504        return top;
13505    }
13506
13507    /**
13508     * @hide
13509     * @param offsetRequired
13510     */
13511    protected int getFadeHeight(boolean offsetRequired) {
13512        int padding = mPaddingTop;
13513        if (offsetRequired) padding += getTopPaddingOffset();
13514        return mBottom - mTop - mPaddingBottom - padding;
13515    }
13516
13517    /**
13518     * <p>Indicates whether this view is attached to a hardware accelerated
13519     * window or not.</p>
13520     *
13521     * <p>Even if this method returns true, it does not mean that every call
13522     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13523     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13524     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13525     * window is hardware accelerated,
13526     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13527     * return false, and this method will return true.</p>
13528     *
13529     * @return True if the view is attached to a window and the window is
13530     *         hardware accelerated; false in any other case.
13531     */
13532    public boolean isHardwareAccelerated() {
13533        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13534    }
13535
13536    /**
13537     * Sets a rectangular area on this view to which the view will be clipped
13538     * when it is drawn. Setting the value to null will remove the clip bounds
13539     * and the view will draw normally, using its full bounds.
13540     *
13541     * @param clipBounds The rectangular area, in the local coordinates of
13542     * this view, to which future drawing operations will be clipped.
13543     */
13544    public void setClipBounds(Rect clipBounds) {
13545        if (clipBounds != null) {
13546            if (clipBounds.equals(mClipBounds)) {
13547                return;
13548            }
13549            if (mClipBounds == null) {
13550                invalidate();
13551                mClipBounds = new Rect(clipBounds);
13552            } else {
13553                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13554                        Math.min(mClipBounds.top, clipBounds.top),
13555                        Math.max(mClipBounds.right, clipBounds.right),
13556                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13557                mClipBounds.set(clipBounds);
13558            }
13559        } else {
13560            if (mClipBounds != null) {
13561                invalidate();
13562                mClipBounds = null;
13563            }
13564        }
13565    }
13566
13567    /**
13568     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13569     *
13570     * @return A copy of the current clip bounds if clip bounds are set,
13571     * otherwise null.
13572     */
13573    public Rect getClipBounds() {
13574        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13575    }
13576
13577    /**
13578     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13579     * case of an active Animation being run on the view.
13580     */
13581    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13582            Animation a, boolean scalingRequired) {
13583        Transformation invalidationTransform;
13584        final int flags = parent.mGroupFlags;
13585        final boolean initialized = a.isInitialized();
13586        if (!initialized) {
13587            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13588            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13589            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13590            onAnimationStart();
13591        }
13592
13593        final Transformation t = parent.getChildTransformation();
13594        boolean more = a.getTransformation(drawingTime, t, 1f);
13595        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13596            if (parent.mInvalidationTransformation == null) {
13597                parent.mInvalidationTransformation = new Transformation();
13598            }
13599            invalidationTransform = parent.mInvalidationTransformation;
13600            a.getTransformation(drawingTime, invalidationTransform, 1f);
13601        } else {
13602            invalidationTransform = t;
13603        }
13604
13605        if (more) {
13606            if (!a.willChangeBounds()) {
13607                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13608                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13609                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13610                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13611                    // The child need to draw an animation, potentially offscreen, so
13612                    // make sure we do not cancel invalidate requests
13613                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13614                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13615                }
13616            } else {
13617                if (parent.mInvalidateRegion == null) {
13618                    parent.mInvalidateRegion = new RectF();
13619                }
13620                final RectF region = parent.mInvalidateRegion;
13621                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13622                        invalidationTransform);
13623
13624                // The child need to draw an animation, potentially offscreen, so
13625                // make sure we do not cancel invalidate requests
13626                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13627
13628                final int left = mLeft + (int) region.left;
13629                final int top = mTop + (int) region.top;
13630                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13631                        top + (int) (region.height() + .5f));
13632            }
13633        }
13634        return more;
13635    }
13636
13637    /**
13638     * This method is called by getDisplayList() when a display list is created or re-rendered.
13639     * It sets or resets the current value of all properties on that display list (resetting is
13640     * necessary when a display list is being re-created, because we need to make sure that
13641     * previously-set transform values
13642     */
13643    void setDisplayListProperties(DisplayList displayList) {
13644        if (displayList != null) {
13645            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13646            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13647            if (mParent instanceof ViewGroup) {
13648                displayList.setClipToBounds(
13649                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13650            }
13651            float alpha = 1;
13652            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13653                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13654                ViewGroup parentVG = (ViewGroup) mParent;
13655                final Transformation t = parentVG.getChildTransformation();
13656                if (parentVG.getChildStaticTransformation(this, t)) {
13657                    final int transformType = t.getTransformationType();
13658                    if (transformType != Transformation.TYPE_IDENTITY) {
13659                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13660                            alpha = t.getAlpha();
13661                        }
13662                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13663                            displayList.setMatrix(t.getMatrix());
13664                        }
13665                    }
13666                }
13667            }
13668            if (mTransformationInfo != null) {
13669                alpha *= mTransformationInfo.mAlpha;
13670                if (alpha < 1) {
13671                    final int multipliedAlpha = (int) (255 * alpha);
13672                    if (onSetAlpha(multipliedAlpha)) {
13673                        alpha = 1;
13674                    }
13675                }
13676                displayList.setTransformationInfo(alpha,
13677                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13678                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13679                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13680                        mTransformationInfo.mScaleY);
13681                if (mTransformationInfo.mCamera == null) {
13682                    mTransformationInfo.mCamera = new Camera();
13683                    mTransformationInfo.matrix3D = new Matrix();
13684                }
13685                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13686                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13687                    displayList.setPivotX(getPivotX());
13688                    displayList.setPivotY(getPivotY());
13689                }
13690            } else if (alpha < 1) {
13691                displayList.setAlpha(alpha);
13692            }
13693        }
13694    }
13695
13696    /**
13697     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13698     * This draw() method is an implementation detail and is not intended to be overridden or
13699     * to be called from anywhere else other than ViewGroup.drawChild().
13700     */
13701    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13702        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13703        boolean more = false;
13704        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13705        final int flags = parent.mGroupFlags;
13706
13707        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13708            parent.getChildTransformation().clear();
13709            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13710        }
13711
13712        Transformation transformToApply = null;
13713        boolean concatMatrix = false;
13714
13715        boolean scalingRequired = false;
13716        boolean caching;
13717        int layerType = getLayerType();
13718
13719        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13720        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13721                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13722            caching = true;
13723            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13724            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13725        } else {
13726            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13727        }
13728
13729        final Animation a = getAnimation();
13730        if (a != null) {
13731            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13732            concatMatrix = a.willChangeTransformationMatrix();
13733            if (concatMatrix) {
13734                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13735            }
13736            transformToApply = parent.getChildTransformation();
13737        } else {
13738            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13739                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13740                // No longer animating: clear out old animation matrix
13741                mDisplayList.setAnimationMatrix(null);
13742                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13743            }
13744            if (!useDisplayListProperties &&
13745                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13746                final Transformation t = parent.getChildTransformation();
13747                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
13748                if (hasTransform) {
13749                    final int transformType = t.getTransformationType();
13750                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
13751                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13752                }
13753            }
13754        }
13755
13756        concatMatrix |= !childHasIdentityMatrix;
13757
13758        // Sets the flag as early as possible to allow draw() implementations
13759        // to call invalidate() successfully when doing animations
13760        mPrivateFlags |= PFLAG_DRAWN;
13761
13762        if (!concatMatrix &&
13763                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13764                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13765                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13766                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13767            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13768            return more;
13769        }
13770        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13771
13772        if (hardwareAccelerated) {
13773            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13774            // retain the flag's value temporarily in the mRecreateDisplayList flag
13775            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13776            mPrivateFlags &= ~PFLAG_INVALIDATED;
13777        }
13778
13779        DisplayList displayList = null;
13780        Bitmap cache = null;
13781        boolean hasDisplayList = false;
13782        if (caching) {
13783            if (!hardwareAccelerated) {
13784                if (layerType != LAYER_TYPE_NONE) {
13785                    layerType = LAYER_TYPE_SOFTWARE;
13786                    buildDrawingCache(true);
13787                }
13788                cache = getDrawingCache(true);
13789            } else {
13790                switch (layerType) {
13791                    case LAYER_TYPE_SOFTWARE:
13792                        if (useDisplayListProperties) {
13793                            hasDisplayList = canHaveDisplayList();
13794                        } else {
13795                            buildDrawingCache(true);
13796                            cache = getDrawingCache(true);
13797                        }
13798                        break;
13799                    case LAYER_TYPE_HARDWARE:
13800                        if (useDisplayListProperties) {
13801                            hasDisplayList = canHaveDisplayList();
13802                        }
13803                        break;
13804                    case LAYER_TYPE_NONE:
13805                        // Delay getting the display list until animation-driven alpha values are
13806                        // set up and possibly passed on to the view
13807                        hasDisplayList = canHaveDisplayList();
13808                        break;
13809                }
13810            }
13811        }
13812        useDisplayListProperties &= hasDisplayList;
13813        if (useDisplayListProperties) {
13814            displayList = getDisplayList();
13815            if (!displayList.isValid()) {
13816                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13817                // to getDisplayList(), the display list will be marked invalid and we should not
13818                // try to use it again.
13819                displayList = null;
13820                hasDisplayList = false;
13821                useDisplayListProperties = false;
13822            }
13823        }
13824
13825        int sx = 0;
13826        int sy = 0;
13827        if (!hasDisplayList) {
13828            computeScroll();
13829            sx = mScrollX;
13830            sy = mScrollY;
13831        }
13832
13833        final boolean hasNoCache = cache == null || hasDisplayList;
13834        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13835                layerType != LAYER_TYPE_HARDWARE;
13836
13837        int restoreTo = -1;
13838        if (!useDisplayListProperties || transformToApply != null) {
13839            restoreTo = canvas.save();
13840        }
13841        if (offsetForScroll) {
13842            canvas.translate(mLeft - sx, mTop - sy);
13843        } else {
13844            if (!useDisplayListProperties) {
13845                canvas.translate(mLeft, mTop);
13846            }
13847            if (scalingRequired) {
13848                if (useDisplayListProperties) {
13849                    // TODO: Might not need this if we put everything inside the DL
13850                    restoreTo = canvas.save();
13851                }
13852                // mAttachInfo cannot be null, otherwise scalingRequired == false
13853                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13854                canvas.scale(scale, scale);
13855            }
13856        }
13857
13858        float alpha = useDisplayListProperties ? 1 : getAlpha();
13859        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13860                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13861            if (transformToApply != null || !childHasIdentityMatrix) {
13862                int transX = 0;
13863                int transY = 0;
13864
13865                if (offsetForScroll) {
13866                    transX = -sx;
13867                    transY = -sy;
13868                }
13869
13870                if (transformToApply != null) {
13871                    if (concatMatrix) {
13872                        if (useDisplayListProperties) {
13873                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13874                        } else {
13875                            // Undo the scroll translation, apply the transformation matrix,
13876                            // then redo the scroll translate to get the correct result.
13877                            canvas.translate(-transX, -transY);
13878                            canvas.concat(transformToApply.getMatrix());
13879                            canvas.translate(transX, transY);
13880                        }
13881                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13882                    }
13883
13884                    float transformAlpha = transformToApply.getAlpha();
13885                    if (transformAlpha < 1) {
13886                        alpha *= transformAlpha;
13887                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13888                    }
13889                }
13890
13891                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13892                    canvas.translate(-transX, -transY);
13893                    canvas.concat(getMatrix());
13894                    canvas.translate(transX, transY);
13895                }
13896            }
13897
13898            // Deal with alpha if it is or used to be <1
13899            if (alpha < 1 ||
13900                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13901                if (alpha < 1) {
13902                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13903                } else {
13904                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13905                }
13906                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13907                if (hasNoCache) {
13908                    final int multipliedAlpha = (int) (255 * alpha);
13909                    if (!onSetAlpha(multipliedAlpha)) {
13910                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13911                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13912                                layerType != LAYER_TYPE_NONE) {
13913                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13914                        }
13915                        if (useDisplayListProperties) {
13916                            displayList.setAlpha(alpha * getAlpha());
13917                        } else  if (layerType == LAYER_TYPE_NONE) {
13918                            final int scrollX = hasDisplayList ? 0 : sx;
13919                            final int scrollY = hasDisplayList ? 0 : sy;
13920                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13921                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13922                        }
13923                    } else {
13924                        // Alpha is handled by the child directly, clobber the layer's alpha
13925                        mPrivateFlags |= PFLAG_ALPHA_SET;
13926                    }
13927                }
13928            }
13929        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13930            onSetAlpha(255);
13931            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13932        }
13933
13934        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13935                !useDisplayListProperties && cache == null) {
13936            if (offsetForScroll) {
13937                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13938            } else {
13939                if (!scalingRequired || cache == null) {
13940                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13941                } else {
13942                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13943                }
13944            }
13945        }
13946
13947        if (!useDisplayListProperties && hasDisplayList) {
13948            displayList = getDisplayList();
13949            if (!displayList.isValid()) {
13950                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13951                // to getDisplayList(), the display list will be marked invalid and we should not
13952                // try to use it again.
13953                displayList = null;
13954                hasDisplayList = false;
13955            }
13956        }
13957
13958        if (hasNoCache) {
13959            boolean layerRendered = false;
13960            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13961                final HardwareLayer layer = getHardwareLayer();
13962                if (layer != null && layer.isValid()) {
13963                    mLayerPaint.setAlpha((int) (alpha * 255));
13964                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13965                    layerRendered = true;
13966                } else {
13967                    final int scrollX = hasDisplayList ? 0 : sx;
13968                    final int scrollY = hasDisplayList ? 0 : sy;
13969                    canvas.saveLayer(scrollX, scrollY,
13970                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13971                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13972                }
13973            }
13974
13975            if (!layerRendered) {
13976                if (!hasDisplayList) {
13977                    // Fast path for layouts with no backgrounds
13978                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13979                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13980                        dispatchDraw(canvas);
13981                    } else {
13982                        draw(canvas);
13983                    }
13984                } else {
13985                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13986                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13987                }
13988            }
13989        } else if (cache != null) {
13990            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13991            Paint cachePaint;
13992
13993            if (layerType == LAYER_TYPE_NONE) {
13994                cachePaint = parent.mCachePaint;
13995                if (cachePaint == null) {
13996                    cachePaint = new Paint();
13997                    cachePaint.setDither(false);
13998                    parent.mCachePaint = cachePaint;
13999                }
14000                if (alpha < 1) {
14001                    cachePaint.setAlpha((int) (alpha * 255));
14002                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14003                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14004                    cachePaint.setAlpha(255);
14005                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14006                }
14007            } else {
14008                cachePaint = mLayerPaint;
14009                cachePaint.setAlpha((int) (alpha * 255));
14010            }
14011            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14012        }
14013
14014        if (restoreTo >= 0) {
14015            canvas.restoreToCount(restoreTo);
14016        }
14017
14018        if (a != null && !more) {
14019            if (!hardwareAccelerated && !a.getFillAfter()) {
14020                onSetAlpha(255);
14021            }
14022            parent.finishAnimatingView(this, a);
14023        }
14024
14025        if (more && hardwareAccelerated) {
14026            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14027                // alpha animations should cause the child to recreate its display list
14028                invalidate(true);
14029            }
14030        }
14031
14032        mRecreateDisplayList = false;
14033
14034        return more;
14035    }
14036
14037    /**
14038     * Manually render this view (and all of its children) to the given Canvas.
14039     * The view must have already done a full layout before this function is
14040     * called.  When implementing a view, implement
14041     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14042     * If you do need to override this method, call the superclass version.
14043     *
14044     * @param canvas The Canvas to which the View is rendered.
14045     */
14046    public void draw(Canvas canvas) {
14047        if (mClipBounds != null) {
14048            canvas.clipRect(mClipBounds);
14049        }
14050        final int privateFlags = mPrivateFlags;
14051        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14052                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14053        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14054
14055        /*
14056         * Draw traversal performs several drawing steps which must be executed
14057         * in the appropriate order:
14058         *
14059         *      1. Draw the background
14060         *      2. If necessary, save the canvas' layers to prepare for fading
14061         *      3. Draw view's content
14062         *      4. Draw children
14063         *      5. If necessary, draw the fading edges and restore layers
14064         *      6. Draw decorations (scrollbars for instance)
14065         */
14066
14067        // Step 1, draw the background, if needed
14068        int saveCount;
14069
14070        if (!dirtyOpaque) {
14071            final Drawable background = mBackground;
14072            if (background != null) {
14073                final int scrollX = mScrollX;
14074                final int scrollY = mScrollY;
14075
14076                if (mBackgroundSizeChanged) {
14077                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14078                    mBackgroundSizeChanged = false;
14079                }
14080
14081                if ((scrollX | scrollY) == 0) {
14082                    background.draw(canvas);
14083                } else {
14084                    canvas.translate(scrollX, scrollY);
14085                    background.draw(canvas);
14086                    canvas.translate(-scrollX, -scrollY);
14087                }
14088            }
14089        }
14090
14091        // skip step 2 & 5 if possible (common case)
14092        final int viewFlags = mViewFlags;
14093        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14094        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14095        if (!verticalEdges && !horizontalEdges) {
14096            // Step 3, draw the content
14097            if (!dirtyOpaque) onDraw(canvas);
14098
14099            // Step 4, draw the children
14100            dispatchDraw(canvas);
14101
14102            // Step 6, draw decorations (scrollbars)
14103            onDrawScrollBars(canvas);
14104
14105            if (mOverlay != null && !mOverlay.isEmpty()) {
14106                mOverlay.getOverlayView().dispatchDraw(canvas);
14107            }
14108
14109            // we're done...
14110            return;
14111        }
14112
14113        /*
14114         * Here we do the full fledged routine...
14115         * (this is an uncommon case where speed matters less,
14116         * this is why we repeat some of the tests that have been
14117         * done above)
14118         */
14119
14120        boolean drawTop = false;
14121        boolean drawBottom = false;
14122        boolean drawLeft = false;
14123        boolean drawRight = false;
14124
14125        float topFadeStrength = 0.0f;
14126        float bottomFadeStrength = 0.0f;
14127        float leftFadeStrength = 0.0f;
14128        float rightFadeStrength = 0.0f;
14129
14130        // Step 2, save the canvas' layers
14131        int paddingLeft = mPaddingLeft;
14132
14133        final boolean offsetRequired = isPaddingOffsetRequired();
14134        if (offsetRequired) {
14135            paddingLeft += getLeftPaddingOffset();
14136        }
14137
14138        int left = mScrollX + paddingLeft;
14139        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14140        int top = mScrollY + getFadeTop(offsetRequired);
14141        int bottom = top + getFadeHeight(offsetRequired);
14142
14143        if (offsetRequired) {
14144            right += getRightPaddingOffset();
14145            bottom += getBottomPaddingOffset();
14146        }
14147
14148        final ScrollabilityCache scrollabilityCache = mScrollCache;
14149        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14150        int length = (int) fadeHeight;
14151
14152        // clip the fade length if top and bottom fades overlap
14153        // overlapping fades produce odd-looking artifacts
14154        if (verticalEdges && (top + length > bottom - length)) {
14155            length = (bottom - top) / 2;
14156        }
14157
14158        // also clip horizontal fades if necessary
14159        if (horizontalEdges && (left + length > right - length)) {
14160            length = (right - left) / 2;
14161        }
14162
14163        if (verticalEdges) {
14164            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14165            drawTop = topFadeStrength * fadeHeight > 1.0f;
14166            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14167            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14168        }
14169
14170        if (horizontalEdges) {
14171            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14172            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14173            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14174            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14175        }
14176
14177        saveCount = canvas.getSaveCount();
14178
14179        int solidColor = getSolidColor();
14180        if (solidColor == 0) {
14181            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14182
14183            if (drawTop) {
14184                canvas.saveLayer(left, top, right, top + length, null, flags);
14185            }
14186
14187            if (drawBottom) {
14188                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14189            }
14190
14191            if (drawLeft) {
14192                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14193            }
14194
14195            if (drawRight) {
14196                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14197            }
14198        } else {
14199            scrollabilityCache.setFadeColor(solidColor);
14200        }
14201
14202        // Step 3, draw the content
14203        if (!dirtyOpaque) onDraw(canvas);
14204
14205        // Step 4, draw the children
14206        dispatchDraw(canvas);
14207
14208        // Step 5, draw the fade effect and restore layers
14209        final Paint p = scrollabilityCache.paint;
14210        final Matrix matrix = scrollabilityCache.matrix;
14211        final Shader fade = scrollabilityCache.shader;
14212
14213        if (drawTop) {
14214            matrix.setScale(1, fadeHeight * topFadeStrength);
14215            matrix.postTranslate(left, top);
14216            fade.setLocalMatrix(matrix);
14217            canvas.drawRect(left, top, right, top + length, p);
14218        }
14219
14220        if (drawBottom) {
14221            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14222            matrix.postRotate(180);
14223            matrix.postTranslate(left, bottom);
14224            fade.setLocalMatrix(matrix);
14225            canvas.drawRect(left, bottom - length, right, bottom, p);
14226        }
14227
14228        if (drawLeft) {
14229            matrix.setScale(1, fadeHeight * leftFadeStrength);
14230            matrix.postRotate(-90);
14231            matrix.postTranslate(left, top);
14232            fade.setLocalMatrix(matrix);
14233            canvas.drawRect(left, top, left + length, bottom, p);
14234        }
14235
14236        if (drawRight) {
14237            matrix.setScale(1, fadeHeight * rightFadeStrength);
14238            matrix.postRotate(90);
14239            matrix.postTranslate(right, top);
14240            fade.setLocalMatrix(matrix);
14241            canvas.drawRect(right - length, top, right, bottom, p);
14242        }
14243
14244        canvas.restoreToCount(saveCount);
14245
14246        // Step 6, draw decorations (scrollbars)
14247        onDrawScrollBars(canvas);
14248
14249        if (mOverlay != null && !mOverlay.isEmpty()) {
14250            mOverlay.getOverlayView().dispatchDraw(canvas);
14251        }
14252    }
14253
14254    /**
14255     * Returns the overlay for this view, creating it if it does not yet exist.
14256     * Adding drawables to the overlay will cause them to be displayed whenever
14257     * the view itself is redrawn. Objects in the overlay should be actively
14258     * managed: remove them when they should not be displayed anymore. The
14259     * overlay will always have the same size as its host view.
14260     *
14261     * <p>Note: Overlays do not currently work correctly with {@link
14262     * SurfaceView} or {@link TextureView}; contents in overlays for these
14263     * types of views may not display correctly.</p>
14264     *
14265     * @return The ViewOverlay object for this view.
14266     * @see ViewOverlay
14267     */
14268    public ViewOverlay getOverlay() {
14269        if (mOverlay == null) {
14270            mOverlay = new ViewOverlay(mContext, this);
14271        }
14272        return mOverlay;
14273    }
14274
14275    /**
14276     * Override this if your view is known to always be drawn on top of a solid color background,
14277     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14278     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14279     * should be set to 0xFF.
14280     *
14281     * @see #setVerticalFadingEdgeEnabled(boolean)
14282     * @see #setHorizontalFadingEdgeEnabled(boolean)
14283     *
14284     * @return The known solid color background for this view, or 0 if the color may vary
14285     */
14286    @ViewDebug.ExportedProperty(category = "drawing")
14287    public int getSolidColor() {
14288        return 0;
14289    }
14290
14291    /**
14292     * Build a human readable string representation of the specified view flags.
14293     *
14294     * @param flags the view flags to convert to a string
14295     * @return a String representing the supplied flags
14296     */
14297    private static String printFlags(int flags) {
14298        String output = "";
14299        int numFlags = 0;
14300        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14301            output += "TAKES_FOCUS";
14302            numFlags++;
14303        }
14304
14305        switch (flags & VISIBILITY_MASK) {
14306        case INVISIBLE:
14307            if (numFlags > 0) {
14308                output += " ";
14309            }
14310            output += "INVISIBLE";
14311            // USELESS HERE numFlags++;
14312            break;
14313        case GONE:
14314            if (numFlags > 0) {
14315                output += " ";
14316            }
14317            output += "GONE";
14318            // USELESS HERE numFlags++;
14319            break;
14320        default:
14321            break;
14322        }
14323        return output;
14324    }
14325
14326    /**
14327     * Build a human readable string representation of the specified private
14328     * view flags.
14329     *
14330     * @param privateFlags the private view flags to convert to a string
14331     * @return a String representing the supplied flags
14332     */
14333    private static String printPrivateFlags(int privateFlags) {
14334        String output = "";
14335        int numFlags = 0;
14336
14337        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14338            output += "WANTS_FOCUS";
14339            numFlags++;
14340        }
14341
14342        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14343            if (numFlags > 0) {
14344                output += " ";
14345            }
14346            output += "FOCUSED";
14347            numFlags++;
14348        }
14349
14350        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14351            if (numFlags > 0) {
14352                output += " ";
14353            }
14354            output += "SELECTED";
14355            numFlags++;
14356        }
14357
14358        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14359            if (numFlags > 0) {
14360                output += " ";
14361            }
14362            output += "IS_ROOT_NAMESPACE";
14363            numFlags++;
14364        }
14365
14366        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14367            if (numFlags > 0) {
14368                output += " ";
14369            }
14370            output += "HAS_BOUNDS";
14371            numFlags++;
14372        }
14373
14374        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14375            if (numFlags > 0) {
14376                output += " ";
14377            }
14378            output += "DRAWN";
14379            // USELESS HERE numFlags++;
14380        }
14381        return output;
14382    }
14383
14384    /**
14385     * <p>Indicates whether or not this view's layout will be requested during
14386     * the next hierarchy layout pass.</p>
14387     *
14388     * @return true if the layout will be forced during next layout pass
14389     */
14390    public boolean isLayoutRequested() {
14391        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14392    }
14393
14394    /**
14395     * Return true if o is a ViewGroup that is laying out using optical bounds.
14396     * @hide
14397     */
14398    public static boolean isLayoutModeOptical(Object o) {
14399        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14400    }
14401
14402    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14403        Insets parentInsets = mParent instanceof View ?
14404                ((View) mParent).getOpticalInsets() : Insets.NONE;
14405        Insets childInsets = getOpticalInsets();
14406        return setFrame(
14407                left   + parentInsets.left - childInsets.left,
14408                top    + parentInsets.top  - childInsets.top,
14409                right  + parentInsets.left + childInsets.right,
14410                bottom + parentInsets.top  + childInsets.bottom);
14411    }
14412
14413    /**
14414     * Assign a size and position to a view and all of its
14415     * descendants
14416     *
14417     * <p>This is the second phase of the layout mechanism.
14418     * (The first is measuring). In this phase, each parent calls
14419     * layout on all of its children to position them.
14420     * This is typically done using the child measurements
14421     * that were stored in the measure pass().</p>
14422     *
14423     * <p>Derived classes should not override this method.
14424     * Derived classes with children should override
14425     * onLayout. In that method, they should
14426     * call layout on each of their children.</p>
14427     *
14428     * @param l Left position, relative to parent
14429     * @param t Top position, relative to parent
14430     * @param r Right position, relative to parent
14431     * @param b Bottom position, relative to parent
14432     */
14433    @SuppressWarnings({"unchecked"})
14434    public void layout(int l, int t, int r, int b) {
14435        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14436            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14437            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14438        }
14439
14440        int oldL = mLeft;
14441        int oldT = mTop;
14442        int oldB = mBottom;
14443        int oldR = mRight;
14444
14445        boolean changed = isLayoutModeOptical(mParent) ?
14446                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14447
14448        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14449            onLayout(changed, l, t, r, b);
14450            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14451
14452            ListenerInfo li = mListenerInfo;
14453            if (li != null && li.mOnLayoutChangeListeners != null) {
14454                ArrayList<OnLayoutChangeListener> listenersCopy =
14455                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14456                int numListeners = listenersCopy.size();
14457                for (int i = 0; i < numListeners; ++i) {
14458                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14459                }
14460            }
14461        }
14462
14463        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14464        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14465    }
14466
14467    /**
14468     * Called from layout when this view should
14469     * assign a size and position to each of its children.
14470     *
14471     * Derived classes with children should override
14472     * this method and call layout on each of
14473     * their children.
14474     * @param changed This is a new size or position for this view
14475     * @param left Left position, relative to parent
14476     * @param top Top position, relative to parent
14477     * @param right Right position, relative to parent
14478     * @param bottom Bottom position, relative to parent
14479     */
14480    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14481    }
14482
14483    /**
14484     * Assign a size and position to this view.
14485     *
14486     * This is called from layout.
14487     *
14488     * @param left Left position, relative to parent
14489     * @param top Top position, relative to parent
14490     * @param right Right position, relative to parent
14491     * @param bottom Bottom position, relative to parent
14492     * @return true if the new size and position are different than the
14493     *         previous ones
14494     * {@hide}
14495     */
14496    protected boolean setFrame(int left, int top, int right, int bottom) {
14497        boolean changed = false;
14498
14499        if (DBG) {
14500            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14501                    + right + "," + bottom + ")");
14502        }
14503
14504        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14505            changed = true;
14506
14507            // Remember our drawn bit
14508            int drawn = mPrivateFlags & PFLAG_DRAWN;
14509
14510            int oldWidth = mRight - mLeft;
14511            int oldHeight = mBottom - mTop;
14512            int newWidth = right - left;
14513            int newHeight = bottom - top;
14514            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14515
14516            // Invalidate our old position
14517            invalidate(sizeChanged);
14518
14519            mLeft = left;
14520            mTop = top;
14521            mRight = right;
14522            mBottom = bottom;
14523            if (mDisplayList != null) {
14524                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14525            }
14526
14527            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14528
14529
14530            if (sizeChanged) {
14531                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14532                    // A change in dimension means an auto-centered pivot point changes, too
14533                    if (mTransformationInfo != null) {
14534                        mTransformationInfo.mMatrixDirty = true;
14535                    }
14536                }
14537                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14538            }
14539
14540            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14541                // If we are visible, force the DRAWN bit to on so that
14542                // this invalidate will go through (at least to our parent).
14543                // This is because someone may have invalidated this view
14544                // before this call to setFrame came in, thereby clearing
14545                // the DRAWN bit.
14546                mPrivateFlags |= PFLAG_DRAWN;
14547                invalidate(sizeChanged);
14548                // parent display list may need to be recreated based on a change in the bounds
14549                // of any child
14550                invalidateParentCaches();
14551            }
14552
14553            // Reset drawn bit to original value (invalidate turns it off)
14554            mPrivateFlags |= drawn;
14555
14556            mBackgroundSizeChanged = true;
14557
14558            notifySubtreeAccessibilityStateChangedIfNeeded();
14559        }
14560        return changed;
14561    }
14562
14563    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14564        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14565        if (mOverlay != null) {
14566            mOverlay.getOverlayView().setRight(newWidth);
14567            mOverlay.getOverlayView().setBottom(newHeight);
14568        }
14569    }
14570
14571    /**
14572     * Finalize inflating a view from XML.  This is called as the last phase
14573     * of inflation, after all child views have been added.
14574     *
14575     * <p>Even if the subclass overrides onFinishInflate, they should always be
14576     * sure to call the super method, so that we get called.
14577     */
14578    protected void onFinishInflate() {
14579    }
14580
14581    /**
14582     * Returns the resources associated with this view.
14583     *
14584     * @return Resources object.
14585     */
14586    public Resources getResources() {
14587        return mResources;
14588    }
14589
14590    /**
14591     * Invalidates the specified Drawable.
14592     *
14593     * @param drawable the drawable to invalidate
14594     */
14595    public void invalidateDrawable(Drawable drawable) {
14596        if (verifyDrawable(drawable)) {
14597            final Rect dirty = drawable.getBounds();
14598            final int scrollX = mScrollX;
14599            final int scrollY = mScrollY;
14600
14601            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14602                    dirty.right + scrollX, dirty.bottom + scrollY);
14603        }
14604    }
14605
14606    /**
14607     * Schedules an action on a drawable to occur at a specified time.
14608     *
14609     * @param who the recipient of the action
14610     * @param what the action to run on the drawable
14611     * @param when the time at which the action must occur. Uses the
14612     *        {@link SystemClock#uptimeMillis} timebase.
14613     */
14614    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14615        if (verifyDrawable(who) && what != null) {
14616            final long delay = when - SystemClock.uptimeMillis();
14617            if (mAttachInfo != null) {
14618                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14619                        Choreographer.CALLBACK_ANIMATION, what, who,
14620                        Choreographer.subtractFrameDelay(delay));
14621            } else {
14622                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14623            }
14624        }
14625    }
14626
14627    /**
14628     * Cancels a scheduled action on a drawable.
14629     *
14630     * @param who the recipient of the action
14631     * @param what the action to cancel
14632     */
14633    public void unscheduleDrawable(Drawable who, Runnable what) {
14634        if (verifyDrawable(who) && what != null) {
14635            if (mAttachInfo != null) {
14636                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14637                        Choreographer.CALLBACK_ANIMATION, what, who);
14638            } else {
14639                ViewRootImpl.getRunQueue().removeCallbacks(what);
14640            }
14641        }
14642    }
14643
14644    /**
14645     * Unschedule any events associated with the given Drawable.  This can be
14646     * used when selecting a new Drawable into a view, so that the previous
14647     * one is completely unscheduled.
14648     *
14649     * @param who The Drawable to unschedule.
14650     *
14651     * @see #drawableStateChanged
14652     */
14653    public void unscheduleDrawable(Drawable who) {
14654        if (mAttachInfo != null && who != null) {
14655            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14656                    Choreographer.CALLBACK_ANIMATION, null, who);
14657        }
14658    }
14659
14660    /**
14661     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14662     * that the View directionality can and will be resolved before its Drawables.
14663     *
14664     * Will call {@link View#onResolveDrawables} when resolution is done.
14665     *
14666     * @hide
14667     */
14668    protected void resolveDrawables() {
14669        // Drawables resolution may need to happen before resolving the layout direction (which is
14670        // done only during the measure() call).
14671        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
14672        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
14673        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
14674        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
14675        // direction to be resolved as its resolved value will be the same as its raw value.
14676        if (!isLayoutDirectionResolved() &&
14677                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
14678            return;
14679        }
14680
14681        final int layoutDirection = isLayoutDirectionResolved() ?
14682                getLayoutDirection() : getRawLayoutDirection();
14683
14684        if (mBackground != null) {
14685            mBackground.setLayoutDirection(layoutDirection);
14686        }
14687        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14688        onResolveDrawables(layoutDirection);
14689    }
14690
14691    /**
14692     * Called when layout direction has been resolved.
14693     *
14694     * The default implementation does nothing.
14695     *
14696     * @param layoutDirection The resolved layout direction.
14697     *
14698     * @see #LAYOUT_DIRECTION_LTR
14699     * @see #LAYOUT_DIRECTION_RTL
14700     *
14701     * @hide
14702     */
14703    public void onResolveDrawables(int layoutDirection) {
14704    }
14705
14706    /**
14707     * @hide
14708     */
14709    protected void resetResolvedDrawables() {
14710        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14711    }
14712
14713    private boolean isDrawablesResolved() {
14714        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14715    }
14716
14717    /**
14718     * If your view subclass is displaying its own Drawable objects, it should
14719     * override this function and return true for any Drawable it is
14720     * displaying.  This allows animations for those drawables to be
14721     * scheduled.
14722     *
14723     * <p>Be sure to call through to the super class when overriding this
14724     * function.
14725     *
14726     * @param who The Drawable to verify.  Return true if it is one you are
14727     *            displaying, else return the result of calling through to the
14728     *            super class.
14729     *
14730     * @return boolean If true than the Drawable is being displayed in the
14731     *         view; else false and it is not allowed to animate.
14732     *
14733     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14734     * @see #drawableStateChanged()
14735     */
14736    protected boolean verifyDrawable(Drawable who) {
14737        return who == mBackground;
14738    }
14739
14740    /**
14741     * This function is called whenever the state of the view changes in such
14742     * a way that it impacts the state of drawables being shown.
14743     *
14744     * <p>Be sure to call through to the superclass when overriding this
14745     * function.
14746     *
14747     * @see Drawable#setState(int[])
14748     */
14749    protected void drawableStateChanged() {
14750        Drawable d = mBackground;
14751        if (d != null && d.isStateful()) {
14752            d.setState(getDrawableState());
14753        }
14754    }
14755
14756    /**
14757     * Call this to force a view to update its drawable state. This will cause
14758     * drawableStateChanged to be called on this view. Views that are interested
14759     * in the new state should call getDrawableState.
14760     *
14761     * @see #drawableStateChanged
14762     * @see #getDrawableState
14763     */
14764    public void refreshDrawableState() {
14765        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14766        drawableStateChanged();
14767
14768        ViewParent parent = mParent;
14769        if (parent != null) {
14770            parent.childDrawableStateChanged(this);
14771        }
14772    }
14773
14774    /**
14775     * Return an array of resource IDs of the drawable states representing the
14776     * current state of the view.
14777     *
14778     * @return The current drawable state
14779     *
14780     * @see Drawable#setState(int[])
14781     * @see #drawableStateChanged()
14782     * @see #onCreateDrawableState(int)
14783     */
14784    public final int[] getDrawableState() {
14785        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14786            return mDrawableState;
14787        } else {
14788            mDrawableState = onCreateDrawableState(0);
14789            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14790            return mDrawableState;
14791        }
14792    }
14793
14794    /**
14795     * Generate the new {@link android.graphics.drawable.Drawable} state for
14796     * this view. This is called by the view
14797     * system when the cached Drawable state is determined to be invalid.  To
14798     * retrieve the current state, you should use {@link #getDrawableState}.
14799     *
14800     * @param extraSpace if non-zero, this is the number of extra entries you
14801     * would like in the returned array in which you can place your own
14802     * states.
14803     *
14804     * @return Returns an array holding the current {@link Drawable} state of
14805     * the view.
14806     *
14807     * @see #mergeDrawableStates(int[], int[])
14808     */
14809    protected int[] onCreateDrawableState(int extraSpace) {
14810        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14811                mParent instanceof View) {
14812            return ((View) mParent).onCreateDrawableState(extraSpace);
14813        }
14814
14815        int[] drawableState;
14816
14817        int privateFlags = mPrivateFlags;
14818
14819        int viewStateIndex = 0;
14820        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14821        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14822        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14823        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14824        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14825        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14826        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14827                HardwareRenderer.isAvailable()) {
14828            // This is set if HW acceleration is requested, even if the current
14829            // process doesn't allow it.  This is just to allow app preview
14830            // windows to better match their app.
14831            viewStateIndex |= VIEW_STATE_ACCELERATED;
14832        }
14833        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14834
14835        final int privateFlags2 = mPrivateFlags2;
14836        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14837        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14838
14839        drawableState = VIEW_STATE_SETS[viewStateIndex];
14840
14841        //noinspection ConstantIfStatement
14842        if (false) {
14843            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14844            Log.i("View", toString()
14845                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14846                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14847                    + " fo=" + hasFocus()
14848                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14849                    + " wf=" + hasWindowFocus()
14850                    + ": " + Arrays.toString(drawableState));
14851        }
14852
14853        if (extraSpace == 0) {
14854            return drawableState;
14855        }
14856
14857        final int[] fullState;
14858        if (drawableState != null) {
14859            fullState = new int[drawableState.length + extraSpace];
14860            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14861        } else {
14862            fullState = new int[extraSpace];
14863        }
14864
14865        return fullState;
14866    }
14867
14868    /**
14869     * Merge your own state values in <var>additionalState</var> into the base
14870     * state values <var>baseState</var> that were returned by
14871     * {@link #onCreateDrawableState(int)}.
14872     *
14873     * @param baseState The base state values returned by
14874     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14875     * own additional state values.
14876     *
14877     * @param additionalState The additional state values you would like
14878     * added to <var>baseState</var>; this array is not modified.
14879     *
14880     * @return As a convenience, the <var>baseState</var> array you originally
14881     * passed into the function is returned.
14882     *
14883     * @see #onCreateDrawableState(int)
14884     */
14885    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14886        final int N = baseState.length;
14887        int i = N - 1;
14888        while (i >= 0 && baseState[i] == 0) {
14889            i--;
14890        }
14891        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14892        return baseState;
14893    }
14894
14895    /**
14896     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14897     * on all Drawable objects associated with this view.
14898     */
14899    public void jumpDrawablesToCurrentState() {
14900        if (mBackground != null) {
14901            mBackground.jumpToCurrentState();
14902        }
14903    }
14904
14905    /**
14906     * Sets the background color for this view.
14907     * @param color the color of the background
14908     */
14909    @RemotableViewMethod
14910    public void setBackgroundColor(int color) {
14911        if (mBackground instanceof ColorDrawable) {
14912            ((ColorDrawable) mBackground.mutate()).setColor(color);
14913            computeOpaqueFlags();
14914            mBackgroundResource = 0;
14915        } else {
14916            setBackground(new ColorDrawable(color));
14917        }
14918    }
14919
14920    /**
14921     * Set the background to a given resource. The resource should refer to
14922     * a Drawable object or 0 to remove the background.
14923     * @param resid The identifier of the resource.
14924     *
14925     * @attr ref android.R.styleable#View_background
14926     */
14927    @RemotableViewMethod
14928    public void setBackgroundResource(int resid) {
14929        if (resid != 0 && resid == mBackgroundResource) {
14930            return;
14931        }
14932
14933        Drawable d= null;
14934        if (resid != 0) {
14935            d = mResources.getDrawable(resid);
14936        }
14937        setBackground(d);
14938
14939        mBackgroundResource = resid;
14940    }
14941
14942    /**
14943     * Set the background to a given Drawable, or remove the background. If the
14944     * background has padding, this View's padding is set to the background's
14945     * padding. However, when a background is removed, this View's padding isn't
14946     * touched. If setting the padding is desired, please use
14947     * {@link #setPadding(int, int, int, int)}.
14948     *
14949     * @param background The Drawable to use as the background, or null to remove the
14950     *        background
14951     */
14952    public void setBackground(Drawable background) {
14953        //noinspection deprecation
14954        setBackgroundDrawable(background);
14955    }
14956
14957    /**
14958     * @deprecated use {@link #setBackground(Drawable)} instead
14959     */
14960    @Deprecated
14961    public void setBackgroundDrawable(Drawable background) {
14962        computeOpaqueFlags();
14963
14964        if (background == mBackground) {
14965            return;
14966        }
14967
14968        boolean requestLayout = false;
14969
14970        mBackgroundResource = 0;
14971
14972        /*
14973         * Regardless of whether we're setting a new background or not, we want
14974         * to clear the previous drawable.
14975         */
14976        if (mBackground != null) {
14977            mBackground.setCallback(null);
14978            unscheduleDrawable(mBackground);
14979        }
14980
14981        if (background != null) {
14982            Rect padding = sThreadLocal.get();
14983            if (padding == null) {
14984                padding = new Rect();
14985                sThreadLocal.set(padding);
14986            }
14987            resetResolvedDrawables();
14988            background.setLayoutDirection(getLayoutDirection());
14989            if (background.getPadding(padding)) {
14990                resetResolvedPadding();
14991                switch (background.getLayoutDirection()) {
14992                    case LAYOUT_DIRECTION_RTL:
14993                        mUserPaddingLeftInitial = padding.right;
14994                        mUserPaddingRightInitial = padding.left;
14995                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14996                        break;
14997                    case LAYOUT_DIRECTION_LTR:
14998                    default:
14999                        mUserPaddingLeftInitial = padding.left;
15000                        mUserPaddingRightInitial = padding.right;
15001                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15002                }
15003            }
15004
15005            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15006            // if it has a different minimum size, we should layout again
15007            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15008                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15009                requestLayout = true;
15010            }
15011
15012            background.setCallback(this);
15013            if (background.isStateful()) {
15014                background.setState(getDrawableState());
15015            }
15016            background.setVisible(getVisibility() == VISIBLE, false);
15017            mBackground = background;
15018
15019            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15020                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15021                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15022                requestLayout = true;
15023            }
15024        } else {
15025            /* Remove the background */
15026            mBackground = null;
15027
15028            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15029                /*
15030                 * This view ONLY drew the background before and we're removing
15031                 * the background, so now it won't draw anything
15032                 * (hence we SKIP_DRAW)
15033                 */
15034                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15035                mPrivateFlags |= PFLAG_SKIP_DRAW;
15036            }
15037
15038            /*
15039             * When the background is set, we try to apply its padding to this
15040             * View. When the background is removed, we don't touch this View's
15041             * padding. This is noted in the Javadocs. Hence, we don't need to
15042             * requestLayout(), the invalidate() below is sufficient.
15043             */
15044
15045            // The old background's minimum size could have affected this
15046            // View's layout, so let's requestLayout
15047            requestLayout = true;
15048        }
15049
15050        computeOpaqueFlags();
15051
15052        if (requestLayout) {
15053            requestLayout();
15054        }
15055
15056        mBackgroundSizeChanged = true;
15057        invalidate(true);
15058    }
15059
15060    /**
15061     * Gets the background drawable
15062     *
15063     * @return The drawable used as the background for this view, if any.
15064     *
15065     * @see #setBackground(Drawable)
15066     *
15067     * @attr ref android.R.styleable#View_background
15068     */
15069    public Drawable getBackground() {
15070        return mBackground;
15071    }
15072
15073    /**
15074     * Sets the padding. The view may add on the space required to display
15075     * the scrollbars, depending on the style and visibility of the scrollbars.
15076     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15077     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15078     * from the values set in this call.
15079     *
15080     * @attr ref android.R.styleable#View_padding
15081     * @attr ref android.R.styleable#View_paddingBottom
15082     * @attr ref android.R.styleable#View_paddingLeft
15083     * @attr ref android.R.styleable#View_paddingRight
15084     * @attr ref android.R.styleable#View_paddingTop
15085     * @param left the left padding in pixels
15086     * @param top the top padding in pixels
15087     * @param right the right padding in pixels
15088     * @param bottom the bottom padding in pixels
15089     */
15090    public void setPadding(int left, int top, int right, int bottom) {
15091        resetResolvedPadding();
15092
15093        mUserPaddingStart = UNDEFINED_PADDING;
15094        mUserPaddingEnd = UNDEFINED_PADDING;
15095
15096        mUserPaddingLeftInitial = left;
15097        mUserPaddingRightInitial = right;
15098
15099        internalSetPadding(left, top, right, bottom);
15100    }
15101
15102    /**
15103     * @hide
15104     */
15105    protected void internalSetPadding(int left, int top, int right, int bottom) {
15106        mUserPaddingLeft = left;
15107        mUserPaddingRight = right;
15108        mUserPaddingBottom = bottom;
15109
15110        final int viewFlags = mViewFlags;
15111        boolean changed = false;
15112
15113        // Common case is there are no scroll bars.
15114        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15115            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15116                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15117                        ? 0 : getVerticalScrollbarWidth();
15118                switch (mVerticalScrollbarPosition) {
15119                    case SCROLLBAR_POSITION_DEFAULT:
15120                        if (isLayoutRtl()) {
15121                            left += offset;
15122                        } else {
15123                            right += offset;
15124                        }
15125                        break;
15126                    case SCROLLBAR_POSITION_RIGHT:
15127                        right += offset;
15128                        break;
15129                    case SCROLLBAR_POSITION_LEFT:
15130                        left += offset;
15131                        break;
15132                }
15133            }
15134            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15135                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15136                        ? 0 : getHorizontalScrollbarHeight();
15137            }
15138        }
15139
15140        if (mPaddingLeft != left) {
15141            changed = true;
15142            mPaddingLeft = left;
15143        }
15144        if (mPaddingTop != top) {
15145            changed = true;
15146            mPaddingTop = top;
15147        }
15148        if (mPaddingRight != right) {
15149            changed = true;
15150            mPaddingRight = right;
15151        }
15152        if (mPaddingBottom != bottom) {
15153            changed = true;
15154            mPaddingBottom = bottom;
15155        }
15156
15157        if (changed) {
15158            requestLayout();
15159        }
15160    }
15161
15162    /**
15163     * Sets the relative padding. The view may add on the space required to display
15164     * the scrollbars, depending on the style and visibility of the scrollbars.
15165     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15166     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15167     * from the values set in this call.
15168     *
15169     * @attr ref android.R.styleable#View_padding
15170     * @attr ref android.R.styleable#View_paddingBottom
15171     * @attr ref android.R.styleable#View_paddingStart
15172     * @attr ref android.R.styleable#View_paddingEnd
15173     * @attr ref android.R.styleable#View_paddingTop
15174     * @param start the start padding in pixels
15175     * @param top the top padding in pixels
15176     * @param end the end padding in pixels
15177     * @param bottom the bottom padding in pixels
15178     */
15179    public void setPaddingRelative(int start, int top, int end, int bottom) {
15180        resetResolvedPadding();
15181
15182        mUserPaddingStart = start;
15183        mUserPaddingEnd = end;
15184
15185        switch(getLayoutDirection()) {
15186            case LAYOUT_DIRECTION_RTL:
15187                mUserPaddingLeftInitial = end;
15188                mUserPaddingRightInitial = start;
15189                internalSetPadding(end, top, start, bottom);
15190                break;
15191            case LAYOUT_DIRECTION_LTR:
15192            default:
15193                mUserPaddingLeftInitial = start;
15194                mUserPaddingRightInitial = end;
15195                internalSetPadding(start, top, end, bottom);
15196        }
15197    }
15198
15199    /**
15200     * Returns the top padding of this view.
15201     *
15202     * @return the top padding in pixels
15203     */
15204    public int getPaddingTop() {
15205        return mPaddingTop;
15206    }
15207
15208    /**
15209     * Returns the bottom padding of this view. If there are inset and enabled
15210     * scrollbars, this value may include the space required to display the
15211     * scrollbars as well.
15212     *
15213     * @return the bottom padding in pixels
15214     */
15215    public int getPaddingBottom() {
15216        return mPaddingBottom;
15217    }
15218
15219    /**
15220     * Returns the left padding of this view. If there are inset and enabled
15221     * scrollbars, this value may include the space required to display the
15222     * scrollbars as well.
15223     *
15224     * @return the left padding in pixels
15225     */
15226    public int getPaddingLeft() {
15227        if (!isPaddingResolved()) {
15228            resolvePadding();
15229        }
15230        return mPaddingLeft;
15231    }
15232
15233    /**
15234     * Returns the start padding of this view depending on its resolved layout direction.
15235     * If there are inset and enabled scrollbars, this value may include the space
15236     * required to display the scrollbars as well.
15237     *
15238     * @return the start padding in pixels
15239     */
15240    public int getPaddingStart() {
15241        if (!isPaddingResolved()) {
15242            resolvePadding();
15243        }
15244        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15245                mPaddingRight : mPaddingLeft;
15246    }
15247
15248    /**
15249     * Returns the right padding of this view. If there are inset and enabled
15250     * scrollbars, this value may include the space required to display the
15251     * scrollbars as well.
15252     *
15253     * @return the right padding in pixels
15254     */
15255    public int getPaddingRight() {
15256        if (!isPaddingResolved()) {
15257            resolvePadding();
15258        }
15259        return mPaddingRight;
15260    }
15261
15262    /**
15263     * Returns the end padding of this view depending on its resolved layout direction.
15264     * If there are inset and enabled scrollbars, this value may include the space
15265     * required to display the scrollbars as well.
15266     *
15267     * @return the end padding in pixels
15268     */
15269    public int getPaddingEnd() {
15270        if (!isPaddingResolved()) {
15271            resolvePadding();
15272        }
15273        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15274                mPaddingLeft : mPaddingRight;
15275    }
15276
15277    /**
15278     * Return if the padding as been set thru relative values
15279     * {@link #setPaddingRelative(int, int, int, int)} or thru
15280     * @attr ref android.R.styleable#View_paddingStart or
15281     * @attr ref android.R.styleable#View_paddingEnd
15282     *
15283     * @return true if the padding is relative or false if it is not.
15284     */
15285    public boolean isPaddingRelative() {
15286        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15287    }
15288
15289    Insets computeOpticalInsets() {
15290        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15291    }
15292
15293    /**
15294     * @hide
15295     */
15296    public void resetPaddingToInitialValues() {
15297        if (isRtlCompatibilityMode()) {
15298            mPaddingLeft = mUserPaddingLeftInitial;
15299            mPaddingRight = mUserPaddingRightInitial;
15300            return;
15301        }
15302        if (isLayoutRtl()) {
15303            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15304            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15305        } else {
15306            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15307            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15308        }
15309    }
15310
15311    /**
15312     * @hide
15313     */
15314    public Insets getOpticalInsets() {
15315        if (mLayoutInsets == null) {
15316            mLayoutInsets = computeOpticalInsets();
15317        }
15318        return mLayoutInsets;
15319    }
15320
15321    /**
15322     * Changes the selection state of this view. A view can be selected or not.
15323     * Note that selection is not the same as focus. Views are typically
15324     * selected in the context of an AdapterView like ListView or GridView;
15325     * the selected view is the view that is highlighted.
15326     *
15327     * @param selected true if the view must be selected, false otherwise
15328     */
15329    public void setSelected(boolean selected) {
15330        //noinspection DoubleNegation
15331        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15332            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15333            if (!selected) resetPressedState();
15334            invalidate(true);
15335            refreshDrawableState();
15336            dispatchSetSelected(selected);
15337            notifyViewAccessibilityStateChangedIfNeeded();
15338        }
15339    }
15340
15341    /**
15342     * Dispatch setSelected to all of this View's children.
15343     *
15344     * @see #setSelected(boolean)
15345     *
15346     * @param selected The new selected state
15347     */
15348    protected void dispatchSetSelected(boolean selected) {
15349    }
15350
15351    /**
15352     * Indicates the selection state of this view.
15353     *
15354     * @return true if the view is selected, false otherwise
15355     */
15356    @ViewDebug.ExportedProperty
15357    public boolean isSelected() {
15358        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15359    }
15360
15361    /**
15362     * Changes the activated state of this view. A view can be activated or not.
15363     * Note that activation is not the same as selection.  Selection is
15364     * a transient property, representing the view (hierarchy) the user is
15365     * currently interacting with.  Activation is a longer-term state that the
15366     * user can move views in and out of.  For example, in a list view with
15367     * single or multiple selection enabled, the views in the current selection
15368     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15369     * here.)  The activated state is propagated down to children of the view it
15370     * is set on.
15371     *
15372     * @param activated true if the view must be activated, false otherwise
15373     */
15374    public void setActivated(boolean activated) {
15375        //noinspection DoubleNegation
15376        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15377            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15378            invalidate(true);
15379            refreshDrawableState();
15380            dispatchSetActivated(activated);
15381        }
15382    }
15383
15384    /**
15385     * Dispatch setActivated to all of this View's children.
15386     *
15387     * @see #setActivated(boolean)
15388     *
15389     * @param activated The new activated state
15390     */
15391    protected void dispatchSetActivated(boolean activated) {
15392    }
15393
15394    /**
15395     * Indicates the activation state of this view.
15396     *
15397     * @return true if the view is activated, false otherwise
15398     */
15399    @ViewDebug.ExportedProperty
15400    public boolean isActivated() {
15401        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15402    }
15403
15404    /**
15405     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15406     * observer can be used to get notifications when global events, like
15407     * layout, happen.
15408     *
15409     * The returned ViewTreeObserver observer is not guaranteed to remain
15410     * valid for the lifetime of this View. If the caller of this method keeps
15411     * a long-lived reference to ViewTreeObserver, it should always check for
15412     * the return value of {@link ViewTreeObserver#isAlive()}.
15413     *
15414     * @return The ViewTreeObserver for this view's hierarchy.
15415     */
15416    public ViewTreeObserver getViewTreeObserver() {
15417        if (mAttachInfo != null) {
15418            return mAttachInfo.mTreeObserver;
15419        }
15420        if (mFloatingTreeObserver == null) {
15421            mFloatingTreeObserver = new ViewTreeObserver();
15422        }
15423        return mFloatingTreeObserver;
15424    }
15425
15426    /**
15427     * <p>Finds the topmost view in the current view hierarchy.</p>
15428     *
15429     * @return the topmost view containing this view
15430     */
15431    public View getRootView() {
15432        if (mAttachInfo != null) {
15433            final View v = mAttachInfo.mRootView;
15434            if (v != null) {
15435                return v;
15436            }
15437        }
15438
15439        View parent = this;
15440
15441        while (parent.mParent != null && parent.mParent instanceof View) {
15442            parent = (View) parent.mParent;
15443        }
15444
15445        return parent;
15446    }
15447
15448    /**
15449     * Transforms a motion event from view-local coordinates to on-screen
15450     * coordinates.
15451     *
15452     * @param ev the view-local motion event
15453     * @return false if the transformation could not be applied
15454     * @hide
15455     */
15456    public boolean toGlobalMotionEvent(MotionEvent ev) {
15457        final AttachInfo info = mAttachInfo;
15458        if (info == null) {
15459            return false;
15460        }
15461
15462        transformMotionEventToGlobal(ev);
15463        ev.offsetLocation(info.mWindowLeft, info.mWindowTop);
15464        return true;
15465    }
15466
15467    /**
15468     * Transforms a motion event from on-screen coordinates to view-local
15469     * coordinates.
15470     *
15471     * @param ev the on-screen motion event
15472     * @return false if the transformation could not be applied
15473     * @hide
15474     */
15475    public boolean toLocalMotionEvent(MotionEvent ev) {
15476        final AttachInfo info = mAttachInfo;
15477        if (info == null) {
15478            return false;
15479        }
15480
15481        ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop);
15482        transformMotionEventToLocal(ev);
15483        return true;
15484    }
15485
15486    /**
15487     * Recursive helper method that applies transformations in post-order.
15488     *
15489     * @param ev the on-screen motion event
15490     */
15491    private void transformMotionEventToLocal(MotionEvent ev) {
15492        final ViewParent parent = mParent;
15493        if (parent instanceof View) {
15494            final View vp = (View) parent;
15495            vp.transformMotionEventToLocal(ev);
15496            ev.offsetLocation(vp.mScrollX, vp.mScrollY);
15497        } else if (parent instanceof ViewRootImpl) {
15498            final ViewRootImpl vr = (ViewRootImpl) parent;
15499            ev.offsetLocation(0, vr.mCurScrollY);
15500        }
15501
15502        ev.offsetLocation(-mLeft, -mTop);
15503
15504        if (!hasIdentityMatrix()) {
15505            ev.transform(getInverseMatrix());
15506        }
15507    }
15508
15509    /**
15510     * Recursive helper method that applies transformations in pre-order.
15511     *
15512     * @param ev the on-screen motion event
15513     */
15514    private void transformMotionEventToGlobal(MotionEvent ev) {
15515        if (!hasIdentityMatrix()) {
15516            ev.transform(getMatrix());
15517        }
15518
15519        ev.offsetLocation(mLeft, mTop);
15520
15521        final ViewParent parent = mParent;
15522        if (parent instanceof View) {
15523            final View vp = (View) parent;
15524            ev.offsetLocation(-vp.mScrollX, -vp.mScrollY);
15525            vp.transformMotionEventToGlobal(ev);
15526        } else if (parent instanceof ViewRootImpl) {
15527            final ViewRootImpl vr = (ViewRootImpl) parent;
15528            ev.offsetLocation(0, -vr.mCurScrollY);
15529        }
15530    }
15531
15532    /**
15533     * <p>Computes the coordinates of this view on the screen. The argument
15534     * must be an array of two integers. After the method returns, the array
15535     * contains the x and y location in that order.</p>
15536     *
15537     * @param location an array of two integers in which to hold the coordinates
15538     */
15539    public void getLocationOnScreen(int[] location) {
15540        getLocationInWindow(location);
15541
15542        final AttachInfo info = mAttachInfo;
15543        if (info != null) {
15544            location[0] += info.mWindowLeft;
15545            location[1] += info.mWindowTop;
15546        }
15547    }
15548
15549    /**
15550     * <p>Computes the coordinates of this view in its window. The argument
15551     * must be an array of two integers. After the method returns, the array
15552     * contains the x and y location in that order.</p>
15553     *
15554     * @param location an array of two integers in which to hold the coordinates
15555     */
15556    public void getLocationInWindow(int[] location) {
15557        if (location == null || location.length < 2) {
15558            throw new IllegalArgumentException("location must be an array of two integers");
15559        }
15560
15561        if (mAttachInfo == null) {
15562            // When the view is not attached to a window, this method does not make sense
15563            location[0] = location[1] = 0;
15564            return;
15565        }
15566
15567        float[] position = mAttachInfo.mTmpTransformLocation;
15568        position[0] = position[1] = 0.0f;
15569
15570        if (!hasIdentityMatrix()) {
15571            getMatrix().mapPoints(position);
15572        }
15573
15574        position[0] += mLeft;
15575        position[1] += mTop;
15576
15577        ViewParent viewParent = mParent;
15578        while (viewParent instanceof View) {
15579            final View view = (View) viewParent;
15580
15581            position[0] -= view.mScrollX;
15582            position[1] -= view.mScrollY;
15583
15584            if (!view.hasIdentityMatrix()) {
15585                view.getMatrix().mapPoints(position);
15586            }
15587
15588            position[0] += view.mLeft;
15589            position[1] += view.mTop;
15590
15591            viewParent = view.mParent;
15592         }
15593
15594        if (viewParent instanceof ViewRootImpl) {
15595            // *cough*
15596            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15597            position[1] -= vr.mCurScrollY;
15598        }
15599
15600        location[0] = (int) (position[0] + 0.5f);
15601        location[1] = (int) (position[1] + 0.5f);
15602    }
15603
15604    /**
15605     * {@hide}
15606     * @param id the id of the view to be found
15607     * @return the view of the specified id, null if cannot be found
15608     */
15609    protected View findViewTraversal(int id) {
15610        if (id == mID) {
15611            return this;
15612        }
15613        return null;
15614    }
15615
15616    /**
15617     * {@hide}
15618     * @param tag the tag of the view to be found
15619     * @return the view of specified tag, null if cannot be found
15620     */
15621    protected View findViewWithTagTraversal(Object tag) {
15622        if (tag != null && tag.equals(mTag)) {
15623            return this;
15624        }
15625        return null;
15626    }
15627
15628    /**
15629     * {@hide}
15630     * @param predicate The predicate to evaluate.
15631     * @param childToSkip If not null, ignores this child during the recursive traversal.
15632     * @return The first view that matches the predicate or null.
15633     */
15634    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15635        if (predicate.apply(this)) {
15636            return this;
15637        }
15638        return null;
15639    }
15640
15641    /**
15642     * Look for a child view with the given id.  If this view has the given
15643     * id, return this view.
15644     *
15645     * @param id The id to search for.
15646     * @return The view that has the given id in the hierarchy or null
15647     */
15648    public final View findViewById(int id) {
15649        if (id < 0) {
15650            return null;
15651        }
15652        return findViewTraversal(id);
15653    }
15654
15655    /**
15656     * Finds a view by its unuque and stable accessibility id.
15657     *
15658     * @param accessibilityId The searched accessibility id.
15659     * @return The found view.
15660     */
15661    final View findViewByAccessibilityId(int accessibilityId) {
15662        if (accessibilityId < 0) {
15663            return null;
15664        }
15665        return findViewByAccessibilityIdTraversal(accessibilityId);
15666    }
15667
15668    /**
15669     * Performs the traversal to find a view by its unuque and stable accessibility id.
15670     *
15671     * <strong>Note:</strong>This method does not stop at the root namespace
15672     * boundary since the user can touch the screen at an arbitrary location
15673     * potentially crossing the root namespace bounday which will send an
15674     * accessibility event to accessibility services and they should be able
15675     * to obtain the event source. Also accessibility ids are guaranteed to be
15676     * unique in the window.
15677     *
15678     * @param accessibilityId The accessibility id.
15679     * @return The found view.
15680     *
15681     * @hide
15682     */
15683    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
15684        if (getAccessibilityViewId() == accessibilityId) {
15685            return this;
15686        }
15687        return null;
15688    }
15689
15690    /**
15691     * Look for a child view with the given tag.  If this view has the given
15692     * tag, return this view.
15693     *
15694     * @param tag The tag to search for, using "tag.equals(getTag())".
15695     * @return The View that has the given tag in the hierarchy or null
15696     */
15697    public final View findViewWithTag(Object tag) {
15698        if (tag == null) {
15699            return null;
15700        }
15701        return findViewWithTagTraversal(tag);
15702    }
15703
15704    /**
15705     * {@hide}
15706     * Look for a child view that matches the specified predicate.
15707     * If this view matches the predicate, return this view.
15708     *
15709     * @param predicate The predicate to evaluate.
15710     * @return The first view that matches the predicate or null.
15711     */
15712    public final View findViewByPredicate(Predicate<View> predicate) {
15713        return findViewByPredicateTraversal(predicate, null);
15714    }
15715
15716    /**
15717     * {@hide}
15718     * Look for a child view that matches the specified predicate,
15719     * starting with the specified view and its descendents and then
15720     * recusively searching the ancestors and siblings of that view
15721     * until this view is reached.
15722     *
15723     * This method is useful in cases where the predicate does not match
15724     * a single unique view (perhaps multiple views use the same id)
15725     * and we are trying to find the view that is "closest" in scope to the
15726     * starting view.
15727     *
15728     * @param start The view to start from.
15729     * @param predicate The predicate to evaluate.
15730     * @return The first view that matches the predicate or null.
15731     */
15732    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15733        View childToSkip = null;
15734        for (;;) {
15735            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15736            if (view != null || start == this) {
15737                return view;
15738            }
15739
15740            ViewParent parent = start.getParent();
15741            if (parent == null || !(parent instanceof View)) {
15742                return null;
15743            }
15744
15745            childToSkip = start;
15746            start = (View) parent;
15747        }
15748    }
15749
15750    /**
15751     * Sets the identifier for this view. The identifier does not have to be
15752     * unique in this view's hierarchy. The identifier should be a positive
15753     * number.
15754     *
15755     * @see #NO_ID
15756     * @see #getId()
15757     * @see #findViewById(int)
15758     *
15759     * @param id a number used to identify the view
15760     *
15761     * @attr ref android.R.styleable#View_id
15762     */
15763    public void setId(int id) {
15764        mID = id;
15765        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15766            mID = generateViewId();
15767        }
15768    }
15769
15770    /**
15771     * {@hide}
15772     *
15773     * @param isRoot true if the view belongs to the root namespace, false
15774     *        otherwise
15775     */
15776    public void setIsRootNamespace(boolean isRoot) {
15777        if (isRoot) {
15778            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15779        } else {
15780            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15781        }
15782    }
15783
15784    /**
15785     * {@hide}
15786     *
15787     * @return true if the view belongs to the root namespace, false otherwise
15788     */
15789    public boolean isRootNamespace() {
15790        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15791    }
15792
15793    /**
15794     * Returns this view's identifier.
15795     *
15796     * @return a positive integer used to identify the view or {@link #NO_ID}
15797     *         if the view has no ID
15798     *
15799     * @see #setId(int)
15800     * @see #findViewById(int)
15801     * @attr ref android.R.styleable#View_id
15802     */
15803    @ViewDebug.CapturedViewProperty
15804    public int getId() {
15805        return mID;
15806    }
15807
15808    /**
15809     * Returns this view's tag.
15810     *
15811     * @return the Object stored in this view as a tag
15812     *
15813     * @see #setTag(Object)
15814     * @see #getTag(int)
15815     */
15816    @ViewDebug.ExportedProperty
15817    public Object getTag() {
15818        return mTag;
15819    }
15820
15821    /**
15822     * Sets the tag associated with this view. A tag can be used to mark
15823     * a view in its hierarchy and does not have to be unique within the
15824     * hierarchy. Tags can also be used to store data within a view without
15825     * resorting to another data structure.
15826     *
15827     * @param tag an Object to tag the view with
15828     *
15829     * @see #getTag()
15830     * @see #setTag(int, Object)
15831     */
15832    public void setTag(final Object tag) {
15833        mTag = tag;
15834    }
15835
15836    /**
15837     * Returns the tag associated with this view and the specified key.
15838     *
15839     * @param key The key identifying the tag
15840     *
15841     * @return the Object stored in this view as a tag
15842     *
15843     * @see #setTag(int, Object)
15844     * @see #getTag()
15845     */
15846    public Object getTag(int key) {
15847        if (mKeyedTags != null) return mKeyedTags.get(key);
15848        return null;
15849    }
15850
15851    /**
15852     * Sets a tag associated with this view and a key. A tag can be used
15853     * to mark a view in its hierarchy and does not have to be unique within
15854     * the hierarchy. Tags can also be used to store data within a view
15855     * without resorting to another data structure.
15856     *
15857     * The specified key should be an id declared in the resources of the
15858     * application to ensure it is unique (see the <a
15859     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15860     * Keys identified as belonging to
15861     * the Android framework or not associated with any package will cause
15862     * an {@link IllegalArgumentException} to be thrown.
15863     *
15864     * @param key The key identifying the tag
15865     * @param tag An Object to tag the view with
15866     *
15867     * @throws IllegalArgumentException If they specified key is not valid
15868     *
15869     * @see #setTag(Object)
15870     * @see #getTag(int)
15871     */
15872    public void setTag(int key, final Object tag) {
15873        // If the package id is 0x00 or 0x01, it's either an undefined package
15874        // or a framework id
15875        if ((key >>> 24) < 2) {
15876            throw new IllegalArgumentException("The key must be an application-specific "
15877                    + "resource id.");
15878        }
15879
15880        setKeyedTag(key, tag);
15881    }
15882
15883    /**
15884     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15885     * framework id.
15886     *
15887     * @hide
15888     */
15889    public void setTagInternal(int key, Object tag) {
15890        if ((key >>> 24) != 0x1) {
15891            throw new IllegalArgumentException("The key must be a framework-specific "
15892                    + "resource id.");
15893        }
15894
15895        setKeyedTag(key, tag);
15896    }
15897
15898    private void setKeyedTag(int key, Object tag) {
15899        if (mKeyedTags == null) {
15900            mKeyedTags = new SparseArray<Object>(2);
15901        }
15902
15903        mKeyedTags.put(key, tag);
15904    }
15905
15906    /**
15907     * Prints information about this view in the log output, with the tag
15908     * {@link #VIEW_LOG_TAG}.
15909     *
15910     * @hide
15911     */
15912    public void debug() {
15913        debug(0);
15914    }
15915
15916    /**
15917     * Prints information about this view in the log output, with the tag
15918     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15919     * indentation defined by the <code>depth</code>.
15920     *
15921     * @param depth the indentation level
15922     *
15923     * @hide
15924     */
15925    protected void debug(int depth) {
15926        String output = debugIndent(depth - 1);
15927
15928        output += "+ " + this;
15929        int id = getId();
15930        if (id != -1) {
15931            output += " (id=" + id + ")";
15932        }
15933        Object tag = getTag();
15934        if (tag != null) {
15935            output += " (tag=" + tag + ")";
15936        }
15937        Log.d(VIEW_LOG_TAG, output);
15938
15939        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15940            output = debugIndent(depth) + " FOCUSED";
15941            Log.d(VIEW_LOG_TAG, output);
15942        }
15943
15944        output = debugIndent(depth);
15945        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15946                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15947                + "} ";
15948        Log.d(VIEW_LOG_TAG, output);
15949
15950        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15951                || mPaddingBottom != 0) {
15952            output = debugIndent(depth);
15953            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15954                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15955            Log.d(VIEW_LOG_TAG, output);
15956        }
15957
15958        output = debugIndent(depth);
15959        output += "mMeasureWidth=" + mMeasuredWidth +
15960                " mMeasureHeight=" + mMeasuredHeight;
15961        Log.d(VIEW_LOG_TAG, output);
15962
15963        output = debugIndent(depth);
15964        if (mLayoutParams == null) {
15965            output += "BAD! no layout params";
15966        } else {
15967            output = mLayoutParams.debug(output);
15968        }
15969        Log.d(VIEW_LOG_TAG, output);
15970
15971        output = debugIndent(depth);
15972        output += "flags={";
15973        output += View.printFlags(mViewFlags);
15974        output += "}";
15975        Log.d(VIEW_LOG_TAG, output);
15976
15977        output = debugIndent(depth);
15978        output += "privateFlags={";
15979        output += View.printPrivateFlags(mPrivateFlags);
15980        output += "}";
15981        Log.d(VIEW_LOG_TAG, output);
15982    }
15983
15984    /**
15985     * Creates a string of whitespaces used for indentation.
15986     *
15987     * @param depth the indentation level
15988     * @return a String containing (depth * 2 + 3) * 2 white spaces
15989     *
15990     * @hide
15991     */
15992    protected static String debugIndent(int depth) {
15993        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15994        for (int i = 0; i < (depth * 2) + 3; i++) {
15995            spaces.append(' ').append(' ');
15996        }
15997        return spaces.toString();
15998    }
15999
16000    /**
16001     * <p>Return the offset of the widget's text baseline from the widget's top
16002     * boundary. If this widget does not support baseline alignment, this
16003     * method returns -1. </p>
16004     *
16005     * @return the offset of the baseline within the widget's bounds or -1
16006     *         if baseline alignment is not supported
16007     */
16008    @ViewDebug.ExportedProperty(category = "layout")
16009    public int getBaseline() {
16010        return -1;
16011    }
16012
16013    /**
16014     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16015     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16016     * a layout pass.
16017     *
16018     * @return whether the view hierarchy is currently undergoing a layout pass
16019     */
16020    public boolean isInLayout() {
16021        ViewRootImpl viewRoot = getViewRootImpl();
16022        return (viewRoot != null && viewRoot.isInLayout());
16023    }
16024
16025    /**
16026     * Call this when something has changed which has invalidated the
16027     * layout of this view. This will schedule a layout pass of the view
16028     * tree. This should not be called while the view hierarchy is currently in a layout
16029     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16030     * end of the current layout pass (and then layout will run again) or after the current
16031     * frame is drawn and the next layout occurs.
16032     *
16033     * <p>Subclasses which override this method should call the superclass method to
16034     * handle possible request-during-layout errors correctly.</p>
16035     */
16036    public void requestLayout() {
16037        if (mMeasureCache != null) mMeasureCache.clear();
16038
16039        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16040            // Only trigger request-during-layout logic if this is the view requesting it,
16041            // not the views in its parent hierarchy
16042            ViewRootImpl viewRoot = getViewRootImpl();
16043            if (viewRoot != null && viewRoot.isInLayout()) {
16044                if (!viewRoot.requestLayoutDuringLayout(this)) {
16045                    return;
16046                }
16047            }
16048            mAttachInfo.mViewRequestingLayout = this;
16049        }
16050
16051        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16052        mPrivateFlags |= PFLAG_INVALIDATED;
16053
16054        if (mParent != null && !mParent.isLayoutRequested()) {
16055            mParent.requestLayout();
16056        }
16057        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16058            mAttachInfo.mViewRequestingLayout = null;
16059        }
16060    }
16061
16062    /**
16063     * Forces this view to be laid out during the next layout pass.
16064     * This method does not call requestLayout() or forceLayout()
16065     * on the parent.
16066     */
16067    public void forceLayout() {
16068        if (mMeasureCache != null) mMeasureCache.clear();
16069
16070        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16071        mPrivateFlags |= PFLAG_INVALIDATED;
16072    }
16073
16074    /**
16075     * <p>
16076     * This is called to find out how big a view should be. The parent
16077     * supplies constraint information in the width and height parameters.
16078     * </p>
16079     *
16080     * <p>
16081     * The actual measurement work of a view is performed in
16082     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16083     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16084     * </p>
16085     *
16086     *
16087     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16088     *        parent
16089     * @param heightMeasureSpec Vertical space requirements as imposed by the
16090     *        parent
16091     *
16092     * @see #onMeasure(int, int)
16093     */
16094    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16095        boolean optical = isLayoutModeOptical(this);
16096        if (optical != isLayoutModeOptical(mParent)) {
16097            Insets insets = getOpticalInsets();
16098            int oWidth  = insets.left + insets.right;
16099            int oHeight = insets.top  + insets.bottom;
16100            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16101            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16102        }
16103
16104        // Suppress sign extension for the low bytes
16105        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16106        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16107
16108        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16109                widthMeasureSpec != mOldWidthMeasureSpec ||
16110                heightMeasureSpec != mOldHeightMeasureSpec) {
16111
16112            // first clears the measured dimension flag
16113            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16114
16115            resolveRtlPropertiesIfNeeded();
16116
16117            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16118                    mMeasureCache.indexOfKey(key);
16119            if (cacheIndex < 0) {
16120                // measure ourselves, this should set the measured dimension flag back
16121                onMeasure(widthMeasureSpec, heightMeasureSpec);
16122                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16123            } else {
16124                long value = mMeasureCache.valueAt(cacheIndex);
16125                // Casting a long to int drops the high 32 bits, no mask needed
16126                setMeasuredDimension((int) (value >> 32), (int) value);
16127                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16128            }
16129
16130            // flag not set, setMeasuredDimension() was not invoked, we raise
16131            // an exception to warn the developer
16132            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16133                throw new IllegalStateException("onMeasure() did not set the"
16134                        + " measured dimension by calling"
16135                        + " setMeasuredDimension()");
16136            }
16137
16138            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16139        }
16140
16141        mOldWidthMeasureSpec = widthMeasureSpec;
16142        mOldHeightMeasureSpec = heightMeasureSpec;
16143
16144        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16145                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16146    }
16147
16148    /**
16149     * <p>
16150     * Measure the view and its content to determine the measured width and the
16151     * measured height. This method is invoked by {@link #measure(int, int)} and
16152     * should be overriden by subclasses to provide accurate and efficient
16153     * measurement of their contents.
16154     * </p>
16155     *
16156     * <p>
16157     * <strong>CONTRACT:</strong> When overriding this method, you
16158     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16159     * measured width and height of this view. Failure to do so will trigger an
16160     * <code>IllegalStateException</code>, thrown by
16161     * {@link #measure(int, int)}. Calling the superclass'
16162     * {@link #onMeasure(int, int)} is a valid use.
16163     * </p>
16164     *
16165     * <p>
16166     * The base class implementation of measure defaults to the background size,
16167     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16168     * override {@link #onMeasure(int, int)} to provide better measurements of
16169     * their content.
16170     * </p>
16171     *
16172     * <p>
16173     * If this method is overridden, it is the subclass's responsibility to make
16174     * sure the measured height and width are at least the view's minimum height
16175     * and width ({@link #getSuggestedMinimumHeight()} and
16176     * {@link #getSuggestedMinimumWidth()}).
16177     * </p>
16178     *
16179     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16180     *                         The requirements are encoded with
16181     *                         {@link android.view.View.MeasureSpec}.
16182     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16183     *                         The requirements are encoded with
16184     *                         {@link android.view.View.MeasureSpec}.
16185     *
16186     * @see #getMeasuredWidth()
16187     * @see #getMeasuredHeight()
16188     * @see #setMeasuredDimension(int, int)
16189     * @see #getSuggestedMinimumHeight()
16190     * @see #getSuggestedMinimumWidth()
16191     * @see android.view.View.MeasureSpec#getMode(int)
16192     * @see android.view.View.MeasureSpec#getSize(int)
16193     */
16194    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16195        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16196                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16197    }
16198
16199    /**
16200     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16201     * measured width and measured height. Failing to do so will trigger an
16202     * exception at measurement time.</p>
16203     *
16204     * @param measuredWidth The measured width of this view.  May be a complex
16205     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16206     * {@link #MEASURED_STATE_TOO_SMALL}.
16207     * @param measuredHeight The measured height of this view.  May be a complex
16208     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16209     * {@link #MEASURED_STATE_TOO_SMALL}.
16210     */
16211    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16212        boolean optical = isLayoutModeOptical(this);
16213        if (optical != isLayoutModeOptical(mParent)) {
16214            Insets insets = getOpticalInsets();
16215            int opticalWidth  = insets.left + insets.right;
16216            int opticalHeight = insets.top  + insets.bottom;
16217
16218            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16219            measuredHeight += optical ? opticalHeight : -opticalHeight;
16220        }
16221        mMeasuredWidth = measuredWidth;
16222        mMeasuredHeight = measuredHeight;
16223
16224        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16225    }
16226
16227    /**
16228     * Merge two states as returned by {@link #getMeasuredState()}.
16229     * @param curState The current state as returned from a view or the result
16230     * of combining multiple views.
16231     * @param newState The new view state to combine.
16232     * @return Returns a new integer reflecting the combination of the two
16233     * states.
16234     */
16235    public static int combineMeasuredStates(int curState, int newState) {
16236        return curState | newState;
16237    }
16238
16239    /**
16240     * Version of {@link #resolveSizeAndState(int, int, int)}
16241     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16242     */
16243    public static int resolveSize(int size, int measureSpec) {
16244        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16245    }
16246
16247    /**
16248     * Utility to reconcile a desired size and state, with constraints imposed
16249     * by a MeasureSpec.  Will take the desired size, unless a different size
16250     * is imposed by the constraints.  The returned value is a compound integer,
16251     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16252     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16253     * size is smaller than the size the view wants to be.
16254     *
16255     * @param size How big the view wants to be
16256     * @param measureSpec Constraints imposed by the parent
16257     * @return Size information bit mask as defined by
16258     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16259     */
16260    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16261        int result = size;
16262        int specMode = MeasureSpec.getMode(measureSpec);
16263        int specSize =  MeasureSpec.getSize(measureSpec);
16264        switch (specMode) {
16265        case MeasureSpec.UNSPECIFIED:
16266            result = size;
16267            break;
16268        case MeasureSpec.AT_MOST:
16269            if (specSize < size) {
16270                result = specSize | MEASURED_STATE_TOO_SMALL;
16271            } else {
16272                result = size;
16273            }
16274            break;
16275        case MeasureSpec.EXACTLY:
16276            result = specSize;
16277            break;
16278        }
16279        return result | (childMeasuredState&MEASURED_STATE_MASK);
16280    }
16281
16282    /**
16283     * Utility to return a default size. Uses the supplied size if the
16284     * MeasureSpec imposed no constraints. Will get larger if allowed
16285     * by the MeasureSpec.
16286     *
16287     * @param size Default size for this view
16288     * @param measureSpec Constraints imposed by the parent
16289     * @return The size this view should be.
16290     */
16291    public static int getDefaultSize(int size, int measureSpec) {
16292        int result = size;
16293        int specMode = MeasureSpec.getMode(measureSpec);
16294        int specSize = MeasureSpec.getSize(measureSpec);
16295
16296        switch (specMode) {
16297        case MeasureSpec.UNSPECIFIED:
16298            result = size;
16299            break;
16300        case MeasureSpec.AT_MOST:
16301        case MeasureSpec.EXACTLY:
16302            result = specSize;
16303            break;
16304        }
16305        return result;
16306    }
16307
16308    /**
16309     * Returns the suggested minimum height that the view should use. This
16310     * returns the maximum of the view's minimum height
16311     * and the background's minimum height
16312     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16313     * <p>
16314     * When being used in {@link #onMeasure(int, int)}, the caller should still
16315     * ensure the returned height is within the requirements of the parent.
16316     *
16317     * @return The suggested minimum height of the view.
16318     */
16319    protected int getSuggestedMinimumHeight() {
16320        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16321
16322    }
16323
16324    /**
16325     * Returns the suggested minimum width that the view should use. This
16326     * returns the maximum of the view's minimum width)
16327     * and the background's minimum width
16328     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16329     * <p>
16330     * When being used in {@link #onMeasure(int, int)}, the caller should still
16331     * ensure the returned width is within the requirements of the parent.
16332     *
16333     * @return The suggested minimum width of the view.
16334     */
16335    protected int getSuggestedMinimumWidth() {
16336        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16337    }
16338
16339    /**
16340     * Returns the minimum height of the view.
16341     *
16342     * @return the minimum height the view will try to be.
16343     *
16344     * @see #setMinimumHeight(int)
16345     *
16346     * @attr ref android.R.styleable#View_minHeight
16347     */
16348    public int getMinimumHeight() {
16349        return mMinHeight;
16350    }
16351
16352    /**
16353     * Sets the minimum height of the view. It is not guaranteed the view will
16354     * be able to achieve this minimum height (for example, if its parent layout
16355     * constrains it with less available height).
16356     *
16357     * @param minHeight The minimum height the view will try to be.
16358     *
16359     * @see #getMinimumHeight()
16360     *
16361     * @attr ref android.R.styleable#View_minHeight
16362     */
16363    public void setMinimumHeight(int minHeight) {
16364        mMinHeight = minHeight;
16365        requestLayout();
16366    }
16367
16368    /**
16369     * Returns the minimum width of the view.
16370     *
16371     * @return the minimum width the view will try to be.
16372     *
16373     * @see #setMinimumWidth(int)
16374     *
16375     * @attr ref android.R.styleable#View_minWidth
16376     */
16377    public int getMinimumWidth() {
16378        return mMinWidth;
16379    }
16380
16381    /**
16382     * Sets the minimum width of the view. It is not guaranteed the view will
16383     * be able to achieve this minimum width (for example, if its parent layout
16384     * constrains it with less available width).
16385     *
16386     * @param minWidth The minimum width the view will try to be.
16387     *
16388     * @see #getMinimumWidth()
16389     *
16390     * @attr ref android.R.styleable#View_minWidth
16391     */
16392    public void setMinimumWidth(int minWidth) {
16393        mMinWidth = minWidth;
16394        requestLayout();
16395
16396    }
16397
16398    /**
16399     * Get the animation currently associated with this view.
16400     *
16401     * @return The animation that is currently playing or
16402     *         scheduled to play for this view.
16403     */
16404    public Animation getAnimation() {
16405        return mCurrentAnimation;
16406    }
16407
16408    /**
16409     * Start the specified animation now.
16410     *
16411     * @param animation the animation to start now
16412     */
16413    public void startAnimation(Animation animation) {
16414        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16415        setAnimation(animation);
16416        invalidateParentCaches();
16417        invalidate(true);
16418    }
16419
16420    /**
16421     * Cancels any animations for this view.
16422     */
16423    public void clearAnimation() {
16424        if (mCurrentAnimation != null) {
16425            mCurrentAnimation.detach();
16426        }
16427        mCurrentAnimation = null;
16428        invalidateParentIfNeeded();
16429    }
16430
16431    /**
16432     * Sets the next animation to play for this view.
16433     * If you want the animation to play immediately, use
16434     * {@link #startAnimation(android.view.animation.Animation)} instead.
16435     * This method provides allows fine-grained
16436     * control over the start time and invalidation, but you
16437     * must make sure that 1) the animation has a start time set, and
16438     * 2) the view's parent (which controls animations on its children)
16439     * will be invalidated when the animation is supposed to
16440     * start.
16441     *
16442     * @param animation The next animation, or null.
16443     */
16444    public void setAnimation(Animation animation) {
16445        mCurrentAnimation = animation;
16446
16447        if (animation != null) {
16448            // If the screen is off assume the animation start time is now instead of
16449            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16450            // would cause the animation to start when the screen turns back on
16451            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16452                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16453                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16454            }
16455            animation.reset();
16456        }
16457    }
16458
16459    /**
16460     * Invoked by a parent ViewGroup to notify the start of the animation
16461     * currently associated with this view. If you override this method,
16462     * always call super.onAnimationStart();
16463     *
16464     * @see #setAnimation(android.view.animation.Animation)
16465     * @see #getAnimation()
16466     */
16467    protected void onAnimationStart() {
16468        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16469    }
16470
16471    /**
16472     * Invoked by a parent ViewGroup to notify the end of the animation
16473     * currently associated with this view. If you override this method,
16474     * always call super.onAnimationEnd();
16475     *
16476     * @see #setAnimation(android.view.animation.Animation)
16477     * @see #getAnimation()
16478     */
16479    protected void onAnimationEnd() {
16480        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16481    }
16482
16483    /**
16484     * Invoked if there is a Transform that involves alpha. Subclass that can
16485     * draw themselves with the specified alpha should return true, and then
16486     * respect that alpha when their onDraw() is called. If this returns false
16487     * then the view may be redirected to draw into an offscreen buffer to
16488     * fulfill the request, which will look fine, but may be slower than if the
16489     * subclass handles it internally. The default implementation returns false.
16490     *
16491     * @param alpha The alpha (0..255) to apply to the view's drawing
16492     * @return true if the view can draw with the specified alpha.
16493     */
16494    protected boolean onSetAlpha(int alpha) {
16495        return false;
16496    }
16497
16498    /**
16499     * This is used by the RootView to perform an optimization when
16500     * the view hierarchy contains one or several SurfaceView.
16501     * SurfaceView is always considered transparent, but its children are not,
16502     * therefore all View objects remove themselves from the global transparent
16503     * region (passed as a parameter to this function).
16504     *
16505     * @param region The transparent region for this ViewAncestor (window).
16506     *
16507     * @return Returns true if the effective visibility of the view at this
16508     * point is opaque, regardless of the transparent region; returns false
16509     * if it is possible for underlying windows to be seen behind the view.
16510     *
16511     * {@hide}
16512     */
16513    public boolean gatherTransparentRegion(Region region) {
16514        final AttachInfo attachInfo = mAttachInfo;
16515        if (region != null && attachInfo != null) {
16516            final int pflags = mPrivateFlags;
16517            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16518                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16519                // remove it from the transparent region.
16520                final int[] location = attachInfo.mTransparentLocation;
16521                getLocationInWindow(location);
16522                region.op(location[0], location[1], location[0] + mRight - mLeft,
16523                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16524            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16525                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16526                // exists, so we remove the background drawable's non-transparent
16527                // parts from this transparent region.
16528                applyDrawableToTransparentRegion(mBackground, region);
16529            }
16530        }
16531        return true;
16532    }
16533
16534    /**
16535     * Play a sound effect for this view.
16536     *
16537     * <p>The framework will play sound effects for some built in actions, such as
16538     * clicking, but you may wish to play these effects in your widget,
16539     * for instance, for internal navigation.
16540     *
16541     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16542     * {@link #isSoundEffectsEnabled()} is true.
16543     *
16544     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16545     */
16546    public void playSoundEffect(int soundConstant) {
16547        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16548            return;
16549        }
16550        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16551    }
16552
16553    /**
16554     * BZZZTT!!1!
16555     *
16556     * <p>Provide haptic feedback to the user for this view.
16557     *
16558     * <p>The framework will provide haptic feedback for some built in actions,
16559     * such as long presses, but you may wish to provide feedback for your
16560     * own widget.
16561     *
16562     * <p>The feedback will only be performed if
16563     * {@link #isHapticFeedbackEnabled()} is true.
16564     *
16565     * @param feedbackConstant One of the constants defined in
16566     * {@link HapticFeedbackConstants}
16567     */
16568    public boolean performHapticFeedback(int feedbackConstant) {
16569        return performHapticFeedback(feedbackConstant, 0);
16570    }
16571
16572    /**
16573     * BZZZTT!!1!
16574     *
16575     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16576     *
16577     * @param feedbackConstant One of the constants defined in
16578     * {@link HapticFeedbackConstants}
16579     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16580     */
16581    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16582        if (mAttachInfo == null) {
16583            return false;
16584        }
16585        //noinspection SimplifiableIfStatement
16586        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16587                && !isHapticFeedbackEnabled()) {
16588            return false;
16589        }
16590        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16591                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16592    }
16593
16594    /**
16595     * Request that the visibility of the status bar or other screen/window
16596     * decorations be changed.
16597     *
16598     * <p>This method is used to put the over device UI into temporary modes
16599     * where the user's attention is focused more on the application content,
16600     * by dimming or hiding surrounding system affordances.  This is typically
16601     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16602     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16603     * to be placed behind the action bar (and with these flags other system
16604     * affordances) so that smooth transitions between hiding and showing them
16605     * can be done.
16606     *
16607     * <p>Two representative examples of the use of system UI visibility is
16608     * implementing a content browsing application (like a magazine reader)
16609     * and a video playing application.
16610     *
16611     * <p>The first code shows a typical implementation of a View in a content
16612     * browsing application.  In this implementation, the application goes
16613     * into a content-oriented mode by hiding the status bar and action bar,
16614     * and putting the navigation elements into lights out mode.  The user can
16615     * then interact with content while in this mode.  Such an application should
16616     * provide an easy way for the user to toggle out of the mode (such as to
16617     * check information in the status bar or access notifications).  In the
16618     * implementation here, this is done simply by tapping on the content.
16619     *
16620     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16621     *      content}
16622     *
16623     * <p>This second code sample shows a typical implementation of a View
16624     * in a video playing application.  In this situation, while the video is
16625     * playing the application would like to go into a complete full-screen mode,
16626     * to use as much of the display as possible for the video.  When in this state
16627     * the user can not interact with the application; the system intercepts
16628     * touching on the screen to pop the UI out of full screen mode.  See
16629     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16630     *
16631     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16632     *      content}
16633     *
16634     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16635     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16636     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16637     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT},
16638     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
16639     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
16640     */
16641    public void setSystemUiVisibility(int visibility) {
16642        if (visibility != mSystemUiVisibility) {
16643            mSystemUiVisibility = visibility;
16644            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16645                mParent.recomputeViewAttributes(this);
16646            }
16647        }
16648    }
16649
16650    /**
16651     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
16652     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16653     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16654     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16655     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT},
16656     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
16657     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
16658     */
16659    public int getSystemUiVisibility() {
16660        return mSystemUiVisibility;
16661    }
16662
16663    /**
16664     * Returns the current system UI visibility that is currently set for
16665     * the entire window.  This is the combination of the
16666     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16667     * views in the window.
16668     */
16669    public int getWindowSystemUiVisibility() {
16670        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16671    }
16672
16673    /**
16674     * Override to find out when the window's requested system UI visibility
16675     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16676     * This is different from the callbacks received through
16677     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16678     * in that this is only telling you about the local request of the window,
16679     * not the actual values applied by the system.
16680     */
16681    public void onWindowSystemUiVisibilityChanged(int visible) {
16682    }
16683
16684    /**
16685     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16686     * the view hierarchy.
16687     */
16688    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16689        onWindowSystemUiVisibilityChanged(visible);
16690    }
16691
16692    /**
16693     * Set a listener to receive callbacks when the visibility of the system bar changes.
16694     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16695     */
16696    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16697        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16698        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16699            mParent.recomputeViewAttributes(this);
16700        }
16701    }
16702
16703    /**
16704     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16705     * the view hierarchy.
16706     */
16707    public void dispatchSystemUiVisibilityChanged(int visibility) {
16708        ListenerInfo li = mListenerInfo;
16709        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16710            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16711                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16712        }
16713    }
16714
16715    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16716        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16717        if (val != mSystemUiVisibility) {
16718            setSystemUiVisibility(val);
16719            return true;
16720        }
16721        return false;
16722    }
16723
16724    /** @hide */
16725    public void setDisabledSystemUiVisibility(int flags) {
16726        if (mAttachInfo != null) {
16727            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16728                mAttachInfo.mDisabledSystemUiVisibility = flags;
16729                if (mParent != null) {
16730                    mParent.recomputeViewAttributes(this);
16731                }
16732            }
16733        }
16734    }
16735
16736    /**
16737     * Creates an image that the system displays during the drag and drop
16738     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16739     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16740     * appearance as the given View. The default also positions the center of the drag shadow
16741     * directly under the touch point. If no View is provided (the constructor with no parameters
16742     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16743     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16744     * default is an invisible drag shadow.
16745     * <p>
16746     * You are not required to use the View you provide to the constructor as the basis of the
16747     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16748     * anything you want as the drag shadow.
16749     * </p>
16750     * <p>
16751     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16752     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16753     *  size and position of the drag shadow. It uses this data to construct a
16754     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16755     *  so that your application can draw the shadow image in the Canvas.
16756     * </p>
16757     *
16758     * <div class="special reference">
16759     * <h3>Developer Guides</h3>
16760     * <p>For a guide to implementing drag and drop features, read the
16761     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16762     * </div>
16763     */
16764    public static class DragShadowBuilder {
16765        private final WeakReference<View> mView;
16766
16767        /**
16768         * Constructs a shadow image builder based on a View. By default, the resulting drag
16769         * shadow will have the same appearance and dimensions as the View, with the touch point
16770         * over the center of the View.
16771         * @param view A View. Any View in scope can be used.
16772         */
16773        public DragShadowBuilder(View view) {
16774            mView = new WeakReference<View>(view);
16775        }
16776
16777        /**
16778         * Construct a shadow builder object with no associated View.  This
16779         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16780         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16781         * to supply the drag shadow's dimensions and appearance without
16782         * reference to any View object. If they are not overridden, then the result is an
16783         * invisible drag shadow.
16784         */
16785        public DragShadowBuilder() {
16786            mView = new WeakReference<View>(null);
16787        }
16788
16789        /**
16790         * Returns the View object that had been passed to the
16791         * {@link #View.DragShadowBuilder(View)}
16792         * constructor.  If that View parameter was {@code null} or if the
16793         * {@link #View.DragShadowBuilder()}
16794         * constructor was used to instantiate the builder object, this method will return
16795         * null.
16796         *
16797         * @return The View object associate with this builder object.
16798         */
16799        @SuppressWarnings({"JavadocReference"})
16800        final public View getView() {
16801            return mView.get();
16802        }
16803
16804        /**
16805         * Provides the metrics for the shadow image. These include the dimensions of
16806         * the shadow image, and the point within that shadow that should
16807         * be centered under the touch location while dragging.
16808         * <p>
16809         * The default implementation sets the dimensions of the shadow to be the
16810         * same as the dimensions of the View itself and centers the shadow under
16811         * the touch point.
16812         * </p>
16813         *
16814         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16815         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16816         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16817         * image.
16818         *
16819         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16820         * shadow image that should be underneath the touch point during the drag and drop
16821         * operation. Your application must set {@link android.graphics.Point#x} to the
16822         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16823         */
16824        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16825            final View view = mView.get();
16826            if (view != null) {
16827                shadowSize.set(view.getWidth(), view.getHeight());
16828                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16829            } else {
16830                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16831            }
16832        }
16833
16834        /**
16835         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16836         * based on the dimensions it received from the
16837         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16838         *
16839         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16840         */
16841        public void onDrawShadow(Canvas canvas) {
16842            final View view = mView.get();
16843            if (view != null) {
16844                view.draw(canvas);
16845            } else {
16846                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16847            }
16848        }
16849    }
16850
16851    /**
16852     * Starts a drag and drop operation. When your application calls this method, it passes a
16853     * {@link android.view.View.DragShadowBuilder} object to the system. The
16854     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16855     * to get metrics for the drag shadow, and then calls the object's
16856     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16857     * <p>
16858     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16859     *  drag events to all the View objects in your application that are currently visible. It does
16860     *  this either by calling the View object's drag listener (an implementation of
16861     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16862     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16863     *  Both are passed a {@link android.view.DragEvent} object that has a
16864     *  {@link android.view.DragEvent#getAction()} value of
16865     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16866     * </p>
16867     * <p>
16868     * Your application can invoke startDrag() on any attached View object. The View object does not
16869     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16870     * be related to the View the user selected for dragging.
16871     * </p>
16872     * @param data A {@link android.content.ClipData} object pointing to the data to be
16873     * transferred by the drag and drop operation.
16874     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16875     * drag shadow.
16876     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16877     * drop operation. This Object is put into every DragEvent object sent by the system during the
16878     * current drag.
16879     * <p>
16880     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16881     * to the target Views. For example, it can contain flags that differentiate between a
16882     * a copy operation and a move operation.
16883     * </p>
16884     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16885     * so the parameter should be set to 0.
16886     * @return {@code true} if the method completes successfully, or
16887     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16888     * do a drag, and so no drag operation is in progress.
16889     */
16890    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16891            Object myLocalState, int flags) {
16892        if (ViewDebug.DEBUG_DRAG) {
16893            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16894        }
16895        boolean okay = false;
16896
16897        Point shadowSize = new Point();
16898        Point shadowTouchPoint = new Point();
16899        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16900
16901        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16902                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16903            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16904        }
16905
16906        if (ViewDebug.DEBUG_DRAG) {
16907            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16908                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16909        }
16910        Surface surface = new Surface();
16911        try {
16912            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16913                    flags, shadowSize.x, shadowSize.y, surface);
16914            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16915                    + " surface=" + surface);
16916            if (token != null) {
16917                Canvas canvas = surface.lockCanvas(null);
16918                try {
16919                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16920                    shadowBuilder.onDrawShadow(canvas);
16921                } finally {
16922                    surface.unlockCanvasAndPost(canvas);
16923                }
16924
16925                final ViewRootImpl root = getViewRootImpl();
16926
16927                // Cache the local state object for delivery with DragEvents
16928                root.setLocalDragState(myLocalState);
16929
16930                // repurpose 'shadowSize' for the last touch point
16931                root.getLastTouchPoint(shadowSize);
16932
16933                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16934                        shadowSize.x, shadowSize.y,
16935                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16936                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16937
16938                // Off and running!  Release our local surface instance; the drag
16939                // shadow surface is now managed by the system process.
16940                surface.release();
16941            }
16942        } catch (Exception e) {
16943            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16944            surface.destroy();
16945        }
16946
16947        return okay;
16948    }
16949
16950    /**
16951     * Handles drag events sent by the system following a call to
16952     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16953     *<p>
16954     * When the system calls this method, it passes a
16955     * {@link android.view.DragEvent} object. A call to
16956     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16957     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16958     * operation.
16959     * @param event The {@link android.view.DragEvent} sent by the system.
16960     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16961     * in DragEvent, indicating the type of drag event represented by this object.
16962     * @return {@code true} if the method was successful, otherwise {@code false}.
16963     * <p>
16964     *  The method should return {@code true} in response to an action type of
16965     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16966     *  operation.
16967     * </p>
16968     * <p>
16969     *  The method should also return {@code true} in response to an action type of
16970     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16971     *  {@code false} if it didn't.
16972     * </p>
16973     */
16974    public boolean onDragEvent(DragEvent event) {
16975        return false;
16976    }
16977
16978    /**
16979     * Detects if this View is enabled and has a drag event listener.
16980     * If both are true, then it calls the drag event listener with the
16981     * {@link android.view.DragEvent} it received. If the drag event listener returns
16982     * {@code true}, then dispatchDragEvent() returns {@code true}.
16983     * <p>
16984     * For all other cases, the method calls the
16985     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16986     * method and returns its result.
16987     * </p>
16988     * <p>
16989     * This ensures that a drag event is always consumed, even if the View does not have a drag
16990     * event listener. However, if the View has a listener and the listener returns true, then
16991     * onDragEvent() is not called.
16992     * </p>
16993     */
16994    public boolean dispatchDragEvent(DragEvent event) {
16995        ListenerInfo li = mListenerInfo;
16996        //noinspection SimplifiableIfStatement
16997        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16998                && li.mOnDragListener.onDrag(this, event)) {
16999            return true;
17000        }
17001        return onDragEvent(event);
17002    }
17003
17004    boolean canAcceptDrag() {
17005        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17006    }
17007
17008    /**
17009     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17010     * it is ever exposed at all.
17011     * @hide
17012     */
17013    public void onCloseSystemDialogs(String reason) {
17014    }
17015
17016    /**
17017     * Given a Drawable whose bounds have been set to draw into this view,
17018     * update a Region being computed for
17019     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17020     * that any non-transparent parts of the Drawable are removed from the
17021     * given transparent region.
17022     *
17023     * @param dr The Drawable whose transparency is to be applied to the region.
17024     * @param region A Region holding the current transparency information,
17025     * where any parts of the region that are set are considered to be
17026     * transparent.  On return, this region will be modified to have the
17027     * transparency information reduced by the corresponding parts of the
17028     * Drawable that are not transparent.
17029     * {@hide}
17030     */
17031    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17032        if (DBG) {
17033            Log.i("View", "Getting transparent region for: " + this);
17034        }
17035        final Region r = dr.getTransparentRegion();
17036        final Rect db = dr.getBounds();
17037        final AttachInfo attachInfo = mAttachInfo;
17038        if (r != null && attachInfo != null) {
17039            final int w = getRight()-getLeft();
17040            final int h = getBottom()-getTop();
17041            if (db.left > 0) {
17042                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17043                r.op(0, 0, db.left, h, Region.Op.UNION);
17044            }
17045            if (db.right < w) {
17046                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17047                r.op(db.right, 0, w, h, Region.Op.UNION);
17048            }
17049            if (db.top > 0) {
17050                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17051                r.op(0, 0, w, db.top, Region.Op.UNION);
17052            }
17053            if (db.bottom < h) {
17054                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17055                r.op(0, db.bottom, w, h, Region.Op.UNION);
17056            }
17057            final int[] location = attachInfo.mTransparentLocation;
17058            getLocationInWindow(location);
17059            r.translate(location[0], location[1]);
17060            region.op(r, Region.Op.INTERSECT);
17061        } else {
17062            region.op(db, Region.Op.DIFFERENCE);
17063        }
17064    }
17065
17066    private void checkForLongClick(int delayOffset) {
17067        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17068            mHasPerformedLongPress = false;
17069
17070            if (mPendingCheckForLongPress == null) {
17071                mPendingCheckForLongPress = new CheckForLongPress();
17072            }
17073            mPendingCheckForLongPress.rememberWindowAttachCount();
17074            postDelayed(mPendingCheckForLongPress,
17075                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17076        }
17077    }
17078
17079    /**
17080     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17081     * LayoutInflater} class, which provides a full range of options for view inflation.
17082     *
17083     * @param context The Context object for your activity or application.
17084     * @param resource The resource ID to inflate
17085     * @param root A view group that will be the parent.  Used to properly inflate the
17086     * layout_* parameters.
17087     * @see LayoutInflater
17088     */
17089    public static View inflate(Context context, int resource, ViewGroup root) {
17090        LayoutInflater factory = LayoutInflater.from(context);
17091        return factory.inflate(resource, root);
17092    }
17093
17094    /**
17095     * Scroll the view with standard behavior for scrolling beyond the normal
17096     * content boundaries. Views that call this method should override
17097     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17098     * results of an over-scroll operation.
17099     *
17100     * Views can use this method to handle any touch or fling-based scrolling.
17101     *
17102     * @param deltaX Change in X in pixels
17103     * @param deltaY Change in Y in pixels
17104     * @param scrollX Current X scroll value in pixels before applying deltaX
17105     * @param scrollY Current Y scroll value in pixels before applying deltaY
17106     * @param scrollRangeX Maximum content scroll range along the X axis
17107     * @param scrollRangeY Maximum content scroll range along the Y axis
17108     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17109     *          along the X axis.
17110     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17111     *          along the Y axis.
17112     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17113     * @return true if scrolling was clamped to an over-scroll boundary along either
17114     *          axis, false otherwise.
17115     */
17116    @SuppressWarnings({"UnusedParameters"})
17117    protected boolean overScrollBy(int deltaX, int deltaY,
17118            int scrollX, int scrollY,
17119            int scrollRangeX, int scrollRangeY,
17120            int maxOverScrollX, int maxOverScrollY,
17121            boolean isTouchEvent) {
17122        final int overScrollMode = mOverScrollMode;
17123        final boolean canScrollHorizontal =
17124                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17125        final boolean canScrollVertical =
17126                computeVerticalScrollRange() > computeVerticalScrollExtent();
17127        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17128                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17129        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17130                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17131
17132        int newScrollX = scrollX + deltaX;
17133        if (!overScrollHorizontal) {
17134            maxOverScrollX = 0;
17135        }
17136
17137        int newScrollY = scrollY + deltaY;
17138        if (!overScrollVertical) {
17139            maxOverScrollY = 0;
17140        }
17141
17142        // Clamp values if at the limits and record
17143        final int left = -maxOverScrollX;
17144        final int right = maxOverScrollX + scrollRangeX;
17145        final int top = -maxOverScrollY;
17146        final int bottom = maxOverScrollY + scrollRangeY;
17147
17148        boolean clampedX = false;
17149        if (newScrollX > right) {
17150            newScrollX = right;
17151            clampedX = true;
17152        } else if (newScrollX < left) {
17153            newScrollX = left;
17154            clampedX = true;
17155        }
17156
17157        boolean clampedY = false;
17158        if (newScrollY > bottom) {
17159            newScrollY = bottom;
17160            clampedY = true;
17161        } else if (newScrollY < top) {
17162            newScrollY = top;
17163            clampedY = true;
17164        }
17165
17166        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17167
17168        return clampedX || clampedY;
17169    }
17170
17171    /**
17172     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17173     * respond to the results of an over-scroll operation.
17174     *
17175     * @param scrollX New X scroll value in pixels
17176     * @param scrollY New Y scroll value in pixels
17177     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17178     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17179     */
17180    protected void onOverScrolled(int scrollX, int scrollY,
17181            boolean clampedX, boolean clampedY) {
17182        // Intentionally empty.
17183    }
17184
17185    /**
17186     * Returns the over-scroll mode for this view. The result will be
17187     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17188     * (allow over-scrolling only if the view content is larger than the container),
17189     * or {@link #OVER_SCROLL_NEVER}.
17190     *
17191     * @return This view's over-scroll mode.
17192     */
17193    public int getOverScrollMode() {
17194        return mOverScrollMode;
17195    }
17196
17197    /**
17198     * Set the over-scroll mode for this view. Valid over-scroll modes are
17199     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17200     * (allow over-scrolling only if the view content is larger than the container),
17201     * or {@link #OVER_SCROLL_NEVER}.
17202     *
17203     * Setting the over-scroll mode of a view will have an effect only if the
17204     * view is capable of scrolling.
17205     *
17206     * @param overScrollMode The new over-scroll mode for this view.
17207     */
17208    public void setOverScrollMode(int overScrollMode) {
17209        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17210                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17211                overScrollMode != OVER_SCROLL_NEVER) {
17212            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17213        }
17214        mOverScrollMode = overScrollMode;
17215    }
17216
17217    /**
17218     * Gets a scale factor that determines the distance the view should scroll
17219     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17220     * @return The vertical scroll scale factor.
17221     * @hide
17222     */
17223    protected float getVerticalScrollFactor() {
17224        if (mVerticalScrollFactor == 0) {
17225            TypedValue outValue = new TypedValue();
17226            if (!mContext.getTheme().resolveAttribute(
17227                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17228                throw new IllegalStateException(
17229                        "Expected theme to define listPreferredItemHeight.");
17230            }
17231            mVerticalScrollFactor = outValue.getDimension(
17232                    mContext.getResources().getDisplayMetrics());
17233        }
17234        return mVerticalScrollFactor;
17235    }
17236
17237    /**
17238     * Gets a scale factor that determines the distance the view should scroll
17239     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17240     * @return The horizontal scroll scale factor.
17241     * @hide
17242     */
17243    protected float getHorizontalScrollFactor() {
17244        // TODO: Should use something else.
17245        return getVerticalScrollFactor();
17246    }
17247
17248    /**
17249     * Return the value specifying the text direction or policy that was set with
17250     * {@link #setTextDirection(int)}.
17251     *
17252     * @return the defined text direction. It can be one of:
17253     *
17254     * {@link #TEXT_DIRECTION_INHERIT},
17255     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17256     * {@link #TEXT_DIRECTION_ANY_RTL},
17257     * {@link #TEXT_DIRECTION_LTR},
17258     * {@link #TEXT_DIRECTION_RTL},
17259     * {@link #TEXT_DIRECTION_LOCALE}
17260     *
17261     * @attr ref android.R.styleable#View_textDirection
17262     *
17263     * @hide
17264     */
17265    @ViewDebug.ExportedProperty(category = "text", mapping = {
17266            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17267            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17268            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17269            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17270            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17271            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17272    })
17273    public int getRawTextDirection() {
17274        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17275    }
17276
17277    /**
17278     * Set the text direction.
17279     *
17280     * @param textDirection the direction to set. Should be one of:
17281     *
17282     * {@link #TEXT_DIRECTION_INHERIT},
17283     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17284     * {@link #TEXT_DIRECTION_ANY_RTL},
17285     * {@link #TEXT_DIRECTION_LTR},
17286     * {@link #TEXT_DIRECTION_RTL},
17287     * {@link #TEXT_DIRECTION_LOCALE}
17288     *
17289     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17290     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17291     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17292     *
17293     * @attr ref android.R.styleable#View_textDirection
17294     */
17295    public void setTextDirection(int textDirection) {
17296        if (getRawTextDirection() != textDirection) {
17297            // Reset the current text direction and the resolved one
17298            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17299            resetResolvedTextDirection();
17300            // Set the new text direction
17301            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17302            // Do resolution
17303            resolveTextDirection();
17304            // Notify change
17305            onRtlPropertiesChanged(getLayoutDirection());
17306            // Refresh
17307            requestLayout();
17308            invalidate(true);
17309        }
17310    }
17311
17312    /**
17313     * Return the resolved text direction.
17314     *
17315     * @return the resolved text direction. Returns one of:
17316     *
17317     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17318     * {@link #TEXT_DIRECTION_ANY_RTL},
17319     * {@link #TEXT_DIRECTION_LTR},
17320     * {@link #TEXT_DIRECTION_RTL},
17321     * {@link #TEXT_DIRECTION_LOCALE}
17322     *
17323     * @attr ref android.R.styleable#View_textDirection
17324     */
17325    @ViewDebug.ExportedProperty(category = "text", mapping = {
17326            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17327            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17328            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17329            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17330            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17331            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17332    })
17333    public int getTextDirection() {
17334        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17335    }
17336
17337    /**
17338     * Resolve the text direction.
17339     *
17340     * @return true if resolution has been done, false otherwise.
17341     *
17342     * @hide
17343     */
17344    public boolean resolveTextDirection() {
17345        // Reset any previous text direction resolution
17346        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17347
17348        if (hasRtlSupport()) {
17349            // Set resolved text direction flag depending on text direction flag
17350            final int textDirection = getRawTextDirection();
17351            switch(textDirection) {
17352                case TEXT_DIRECTION_INHERIT:
17353                    if (!canResolveTextDirection()) {
17354                        // We cannot do the resolution if there is no parent, so use the default one
17355                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17356                        // Resolution will need to happen again later
17357                        return false;
17358                    }
17359
17360                    // Parent has not yet resolved, so we still return the default
17361                    try {
17362                        if (!mParent.isTextDirectionResolved()) {
17363                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17364                            // Resolution will need to happen again later
17365                            return false;
17366                        }
17367                    } catch (AbstractMethodError e) {
17368                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17369                                " does not fully implement ViewParent", e);
17370                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17371                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17372                        return true;
17373                    }
17374
17375                    // Set current resolved direction to the same value as the parent's one
17376                    int parentResolvedDirection;
17377                    try {
17378                        parentResolvedDirection = mParent.getTextDirection();
17379                    } catch (AbstractMethodError e) {
17380                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17381                                " does not fully implement ViewParent", e);
17382                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17383                    }
17384                    switch (parentResolvedDirection) {
17385                        case TEXT_DIRECTION_FIRST_STRONG:
17386                        case TEXT_DIRECTION_ANY_RTL:
17387                        case TEXT_DIRECTION_LTR:
17388                        case TEXT_DIRECTION_RTL:
17389                        case TEXT_DIRECTION_LOCALE:
17390                            mPrivateFlags2 |=
17391                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17392                            break;
17393                        default:
17394                            // Default resolved direction is "first strong" heuristic
17395                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17396                    }
17397                    break;
17398                case TEXT_DIRECTION_FIRST_STRONG:
17399                case TEXT_DIRECTION_ANY_RTL:
17400                case TEXT_DIRECTION_LTR:
17401                case TEXT_DIRECTION_RTL:
17402                case TEXT_DIRECTION_LOCALE:
17403                    // Resolved direction is the same as text direction
17404                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17405                    break;
17406                default:
17407                    // Default resolved direction is "first strong" heuristic
17408                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17409            }
17410        } else {
17411            // Default resolved direction is "first strong" heuristic
17412            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17413        }
17414
17415        // Set to resolved
17416        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17417        return true;
17418    }
17419
17420    /**
17421     * Check if text direction resolution can be done.
17422     *
17423     * @return true if text direction resolution can be done otherwise return false.
17424     */
17425    public boolean canResolveTextDirection() {
17426        switch (getRawTextDirection()) {
17427            case TEXT_DIRECTION_INHERIT:
17428                if (mParent != null) {
17429                    try {
17430                        return mParent.canResolveTextDirection();
17431                    } catch (AbstractMethodError e) {
17432                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17433                                " does not fully implement ViewParent", e);
17434                    }
17435                }
17436                return false;
17437
17438            default:
17439                return true;
17440        }
17441    }
17442
17443    /**
17444     * Reset resolved text direction. Text direction will be resolved during a call to
17445     * {@link #onMeasure(int, int)}.
17446     *
17447     * @hide
17448     */
17449    public void resetResolvedTextDirection() {
17450        // Reset any previous text direction resolution
17451        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17452        // Set to default value
17453        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17454    }
17455
17456    /**
17457     * @return true if text direction is inherited.
17458     *
17459     * @hide
17460     */
17461    public boolean isTextDirectionInherited() {
17462        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17463    }
17464
17465    /**
17466     * @return true if text direction is resolved.
17467     */
17468    public boolean isTextDirectionResolved() {
17469        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17470    }
17471
17472    /**
17473     * Return the value specifying the text alignment or policy that was set with
17474     * {@link #setTextAlignment(int)}.
17475     *
17476     * @return the defined text alignment. It can be one of:
17477     *
17478     * {@link #TEXT_ALIGNMENT_INHERIT},
17479     * {@link #TEXT_ALIGNMENT_GRAVITY},
17480     * {@link #TEXT_ALIGNMENT_CENTER},
17481     * {@link #TEXT_ALIGNMENT_TEXT_START},
17482     * {@link #TEXT_ALIGNMENT_TEXT_END},
17483     * {@link #TEXT_ALIGNMENT_VIEW_START},
17484     * {@link #TEXT_ALIGNMENT_VIEW_END}
17485     *
17486     * @attr ref android.R.styleable#View_textAlignment
17487     *
17488     * @hide
17489     */
17490    @ViewDebug.ExportedProperty(category = "text", mapping = {
17491            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17492            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17493            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17494            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17495            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17496            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17497            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17498    })
17499    public int getRawTextAlignment() {
17500        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17501    }
17502
17503    /**
17504     * Set the text alignment.
17505     *
17506     * @param textAlignment The text alignment to set. Should be one of
17507     *
17508     * {@link #TEXT_ALIGNMENT_INHERIT},
17509     * {@link #TEXT_ALIGNMENT_GRAVITY},
17510     * {@link #TEXT_ALIGNMENT_CENTER},
17511     * {@link #TEXT_ALIGNMENT_TEXT_START},
17512     * {@link #TEXT_ALIGNMENT_TEXT_END},
17513     * {@link #TEXT_ALIGNMENT_VIEW_START},
17514     * {@link #TEXT_ALIGNMENT_VIEW_END}
17515     *
17516     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17517     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17518     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17519     *
17520     * @attr ref android.R.styleable#View_textAlignment
17521     */
17522    public void setTextAlignment(int textAlignment) {
17523        if (textAlignment != getRawTextAlignment()) {
17524            // Reset the current and resolved text alignment
17525            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17526            resetResolvedTextAlignment();
17527            // Set the new text alignment
17528            mPrivateFlags2 |=
17529                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17530            // Do resolution
17531            resolveTextAlignment();
17532            // Notify change
17533            onRtlPropertiesChanged(getLayoutDirection());
17534            // Refresh
17535            requestLayout();
17536            invalidate(true);
17537        }
17538    }
17539
17540    /**
17541     * Return the resolved text alignment.
17542     *
17543     * @return the resolved text alignment. Returns one of:
17544     *
17545     * {@link #TEXT_ALIGNMENT_GRAVITY},
17546     * {@link #TEXT_ALIGNMENT_CENTER},
17547     * {@link #TEXT_ALIGNMENT_TEXT_START},
17548     * {@link #TEXT_ALIGNMENT_TEXT_END},
17549     * {@link #TEXT_ALIGNMENT_VIEW_START},
17550     * {@link #TEXT_ALIGNMENT_VIEW_END}
17551     *
17552     * @attr ref android.R.styleable#View_textAlignment
17553     */
17554    @ViewDebug.ExportedProperty(category = "text", mapping = {
17555            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17556            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17557            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17558            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17559            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17560            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17561            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17562    })
17563    public int getTextAlignment() {
17564        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17565                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17566    }
17567
17568    /**
17569     * Resolve the text alignment.
17570     *
17571     * @return true if resolution has been done, false otherwise.
17572     *
17573     * @hide
17574     */
17575    public boolean resolveTextAlignment() {
17576        // Reset any previous text alignment resolution
17577        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17578
17579        if (hasRtlSupport()) {
17580            // Set resolved text alignment flag depending on text alignment flag
17581            final int textAlignment = getRawTextAlignment();
17582            switch (textAlignment) {
17583                case TEXT_ALIGNMENT_INHERIT:
17584                    // Check if we can resolve the text alignment
17585                    if (!canResolveTextAlignment()) {
17586                        // We cannot do the resolution if there is no parent so use the default
17587                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17588                        // Resolution will need to happen again later
17589                        return false;
17590                    }
17591
17592                    // Parent has not yet resolved, so we still return the default
17593                    try {
17594                        if (!mParent.isTextAlignmentResolved()) {
17595                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17596                            // Resolution will need to happen again later
17597                            return false;
17598                        }
17599                    } catch (AbstractMethodError e) {
17600                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17601                                " does not fully implement ViewParent", e);
17602                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
17603                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17604                        return true;
17605                    }
17606
17607                    int parentResolvedTextAlignment;
17608                    try {
17609                        parentResolvedTextAlignment = mParent.getTextAlignment();
17610                    } catch (AbstractMethodError e) {
17611                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17612                                " does not fully implement ViewParent", e);
17613                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
17614                    }
17615                    switch (parentResolvedTextAlignment) {
17616                        case TEXT_ALIGNMENT_GRAVITY:
17617                        case TEXT_ALIGNMENT_TEXT_START:
17618                        case TEXT_ALIGNMENT_TEXT_END:
17619                        case TEXT_ALIGNMENT_CENTER:
17620                        case TEXT_ALIGNMENT_VIEW_START:
17621                        case TEXT_ALIGNMENT_VIEW_END:
17622                            // Resolved text alignment is the same as the parent resolved
17623                            // text alignment
17624                            mPrivateFlags2 |=
17625                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17626                            break;
17627                        default:
17628                            // Use default resolved text alignment
17629                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17630                    }
17631                    break;
17632                case TEXT_ALIGNMENT_GRAVITY:
17633                case TEXT_ALIGNMENT_TEXT_START:
17634                case TEXT_ALIGNMENT_TEXT_END:
17635                case TEXT_ALIGNMENT_CENTER:
17636                case TEXT_ALIGNMENT_VIEW_START:
17637                case TEXT_ALIGNMENT_VIEW_END:
17638                    // Resolved text alignment is the same as text alignment
17639                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17640                    break;
17641                default:
17642                    // Use default resolved text alignment
17643                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17644            }
17645        } else {
17646            // Use default resolved text alignment
17647            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17648        }
17649
17650        // Set the resolved
17651        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17652        return true;
17653    }
17654
17655    /**
17656     * Check if text alignment resolution can be done.
17657     *
17658     * @return true if text alignment resolution can be done otherwise return false.
17659     */
17660    public boolean canResolveTextAlignment() {
17661        switch (getRawTextAlignment()) {
17662            case TEXT_DIRECTION_INHERIT:
17663                if (mParent != null) {
17664                    try {
17665                        return mParent.canResolveTextAlignment();
17666                    } catch (AbstractMethodError e) {
17667                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17668                                " does not fully implement ViewParent", e);
17669                    }
17670                }
17671                return false;
17672
17673            default:
17674                return true;
17675        }
17676    }
17677
17678    /**
17679     * Reset resolved text alignment. Text alignment will be resolved during a call to
17680     * {@link #onMeasure(int, int)}.
17681     *
17682     * @hide
17683     */
17684    public void resetResolvedTextAlignment() {
17685        // Reset any previous text alignment resolution
17686        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17687        // Set to default
17688        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17689    }
17690
17691    /**
17692     * @return true if text alignment is inherited.
17693     *
17694     * @hide
17695     */
17696    public boolean isTextAlignmentInherited() {
17697        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17698    }
17699
17700    /**
17701     * @return true if text alignment is resolved.
17702     */
17703    public boolean isTextAlignmentResolved() {
17704        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17705    }
17706
17707    /**
17708     * Generate a value suitable for use in {@link #setId(int)}.
17709     * This value will not collide with ID values generated at build time by aapt for R.id.
17710     *
17711     * @return a generated ID value
17712     */
17713    public static int generateViewId() {
17714        for (;;) {
17715            final int result = sNextGeneratedId.get();
17716            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17717            int newValue = result + 1;
17718            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17719            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17720                return result;
17721            }
17722        }
17723    }
17724
17725    //
17726    // Properties
17727    //
17728    /**
17729     * A Property wrapper around the <code>alpha</code> functionality handled by the
17730     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17731     */
17732    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17733        @Override
17734        public void setValue(View object, float value) {
17735            object.setAlpha(value);
17736        }
17737
17738        @Override
17739        public Float get(View object) {
17740            return object.getAlpha();
17741        }
17742    };
17743
17744    /**
17745     * A Property wrapper around the <code>translationX</code> functionality handled by the
17746     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17747     */
17748    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17749        @Override
17750        public void setValue(View object, float value) {
17751            object.setTranslationX(value);
17752        }
17753
17754                @Override
17755        public Float get(View object) {
17756            return object.getTranslationX();
17757        }
17758    };
17759
17760    /**
17761     * A Property wrapper around the <code>translationY</code> functionality handled by the
17762     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17763     */
17764    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17765        @Override
17766        public void setValue(View object, float value) {
17767            object.setTranslationY(value);
17768        }
17769
17770        @Override
17771        public Float get(View object) {
17772            return object.getTranslationY();
17773        }
17774    };
17775
17776    /**
17777     * A Property wrapper around the <code>x</code> functionality handled by the
17778     * {@link View#setX(float)} and {@link View#getX()} methods.
17779     */
17780    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17781        @Override
17782        public void setValue(View object, float value) {
17783            object.setX(value);
17784        }
17785
17786        @Override
17787        public Float get(View object) {
17788            return object.getX();
17789        }
17790    };
17791
17792    /**
17793     * A Property wrapper around the <code>y</code> functionality handled by the
17794     * {@link View#setY(float)} and {@link View#getY()} methods.
17795     */
17796    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17797        @Override
17798        public void setValue(View object, float value) {
17799            object.setY(value);
17800        }
17801
17802        @Override
17803        public Float get(View object) {
17804            return object.getY();
17805        }
17806    };
17807
17808    /**
17809     * A Property wrapper around the <code>rotation</code> functionality handled by the
17810     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17811     */
17812    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17813        @Override
17814        public void setValue(View object, float value) {
17815            object.setRotation(value);
17816        }
17817
17818        @Override
17819        public Float get(View object) {
17820            return object.getRotation();
17821        }
17822    };
17823
17824    /**
17825     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17826     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17827     */
17828    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17829        @Override
17830        public void setValue(View object, float value) {
17831            object.setRotationX(value);
17832        }
17833
17834        @Override
17835        public Float get(View object) {
17836            return object.getRotationX();
17837        }
17838    };
17839
17840    /**
17841     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17842     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17843     */
17844    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17845        @Override
17846        public void setValue(View object, float value) {
17847            object.setRotationY(value);
17848        }
17849
17850        @Override
17851        public Float get(View object) {
17852            return object.getRotationY();
17853        }
17854    };
17855
17856    /**
17857     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17858     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17859     */
17860    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17861        @Override
17862        public void setValue(View object, float value) {
17863            object.setScaleX(value);
17864        }
17865
17866        @Override
17867        public Float get(View object) {
17868            return object.getScaleX();
17869        }
17870    };
17871
17872    /**
17873     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17874     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17875     */
17876    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17877        @Override
17878        public void setValue(View object, float value) {
17879            object.setScaleY(value);
17880        }
17881
17882        @Override
17883        public Float get(View object) {
17884            return object.getScaleY();
17885        }
17886    };
17887
17888    /**
17889     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17890     * Each MeasureSpec represents a requirement for either the width or the height.
17891     * A MeasureSpec is comprised of a size and a mode. There are three possible
17892     * modes:
17893     * <dl>
17894     * <dt>UNSPECIFIED</dt>
17895     * <dd>
17896     * The parent has not imposed any constraint on the child. It can be whatever size
17897     * it wants.
17898     * </dd>
17899     *
17900     * <dt>EXACTLY</dt>
17901     * <dd>
17902     * The parent has determined an exact size for the child. The child is going to be
17903     * given those bounds regardless of how big it wants to be.
17904     * </dd>
17905     *
17906     * <dt>AT_MOST</dt>
17907     * <dd>
17908     * The child can be as large as it wants up to the specified size.
17909     * </dd>
17910     * </dl>
17911     *
17912     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17913     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17914     */
17915    public static class MeasureSpec {
17916        private static final int MODE_SHIFT = 30;
17917        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17918
17919        /**
17920         * Measure specification mode: The parent has not imposed any constraint
17921         * on the child. It can be whatever size it wants.
17922         */
17923        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17924
17925        /**
17926         * Measure specification mode: The parent has determined an exact size
17927         * for the child. The child is going to be given those bounds regardless
17928         * of how big it wants to be.
17929         */
17930        public static final int EXACTLY     = 1 << MODE_SHIFT;
17931
17932        /**
17933         * Measure specification mode: The child can be as large as it wants up
17934         * to the specified size.
17935         */
17936        public static final int AT_MOST     = 2 << MODE_SHIFT;
17937
17938        /**
17939         * Creates a measure specification based on the supplied size and mode.
17940         *
17941         * The mode must always be one of the following:
17942         * <ul>
17943         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17944         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17945         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17946         * </ul>
17947         *
17948         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17949         * implementation was such that the order of arguments did not matter
17950         * and overflow in either value could impact the resulting MeasureSpec.
17951         * {@link android.widget.RelativeLayout} was affected by this bug.
17952         * Apps targeting API levels greater than 17 will get the fixed, more strict
17953         * behavior.</p>
17954         *
17955         * @param size the size of the measure specification
17956         * @param mode the mode of the measure specification
17957         * @return the measure specification based on size and mode
17958         */
17959        public static int makeMeasureSpec(int size, int mode) {
17960            if (sUseBrokenMakeMeasureSpec) {
17961                return size + mode;
17962            } else {
17963                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17964            }
17965        }
17966
17967        /**
17968         * Extracts the mode from the supplied measure specification.
17969         *
17970         * @param measureSpec the measure specification to extract the mode from
17971         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17972         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17973         *         {@link android.view.View.MeasureSpec#EXACTLY}
17974         */
17975        public static int getMode(int measureSpec) {
17976            return (measureSpec & MODE_MASK);
17977        }
17978
17979        /**
17980         * Extracts the size from the supplied measure specification.
17981         *
17982         * @param measureSpec the measure specification to extract the size from
17983         * @return the size in pixels defined in the supplied measure specification
17984         */
17985        public static int getSize(int measureSpec) {
17986            return (measureSpec & ~MODE_MASK);
17987        }
17988
17989        static int adjust(int measureSpec, int delta) {
17990            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17991        }
17992
17993        /**
17994         * Returns a String representation of the specified measure
17995         * specification.
17996         *
17997         * @param measureSpec the measure specification to convert to a String
17998         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17999         */
18000        public static String toString(int measureSpec) {
18001            int mode = getMode(measureSpec);
18002            int size = getSize(measureSpec);
18003
18004            StringBuilder sb = new StringBuilder("MeasureSpec: ");
18005
18006            if (mode == UNSPECIFIED)
18007                sb.append("UNSPECIFIED ");
18008            else if (mode == EXACTLY)
18009                sb.append("EXACTLY ");
18010            else if (mode == AT_MOST)
18011                sb.append("AT_MOST ");
18012            else
18013                sb.append(mode).append(" ");
18014
18015            sb.append(size);
18016            return sb.toString();
18017        }
18018    }
18019
18020    class CheckForLongPress implements Runnable {
18021
18022        private int mOriginalWindowAttachCount;
18023
18024        public void run() {
18025            if (isPressed() && (mParent != null)
18026                    && mOriginalWindowAttachCount == mWindowAttachCount) {
18027                if (performLongClick()) {
18028                    mHasPerformedLongPress = true;
18029                }
18030            }
18031        }
18032
18033        public void rememberWindowAttachCount() {
18034            mOriginalWindowAttachCount = mWindowAttachCount;
18035        }
18036    }
18037
18038    private final class CheckForTap implements Runnable {
18039        public void run() {
18040            mPrivateFlags &= ~PFLAG_PREPRESSED;
18041            setPressed(true);
18042            checkForLongClick(ViewConfiguration.getTapTimeout());
18043        }
18044    }
18045
18046    private final class PerformClick implements Runnable {
18047        public void run() {
18048            performClick();
18049        }
18050    }
18051
18052    /** @hide */
18053    public void hackTurnOffWindowResizeAnim(boolean off) {
18054        mAttachInfo.mTurnOffWindowResizeAnim = off;
18055    }
18056
18057    /**
18058     * This method returns a ViewPropertyAnimator object, which can be used to animate
18059     * specific properties on this View.
18060     *
18061     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
18062     */
18063    public ViewPropertyAnimator animate() {
18064        if (mAnimator == null) {
18065            mAnimator = new ViewPropertyAnimator(this);
18066        }
18067        return mAnimator;
18068    }
18069
18070    /**
18071     * Set the current Scene that this view is in. The current scene is set only
18072     * on the root view of a scene, not for every view in that hierarchy. This
18073     * information is used by Scene to determine whether there is a previous
18074     * scene which should be exited before the new scene is entered.
18075     *
18076     * @param scene The new scene being set on the view
18077     *
18078     * @hide
18079     */
18080    public void setCurrentScene(Scene scene) {
18081        mCurrentScene = scene;
18082    }
18083
18084    /**
18085     * Gets the current {@link Scene} set on this view. A scene is set on a view
18086     * only if that view is the scene root.
18087     *
18088     * @return The current Scene set on this view. A value of null indicates that
18089     * no Scene is current set.
18090     */
18091    public Scene getCurrentScene() {
18092        return mCurrentScene;
18093    }
18094
18095    /**
18096     * Interface definition for a callback to be invoked when a hardware key event is
18097     * dispatched to this view. The callback will be invoked before the key event is
18098     * given to the view. This is only useful for hardware keyboards; a software input
18099     * method has no obligation to trigger this listener.
18100     */
18101    public interface OnKeyListener {
18102        /**
18103         * Called when a hardware key is dispatched to a view. This allows listeners to
18104         * get a chance to respond before the target view.
18105         * <p>Key presses in software keyboards will generally NOT trigger this method,
18106         * although some may elect to do so in some situations. Do not assume a
18107         * software input method has to be key-based; even if it is, it may use key presses
18108         * in a different way than you expect, so there is no way to reliably catch soft
18109         * input key presses.
18110         *
18111         * @param v The view the key has been dispatched to.
18112         * @param keyCode The code for the physical key that was pressed
18113         * @param event The KeyEvent object containing full information about
18114         *        the event.
18115         * @return True if the listener has consumed the event, false otherwise.
18116         */
18117        boolean onKey(View v, int keyCode, KeyEvent event);
18118    }
18119
18120    /**
18121     * Interface definition for a callback to be invoked when a touch event is
18122     * dispatched to this view. The callback will be invoked before the touch
18123     * event is given to the view.
18124     */
18125    public interface OnTouchListener {
18126        /**
18127         * Called when a touch event is dispatched to a view. This allows listeners to
18128         * get a chance to respond before the target view.
18129         *
18130         * @param v The view the touch event has been dispatched to.
18131         * @param event The MotionEvent object containing full information about
18132         *        the event.
18133         * @return True if the listener has consumed the event, false otherwise.
18134         */
18135        boolean onTouch(View v, MotionEvent event);
18136    }
18137
18138    /**
18139     * Interface definition for a callback to be invoked when a hover event is
18140     * dispatched to this view. The callback will be invoked before the hover
18141     * event is given to the view.
18142     */
18143    public interface OnHoverListener {
18144        /**
18145         * Called when a hover event is dispatched to a view. This allows listeners to
18146         * get a chance to respond before the target view.
18147         *
18148         * @param v The view the hover event has been dispatched to.
18149         * @param event The MotionEvent object containing full information about
18150         *        the event.
18151         * @return True if the listener has consumed the event, false otherwise.
18152         */
18153        boolean onHover(View v, MotionEvent event);
18154    }
18155
18156    /**
18157     * Interface definition for a callback to be invoked when a generic motion event is
18158     * dispatched to this view. The callback will be invoked before the generic motion
18159     * event is given to the view.
18160     */
18161    public interface OnGenericMotionListener {
18162        /**
18163         * Called when a generic motion event is dispatched to a view. This allows listeners to
18164         * get a chance to respond before the target view.
18165         *
18166         * @param v The view the generic motion event has been dispatched to.
18167         * @param event The MotionEvent object containing full information about
18168         *        the event.
18169         * @return True if the listener has consumed the event, false otherwise.
18170         */
18171        boolean onGenericMotion(View v, MotionEvent event);
18172    }
18173
18174    /**
18175     * Interface definition for a callback to be invoked when a view has been clicked and held.
18176     */
18177    public interface OnLongClickListener {
18178        /**
18179         * Called when a view has been clicked and held.
18180         *
18181         * @param v The view that was clicked and held.
18182         *
18183         * @return true if the callback consumed the long click, false otherwise.
18184         */
18185        boolean onLongClick(View v);
18186    }
18187
18188    /**
18189     * Interface definition for a callback to be invoked when a drag is being dispatched
18190     * to this view.  The callback will be invoked before the hosting view's own
18191     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18192     * onDrag(event) behavior, it should return 'false' from this callback.
18193     *
18194     * <div class="special reference">
18195     * <h3>Developer Guides</h3>
18196     * <p>For a guide to implementing drag and drop features, read the
18197     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18198     * </div>
18199     */
18200    public interface OnDragListener {
18201        /**
18202         * Called when a drag event is dispatched to a view. This allows listeners
18203         * to get a chance to override base View behavior.
18204         *
18205         * @param v The View that received the drag event.
18206         * @param event The {@link android.view.DragEvent} object for the drag event.
18207         * @return {@code true} if the drag event was handled successfully, or {@code false}
18208         * if the drag event was not handled. Note that {@code false} will trigger the View
18209         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18210         */
18211        boolean onDrag(View v, DragEvent event);
18212    }
18213
18214    /**
18215     * Interface definition for a callback to be invoked when the focus state of
18216     * a view changed.
18217     */
18218    public interface OnFocusChangeListener {
18219        /**
18220         * Called when the focus state of a view has changed.
18221         *
18222         * @param v The view whose state has changed.
18223         * @param hasFocus The new focus state of v.
18224         */
18225        void onFocusChange(View v, boolean hasFocus);
18226    }
18227
18228    /**
18229     * Interface definition for a callback to be invoked when a view is clicked.
18230     */
18231    public interface OnClickListener {
18232        /**
18233         * Called when a view has been clicked.
18234         *
18235         * @param v The view that was clicked.
18236         */
18237        void onClick(View v);
18238    }
18239
18240    /**
18241     * Interface definition for a callback to be invoked when the context menu
18242     * for this view is being built.
18243     */
18244    public interface OnCreateContextMenuListener {
18245        /**
18246         * Called when the context menu for this view is being built. It is not
18247         * safe to hold onto the menu after this method returns.
18248         *
18249         * @param menu The context menu that is being built
18250         * @param v The view for which the context menu is being built
18251         * @param menuInfo Extra information about the item for which the
18252         *            context menu should be shown. This information will vary
18253         *            depending on the class of v.
18254         */
18255        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18256    }
18257
18258    /**
18259     * Interface definition for a callback to be invoked when the status bar changes
18260     * visibility.  This reports <strong>global</strong> changes to the system UI
18261     * state, not what the application is requesting.
18262     *
18263     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18264     */
18265    public interface OnSystemUiVisibilityChangeListener {
18266        /**
18267         * Called when the status bar changes visibility because of a call to
18268         * {@link View#setSystemUiVisibility(int)}.
18269         *
18270         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18271         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18272         * This tells you the <strong>global</strong> state of these UI visibility
18273         * flags, not what your app is currently applying.
18274         */
18275        public void onSystemUiVisibilityChange(int visibility);
18276    }
18277
18278    /**
18279     * Interface definition for a callback to be invoked when this view is attached
18280     * or detached from its window.
18281     */
18282    public interface OnAttachStateChangeListener {
18283        /**
18284         * Called when the view is attached to a window.
18285         * @param v The view that was attached
18286         */
18287        public void onViewAttachedToWindow(View v);
18288        /**
18289         * Called when the view is detached from a window.
18290         * @param v The view that was detached
18291         */
18292        public void onViewDetachedFromWindow(View v);
18293    }
18294
18295    private final class UnsetPressedState implements Runnable {
18296        public void run() {
18297            setPressed(false);
18298        }
18299    }
18300
18301    /**
18302     * Base class for derived classes that want to save and restore their own
18303     * state in {@link android.view.View#onSaveInstanceState()}.
18304     */
18305    public static class BaseSavedState extends AbsSavedState {
18306        /**
18307         * Constructor used when reading from a parcel. Reads the state of the superclass.
18308         *
18309         * @param source
18310         */
18311        public BaseSavedState(Parcel source) {
18312            super(source);
18313        }
18314
18315        /**
18316         * Constructor called by derived classes when creating their SavedState objects
18317         *
18318         * @param superState The state of the superclass of this view
18319         */
18320        public BaseSavedState(Parcelable superState) {
18321            super(superState);
18322        }
18323
18324        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18325                new Parcelable.Creator<BaseSavedState>() {
18326            public BaseSavedState createFromParcel(Parcel in) {
18327                return new BaseSavedState(in);
18328            }
18329
18330            public BaseSavedState[] newArray(int size) {
18331                return new BaseSavedState[size];
18332            }
18333        };
18334    }
18335
18336    /**
18337     * A set of information given to a view when it is attached to its parent
18338     * window.
18339     */
18340    static class AttachInfo {
18341        interface Callbacks {
18342            void playSoundEffect(int effectId);
18343            boolean performHapticFeedback(int effectId, boolean always);
18344        }
18345
18346        /**
18347         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18348         * to a Handler. This class contains the target (View) to invalidate and
18349         * the coordinates of the dirty rectangle.
18350         *
18351         * For performance purposes, this class also implements a pool of up to
18352         * POOL_LIMIT objects that get reused. This reduces memory allocations
18353         * whenever possible.
18354         */
18355        static class InvalidateInfo {
18356            private static final int POOL_LIMIT = 10;
18357
18358            private static final SynchronizedPool<InvalidateInfo> sPool =
18359                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18360
18361            View target;
18362
18363            int left;
18364            int top;
18365            int right;
18366            int bottom;
18367
18368            public static InvalidateInfo obtain() {
18369                InvalidateInfo instance = sPool.acquire();
18370                return (instance != null) ? instance : new InvalidateInfo();
18371            }
18372
18373            public void recycle() {
18374                target = null;
18375                sPool.release(this);
18376            }
18377        }
18378
18379        final IWindowSession mSession;
18380
18381        final IWindow mWindow;
18382
18383        final IBinder mWindowToken;
18384
18385        final Display mDisplay;
18386
18387        final Callbacks mRootCallbacks;
18388
18389        HardwareCanvas mHardwareCanvas;
18390
18391        IWindowId mIWindowId;
18392        WindowId mWindowId;
18393
18394        /**
18395         * The top view of the hierarchy.
18396         */
18397        View mRootView;
18398
18399        IBinder mPanelParentWindowToken;
18400        Surface mSurface;
18401
18402        boolean mHardwareAccelerated;
18403        boolean mHardwareAccelerationRequested;
18404        HardwareRenderer mHardwareRenderer;
18405
18406        boolean mScreenOn;
18407
18408        /**
18409         * Scale factor used by the compatibility mode
18410         */
18411        float mApplicationScale;
18412
18413        /**
18414         * Indicates whether the application is in compatibility mode
18415         */
18416        boolean mScalingRequired;
18417
18418        /**
18419         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18420         */
18421        boolean mTurnOffWindowResizeAnim;
18422
18423        /**
18424         * Left position of this view's window
18425         */
18426        int mWindowLeft;
18427
18428        /**
18429         * Top position of this view's window
18430         */
18431        int mWindowTop;
18432
18433        /**
18434         * Indicates whether views need to use 32-bit drawing caches
18435         */
18436        boolean mUse32BitDrawingCache;
18437
18438        /**
18439         * For windows that are full-screen but using insets to layout inside
18440         * of the screen areas, these are the current insets to appear inside
18441         * the overscan area of the display.
18442         */
18443        final Rect mOverscanInsets = new Rect();
18444
18445        /**
18446         * For windows that are full-screen but using insets to layout inside
18447         * of the screen decorations, these are the current insets for the
18448         * content of the window.
18449         */
18450        final Rect mContentInsets = new Rect();
18451
18452        /**
18453         * For windows that are full-screen but using insets to layout inside
18454         * of the screen decorations, these are the current insets for the
18455         * actual visible parts of the window.
18456         */
18457        final Rect mVisibleInsets = new Rect();
18458
18459        /**
18460         * The internal insets given by this window.  This value is
18461         * supplied by the client (through
18462         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18463         * be given to the window manager when changed to be used in laying
18464         * out windows behind it.
18465         */
18466        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18467                = new ViewTreeObserver.InternalInsetsInfo();
18468
18469        /**
18470         * All views in the window's hierarchy that serve as scroll containers,
18471         * used to determine if the window can be resized or must be panned
18472         * to adjust for a soft input area.
18473         */
18474        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18475
18476        final KeyEvent.DispatcherState mKeyDispatchState
18477                = new KeyEvent.DispatcherState();
18478
18479        /**
18480         * Indicates whether the view's window currently has the focus.
18481         */
18482        boolean mHasWindowFocus;
18483
18484        /**
18485         * The current visibility of the window.
18486         */
18487        int mWindowVisibility;
18488
18489        /**
18490         * Indicates the time at which drawing started to occur.
18491         */
18492        long mDrawingTime;
18493
18494        /**
18495         * Indicates whether or not ignoring the DIRTY_MASK flags.
18496         */
18497        boolean mIgnoreDirtyState;
18498
18499        /**
18500         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18501         * to avoid clearing that flag prematurely.
18502         */
18503        boolean mSetIgnoreDirtyState = false;
18504
18505        /**
18506         * Indicates whether the view's window is currently in touch mode.
18507         */
18508        boolean mInTouchMode;
18509
18510        /**
18511         * Indicates that ViewAncestor should trigger a global layout change
18512         * the next time it performs a traversal
18513         */
18514        boolean mRecomputeGlobalAttributes;
18515
18516        /**
18517         * Always report new attributes at next traversal.
18518         */
18519        boolean mForceReportNewAttributes;
18520
18521        /**
18522         * Set during a traveral if any views want to keep the screen on.
18523         */
18524        boolean mKeepScreenOn;
18525
18526        /**
18527         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18528         */
18529        int mSystemUiVisibility;
18530
18531        /**
18532         * Hack to force certain system UI visibility flags to be cleared.
18533         */
18534        int mDisabledSystemUiVisibility;
18535
18536        /**
18537         * Last global system UI visibility reported by the window manager.
18538         */
18539        int mGlobalSystemUiVisibility;
18540
18541        /**
18542         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18543         * attached.
18544         */
18545        boolean mHasSystemUiListeners;
18546
18547        /**
18548         * Set if the window has requested to extend into the overscan region
18549         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18550         */
18551        boolean mOverscanRequested;
18552
18553        /**
18554         * Set if the visibility of any views has changed.
18555         */
18556        boolean mViewVisibilityChanged;
18557
18558        /**
18559         * Set to true if a view has been scrolled.
18560         */
18561        boolean mViewScrollChanged;
18562
18563        /**
18564         * Global to the view hierarchy used as a temporary for dealing with
18565         * x/y points in the transparent region computations.
18566         */
18567        final int[] mTransparentLocation = new int[2];
18568
18569        /**
18570         * Global to the view hierarchy used as a temporary for dealing with
18571         * x/y points in the ViewGroup.invalidateChild implementation.
18572         */
18573        final int[] mInvalidateChildLocation = new int[2];
18574
18575
18576        /**
18577         * Global to the view hierarchy used as a temporary for dealing with
18578         * x/y location when view is transformed.
18579         */
18580        final float[] mTmpTransformLocation = new float[2];
18581
18582        /**
18583         * The view tree observer used to dispatch global events like
18584         * layout, pre-draw, touch mode change, etc.
18585         */
18586        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18587
18588        /**
18589         * A Canvas used by the view hierarchy to perform bitmap caching.
18590         */
18591        Canvas mCanvas;
18592
18593        /**
18594         * The view root impl.
18595         */
18596        final ViewRootImpl mViewRootImpl;
18597
18598        /**
18599         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18600         * handler can be used to pump events in the UI events queue.
18601         */
18602        final Handler mHandler;
18603
18604        /**
18605         * Temporary for use in computing invalidate rectangles while
18606         * calling up the hierarchy.
18607         */
18608        final Rect mTmpInvalRect = new Rect();
18609
18610        /**
18611         * Temporary for use in computing hit areas with transformed views
18612         */
18613        final RectF mTmpTransformRect = new RectF();
18614
18615        /**
18616         * Temporary for use in transforming invalidation rect
18617         */
18618        final Matrix mTmpMatrix = new Matrix();
18619
18620        /**
18621         * Temporary for use in transforming invalidation rect
18622         */
18623        final Transformation mTmpTransformation = new Transformation();
18624
18625        /**
18626         * Temporary list for use in collecting focusable descendents of a view.
18627         */
18628        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18629
18630        /**
18631         * The id of the window for accessibility purposes.
18632         */
18633        int mAccessibilityWindowId = View.NO_ID;
18634
18635        /**
18636         * Flags related to accessibility processing.
18637         *
18638         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18639         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18640         */
18641        int mAccessibilityFetchFlags;
18642
18643        /**
18644         * The drawable for highlighting accessibility focus.
18645         */
18646        Drawable mAccessibilityFocusDrawable;
18647
18648        /**
18649         * Show where the margins, bounds and layout bounds are for each view.
18650         */
18651        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18652
18653        /**
18654         * Point used to compute visible regions.
18655         */
18656        final Point mPoint = new Point();
18657
18658        /**
18659         * Used to track which View originated a requestLayout() call, used when
18660         * requestLayout() is called during layout.
18661         */
18662        View mViewRequestingLayout;
18663
18664        /**
18665         * Creates a new set of attachment information with the specified
18666         * events handler and thread.
18667         *
18668         * @param handler the events handler the view must use
18669         */
18670        AttachInfo(IWindowSession session, IWindow window, Display display,
18671                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18672            mSession = session;
18673            mWindow = window;
18674            mWindowToken = window.asBinder();
18675            mDisplay = display;
18676            mViewRootImpl = viewRootImpl;
18677            mHandler = handler;
18678            mRootCallbacks = effectPlayer;
18679        }
18680    }
18681
18682    /**
18683     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18684     * is supported. This avoids keeping too many unused fields in most
18685     * instances of View.</p>
18686     */
18687    private static class ScrollabilityCache implements Runnable {
18688
18689        /**
18690         * Scrollbars are not visible
18691         */
18692        public static final int OFF = 0;
18693
18694        /**
18695         * Scrollbars are visible
18696         */
18697        public static final int ON = 1;
18698
18699        /**
18700         * Scrollbars are fading away
18701         */
18702        public static final int FADING = 2;
18703
18704        public boolean fadeScrollBars;
18705
18706        public int fadingEdgeLength;
18707        public int scrollBarDefaultDelayBeforeFade;
18708        public int scrollBarFadeDuration;
18709
18710        public int scrollBarSize;
18711        public ScrollBarDrawable scrollBar;
18712        public float[] interpolatorValues;
18713        public View host;
18714
18715        public final Paint paint;
18716        public final Matrix matrix;
18717        public Shader shader;
18718
18719        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18720
18721        private static final float[] OPAQUE = { 255 };
18722        private static final float[] TRANSPARENT = { 0.0f };
18723
18724        /**
18725         * When fading should start. This time moves into the future every time
18726         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18727         */
18728        public long fadeStartTime;
18729
18730
18731        /**
18732         * The current state of the scrollbars: ON, OFF, or FADING
18733         */
18734        public int state = OFF;
18735
18736        private int mLastColor;
18737
18738        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18739            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18740            scrollBarSize = configuration.getScaledScrollBarSize();
18741            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18742            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18743
18744            paint = new Paint();
18745            matrix = new Matrix();
18746            // use use a height of 1, and then wack the matrix each time we
18747            // actually use it.
18748            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18749            paint.setShader(shader);
18750            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18751
18752            this.host = host;
18753        }
18754
18755        public void setFadeColor(int color) {
18756            if (color != mLastColor) {
18757                mLastColor = color;
18758
18759                if (color != 0) {
18760                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18761                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18762                    paint.setShader(shader);
18763                    // Restore the default transfer mode (src_over)
18764                    paint.setXfermode(null);
18765                } else {
18766                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18767                    paint.setShader(shader);
18768                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18769                }
18770            }
18771        }
18772
18773        public void run() {
18774            long now = AnimationUtils.currentAnimationTimeMillis();
18775            if (now >= fadeStartTime) {
18776
18777                // the animation fades the scrollbars out by changing
18778                // the opacity (alpha) from fully opaque to fully
18779                // transparent
18780                int nextFrame = (int) now;
18781                int framesCount = 0;
18782
18783                Interpolator interpolator = scrollBarInterpolator;
18784
18785                // Start opaque
18786                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18787
18788                // End transparent
18789                nextFrame += scrollBarFadeDuration;
18790                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18791
18792                state = FADING;
18793
18794                // Kick off the fade animation
18795                host.invalidate(true);
18796            }
18797        }
18798    }
18799
18800    /**
18801     * Resuable callback for sending
18802     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18803     */
18804    private class SendViewScrolledAccessibilityEvent implements Runnable {
18805        public volatile boolean mIsPending;
18806
18807        public void run() {
18808            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18809            mIsPending = false;
18810        }
18811    }
18812
18813    /**
18814     * <p>
18815     * This class represents a delegate that can be registered in a {@link View}
18816     * to enhance accessibility support via composition rather via inheritance.
18817     * It is specifically targeted to widget developers that extend basic View
18818     * classes i.e. classes in package android.view, that would like their
18819     * applications to be backwards compatible.
18820     * </p>
18821     * <div class="special reference">
18822     * <h3>Developer Guides</h3>
18823     * <p>For more information about making applications accessible, read the
18824     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18825     * developer guide.</p>
18826     * </div>
18827     * <p>
18828     * A scenario in which a developer would like to use an accessibility delegate
18829     * is overriding a method introduced in a later API version then the minimal API
18830     * version supported by the application. For example, the method
18831     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18832     * in API version 4 when the accessibility APIs were first introduced. If a
18833     * developer would like his application to run on API version 4 devices (assuming
18834     * all other APIs used by the application are version 4 or lower) and take advantage
18835     * of this method, instead of overriding the method which would break the application's
18836     * backwards compatibility, he can override the corresponding method in this
18837     * delegate and register the delegate in the target View if the API version of
18838     * the system is high enough i.e. the API version is same or higher to the API
18839     * version that introduced
18840     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18841     * </p>
18842     * <p>
18843     * Here is an example implementation:
18844     * </p>
18845     * <code><pre><p>
18846     * if (Build.VERSION.SDK_INT >= 14) {
18847     *     // If the API version is equal of higher than the version in
18848     *     // which onInitializeAccessibilityNodeInfo was introduced we
18849     *     // register a delegate with a customized implementation.
18850     *     View view = findViewById(R.id.view_id);
18851     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18852     *         public void onInitializeAccessibilityNodeInfo(View host,
18853     *                 AccessibilityNodeInfo info) {
18854     *             // Let the default implementation populate the info.
18855     *             super.onInitializeAccessibilityNodeInfo(host, info);
18856     *             // Set some other information.
18857     *             info.setEnabled(host.isEnabled());
18858     *         }
18859     *     });
18860     * }
18861     * </code></pre></p>
18862     * <p>
18863     * This delegate contains methods that correspond to the accessibility methods
18864     * in View. If a delegate has been specified the implementation in View hands
18865     * off handling to the corresponding method in this delegate. The default
18866     * implementation the delegate methods behaves exactly as the corresponding
18867     * method in View for the case of no accessibility delegate been set. Hence,
18868     * to customize the behavior of a View method, clients can override only the
18869     * corresponding delegate method without altering the behavior of the rest
18870     * accessibility related methods of the host view.
18871     * </p>
18872     */
18873    public static class AccessibilityDelegate {
18874
18875        /**
18876         * Sends an accessibility event of the given type. If accessibility is not
18877         * enabled this method has no effect.
18878         * <p>
18879         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18880         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18881         * been set.
18882         * </p>
18883         *
18884         * @param host The View hosting the delegate.
18885         * @param eventType The type of the event to send.
18886         *
18887         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18888         */
18889        public void sendAccessibilityEvent(View host, int eventType) {
18890            host.sendAccessibilityEventInternal(eventType);
18891        }
18892
18893        /**
18894         * Performs the specified accessibility action on the view. For
18895         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18896         * <p>
18897         * The default implementation behaves as
18898         * {@link View#performAccessibilityAction(int, Bundle)
18899         *  View#performAccessibilityAction(int, Bundle)} for the case of
18900         *  no accessibility delegate been set.
18901         * </p>
18902         *
18903         * @param action The action to perform.
18904         * @return Whether the action was performed.
18905         *
18906         * @see View#performAccessibilityAction(int, Bundle)
18907         *      View#performAccessibilityAction(int, Bundle)
18908         */
18909        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18910            return host.performAccessibilityActionInternal(action, args);
18911        }
18912
18913        /**
18914         * Sends an accessibility event. This method behaves exactly as
18915         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18916         * empty {@link AccessibilityEvent} and does not perform a check whether
18917         * accessibility is enabled.
18918         * <p>
18919         * The default implementation behaves as
18920         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18921         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18922         * the case of no accessibility delegate been set.
18923         * </p>
18924         *
18925         * @param host The View hosting the delegate.
18926         * @param event The event to send.
18927         *
18928         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18929         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18930         */
18931        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18932            host.sendAccessibilityEventUncheckedInternal(event);
18933        }
18934
18935        /**
18936         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18937         * to its children for adding their text content to the event.
18938         * <p>
18939         * The default implementation behaves as
18940         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18941         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18942         * the case of no accessibility delegate been set.
18943         * </p>
18944         *
18945         * @param host The View hosting the delegate.
18946         * @param event The event.
18947         * @return True if the event population was completed.
18948         *
18949         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18950         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18951         */
18952        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18953            return host.dispatchPopulateAccessibilityEventInternal(event);
18954        }
18955
18956        /**
18957         * Gives a chance to the host View to populate the accessibility event with its
18958         * text content.
18959         * <p>
18960         * The default implementation behaves as
18961         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18962         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18963         * the case of no accessibility delegate been set.
18964         * </p>
18965         *
18966         * @param host The View hosting the delegate.
18967         * @param event The accessibility event which to populate.
18968         *
18969         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18970         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18971         */
18972        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18973            host.onPopulateAccessibilityEventInternal(event);
18974        }
18975
18976        /**
18977         * Initializes an {@link AccessibilityEvent} with information about the
18978         * the host View which is the event source.
18979         * <p>
18980         * The default implementation behaves as
18981         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18982         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18983         * the case of no accessibility delegate been set.
18984         * </p>
18985         *
18986         * @param host The View hosting the delegate.
18987         * @param event The event to initialize.
18988         *
18989         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18990         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18991         */
18992        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18993            host.onInitializeAccessibilityEventInternal(event);
18994        }
18995
18996        /**
18997         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18998         * <p>
18999         * The default implementation behaves as
19000         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19001         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
19002         * the case of no accessibility delegate been set.
19003         * </p>
19004         *
19005         * @param host The View hosting the delegate.
19006         * @param info The instance to initialize.
19007         *
19008         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19009         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19010         */
19011        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
19012            host.onInitializeAccessibilityNodeInfoInternal(info);
19013        }
19014
19015        /**
19016         * Called when a child of the host View has requested sending an
19017         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
19018         * to augment the event.
19019         * <p>
19020         * The default implementation behaves as
19021         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19022         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
19023         * the case of no accessibility delegate been set.
19024         * </p>
19025         *
19026         * @param host The View hosting the delegate.
19027         * @param child The child which requests sending the event.
19028         * @param event The event to be sent.
19029         * @return True if the event should be sent
19030         *
19031         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19032         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19033         */
19034        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
19035                AccessibilityEvent event) {
19036            return host.onRequestSendAccessibilityEventInternal(child, event);
19037        }
19038
19039        /**
19040         * Gets the provider for managing a virtual view hierarchy rooted at this View
19041         * and reported to {@link android.accessibilityservice.AccessibilityService}s
19042         * that explore the window content.
19043         * <p>
19044         * The default implementation behaves as
19045         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
19046         * the case of no accessibility delegate been set.
19047         * </p>
19048         *
19049         * @return The provider.
19050         *
19051         * @see AccessibilityNodeProvider
19052         */
19053        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
19054            return null;
19055        }
19056
19057        /**
19058         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
19059         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
19060         * This method is responsible for obtaining an accessibility node info from a
19061         * pool of reusable instances and calling
19062         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
19063         * view to initialize the former.
19064         * <p>
19065         * <strong>Note:</strong> The client is responsible for recycling the obtained
19066         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
19067         * creation.
19068         * </p>
19069         * <p>
19070         * The default implementation behaves as
19071         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
19072         * the case of no accessibility delegate been set.
19073         * </p>
19074         * @return A populated {@link AccessibilityNodeInfo}.
19075         *
19076         * @see AccessibilityNodeInfo
19077         *
19078         * @hide
19079         */
19080        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
19081            return host.createAccessibilityNodeInfoInternal();
19082        }
19083    }
19084
19085    private class MatchIdPredicate implements Predicate<View> {
19086        public int mId;
19087
19088        @Override
19089        public boolean apply(View view) {
19090            return (view.mID == mId);
19091        }
19092    }
19093
19094    private class MatchLabelForPredicate implements Predicate<View> {
19095        private int mLabeledId;
19096
19097        @Override
19098        public boolean apply(View view) {
19099            return (view.mLabelForId == mLabeledId);
19100        }
19101    }
19102
19103    private class SendViewStateChangedAccessibilityEvent implements Runnable {
19104        private boolean mPosted;
19105        private long mLastEventTimeMillis;
19106
19107        public void run() {
19108            mPosted = false;
19109            mLastEventTimeMillis = SystemClock.uptimeMillis();
19110            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
19111                AccessibilityEvent event = AccessibilityEvent.obtain();
19112                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
19113                event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE);
19114                sendAccessibilityEventUnchecked(event);
19115            }
19116        }
19117
19118        public void runOrPost() {
19119            if (mPosted) {
19120                return;
19121            }
19122            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
19123            final long minEventIntevalMillis =
19124                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
19125            if (timeSinceLastMillis >= minEventIntevalMillis) {
19126                removeCallbacks(this);
19127                run();
19128            } else {
19129                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19130                mPosted = true;
19131            }
19132        }
19133    }
19134
19135    /**
19136     * Dump all private flags in readable format, useful for documentation and
19137     * sanity checking.
19138     */
19139    private static void dumpFlags() {
19140        final HashMap<String, String> found = Maps.newHashMap();
19141        try {
19142            for (Field field : View.class.getDeclaredFields()) {
19143                final int modifiers = field.getModifiers();
19144                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19145                    if (field.getType().equals(int.class)) {
19146                        final int value = field.getInt(null);
19147                        dumpFlag(found, field.getName(), value);
19148                    } else if (field.getType().equals(int[].class)) {
19149                        final int[] values = (int[]) field.get(null);
19150                        for (int i = 0; i < values.length; i++) {
19151                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19152                        }
19153                    }
19154                }
19155            }
19156        } catch (IllegalAccessException e) {
19157            throw new RuntimeException(e);
19158        }
19159
19160        final ArrayList<String> keys = Lists.newArrayList();
19161        keys.addAll(found.keySet());
19162        Collections.sort(keys);
19163        for (String key : keys) {
19164            Log.d(VIEW_LOG_TAG, found.get(key));
19165        }
19166    }
19167
19168    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19169        // Sort flags by prefix, then by bits, always keeping unique keys
19170        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19171        final int prefix = name.indexOf('_');
19172        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19173        final String output = bits + " " + name;
19174        found.put(key, output);
19175    }
19176}
19177