View.java revision 84ebb35f392478600ddf8f08107fb345f13ef91c
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.Log;
55import android.util.Pool;
56import android.util.Poolable;
57import android.util.PoolableManager;
58import android.util.Pools;
59import android.util.Property;
60import android.util.SparseArray;
61import android.util.TypedValue;
62import android.view.ContextMenu.ContextMenuInfo;
63import android.view.AccessibilityIterators.TextSegmentIterator;
64import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
65import android.view.AccessibilityIterators.WordTextSegmentIterator;
66import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
67import android.view.accessibility.AccessibilityEvent;
68import android.view.accessibility.AccessibilityEventSource;
69import android.view.accessibility.AccessibilityManager;
70import android.view.accessibility.AccessibilityNodeInfo;
71import android.view.accessibility.AccessibilityNodeProvider;
72import android.view.animation.Animation;
73import android.view.animation.AnimationUtils;
74import android.view.animation.Transformation;
75import android.view.inputmethod.EditorInfo;
76import android.view.inputmethod.InputConnection;
77import android.view.inputmethod.InputMethodManager;
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_longClickable
627 * @attr ref android.R.styleable#View_minHeight
628 * @attr ref android.R.styleable#View_minWidth
629 * @attr ref android.R.styleable#View_nextFocusDown
630 * @attr ref android.R.styleable#View_nextFocusLeft
631 * @attr ref android.R.styleable#View_nextFocusRight
632 * @attr ref android.R.styleable#View_nextFocusUp
633 * @attr ref android.R.styleable#View_onClick
634 * @attr ref android.R.styleable#View_padding
635 * @attr ref android.R.styleable#View_paddingBottom
636 * @attr ref android.R.styleable#View_paddingLeft
637 * @attr ref android.R.styleable#View_paddingRight
638 * @attr ref android.R.styleable#View_paddingTop
639 * @attr ref android.R.styleable#View_paddingStart
640 * @attr ref android.R.styleable#View_paddingEnd
641 * @attr ref android.R.styleable#View_saveEnabled
642 * @attr ref android.R.styleable#View_rotation
643 * @attr ref android.R.styleable#View_rotationX
644 * @attr ref android.R.styleable#View_rotationY
645 * @attr ref android.R.styleable#View_scaleX
646 * @attr ref android.R.styleable#View_scaleY
647 * @attr ref android.R.styleable#View_scrollX
648 * @attr ref android.R.styleable#View_scrollY
649 * @attr ref android.R.styleable#View_scrollbarSize
650 * @attr ref android.R.styleable#View_scrollbarStyle
651 * @attr ref android.R.styleable#View_scrollbars
652 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
653 * @attr ref android.R.styleable#View_scrollbarFadeDuration
654 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
655 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
656 * @attr ref android.R.styleable#View_scrollbarThumbVertical
657 * @attr ref android.R.styleable#View_scrollbarTrackVertical
658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
660 * @attr ref android.R.styleable#View_soundEffectsEnabled
661 * @attr ref android.R.styleable#View_tag
662 * @attr ref android.R.styleable#View_textAlignment
663 * @attr ref android.R.styleable#View_transformPivotX
664 * @attr ref android.R.styleable#View_transformPivotY
665 * @attr ref android.R.styleable#View_translationX
666 * @attr ref android.R.styleable#View_translationY
667 * @attr ref android.R.styleable#View_visibility
668 *
669 * @see android.view.ViewGroup
670 */
671public class View implements Drawable.Callback, KeyEvent.Callback,
672        AccessibilityEventSource {
673    private static final boolean DBG = false;
674
675    /**
676     * The logging tag used by this class with android.util.Log.
677     */
678    protected static final String VIEW_LOG_TAG = "View";
679
680    /**
681     * When set to true, apps will draw debugging information about their layouts.
682     *
683     * @hide
684     */
685    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
686
687    /**
688     * Used to mark a View that has no ID.
689     */
690    public static final int NO_ID = -1;
691
692    /**
693     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
694     * calling setFlags.
695     */
696    private static final int NOT_FOCUSABLE = 0x00000000;
697
698    /**
699     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
700     * setFlags.
701     */
702    private static final int FOCUSABLE = 0x00000001;
703
704    /**
705     * Mask for use with setFlags indicating bits used for focus.
706     */
707    private static final int FOCUSABLE_MASK = 0x00000001;
708
709    /**
710     * This view will adjust its padding to fit sytem windows (e.g. status bar)
711     */
712    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
713
714    /**
715     * This view is visible.
716     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
717     * android:visibility}.
718     */
719    public static final int VISIBLE = 0x00000000;
720
721    /**
722     * This view is invisible, but it still takes up space for layout purposes.
723     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
724     * android:visibility}.
725     */
726    public static final int INVISIBLE = 0x00000004;
727
728    /**
729     * This view is invisible, and it doesn't take any space for layout
730     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
731     * android:visibility}.
732     */
733    public static final int GONE = 0x00000008;
734
735    /**
736     * Mask for use with setFlags indicating bits used for visibility.
737     * {@hide}
738     */
739    static final int VISIBILITY_MASK = 0x0000000C;
740
741    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
742
743    /**
744     * This view is enabled. Interpretation varies by subclass.
745     * Use with ENABLED_MASK when calling setFlags.
746     * {@hide}
747     */
748    static final int ENABLED = 0x00000000;
749
750    /**
751     * This view is disabled. Interpretation varies by subclass.
752     * Use with ENABLED_MASK when calling setFlags.
753     * {@hide}
754     */
755    static final int DISABLED = 0x00000020;
756
757   /**
758    * Mask for use with setFlags indicating bits used for indicating whether
759    * this view is enabled
760    * {@hide}
761    */
762    static final int ENABLED_MASK = 0x00000020;
763
764    /**
765     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
766     * called and further optimizations will be performed. It is okay to have
767     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
768     * {@hide}
769     */
770    static final int WILL_NOT_DRAW = 0x00000080;
771
772    /**
773     * Mask for use with setFlags indicating bits used for indicating whether
774     * this view is will draw
775     * {@hide}
776     */
777    static final int DRAW_MASK = 0x00000080;
778
779    /**
780     * <p>This view doesn't show scrollbars.</p>
781     * {@hide}
782     */
783    static final int SCROLLBARS_NONE = 0x00000000;
784
785    /**
786     * <p>This view shows horizontal scrollbars.</p>
787     * {@hide}
788     */
789    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
790
791    /**
792     * <p>This view shows vertical scrollbars.</p>
793     * {@hide}
794     */
795    static final int SCROLLBARS_VERTICAL = 0x00000200;
796
797    /**
798     * <p>Mask for use with setFlags indicating bits used for indicating which
799     * scrollbars are enabled.</p>
800     * {@hide}
801     */
802    static final int SCROLLBARS_MASK = 0x00000300;
803
804    /**
805     * Indicates that the view should filter touches when its window is obscured.
806     * Refer to the class comments for more information about this security feature.
807     * {@hide}
808     */
809    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
810
811    /**
812     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
813     * that they are optional and should be skipped if the window has
814     * requested system UI flags that ignore those insets for layout.
815     */
816    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
817
818    /**
819     * <p>This view doesn't show fading edges.</p>
820     * {@hide}
821     */
822    static final int FADING_EDGE_NONE = 0x00000000;
823
824    /**
825     * <p>This view shows horizontal fading edges.</p>
826     * {@hide}
827     */
828    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
829
830    /**
831     * <p>This view shows vertical fading edges.</p>
832     * {@hide}
833     */
834    static final int FADING_EDGE_VERTICAL = 0x00002000;
835
836    /**
837     * <p>Mask for use with setFlags indicating bits used for indicating which
838     * fading edges are enabled.</p>
839     * {@hide}
840     */
841    static final int FADING_EDGE_MASK = 0x00003000;
842
843    /**
844     * <p>Indicates this view can be clicked. When clickable, a View reacts
845     * to clicks by notifying the OnClickListener.<p>
846     * {@hide}
847     */
848    static final int CLICKABLE = 0x00004000;
849
850    /**
851     * <p>Indicates this view is caching its drawing into a bitmap.</p>
852     * {@hide}
853     */
854    static final int DRAWING_CACHE_ENABLED = 0x00008000;
855
856    /**
857     * <p>Indicates that no icicle should be saved for this view.<p>
858     * {@hide}
859     */
860    static final int SAVE_DISABLED = 0x000010000;
861
862    /**
863     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
864     * property.</p>
865     * {@hide}
866     */
867    static final int SAVE_DISABLED_MASK = 0x000010000;
868
869    /**
870     * <p>Indicates that no drawing cache should ever be created for this view.<p>
871     * {@hide}
872     */
873    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
874
875    /**
876     * <p>Indicates this view can take / keep focus when int touch mode.</p>
877     * {@hide}
878     */
879    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
880
881    /**
882     * <p>Enables low quality mode for the drawing cache.</p>
883     */
884    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
885
886    /**
887     * <p>Enables high quality mode for the drawing cache.</p>
888     */
889    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
890
891    /**
892     * <p>Enables automatic quality mode for the drawing cache.</p>
893     */
894    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
895
896    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
897            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
898    };
899
900    /**
901     * <p>Mask for use with setFlags indicating bits used for the cache
902     * quality property.</p>
903     * {@hide}
904     */
905    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
906
907    /**
908     * <p>
909     * Indicates this view can be long clicked. When long clickable, a View
910     * reacts to long clicks by notifying the OnLongClickListener or showing a
911     * context menu.
912     * </p>
913     * {@hide}
914     */
915    static final int LONG_CLICKABLE = 0x00200000;
916
917    /**
918     * <p>Indicates that this view gets its drawable states from its direct parent
919     * and ignores its original internal states.</p>
920     *
921     * @hide
922     */
923    static final int DUPLICATE_PARENT_STATE = 0x00400000;
924
925    /**
926     * The scrollbar style to display the scrollbars inside the content area,
927     * without increasing the padding. The scrollbars will be overlaid with
928     * translucency on the view's content.
929     */
930    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
931
932    /**
933     * The scrollbar style to display the scrollbars inside the padded area,
934     * increasing the padding of the view. The scrollbars will not overlap the
935     * content area of the view.
936     */
937    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
938
939    /**
940     * The scrollbar style to display the scrollbars at the edge of the view,
941     * without increasing the padding. The scrollbars will be overlaid with
942     * translucency.
943     */
944    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
945
946    /**
947     * The scrollbar style to display the scrollbars at the edge of the view,
948     * increasing the padding of the view. The scrollbars will only overlap the
949     * background, if any.
950     */
951    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
952
953    /**
954     * Mask to check if the scrollbar style is overlay or inset.
955     * {@hide}
956     */
957    static final int SCROLLBARS_INSET_MASK = 0x01000000;
958
959    /**
960     * Mask to check if the scrollbar style is inside or outside.
961     * {@hide}
962     */
963    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
964
965    /**
966     * Mask for scrollbar style.
967     * {@hide}
968     */
969    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
970
971    /**
972     * View flag indicating that the screen should remain on while the
973     * window containing this view is visible to the user.  This effectively
974     * takes care of automatically setting the WindowManager's
975     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
976     */
977    public static final int KEEP_SCREEN_ON = 0x04000000;
978
979    /**
980     * View flag indicating whether this view should have sound effects enabled
981     * for events such as clicking and touching.
982     */
983    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
984
985    /**
986     * View flag indicating whether this view should have haptic feedback
987     * enabled for events such as long presses.
988     */
989    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
990
991    /**
992     * <p>Indicates that the view hierarchy should stop saving state when
993     * it reaches this view.  If state saving is initiated immediately at
994     * the view, it will be allowed.
995     * {@hide}
996     */
997    static final int PARENT_SAVE_DISABLED = 0x20000000;
998
999    /**
1000     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1001     * {@hide}
1002     */
1003    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1004
1005    /**
1006     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1007     * should add all focusable Views regardless if they are focusable in touch mode.
1008     */
1009    public static final int FOCUSABLES_ALL = 0x00000000;
1010
1011    /**
1012     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1013     * should add only Views focusable in touch mode.
1014     */
1015    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1016
1017    /**
1018     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1019     * item.
1020     */
1021    public static final int FOCUS_BACKWARD = 0x00000001;
1022
1023    /**
1024     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1025     * item.
1026     */
1027    public static final int FOCUS_FORWARD = 0x00000002;
1028
1029    /**
1030     * Use with {@link #focusSearch(int)}. Move focus to the left.
1031     */
1032    public static final int FOCUS_LEFT = 0x00000011;
1033
1034    /**
1035     * Use with {@link #focusSearch(int)}. Move focus up.
1036     */
1037    public static final int FOCUS_UP = 0x00000021;
1038
1039    /**
1040     * Use with {@link #focusSearch(int)}. Move focus to the right.
1041     */
1042    public static final int FOCUS_RIGHT = 0x00000042;
1043
1044    /**
1045     * Use with {@link #focusSearch(int)}. Move focus down.
1046     */
1047    public static final int FOCUS_DOWN = 0x00000082;
1048
1049    /**
1050     * Bits of {@link #getMeasuredWidthAndState()} and
1051     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1052     */
1053    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1054
1055    /**
1056     * Bits of {@link #getMeasuredWidthAndState()} and
1057     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1058     */
1059    public static final int MEASURED_STATE_MASK = 0xff000000;
1060
1061    /**
1062     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1063     * for functions that combine both width and height into a single int,
1064     * such as {@link #getMeasuredState()} and the childState argument of
1065     * {@link #resolveSizeAndState(int, int, int)}.
1066     */
1067    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1068
1069    /**
1070     * Bit of {@link #getMeasuredWidthAndState()} and
1071     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1072     * is smaller that the space the view would like to have.
1073     */
1074    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1075
1076    /**
1077     * Base View state sets
1078     */
1079    // Singles
1080    /**
1081     * Indicates the view has no states set. States are used with
1082     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1083     * view depending on its state.
1084     *
1085     * @see android.graphics.drawable.Drawable
1086     * @see #getDrawableState()
1087     */
1088    protected static final int[] EMPTY_STATE_SET;
1089    /**
1090     * Indicates the view is enabled. States are used with
1091     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1092     * view depending on its state.
1093     *
1094     * @see android.graphics.drawable.Drawable
1095     * @see #getDrawableState()
1096     */
1097    protected static final int[] ENABLED_STATE_SET;
1098    /**
1099     * Indicates the view is focused. States are used with
1100     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1101     * view depending on its state.
1102     *
1103     * @see android.graphics.drawable.Drawable
1104     * @see #getDrawableState()
1105     */
1106    protected static final int[] FOCUSED_STATE_SET;
1107    /**
1108     * Indicates the view is selected. States are used with
1109     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1110     * view depending on its state.
1111     *
1112     * @see android.graphics.drawable.Drawable
1113     * @see #getDrawableState()
1114     */
1115    protected static final int[] SELECTED_STATE_SET;
1116    /**
1117     * Indicates the view is pressed. States are used with
1118     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1119     * view depending on its state.
1120     *
1121     * @see android.graphics.drawable.Drawable
1122     * @see #getDrawableState()
1123     * @hide
1124     */
1125    protected static final int[] PRESSED_STATE_SET;
1126    /**
1127     * Indicates the view's window has focus. States are used with
1128     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1129     * view depending on its state.
1130     *
1131     * @see android.graphics.drawable.Drawable
1132     * @see #getDrawableState()
1133     */
1134    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1135    // Doubles
1136    /**
1137     * Indicates the view is enabled and has the focus.
1138     *
1139     * @see #ENABLED_STATE_SET
1140     * @see #FOCUSED_STATE_SET
1141     */
1142    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1143    /**
1144     * Indicates the view is enabled and selected.
1145     *
1146     * @see #ENABLED_STATE_SET
1147     * @see #SELECTED_STATE_SET
1148     */
1149    protected static final int[] ENABLED_SELECTED_STATE_SET;
1150    /**
1151     * Indicates the view is enabled and that its window has focus.
1152     *
1153     * @see #ENABLED_STATE_SET
1154     * @see #WINDOW_FOCUSED_STATE_SET
1155     */
1156    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1157    /**
1158     * Indicates the view is focused and selected.
1159     *
1160     * @see #FOCUSED_STATE_SET
1161     * @see #SELECTED_STATE_SET
1162     */
1163    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1164    /**
1165     * Indicates the view has the focus and that its window has the focus.
1166     *
1167     * @see #FOCUSED_STATE_SET
1168     * @see #WINDOW_FOCUSED_STATE_SET
1169     */
1170    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1171    /**
1172     * Indicates the view is selected and that its window has the focus.
1173     *
1174     * @see #SELECTED_STATE_SET
1175     * @see #WINDOW_FOCUSED_STATE_SET
1176     */
1177    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1178    // Triples
1179    /**
1180     * Indicates the view is enabled, focused and selected.
1181     *
1182     * @see #ENABLED_STATE_SET
1183     * @see #FOCUSED_STATE_SET
1184     * @see #SELECTED_STATE_SET
1185     */
1186    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1187    /**
1188     * Indicates the view is enabled, focused and its window has the focus.
1189     *
1190     * @see #ENABLED_STATE_SET
1191     * @see #FOCUSED_STATE_SET
1192     * @see #WINDOW_FOCUSED_STATE_SET
1193     */
1194    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1195    /**
1196     * Indicates the view is enabled, selected and its window has the focus.
1197     *
1198     * @see #ENABLED_STATE_SET
1199     * @see #SELECTED_STATE_SET
1200     * @see #WINDOW_FOCUSED_STATE_SET
1201     */
1202    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1203    /**
1204     * Indicates the view is focused, selected and its window has the focus.
1205     *
1206     * @see #FOCUSED_STATE_SET
1207     * @see #SELECTED_STATE_SET
1208     * @see #WINDOW_FOCUSED_STATE_SET
1209     */
1210    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1211    /**
1212     * Indicates the view is enabled, focused, selected and its window
1213     * has the focus.
1214     *
1215     * @see #ENABLED_STATE_SET
1216     * @see #FOCUSED_STATE_SET
1217     * @see #SELECTED_STATE_SET
1218     * @see #WINDOW_FOCUSED_STATE_SET
1219     */
1220    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1221    /**
1222     * Indicates the view is pressed and its window has the focus.
1223     *
1224     * @see #PRESSED_STATE_SET
1225     * @see #WINDOW_FOCUSED_STATE_SET
1226     */
1227    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1228    /**
1229     * Indicates the view is pressed and selected.
1230     *
1231     * @see #PRESSED_STATE_SET
1232     * @see #SELECTED_STATE_SET
1233     */
1234    protected static final int[] PRESSED_SELECTED_STATE_SET;
1235    /**
1236     * Indicates the view is pressed, selected and its window has the focus.
1237     *
1238     * @see #PRESSED_STATE_SET
1239     * @see #SELECTED_STATE_SET
1240     * @see #WINDOW_FOCUSED_STATE_SET
1241     */
1242    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1243    /**
1244     * Indicates the view is pressed and focused.
1245     *
1246     * @see #PRESSED_STATE_SET
1247     * @see #FOCUSED_STATE_SET
1248     */
1249    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1250    /**
1251     * Indicates the view is pressed, focused and its window has the focus.
1252     *
1253     * @see #PRESSED_STATE_SET
1254     * @see #FOCUSED_STATE_SET
1255     * @see #WINDOW_FOCUSED_STATE_SET
1256     */
1257    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1258    /**
1259     * Indicates the view is pressed, focused and selected.
1260     *
1261     * @see #PRESSED_STATE_SET
1262     * @see #SELECTED_STATE_SET
1263     * @see #FOCUSED_STATE_SET
1264     */
1265    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1266    /**
1267     * Indicates the view is pressed, focused, selected and its window has the focus.
1268     *
1269     * @see #PRESSED_STATE_SET
1270     * @see #FOCUSED_STATE_SET
1271     * @see #SELECTED_STATE_SET
1272     * @see #WINDOW_FOCUSED_STATE_SET
1273     */
1274    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1275    /**
1276     * Indicates the view is pressed and enabled.
1277     *
1278     * @see #PRESSED_STATE_SET
1279     * @see #ENABLED_STATE_SET
1280     */
1281    protected static final int[] PRESSED_ENABLED_STATE_SET;
1282    /**
1283     * Indicates the view is pressed, enabled and its window has the focus.
1284     *
1285     * @see #PRESSED_STATE_SET
1286     * @see #ENABLED_STATE_SET
1287     * @see #WINDOW_FOCUSED_STATE_SET
1288     */
1289    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1290    /**
1291     * Indicates the view is pressed, enabled and selected.
1292     *
1293     * @see #PRESSED_STATE_SET
1294     * @see #ENABLED_STATE_SET
1295     * @see #SELECTED_STATE_SET
1296     */
1297    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1298    /**
1299     * Indicates the view is pressed, enabled, selected and its window has the
1300     * focus.
1301     *
1302     * @see #PRESSED_STATE_SET
1303     * @see #ENABLED_STATE_SET
1304     * @see #SELECTED_STATE_SET
1305     * @see #WINDOW_FOCUSED_STATE_SET
1306     */
1307    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed, enabled and focused.
1310     *
1311     * @see #PRESSED_STATE_SET
1312     * @see #ENABLED_STATE_SET
1313     * @see #FOCUSED_STATE_SET
1314     */
1315    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed, enabled, focused and its window has the
1318     * focus.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #ENABLED_STATE_SET
1322     * @see #FOCUSED_STATE_SET
1323     * @see #WINDOW_FOCUSED_STATE_SET
1324     */
1325    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1326    /**
1327     * Indicates the view is pressed, enabled, focused and selected.
1328     *
1329     * @see #PRESSED_STATE_SET
1330     * @see #ENABLED_STATE_SET
1331     * @see #SELECTED_STATE_SET
1332     * @see #FOCUSED_STATE_SET
1333     */
1334    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1335    /**
1336     * Indicates the view is pressed, enabled, focused, selected and its window
1337     * has the focus.
1338     *
1339     * @see #PRESSED_STATE_SET
1340     * @see #ENABLED_STATE_SET
1341     * @see #SELECTED_STATE_SET
1342     * @see #FOCUSED_STATE_SET
1343     * @see #WINDOW_FOCUSED_STATE_SET
1344     */
1345    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1346
1347    /**
1348     * The order here is very important to {@link #getDrawableState()}
1349     */
1350    private static final int[][] VIEW_STATE_SETS;
1351
1352    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1353    static final int VIEW_STATE_SELECTED = 1 << 1;
1354    static final int VIEW_STATE_FOCUSED = 1 << 2;
1355    static final int VIEW_STATE_ENABLED = 1 << 3;
1356    static final int VIEW_STATE_PRESSED = 1 << 4;
1357    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1358    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1359    static final int VIEW_STATE_HOVERED = 1 << 7;
1360    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1361    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1362
1363    static final int[] VIEW_STATE_IDS = new int[] {
1364        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1365        R.attr.state_selected,          VIEW_STATE_SELECTED,
1366        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1367        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1368        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1369        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1370        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1371        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1372        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1373        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1374    };
1375
1376    static {
1377        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1378            throw new IllegalStateException(
1379                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1380        }
1381        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1382        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1383            int viewState = R.styleable.ViewDrawableStates[i];
1384            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1385                if (VIEW_STATE_IDS[j] == viewState) {
1386                    orderedIds[i * 2] = viewState;
1387                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1388                }
1389            }
1390        }
1391        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1392        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1393        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1394            int numBits = Integer.bitCount(i);
1395            int[] set = new int[numBits];
1396            int pos = 0;
1397            for (int j = 0; j < orderedIds.length; j += 2) {
1398                if ((i & orderedIds[j+1]) != 0) {
1399                    set[pos++] = orderedIds[j];
1400                }
1401            }
1402            VIEW_STATE_SETS[i] = set;
1403        }
1404
1405        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1406        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1407        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1408        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1409                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1410        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1411        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1413        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1415        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1417                | VIEW_STATE_FOCUSED];
1418        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1419        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1421        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1423        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1425                | VIEW_STATE_ENABLED];
1426        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1428        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1430                | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1436                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1437
1438        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1439        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1441        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1443        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1445                | VIEW_STATE_PRESSED];
1446        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1448        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1450                | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1456                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1457        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1459        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1461                | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1464                | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1467                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1470                | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1473                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1476                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1479                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1480                | VIEW_STATE_PRESSED];
1481    }
1482
1483    /**
1484     * Accessibility event types that are dispatched for text population.
1485     */
1486    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1487            AccessibilityEvent.TYPE_VIEW_CLICKED
1488            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1489            | AccessibilityEvent.TYPE_VIEW_SELECTED
1490            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1491            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1492            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1493            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1494            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1495            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1496            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1498
1499    /**
1500     * Temporary Rect currently for use in setBackground().  This will probably
1501     * be extended in the future to hold our own class with more than just
1502     * a Rect. :)
1503     */
1504    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1505
1506    /**
1507     * Map used to store views' tags.
1508     */
1509    private SparseArray<Object> mKeyedTags;
1510
1511    /**
1512     * The next available accessibility id.
1513     */
1514    private static int sNextAccessibilityViewId;
1515
1516    /**
1517     * The animation currently associated with this view.
1518     * @hide
1519     */
1520    protected Animation mCurrentAnimation = null;
1521
1522    /**
1523     * Width as measured during measure pass.
1524     * {@hide}
1525     */
1526    @ViewDebug.ExportedProperty(category = "measurement")
1527    int mMeasuredWidth;
1528
1529    /**
1530     * Height as measured during measure pass.
1531     * {@hide}
1532     */
1533    @ViewDebug.ExportedProperty(category = "measurement")
1534    int mMeasuredHeight;
1535
1536    /**
1537     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1538     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1539     * its display list. This flag, used only when hw accelerated, allows us to clear the
1540     * flag while retaining this information until it's needed (at getDisplayList() time and
1541     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1542     *
1543     * {@hide}
1544     */
1545    boolean mRecreateDisplayList = false;
1546
1547    /**
1548     * The view's identifier.
1549     * {@hide}
1550     *
1551     * @see #setId(int)
1552     * @see #getId()
1553     */
1554    @ViewDebug.ExportedProperty(resolveId = true)
1555    int mID = NO_ID;
1556
1557    /**
1558     * The stable ID of this view for accessibility purposes.
1559     */
1560    int mAccessibilityViewId = NO_ID;
1561
1562    /**
1563     * @hide
1564     */
1565    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1566
1567    /**
1568     * The view's tag.
1569     * {@hide}
1570     *
1571     * @see #setTag(Object)
1572     * @see #getTag()
1573     */
1574    protected Object mTag;
1575
1576    // for mPrivateFlags:
1577    /** {@hide} */
1578    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1579    /** {@hide} */
1580    static final int PFLAG_FOCUSED                     = 0x00000002;
1581    /** {@hide} */
1582    static final int PFLAG_SELECTED                    = 0x00000004;
1583    /** {@hide} */
1584    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1585    /** {@hide} */
1586    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1587    /** {@hide} */
1588    static final int PFLAG_DRAWN                       = 0x00000020;
1589    /**
1590     * When this flag is set, this view is running an animation on behalf of its
1591     * children and should therefore not cancel invalidate requests, even if they
1592     * lie outside of this view's bounds.
1593     *
1594     * {@hide}
1595     */
1596    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1597    /** {@hide} */
1598    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1599    /** {@hide} */
1600    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1601    /** {@hide} */
1602    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1603    /** {@hide} */
1604    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1605    /** {@hide} */
1606    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1607    /** {@hide} */
1608    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1609    /** {@hide} */
1610    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1611
1612    private static final int PFLAG_PRESSED             = 0x00004000;
1613
1614    /** {@hide} */
1615    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1616    /**
1617     * Flag used to indicate that this view should be drawn once more (and only once
1618     * more) after its animation has completed.
1619     * {@hide}
1620     */
1621    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1622
1623    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1624
1625    /**
1626     * Indicates that the View returned true when onSetAlpha() was called and that
1627     * the alpha must be restored.
1628     * {@hide}
1629     */
1630    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1631
1632    /**
1633     * Set by {@link #setScrollContainer(boolean)}.
1634     */
1635    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1636
1637    /**
1638     * Set by {@link #setScrollContainer(boolean)}.
1639     */
1640    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1641
1642    /**
1643     * View flag indicating whether this view was invalidated (fully or partially.)
1644     *
1645     * @hide
1646     */
1647    static final int PFLAG_DIRTY                       = 0x00200000;
1648
1649    /**
1650     * View flag indicating whether this view was invalidated by an opaque
1651     * invalidate request.
1652     *
1653     * @hide
1654     */
1655    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1656
1657    /**
1658     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1659     *
1660     * @hide
1661     */
1662    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1663
1664    /**
1665     * Indicates whether the background is opaque.
1666     *
1667     * @hide
1668     */
1669    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1670
1671    /**
1672     * Indicates whether the scrollbars are opaque.
1673     *
1674     * @hide
1675     */
1676    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1677
1678    /**
1679     * Indicates whether the view is opaque.
1680     *
1681     * @hide
1682     */
1683    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1684
1685    /**
1686     * Indicates a prepressed state;
1687     * the short time between ACTION_DOWN and recognizing
1688     * a 'real' press. Prepressed is used to recognize quick taps
1689     * even when they are shorter than ViewConfiguration.getTapTimeout().
1690     *
1691     * @hide
1692     */
1693    private static final int PFLAG_PREPRESSED          = 0x02000000;
1694
1695    /**
1696     * Indicates whether the view is temporarily detached.
1697     *
1698     * @hide
1699     */
1700    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1701
1702    /**
1703     * Indicates that we should awaken scroll bars once attached
1704     *
1705     * @hide
1706     */
1707    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1708
1709    /**
1710     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1711     * @hide
1712     */
1713    private static final int PFLAG_HOVERED             = 0x10000000;
1714
1715    /**
1716     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1717     * for transform operations
1718     *
1719     * @hide
1720     */
1721    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1722
1723    /** {@hide} */
1724    static final int PFLAG_ACTIVATED                   = 0x40000000;
1725
1726    /**
1727     * Indicates that this view was specifically invalidated, not just dirtied because some
1728     * child view was invalidated. The flag is used to determine when we need to recreate
1729     * a view's display list (as opposed to just returning a reference to its existing
1730     * display list).
1731     *
1732     * @hide
1733     */
1734    static final int PFLAG_INVALIDATED                 = 0x80000000;
1735
1736    /**
1737     * Masks for mPrivateFlags2, as generated by dumpFlags():
1738     *
1739     * -------|-------|-------|-------|
1740     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1741     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1742     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1743     *                               1  PFLAG2_DRAG_HOVERED
1744     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1745     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1746     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1747     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1748     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1749     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1750     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1751     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1752     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1753     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1754     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1755     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1756     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1757     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1758     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1759     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1760     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1761     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1762     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1763     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1764     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1765     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1766     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1767     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1768     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1769     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1770     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1771     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1772     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1773     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1774     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1775     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1776     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1777     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1778     *   1                              PFLAG2_PADDING_RESOLVED
1779     * -------|-------|-------|-------|
1780     */
1781
1782    /**
1783     * Indicates that this view has reported that it can accept the current drag's content.
1784     * Cleared when the drag operation concludes.
1785     * @hide
1786     */
1787    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1788
1789    /**
1790     * Indicates that this view is currently directly under the drag location in a
1791     * drag-and-drop operation involving content that it can accept.  Cleared when
1792     * the drag exits the view, or when the drag operation concludes.
1793     * @hide
1794     */
1795    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1796
1797    /**
1798     * Horizontal layout direction of this view is from Left to Right.
1799     * Use with {@link #setLayoutDirection}.
1800     */
1801    public static final int LAYOUT_DIRECTION_LTR = 0;
1802
1803    /**
1804     * Horizontal layout direction of this view is from Right to Left.
1805     * Use with {@link #setLayoutDirection}.
1806     */
1807    public static final int LAYOUT_DIRECTION_RTL = 1;
1808
1809    /**
1810     * Horizontal layout direction of this view is inherited from its parent.
1811     * Use with {@link #setLayoutDirection}.
1812     */
1813    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1814
1815    /**
1816     * Horizontal layout direction of this view is from deduced from the default language
1817     * script for the locale. Use with {@link #setLayoutDirection}.
1818     */
1819    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1820
1821    /**
1822     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1823     * @hide
1824     */
1825    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1826
1827    /**
1828     * Mask for use with private flags indicating bits used for horizontal layout direction.
1829     * @hide
1830     */
1831    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1832
1833    /**
1834     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1835     * right-to-left direction.
1836     * @hide
1837     */
1838    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1839
1840    /**
1841     * Indicates whether the view horizontal layout direction has been resolved.
1842     * @hide
1843     */
1844    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1845
1846    /**
1847     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1848     * @hide
1849     */
1850    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1851            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1852
1853    /*
1854     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1855     * flag value.
1856     * @hide
1857     */
1858    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1859            LAYOUT_DIRECTION_LTR,
1860            LAYOUT_DIRECTION_RTL,
1861            LAYOUT_DIRECTION_INHERIT,
1862            LAYOUT_DIRECTION_LOCALE
1863    };
1864
1865    /**
1866     * Default horizontal layout direction.
1867     * @hide
1868     */
1869    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1870
1871    /**
1872     * Indicates that the view is tracking some sort of transient state
1873     * that the app should not need to be aware of, but that the framework
1874     * should take special care to preserve.
1875     *
1876     * @hide
1877     */
1878    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1879
1880    /**
1881     * Text direction is inherited thru {@link ViewGroup}
1882     */
1883    public static final int TEXT_DIRECTION_INHERIT = 0;
1884
1885    /**
1886     * Text direction is using "first strong algorithm". The first strong directional character
1887     * determines the paragraph direction. If there is no strong directional character, the
1888     * paragraph direction is the view's resolved layout direction.
1889     */
1890    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1891
1892    /**
1893     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1894     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1895     * If there are neither, the paragraph direction is the view's resolved layout direction.
1896     */
1897    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1898
1899    /**
1900     * Text direction is forced to LTR.
1901     */
1902    public static final int TEXT_DIRECTION_LTR = 3;
1903
1904    /**
1905     * Text direction is forced to RTL.
1906     */
1907    public static final int TEXT_DIRECTION_RTL = 4;
1908
1909    /**
1910     * Text direction is coming from the system Locale.
1911     */
1912    public static final int TEXT_DIRECTION_LOCALE = 5;
1913
1914    /**
1915     * Default text direction is inherited
1916     */
1917    public static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1918
1919    /**
1920     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1921     * @hide
1922     */
1923    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1924
1925    /**
1926     * Mask for use with private flags indicating bits used for text direction.
1927     * @hide
1928     */
1929    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1930            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1931
1932    /**
1933     * Array of text direction flags for mapping attribute "textDirection" to correct
1934     * flag value.
1935     * @hide
1936     */
1937    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1938            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1939            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1940            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1941            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1942            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1943            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1944    };
1945
1946    /**
1947     * Indicates whether the view text direction has been resolved.
1948     * @hide
1949     */
1950    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1951            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1952
1953    /**
1954     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1955     * @hide
1956     */
1957    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1958
1959    /**
1960     * Mask for use with private flags indicating bits used for resolved text direction.
1961     * @hide
1962     */
1963    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1964            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1965
1966    /**
1967     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1968     * @hide
1969     */
1970    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1971            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1972
1973    /*
1974     * Default text alignment. The text alignment of this View is inherited from its parent.
1975     * Use with {@link #setTextAlignment(int)}
1976     */
1977    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1978
1979    /**
1980     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1981     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1982     *
1983     * Use with {@link #setTextAlignment(int)}
1984     */
1985    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1986
1987    /**
1988     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1989     *
1990     * Use with {@link #setTextAlignment(int)}
1991     */
1992    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1993
1994    /**
1995     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1996     *
1997     * Use with {@link #setTextAlignment(int)}
1998     */
1999    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2000
2001    /**
2002     * Center the paragraph, e.g. ALIGN_CENTER.
2003     *
2004     * Use with {@link #setTextAlignment(int)}
2005     */
2006    public static final int TEXT_ALIGNMENT_CENTER = 4;
2007
2008    /**
2009     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2010     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2011     *
2012     * Use with {@link #setTextAlignment(int)}
2013     */
2014    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2015
2016    /**
2017     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2018     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2019     *
2020     * Use with {@link #setTextAlignment(int)}
2021     */
2022    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2023
2024    /**
2025     * Default text alignment is inherited
2026     */
2027    public static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2028
2029    /**
2030      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2031      * @hide
2032      */
2033    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2034
2035    /**
2036      * Mask for use with private flags indicating bits used for text alignment.
2037      * @hide
2038      */
2039    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2040
2041    /**
2042     * Array of text direction flags for mapping attribute "textAlignment" to correct
2043     * flag value.
2044     * @hide
2045     */
2046    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2047            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2048            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2049            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2050            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2051            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2052            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2053            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2054    };
2055
2056    /**
2057     * Indicates whether the view text alignment has been resolved.
2058     * @hide
2059     */
2060    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2061
2062    /**
2063     * Bit shift to get the resolved text alignment.
2064     * @hide
2065     */
2066    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2067
2068    /**
2069     * Mask for use with private flags indicating bits used for text alignment.
2070     * @hide
2071     */
2072    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2073            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2074
2075    /**
2076     * Indicates whether if the view text alignment has been resolved to gravity
2077     */
2078    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2079            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2080
2081    // Accessiblity constants for mPrivateFlags2
2082
2083    /**
2084     * Shift for the bits in {@link #mPrivateFlags2} related to the
2085     * "importantForAccessibility" attribute.
2086     */
2087    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2088
2089    /**
2090     * Automatically determine whether a view is important for accessibility.
2091     */
2092    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2093
2094    /**
2095     * The view is important for accessibility.
2096     */
2097    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2098
2099    /**
2100     * The view is not important for accessibility.
2101     */
2102    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2103
2104    /**
2105     * The default whether the view is important for accessibility.
2106     */
2107    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2108
2109    /**
2110     * Mask for obtainig the bits which specify how to determine
2111     * whether a view is important for accessibility.
2112     */
2113    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2114        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2115        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2116
2117    /**
2118     * Flag indicating whether a view has accessibility focus.
2119     */
2120    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2121
2122    /**
2123     * Flag indicating whether a view state for accessibility has changed.
2124     */
2125    static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080
2126            << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2127
2128    /**
2129     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2130     * is used to check whether later changes to the view's transform should invalidate the
2131     * view to force the quickReject test to run again.
2132     */
2133    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2134
2135    /**
2136     * Flag indicating that start/end padding has been resolved into left/right padding
2137     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2138     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2139     * during measurement. In some special cases this is required such as when an adapter-based
2140     * view measures prospective children without attaching them to a window.
2141     */
2142    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2143
2144    /**
2145     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2146     */
2147    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2148
2149    /**
2150     * Group of bits indicating that RTL properties resolution is done.
2151     */
2152    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2153            PFLAG2_TEXT_DIRECTION_RESOLVED |
2154            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2155            PFLAG2_PADDING_RESOLVED |
2156            PFLAG2_DRAWABLE_RESOLVED;
2157
2158    // There are a couple of flags left in mPrivateFlags2
2159
2160    /* End of masks for mPrivateFlags2 */
2161
2162    /* Masks for mPrivateFlags3 */
2163
2164    /**
2165     * Flag indicating that view has a transform animation set on it. This is used to track whether
2166     * an animation is cleared between successive frames, in order to tell the associated
2167     * DisplayList to clear its animation matrix.
2168     */
2169    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2170
2171    /**
2172     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2173     * animation is cleared between successive frames, in order to tell the associated
2174     * DisplayList to restore its alpha value.
2175     */
2176    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2177
2178
2179    /* End of masks for mPrivateFlags3 */
2180
2181    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2182
2183    /**
2184     * Always allow a user to over-scroll this view, provided it is a
2185     * view that can scroll.
2186     *
2187     * @see #getOverScrollMode()
2188     * @see #setOverScrollMode(int)
2189     */
2190    public static final int OVER_SCROLL_ALWAYS = 0;
2191
2192    /**
2193     * Allow a user to over-scroll this view only if the content is large
2194     * enough to meaningfully scroll, provided it is a view that can scroll.
2195     *
2196     * @see #getOverScrollMode()
2197     * @see #setOverScrollMode(int)
2198     */
2199    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2200
2201    /**
2202     * Never allow a user to over-scroll this view.
2203     *
2204     * @see #getOverScrollMode()
2205     * @see #setOverScrollMode(int)
2206     */
2207    public static final int OVER_SCROLL_NEVER = 2;
2208
2209    /**
2210     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2211     * requested the system UI (status bar) to be visible (the default).
2212     *
2213     * @see #setSystemUiVisibility(int)
2214     */
2215    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2216
2217    /**
2218     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2219     * system UI to enter an unobtrusive "low profile" mode.
2220     *
2221     * <p>This is for use in games, book readers, video players, or any other
2222     * "immersive" application where the usual system chrome is deemed too distracting.
2223     *
2224     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2225     *
2226     * @see #setSystemUiVisibility(int)
2227     */
2228    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2229
2230    /**
2231     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2232     * system navigation be temporarily hidden.
2233     *
2234     * <p>This is an even less obtrusive state than that called for by
2235     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2236     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2237     * those to disappear. This is useful (in conjunction with the
2238     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2239     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2240     * window flags) for displaying content using every last pixel on the display.
2241     *
2242     * <p>There is a limitation: because navigation controls are so important, the least user
2243     * interaction will cause them to reappear immediately.  When this happens, both
2244     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2245     * so that both elements reappear at the same time.
2246     *
2247     * @see #setSystemUiVisibility(int)
2248     */
2249    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2250
2251    /**
2252     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2253     * into the normal fullscreen mode so that its content can take over the screen
2254     * while still allowing the user to interact with the application.
2255     *
2256     * <p>This has the same visual effect as
2257     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2258     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2259     * meaning that non-critical screen decorations (such as the status bar) will be
2260     * hidden while the user is in the View's window, focusing the experience on
2261     * that content.  Unlike the window flag, if you are using ActionBar in
2262     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2263     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2264     * hide the action bar.
2265     *
2266     * <p>This approach to going fullscreen is best used over the window flag when
2267     * it is a transient state -- that is, the application does this at certain
2268     * points in its user interaction where it wants to allow the user to focus
2269     * on content, but not as a continuous state.  For situations where the application
2270     * would like to simply stay full screen the entire time (such as a game that
2271     * wants to take over the screen), the
2272     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2273     * is usually a better approach.  The state set here will be removed by the system
2274     * in various situations (such as the user moving to another application) like
2275     * the other system UI states.
2276     *
2277     * <p>When using this flag, the application should provide some easy facility
2278     * for the user to go out of it.  A common example would be in an e-book
2279     * reader, where tapping on the screen brings back whatever screen and UI
2280     * decorations that had been hidden while the user was immersed in reading
2281     * the book.
2282     *
2283     * @see #setSystemUiVisibility(int)
2284     */
2285    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2286
2287    /**
2288     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2289     * flags, we would like a stable view of the content insets given to
2290     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2291     * will always represent the worst case that the application can expect
2292     * as a continuous state.  In the stock Android UI this is the space for
2293     * the system bar, nav bar, and status bar, but not more transient elements
2294     * such as an input method.
2295     *
2296     * The stable layout your UI sees is based on the system UI modes you can
2297     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2298     * then you will get a stable layout for changes of the
2299     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2300     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2301     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2302     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2303     * with a stable layout.  (Note that you should avoid using
2304     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2305     *
2306     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2307     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2308     * then a hidden status bar will be considered a "stable" state for purposes
2309     * here.  This allows your UI to continually hide the status bar, while still
2310     * using the system UI flags to hide the action bar while still retaining
2311     * a stable layout.  Note that changing the window fullscreen flag will never
2312     * provide a stable layout for a clean transition.
2313     *
2314     * <p>If you are using ActionBar in
2315     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2316     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2317     * insets it adds to those given to the application.
2318     */
2319    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2320
2321    /**
2322     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2323     * to be layed out as if it has requested
2324     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2325     * allows it to avoid artifacts when switching in and out of that mode, at
2326     * the expense that some of its user interface may be covered by screen
2327     * decorations when they are shown.  You can perform layout of your inner
2328     * UI elements to account for the navagation system UI through the
2329     * {@link #fitSystemWindows(Rect)} method.
2330     */
2331    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2332
2333    /**
2334     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2335     * to be layed out as if it has requested
2336     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2337     * allows it to avoid artifacts when switching in and out of that mode, at
2338     * the expense that some of its user interface may be covered by screen
2339     * decorations when they are shown.  You can perform layout of your inner
2340     * UI elements to account for non-fullscreen system UI through the
2341     * {@link #fitSystemWindows(Rect)} method.
2342     */
2343    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2344
2345    /**
2346     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2347     */
2348    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2349
2350    /**
2351     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2352     */
2353    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2354
2355    /**
2356     * @hide
2357     *
2358     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2359     * out of the public fields to keep the undefined bits out of the developer's way.
2360     *
2361     * Flag to make the status bar not expandable.  Unless you also
2362     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2363     */
2364    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2365
2366    /**
2367     * @hide
2368     *
2369     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2370     * out of the public fields to keep the undefined bits out of the developer's way.
2371     *
2372     * Flag to hide notification icons and scrolling ticker text.
2373     */
2374    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2375
2376    /**
2377     * @hide
2378     *
2379     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2380     * out of the public fields to keep the undefined bits out of the developer's way.
2381     *
2382     * Flag to disable incoming notification alerts.  This will not block
2383     * icons, but it will block sound, vibrating and other visual or aural notifications.
2384     */
2385    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2386
2387    /**
2388     * @hide
2389     *
2390     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2391     * out of the public fields to keep the undefined bits out of the developer's way.
2392     *
2393     * Flag to hide only the scrolling ticker.  Note that
2394     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2395     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2396     */
2397    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2398
2399    /**
2400     * @hide
2401     *
2402     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2403     * out of the public fields to keep the undefined bits out of the developer's way.
2404     *
2405     * Flag to hide the center system info area.
2406     */
2407    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2408
2409    /**
2410     * @hide
2411     *
2412     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2413     * out of the public fields to keep the undefined bits out of the developer's way.
2414     *
2415     * Flag to hide only the home button.  Don't use this
2416     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2417     */
2418    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2419
2420    /**
2421     * @hide
2422     *
2423     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2424     * out of the public fields to keep the undefined bits out of the developer's way.
2425     *
2426     * Flag to hide only the back button. Don't use this
2427     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2428     */
2429    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2430
2431    /**
2432     * @hide
2433     *
2434     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2435     * out of the public fields to keep the undefined bits out of the developer's way.
2436     *
2437     * Flag to hide only the clock.  You might use this if your activity has
2438     * its own clock making the status bar's clock redundant.
2439     */
2440    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2441
2442    /**
2443     * @hide
2444     *
2445     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2446     * out of the public fields to keep the undefined bits out of the developer's way.
2447     *
2448     * Flag to hide only the recent apps button. Don't use this
2449     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2450     */
2451    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2452
2453    /**
2454     * @hide
2455     */
2456    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2457
2458    /**
2459     * These are the system UI flags that can be cleared by events outside
2460     * of an application.  Currently this is just the ability to tap on the
2461     * screen while hiding the navigation bar to have it return.
2462     * @hide
2463     */
2464    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2465            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2466            | SYSTEM_UI_FLAG_FULLSCREEN;
2467
2468    /**
2469     * Flags that can impact the layout in relation to system UI.
2470     */
2471    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2472            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2473            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2474
2475    /**
2476     * Find views that render the specified text.
2477     *
2478     * @see #findViewsWithText(ArrayList, CharSequence, int)
2479     */
2480    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2481
2482    /**
2483     * Find find views that contain the specified content description.
2484     *
2485     * @see #findViewsWithText(ArrayList, CharSequence, int)
2486     */
2487    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2488
2489    /**
2490     * Find views that contain {@link AccessibilityNodeProvider}. Such
2491     * a View is a root of virtual view hierarchy and may contain the searched
2492     * text. If this flag is set Views with providers are automatically
2493     * added and it is a responsibility of the client to call the APIs of
2494     * the provider to determine whether the virtual tree rooted at this View
2495     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2496     * represeting the virtual views with this text.
2497     *
2498     * @see #findViewsWithText(ArrayList, CharSequence, int)
2499     *
2500     * @hide
2501     */
2502    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2503
2504    /**
2505     * The undefined cursor position.
2506     */
2507    private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2508
2509    /**
2510     * Indicates that the screen has changed state and is now off.
2511     *
2512     * @see #onScreenStateChanged(int)
2513     */
2514    public static final int SCREEN_STATE_OFF = 0x0;
2515
2516    /**
2517     * Indicates that the screen has changed state and is now on.
2518     *
2519     * @see #onScreenStateChanged(int)
2520     */
2521    public static final int SCREEN_STATE_ON = 0x1;
2522
2523    /**
2524     * Controls the over-scroll mode for this view.
2525     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2526     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2527     * and {@link #OVER_SCROLL_NEVER}.
2528     */
2529    private int mOverScrollMode;
2530
2531    /**
2532     * The parent this view is attached to.
2533     * {@hide}
2534     *
2535     * @see #getParent()
2536     */
2537    protected ViewParent mParent;
2538
2539    /**
2540     * {@hide}
2541     */
2542    AttachInfo mAttachInfo;
2543
2544    /**
2545     * {@hide}
2546     */
2547    @ViewDebug.ExportedProperty(flagMapping = {
2548        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2549                name = "FORCE_LAYOUT"),
2550        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2551                name = "LAYOUT_REQUIRED"),
2552        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2553            name = "DRAWING_CACHE_INVALID", outputIf = false),
2554        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2555        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2556        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2557        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2558    })
2559    int mPrivateFlags;
2560    int mPrivateFlags2;
2561    int mPrivateFlags3;
2562
2563    /**
2564     * This view's request for the visibility of the status bar.
2565     * @hide
2566     */
2567    @ViewDebug.ExportedProperty(flagMapping = {
2568        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2569                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2570                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2571        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2572                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2573                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2574        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2575                                equals = SYSTEM_UI_FLAG_VISIBLE,
2576                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2577    })
2578    int mSystemUiVisibility;
2579
2580    /**
2581     * Reference count for transient state.
2582     * @see #setHasTransientState(boolean)
2583     */
2584    int mTransientStateCount = 0;
2585
2586    /**
2587     * Count of how many windows this view has been attached to.
2588     */
2589    int mWindowAttachCount;
2590
2591    /**
2592     * The layout parameters associated with this view and used by the parent
2593     * {@link android.view.ViewGroup} to determine how this view should be
2594     * laid out.
2595     * {@hide}
2596     */
2597    protected ViewGroup.LayoutParams mLayoutParams;
2598
2599    /**
2600     * The view flags hold various views states.
2601     * {@hide}
2602     */
2603    @ViewDebug.ExportedProperty
2604    int mViewFlags;
2605
2606    static class TransformationInfo {
2607        /**
2608         * The transform matrix for the View. This transform is calculated internally
2609         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2610         * is used by default. Do *not* use this variable directly; instead call
2611         * getMatrix(), which will automatically recalculate the matrix if necessary
2612         * to get the correct matrix based on the latest rotation and scale properties.
2613         */
2614        private final Matrix mMatrix = new Matrix();
2615
2616        /**
2617         * The transform matrix for the View. This transform is calculated internally
2618         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2619         * is used by default. Do *not* use this variable directly; instead call
2620         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2621         * to get the correct matrix based on the latest rotation and scale properties.
2622         */
2623        private Matrix mInverseMatrix;
2624
2625        /**
2626         * An internal variable that tracks whether we need to recalculate the
2627         * transform matrix, based on whether the rotation or scaleX/Y properties
2628         * have changed since the matrix was last calculated.
2629         */
2630        boolean mMatrixDirty = false;
2631
2632        /**
2633         * An internal variable that tracks whether we need to recalculate the
2634         * transform matrix, based on whether the rotation or scaleX/Y properties
2635         * have changed since the matrix was last calculated.
2636         */
2637        private boolean mInverseMatrixDirty = true;
2638
2639        /**
2640         * A variable that tracks whether we need to recalculate the
2641         * transform matrix, based on whether the rotation or scaleX/Y properties
2642         * have changed since the matrix was last calculated. This variable
2643         * is only valid after a call to updateMatrix() or to a function that
2644         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2645         */
2646        private boolean mMatrixIsIdentity = true;
2647
2648        /**
2649         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2650         */
2651        private Camera mCamera = null;
2652
2653        /**
2654         * This matrix is used when computing the matrix for 3D rotations.
2655         */
2656        private Matrix matrix3D = null;
2657
2658        /**
2659         * These prev values are used to recalculate a centered pivot point when necessary. The
2660         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2661         * set), so thes values are only used then as well.
2662         */
2663        private int mPrevWidth = -1;
2664        private int mPrevHeight = -1;
2665
2666        /**
2667         * The degrees rotation around the vertical axis through the pivot point.
2668         */
2669        @ViewDebug.ExportedProperty
2670        float mRotationY = 0f;
2671
2672        /**
2673         * The degrees rotation around the horizontal axis through the pivot point.
2674         */
2675        @ViewDebug.ExportedProperty
2676        float mRotationX = 0f;
2677
2678        /**
2679         * The degrees rotation around the pivot point.
2680         */
2681        @ViewDebug.ExportedProperty
2682        float mRotation = 0f;
2683
2684        /**
2685         * The amount of translation of the object away from its left property (post-layout).
2686         */
2687        @ViewDebug.ExportedProperty
2688        float mTranslationX = 0f;
2689
2690        /**
2691         * The amount of translation of the object away from its top property (post-layout).
2692         */
2693        @ViewDebug.ExportedProperty
2694        float mTranslationY = 0f;
2695
2696        /**
2697         * The amount of scale in the x direction around the pivot point. A
2698         * value of 1 means no scaling is applied.
2699         */
2700        @ViewDebug.ExportedProperty
2701        float mScaleX = 1f;
2702
2703        /**
2704         * The amount of scale in the y direction around the pivot point. A
2705         * value of 1 means no scaling is applied.
2706         */
2707        @ViewDebug.ExportedProperty
2708        float mScaleY = 1f;
2709
2710        /**
2711         * The x location of the point around which the view is rotated and scaled.
2712         */
2713        @ViewDebug.ExportedProperty
2714        float mPivotX = 0f;
2715
2716        /**
2717         * The y location of the point around which the view is rotated and scaled.
2718         */
2719        @ViewDebug.ExportedProperty
2720        float mPivotY = 0f;
2721
2722        /**
2723         * The opacity of the View. This is a value from 0 to 1, where 0 means
2724         * completely transparent and 1 means completely opaque.
2725         */
2726        @ViewDebug.ExportedProperty
2727        float mAlpha = 1f;
2728    }
2729
2730    TransformationInfo mTransformationInfo;
2731
2732    private boolean mLastIsOpaque;
2733
2734    /**
2735     * Convenience value to check for float values that are close enough to zero to be considered
2736     * zero.
2737     */
2738    private static final float NONZERO_EPSILON = .001f;
2739
2740    /**
2741     * The distance in pixels from the left edge of this view's parent
2742     * to the left edge of this view.
2743     * {@hide}
2744     */
2745    @ViewDebug.ExportedProperty(category = "layout")
2746    protected int mLeft;
2747    /**
2748     * The distance in pixels from the left edge of this view's parent
2749     * to the right edge of this view.
2750     * {@hide}
2751     */
2752    @ViewDebug.ExportedProperty(category = "layout")
2753    protected int mRight;
2754    /**
2755     * The distance in pixels from the top edge of this view's parent
2756     * to the top edge of this view.
2757     * {@hide}
2758     */
2759    @ViewDebug.ExportedProperty(category = "layout")
2760    protected int mTop;
2761    /**
2762     * The distance in pixels from the top edge of this view's parent
2763     * to the bottom edge of this view.
2764     * {@hide}
2765     */
2766    @ViewDebug.ExportedProperty(category = "layout")
2767    protected int mBottom;
2768
2769    /**
2770     * The offset, in pixels, by which the content of this view is scrolled
2771     * horizontally.
2772     * {@hide}
2773     */
2774    @ViewDebug.ExportedProperty(category = "scrolling")
2775    protected int mScrollX;
2776    /**
2777     * The offset, in pixels, by which the content of this view is scrolled
2778     * vertically.
2779     * {@hide}
2780     */
2781    @ViewDebug.ExportedProperty(category = "scrolling")
2782    protected int mScrollY;
2783
2784    /**
2785     * The left padding in pixels, that is the distance in pixels between the
2786     * left edge of this view and the left edge of its content.
2787     * {@hide}
2788     */
2789    @ViewDebug.ExportedProperty(category = "padding")
2790    protected int mPaddingLeft = 0;
2791    /**
2792     * The right padding in pixels, that is the distance in pixels between the
2793     * right edge of this view and the right edge of its content.
2794     * {@hide}
2795     */
2796    @ViewDebug.ExportedProperty(category = "padding")
2797    protected int mPaddingRight = 0;
2798    /**
2799     * The top padding in pixels, that is the distance in pixels between the
2800     * top edge of this view and the top edge of its content.
2801     * {@hide}
2802     */
2803    @ViewDebug.ExportedProperty(category = "padding")
2804    protected int mPaddingTop;
2805    /**
2806     * The bottom padding in pixels, that is the distance in pixels between the
2807     * bottom edge of this view and the bottom edge of its content.
2808     * {@hide}
2809     */
2810    @ViewDebug.ExportedProperty(category = "padding")
2811    protected int mPaddingBottom;
2812
2813    /**
2814     * The layout insets in pixels, that is the distance in pixels between the
2815     * visible edges of this view its bounds.
2816     */
2817    private Insets mLayoutInsets;
2818
2819    /**
2820     * Briefly describes the view and is primarily used for accessibility support.
2821     */
2822    private CharSequence mContentDescription;
2823
2824    /**
2825     * Specifies the id of a view for which this view serves as a label for
2826     * accessibility purposes.
2827     */
2828    private int mLabelForId = View.NO_ID;
2829
2830    /**
2831     * Predicate for matching labeled view id with its label for
2832     * accessibility purposes.
2833     */
2834    private MatchLabelForPredicate mMatchLabelForPredicate;
2835
2836    /**
2837     * Predicate for matching a view by its id.
2838     */
2839    private MatchIdPredicate mMatchIdPredicate;
2840
2841    /**
2842     * Cache the paddingRight set by the user to append to the scrollbar's size.
2843     *
2844     * @hide
2845     */
2846    @ViewDebug.ExportedProperty(category = "padding")
2847    protected int mUserPaddingRight;
2848
2849    /**
2850     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2851     *
2852     * @hide
2853     */
2854    @ViewDebug.ExportedProperty(category = "padding")
2855    protected int mUserPaddingBottom;
2856
2857    /**
2858     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2859     *
2860     * @hide
2861     */
2862    @ViewDebug.ExportedProperty(category = "padding")
2863    protected int mUserPaddingLeft;
2864
2865    /**
2866     * Cache the paddingStart set by the user to append to the scrollbar's size.
2867     *
2868     */
2869    @ViewDebug.ExportedProperty(category = "padding")
2870    int mUserPaddingStart;
2871
2872    /**
2873     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2874     *
2875     */
2876    @ViewDebug.ExportedProperty(category = "padding")
2877    int mUserPaddingEnd;
2878
2879    /**
2880     * Cache initial left padding.
2881     *
2882     * @hide
2883     */
2884    int mUserPaddingLeftInitial = 0;
2885
2886    /**
2887     * Cache initial right padding.
2888     *
2889     * @hide
2890     */
2891    int mUserPaddingRightInitial = 0;
2892
2893    /**
2894     * Default undefined padding
2895     */
2896    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2897
2898    /**
2899     * @hide
2900     */
2901    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2902    /**
2903     * @hide
2904     */
2905    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2906
2907    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
2908    private Drawable mBackground;
2909
2910    private int mBackgroundResource;
2911    private boolean mBackgroundSizeChanged;
2912
2913    static class ListenerInfo {
2914        /**
2915         * Listener used to dispatch focus change events.
2916         * This field should be made private, so it is hidden from the SDK.
2917         * {@hide}
2918         */
2919        protected OnFocusChangeListener mOnFocusChangeListener;
2920
2921        /**
2922         * Listeners for layout change events.
2923         */
2924        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2925
2926        /**
2927         * Listeners for attach events.
2928         */
2929        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2930
2931        /**
2932         * Listener used to dispatch click events.
2933         * This field should be made private, so it is hidden from the SDK.
2934         * {@hide}
2935         */
2936        public OnClickListener mOnClickListener;
2937
2938        /**
2939         * Listener used to dispatch long click events.
2940         * This field should be made private, so it is hidden from the SDK.
2941         * {@hide}
2942         */
2943        protected OnLongClickListener mOnLongClickListener;
2944
2945        /**
2946         * Listener used to build the context menu.
2947         * This field should be made private, so it is hidden from the SDK.
2948         * {@hide}
2949         */
2950        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2951
2952        private OnKeyListener mOnKeyListener;
2953
2954        private OnTouchListener mOnTouchListener;
2955
2956        private OnHoverListener mOnHoverListener;
2957
2958        private OnGenericMotionListener mOnGenericMotionListener;
2959
2960        private OnDragListener mOnDragListener;
2961
2962        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2963    }
2964
2965    ListenerInfo mListenerInfo;
2966
2967    /**
2968     * The application environment this view lives in.
2969     * This field should be made private, so it is hidden from the SDK.
2970     * {@hide}
2971     */
2972    protected Context mContext;
2973
2974    private final Resources mResources;
2975
2976    private ScrollabilityCache mScrollCache;
2977
2978    private int[] mDrawableState = null;
2979
2980    /**
2981     * Set to true when drawing cache is enabled and cannot be created.
2982     *
2983     * @hide
2984     */
2985    public boolean mCachingFailed;
2986
2987    private Bitmap mDrawingCache;
2988    private Bitmap mUnscaledDrawingCache;
2989    private HardwareLayer mHardwareLayer;
2990    DisplayList mDisplayList;
2991
2992    /**
2993     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2994     * the user may specify which view to go to next.
2995     */
2996    private int mNextFocusLeftId = View.NO_ID;
2997
2998    /**
2999     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3000     * the user may specify which view to go to next.
3001     */
3002    private int mNextFocusRightId = View.NO_ID;
3003
3004    /**
3005     * When this view has focus and the next focus is {@link #FOCUS_UP},
3006     * the user may specify which view to go to next.
3007     */
3008    private int mNextFocusUpId = View.NO_ID;
3009
3010    /**
3011     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3012     * the user may specify which view to go to next.
3013     */
3014    private int mNextFocusDownId = View.NO_ID;
3015
3016    /**
3017     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3018     * the user may specify which view to go to next.
3019     */
3020    int mNextFocusForwardId = View.NO_ID;
3021
3022    private CheckForLongPress mPendingCheckForLongPress;
3023    private CheckForTap mPendingCheckForTap = null;
3024    private PerformClick mPerformClick;
3025    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3026
3027    private UnsetPressedState mUnsetPressedState;
3028
3029    /**
3030     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3031     * up event while a long press is invoked as soon as the long press duration is reached, so
3032     * a long press could be performed before the tap is checked, in which case the tap's action
3033     * should not be invoked.
3034     */
3035    private boolean mHasPerformedLongPress;
3036
3037    /**
3038     * The minimum height of the view. We'll try our best to have the height
3039     * of this view to at least this amount.
3040     */
3041    @ViewDebug.ExportedProperty(category = "measurement")
3042    private int mMinHeight;
3043
3044    /**
3045     * The minimum width of the view. We'll try our best to have the width
3046     * of this view to at least this amount.
3047     */
3048    @ViewDebug.ExportedProperty(category = "measurement")
3049    private int mMinWidth;
3050
3051    /**
3052     * The delegate to handle touch events that are physically in this view
3053     * but should be handled by another view.
3054     */
3055    private TouchDelegate mTouchDelegate = null;
3056
3057    /**
3058     * Solid color to use as a background when creating the drawing cache. Enables
3059     * the cache to use 16 bit bitmaps instead of 32 bit.
3060     */
3061    private int mDrawingCacheBackgroundColor = 0;
3062
3063    /**
3064     * Special tree observer used when mAttachInfo is null.
3065     */
3066    private ViewTreeObserver mFloatingTreeObserver;
3067
3068    /**
3069     * Cache the touch slop from the context that created the view.
3070     */
3071    private int mTouchSlop;
3072
3073    /**
3074     * Object that handles automatic animation of view properties.
3075     */
3076    private ViewPropertyAnimator mAnimator = null;
3077
3078    /**
3079     * Flag indicating that a drag can cross window boundaries.  When
3080     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3081     * with this flag set, all visible applications will be able to participate
3082     * in the drag operation and receive the dragged content.
3083     *
3084     * @hide
3085     */
3086    public static final int DRAG_FLAG_GLOBAL = 1;
3087
3088    /**
3089     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3090     */
3091    private float mVerticalScrollFactor;
3092
3093    /**
3094     * Position of the vertical scroll bar.
3095     */
3096    private int mVerticalScrollbarPosition;
3097
3098    /**
3099     * Position the scroll bar at the default position as determined by the system.
3100     */
3101    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3102
3103    /**
3104     * Position the scroll bar along the left edge.
3105     */
3106    public static final int SCROLLBAR_POSITION_LEFT = 1;
3107
3108    /**
3109     * Position the scroll bar along the right edge.
3110     */
3111    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3112
3113    /**
3114     * Indicates that the view does not have a layer.
3115     *
3116     * @see #getLayerType()
3117     * @see #setLayerType(int, android.graphics.Paint)
3118     * @see #LAYER_TYPE_SOFTWARE
3119     * @see #LAYER_TYPE_HARDWARE
3120     */
3121    public static final int LAYER_TYPE_NONE = 0;
3122
3123    /**
3124     * <p>Indicates that the view has a software layer. A software layer is backed
3125     * by a bitmap and causes the view to be rendered using Android's software
3126     * rendering pipeline, even if hardware acceleration is enabled.</p>
3127     *
3128     * <p>Software layers have various usages:</p>
3129     * <p>When the application is not using hardware acceleration, a software layer
3130     * is useful to apply a specific color filter and/or blending mode and/or
3131     * translucency to a view and all its children.</p>
3132     * <p>When the application is using hardware acceleration, a software layer
3133     * is useful to render drawing primitives not supported by the hardware
3134     * accelerated pipeline. It can also be used to cache a complex view tree
3135     * into a texture and reduce the complexity of drawing operations. For instance,
3136     * when animating a complex view tree with a translation, a software layer can
3137     * be used to render the view tree only once.</p>
3138     * <p>Software layers should be avoided when the affected view tree updates
3139     * often. Every update will require to re-render the software layer, which can
3140     * potentially be slow (particularly when hardware acceleration is turned on
3141     * since the layer will have to be uploaded into a hardware texture after every
3142     * update.)</p>
3143     *
3144     * @see #getLayerType()
3145     * @see #setLayerType(int, android.graphics.Paint)
3146     * @see #LAYER_TYPE_NONE
3147     * @see #LAYER_TYPE_HARDWARE
3148     */
3149    public static final int LAYER_TYPE_SOFTWARE = 1;
3150
3151    /**
3152     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3153     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3154     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3155     * rendering pipeline, but only if hardware acceleration is turned on for the
3156     * view hierarchy. When hardware acceleration is turned off, hardware layers
3157     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3158     *
3159     * <p>A hardware layer is useful to apply a specific color filter and/or
3160     * blending mode and/or translucency to a view and all its children.</p>
3161     * <p>A hardware layer can be used to cache a complex view tree into a
3162     * texture and reduce the complexity of drawing operations. For instance,
3163     * when animating a complex view tree with a translation, a hardware layer can
3164     * be used to render the view tree only once.</p>
3165     * <p>A hardware layer can also be used to increase the rendering quality when
3166     * rotation transformations are applied on a view. It can also be used to
3167     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3168     *
3169     * @see #getLayerType()
3170     * @see #setLayerType(int, android.graphics.Paint)
3171     * @see #LAYER_TYPE_NONE
3172     * @see #LAYER_TYPE_SOFTWARE
3173     */
3174    public static final int LAYER_TYPE_HARDWARE = 2;
3175
3176    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3177            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3178            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3179            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3180    })
3181    int mLayerType = LAYER_TYPE_NONE;
3182    Paint mLayerPaint;
3183    Rect mLocalDirtyRect;
3184
3185    /**
3186     * Set to true when the view is sending hover accessibility events because it
3187     * is the innermost hovered view.
3188     */
3189    private boolean mSendingHoverAccessibilityEvents;
3190
3191    /**
3192     * Delegate for injecting accessibility functionality.
3193     */
3194    AccessibilityDelegate mAccessibilityDelegate;
3195
3196    /**
3197     * Consistency verifier for debugging purposes.
3198     * @hide
3199     */
3200    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3201            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3202                    new InputEventConsistencyVerifier(this, 0) : null;
3203
3204    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3205
3206    /**
3207     * Simple constructor to use when creating a view from code.
3208     *
3209     * @param context The Context the view is running in, through which it can
3210     *        access the current theme, resources, etc.
3211     */
3212    public View(Context context) {
3213        mContext = context;
3214        mResources = context != null ? context.getResources() : null;
3215        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3216        // Set layout and text direction defaults
3217        mPrivateFlags2 =
3218                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3219                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3220                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3221                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3222                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3223                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3224        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3225        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3226        mUserPaddingStart = UNDEFINED_PADDING;
3227        mUserPaddingEnd = UNDEFINED_PADDING;
3228    }
3229
3230    /**
3231     * Constructor that is called when inflating a view from XML. This is called
3232     * when a view is being constructed from an XML file, supplying attributes
3233     * that were specified in the XML file. This version uses a default style of
3234     * 0, so the only attribute values applied are those in the Context's Theme
3235     * and the given AttributeSet.
3236     *
3237     * <p>
3238     * The method onFinishInflate() will be called after all children have been
3239     * added.
3240     *
3241     * @param context The Context the view is running in, through which it can
3242     *        access the current theme, resources, etc.
3243     * @param attrs The attributes of the XML tag that is inflating the view.
3244     * @see #View(Context, AttributeSet, int)
3245     */
3246    public View(Context context, AttributeSet attrs) {
3247        this(context, attrs, 0);
3248    }
3249
3250    /**
3251     * Perform inflation from XML and apply a class-specific base style. This
3252     * constructor of View allows subclasses to use their own base style when
3253     * they are inflating. For example, a Button class's constructor would call
3254     * this version of the super class constructor and supply
3255     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3256     * the theme's button style to modify all of the base view attributes (in
3257     * particular its background) as well as the Button class's attributes.
3258     *
3259     * @param context The Context the view is running in, through which it can
3260     *        access the current theme, resources, etc.
3261     * @param attrs The attributes of the XML tag that is inflating the view.
3262     * @param defStyle The default style to apply to this view. If 0, no style
3263     *        will be applied (beyond what is included in the theme). This may
3264     *        either be an attribute resource, whose value will be retrieved
3265     *        from the current theme, or an explicit style resource.
3266     * @see #View(Context, AttributeSet)
3267     */
3268    public View(Context context, AttributeSet attrs, int defStyle) {
3269        this(context);
3270
3271        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3272                defStyle, 0);
3273
3274        Drawable background = null;
3275
3276        int leftPadding = -1;
3277        int topPadding = -1;
3278        int rightPadding = -1;
3279        int bottomPadding = -1;
3280        int startPadding = UNDEFINED_PADDING;
3281        int endPadding = UNDEFINED_PADDING;
3282
3283        int padding = -1;
3284
3285        int viewFlagValues = 0;
3286        int viewFlagMasks = 0;
3287
3288        boolean setScrollContainer = false;
3289
3290        int x = 0;
3291        int y = 0;
3292
3293        float tx = 0;
3294        float ty = 0;
3295        float rotation = 0;
3296        float rotationX = 0;
3297        float rotationY = 0;
3298        float sx = 1f;
3299        float sy = 1f;
3300        boolean transformSet = false;
3301
3302        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3303        int overScrollMode = mOverScrollMode;
3304        boolean initializeScrollbars = false;
3305
3306        boolean leftPaddingDefined = false;
3307        boolean rightPaddingDefined = false;
3308        boolean startPaddingDefined = false;
3309        boolean endPaddingDefined = false;
3310
3311        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3312
3313        final int N = a.getIndexCount();
3314        for (int i = 0; i < N; i++) {
3315            int attr = a.getIndex(i);
3316            switch (attr) {
3317                case com.android.internal.R.styleable.View_background:
3318                    background = a.getDrawable(attr);
3319                    break;
3320                case com.android.internal.R.styleable.View_padding:
3321                    padding = a.getDimensionPixelSize(attr, -1);
3322                    mUserPaddingLeftInitial = padding;
3323                    mUserPaddingRightInitial = padding;
3324                    leftPaddingDefined = true;
3325                    rightPaddingDefined = true;
3326                    break;
3327                 case com.android.internal.R.styleable.View_paddingLeft:
3328                    leftPadding = a.getDimensionPixelSize(attr, -1);
3329                    mUserPaddingLeftInitial = leftPadding;
3330                    leftPaddingDefined = true;
3331                    break;
3332                case com.android.internal.R.styleable.View_paddingTop:
3333                    topPadding = a.getDimensionPixelSize(attr, -1);
3334                    break;
3335                case com.android.internal.R.styleable.View_paddingRight:
3336                    rightPadding = a.getDimensionPixelSize(attr, -1);
3337                    mUserPaddingRightInitial = rightPadding;
3338                    rightPaddingDefined = true;
3339                    break;
3340                case com.android.internal.R.styleable.View_paddingBottom:
3341                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3342                    break;
3343                case com.android.internal.R.styleable.View_paddingStart:
3344                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3345                    startPaddingDefined = true;
3346                    break;
3347                case com.android.internal.R.styleable.View_paddingEnd:
3348                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3349                    endPaddingDefined = true;
3350                    break;
3351                case com.android.internal.R.styleable.View_scrollX:
3352                    x = a.getDimensionPixelOffset(attr, 0);
3353                    break;
3354                case com.android.internal.R.styleable.View_scrollY:
3355                    y = a.getDimensionPixelOffset(attr, 0);
3356                    break;
3357                case com.android.internal.R.styleable.View_alpha:
3358                    setAlpha(a.getFloat(attr, 1f));
3359                    break;
3360                case com.android.internal.R.styleable.View_transformPivotX:
3361                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3362                    break;
3363                case com.android.internal.R.styleable.View_transformPivotY:
3364                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3365                    break;
3366                case com.android.internal.R.styleable.View_translationX:
3367                    tx = a.getDimensionPixelOffset(attr, 0);
3368                    transformSet = true;
3369                    break;
3370                case com.android.internal.R.styleable.View_translationY:
3371                    ty = a.getDimensionPixelOffset(attr, 0);
3372                    transformSet = true;
3373                    break;
3374                case com.android.internal.R.styleable.View_rotation:
3375                    rotation = a.getFloat(attr, 0);
3376                    transformSet = true;
3377                    break;
3378                case com.android.internal.R.styleable.View_rotationX:
3379                    rotationX = a.getFloat(attr, 0);
3380                    transformSet = true;
3381                    break;
3382                case com.android.internal.R.styleable.View_rotationY:
3383                    rotationY = a.getFloat(attr, 0);
3384                    transformSet = true;
3385                    break;
3386                case com.android.internal.R.styleable.View_scaleX:
3387                    sx = a.getFloat(attr, 1f);
3388                    transformSet = true;
3389                    break;
3390                case com.android.internal.R.styleable.View_scaleY:
3391                    sy = a.getFloat(attr, 1f);
3392                    transformSet = true;
3393                    break;
3394                case com.android.internal.R.styleable.View_id:
3395                    mID = a.getResourceId(attr, NO_ID);
3396                    break;
3397                case com.android.internal.R.styleable.View_tag:
3398                    mTag = a.getText(attr);
3399                    break;
3400                case com.android.internal.R.styleable.View_fitsSystemWindows:
3401                    if (a.getBoolean(attr, false)) {
3402                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3403                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3404                    }
3405                    break;
3406                case com.android.internal.R.styleable.View_focusable:
3407                    if (a.getBoolean(attr, false)) {
3408                        viewFlagValues |= FOCUSABLE;
3409                        viewFlagMasks |= FOCUSABLE_MASK;
3410                    }
3411                    break;
3412                case com.android.internal.R.styleable.View_focusableInTouchMode:
3413                    if (a.getBoolean(attr, false)) {
3414                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3415                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3416                    }
3417                    break;
3418                case com.android.internal.R.styleable.View_clickable:
3419                    if (a.getBoolean(attr, false)) {
3420                        viewFlagValues |= CLICKABLE;
3421                        viewFlagMasks |= CLICKABLE;
3422                    }
3423                    break;
3424                case com.android.internal.R.styleable.View_longClickable:
3425                    if (a.getBoolean(attr, false)) {
3426                        viewFlagValues |= LONG_CLICKABLE;
3427                        viewFlagMasks |= LONG_CLICKABLE;
3428                    }
3429                    break;
3430                case com.android.internal.R.styleable.View_saveEnabled:
3431                    if (!a.getBoolean(attr, true)) {
3432                        viewFlagValues |= SAVE_DISABLED;
3433                        viewFlagMasks |= SAVE_DISABLED_MASK;
3434                    }
3435                    break;
3436                case com.android.internal.R.styleable.View_duplicateParentState:
3437                    if (a.getBoolean(attr, false)) {
3438                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3439                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3440                    }
3441                    break;
3442                case com.android.internal.R.styleable.View_visibility:
3443                    final int visibility = a.getInt(attr, 0);
3444                    if (visibility != 0) {
3445                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3446                        viewFlagMasks |= VISIBILITY_MASK;
3447                    }
3448                    break;
3449                case com.android.internal.R.styleable.View_layoutDirection:
3450                    // Clear any layout direction flags (included resolved bits) already set
3451                    mPrivateFlags2 &=
3452                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3453                    // Set the layout direction flags depending on the value of the attribute
3454                    final int layoutDirection = a.getInt(attr, -1);
3455                    final int value = (layoutDirection != -1) ?
3456                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3457                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3458                    break;
3459                case com.android.internal.R.styleable.View_drawingCacheQuality:
3460                    final int cacheQuality = a.getInt(attr, 0);
3461                    if (cacheQuality != 0) {
3462                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3463                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3464                    }
3465                    break;
3466                case com.android.internal.R.styleable.View_contentDescription:
3467                    setContentDescription(a.getString(attr));
3468                    break;
3469                case com.android.internal.R.styleable.View_labelFor:
3470                    setLabelFor(a.getResourceId(attr, NO_ID));
3471                    break;
3472                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3473                    if (!a.getBoolean(attr, true)) {
3474                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3475                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3476                    }
3477                    break;
3478                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3479                    if (!a.getBoolean(attr, true)) {
3480                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3481                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3482                    }
3483                    break;
3484                case R.styleable.View_scrollbars:
3485                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3486                    if (scrollbars != SCROLLBARS_NONE) {
3487                        viewFlagValues |= scrollbars;
3488                        viewFlagMasks |= SCROLLBARS_MASK;
3489                        initializeScrollbars = true;
3490                    }
3491                    break;
3492                //noinspection deprecation
3493                case R.styleable.View_fadingEdge:
3494                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3495                        // Ignore the attribute starting with ICS
3496                        break;
3497                    }
3498                    // With builds < ICS, fall through and apply fading edges
3499                case R.styleable.View_requiresFadingEdge:
3500                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3501                    if (fadingEdge != FADING_EDGE_NONE) {
3502                        viewFlagValues |= fadingEdge;
3503                        viewFlagMasks |= FADING_EDGE_MASK;
3504                        initializeFadingEdge(a);
3505                    }
3506                    break;
3507                case R.styleable.View_scrollbarStyle:
3508                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3509                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3510                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3511                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3512                    }
3513                    break;
3514                case R.styleable.View_isScrollContainer:
3515                    setScrollContainer = true;
3516                    if (a.getBoolean(attr, false)) {
3517                        setScrollContainer(true);
3518                    }
3519                    break;
3520                case com.android.internal.R.styleable.View_keepScreenOn:
3521                    if (a.getBoolean(attr, false)) {
3522                        viewFlagValues |= KEEP_SCREEN_ON;
3523                        viewFlagMasks |= KEEP_SCREEN_ON;
3524                    }
3525                    break;
3526                case R.styleable.View_filterTouchesWhenObscured:
3527                    if (a.getBoolean(attr, false)) {
3528                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3529                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3530                    }
3531                    break;
3532                case R.styleable.View_nextFocusLeft:
3533                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3534                    break;
3535                case R.styleable.View_nextFocusRight:
3536                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3537                    break;
3538                case R.styleable.View_nextFocusUp:
3539                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3540                    break;
3541                case R.styleable.View_nextFocusDown:
3542                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3543                    break;
3544                case R.styleable.View_nextFocusForward:
3545                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3546                    break;
3547                case R.styleable.View_minWidth:
3548                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3549                    break;
3550                case R.styleable.View_minHeight:
3551                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3552                    break;
3553                case R.styleable.View_onClick:
3554                    if (context.isRestricted()) {
3555                        throw new IllegalStateException("The android:onClick attribute cannot "
3556                                + "be used within a restricted context");
3557                    }
3558
3559                    final String handlerName = a.getString(attr);
3560                    if (handlerName != null) {
3561                        setOnClickListener(new OnClickListener() {
3562                            private Method mHandler;
3563
3564                            public void onClick(View v) {
3565                                if (mHandler == null) {
3566                                    try {
3567                                        mHandler = getContext().getClass().getMethod(handlerName,
3568                                                View.class);
3569                                    } catch (NoSuchMethodException e) {
3570                                        int id = getId();
3571                                        String idText = id == NO_ID ? "" : " with id '"
3572                                                + getContext().getResources().getResourceEntryName(
3573                                                    id) + "'";
3574                                        throw new IllegalStateException("Could not find a method " +
3575                                                handlerName + "(View) in the activity "
3576                                                + getContext().getClass() + " for onClick handler"
3577                                                + " on view " + View.this.getClass() + idText, e);
3578                                    }
3579                                }
3580
3581                                try {
3582                                    mHandler.invoke(getContext(), View.this);
3583                                } catch (IllegalAccessException e) {
3584                                    throw new IllegalStateException("Could not execute non "
3585                                            + "public method of the activity", e);
3586                                } catch (InvocationTargetException e) {
3587                                    throw new IllegalStateException("Could not execute "
3588                                            + "method of the activity", e);
3589                                }
3590                            }
3591                        });
3592                    }
3593                    break;
3594                case R.styleable.View_overScrollMode:
3595                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3596                    break;
3597                case R.styleable.View_verticalScrollbarPosition:
3598                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3599                    break;
3600                case R.styleable.View_layerType:
3601                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3602                    break;
3603                case R.styleable.View_textDirection:
3604                    // Clear any text direction flag already set
3605                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3606                    // Set the text direction flags depending on the value of the attribute
3607                    final int textDirection = a.getInt(attr, -1);
3608                    if (textDirection != -1) {
3609                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3610                    }
3611                    break;
3612                case R.styleable.View_textAlignment:
3613                    // Clear any text alignment flag already set
3614                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3615                    // Set the text alignment flag depending on the value of the attribute
3616                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3617                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3618                    break;
3619                case R.styleable.View_importantForAccessibility:
3620                    setImportantForAccessibility(a.getInt(attr,
3621                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3622                    break;
3623            }
3624        }
3625
3626        setOverScrollMode(overScrollMode);
3627
3628        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3629        // the resolved layout direction). Those cached values will be used later during padding
3630        // resolution.
3631        mUserPaddingStart = startPadding;
3632        mUserPaddingEnd = endPadding;
3633
3634        if (background != null) {
3635            setBackground(background);
3636        }
3637
3638        if (padding >= 0) {
3639            leftPadding = padding;
3640            topPadding = padding;
3641            rightPadding = padding;
3642            bottomPadding = padding;
3643            mUserPaddingLeftInitial = padding;
3644            mUserPaddingRightInitial = padding;
3645        }
3646
3647        if (isRtlCompatibilityMode()) {
3648            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3649            // left / right padding are used if defined (meaning here nothing to do). If they are not
3650            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3651            // start / end and resolve them as left / right (layout direction is not taken into account).
3652            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3653            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3654            // defined.
3655            if (!leftPaddingDefined && startPaddingDefined) {
3656                leftPadding = startPadding;
3657            }
3658            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3659            if (!rightPaddingDefined && endPaddingDefined) {
3660                rightPadding = endPadding;
3661            }
3662            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3663        } else {
3664            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3665            // values defined. Otherwise, left /right values are used.
3666            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3667            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3668            // defined.
3669            if (leftPaddingDefined) {
3670                mUserPaddingLeftInitial = leftPadding;
3671            }
3672            if (rightPaddingDefined) {
3673                mUserPaddingRightInitial = rightPadding;
3674            }
3675        }
3676
3677        internalSetPadding(
3678                mUserPaddingLeftInitial,
3679                topPadding >= 0 ? topPadding : mPaddingTop,
3680                mUserPaddingRightInitial,
3681                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3682
3683        if (viewFlagMasks != 0) {
3684            setFlags(viewFlagValues, viewFlagMasks);
3685        }
3686
3687        if (initializeScrollbars) {
3688            initializeScrollbars(a);
3689        }
3690
3691        a.recycle();
3692
3693        // Needs to be called after mViewFlags is set
3694        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3695            recomputePadding();
3696        }
3697
3698        if (x != 0 || y != 0) {
3699            scrollTo(x, y);
3700        }
3701
3702        if (transformSet) {
3703            setTranslationX(tx);
3704            setTranslationY(ty);
3705            setRotation(rotation);
3706            setRotationX(rotationX);
3707            setRotationY(rotationY);
3708            setScaleX(sx);
3709            setScaleY(sy);
3710        }
3711
3712        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3713            setScrollContainer(true);
3714        }
3715
3716        computeOpaqueFlags();
3717    }
3718
3719    /**
3720     * Non-public constructor for use in testing
3721     */
3722    View() {
3723        mResources = null;
3724    }
3725
3726    public String toString() {
3727        StringBuilder out = new StringBuilder(128);
3728        out.append(getClass().getName());
3729        out.append('{');
3730        out.append(Integer.toHexString(System.identityHashCode(this)));
3731        out.append(' ');
3732        switch (mViewFlags&VISIBILITY_MASK) {
3733            case VISIBLE: out.append('V'); break;
3734            case INVISIBLE: out.append('I'); break;
3735            case GONE: out.append('G'); break;
3736            default: out.append('.'); break;
3737        }
3738        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3739        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3740        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3741        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3742        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3743        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3744        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3745        out.append(' ');
3746        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3747        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3748        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3749        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3750            out.append('p');
3751        } else {
3752            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3753        }
3754        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3755        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3756        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3757        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3758        out.append(' ');
3759        out.append(mLeft);
3760        out.append(',');
3761        out.append(mTop);
3762        out.append('-');
3763        out.append(mRight);
3764        out.append(',');
3765        out.append(mBottom);
3766        final int id = getId();
3767        if (id != NO_ID) {
3768            out.append(" #");
3769            out.append(Integer.toHexString(id));
3770            final Resources r = mResources;
3771            if (id != 0 && r != null) {
3772                try {
3773                    String pkgname;
3774                    switch (id&0xff000000) {
3775                        case 0x7f000000:
3776                            pkgname="app";
3777                            break;
3778                        case 0x01000000:
3779                            pkgname="android";
3780                            break;
3781                        default:
3782                            pkgname = r.getResourcePackageName(id);
3783                            break;
3784                    }
3785                    String typename = r.getResourceTypeName(id);
3786                    String entryname = r.getResourceEntryName(id);
3787                    out.append(" ");
3788                    out.append(pkgname);
3789                    out.append(":");
3790                    out.append(typename);
3791                    out.append("/");
3792                    out.append(entryname);
3793                } catch (Resources.NotFoundException e) {
3794                }
3795            }
3796        }
3797        out.append("}");
3798        return out.toString();
3799    }
3800
3801    /**
3802     * <p>
3803     * Initializes the fading edges from a given set of styled attributes. This
3804     * method should be called by subclasses that need fading edges and when an
3805     * instance of these subclasses is created programmatically rather than
3806     * being inflated from XML. This method is automatically called when the XML
3807     * is inflated.
3808     * </p>
3809     *
3810     * @param a the styled attributes set to initialize the fading edges from
3811     */
3812    protected void initializeFadingEdge(TypedArray a) {
3813        initScrollCache();
3814
3815        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3816                R.styleable.View_fadingEdgeLength,
3817                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3818    }
3819
3820    /**
3821     * Returns the size of the vertical faded edges used to indicate that more
3822     * content in this view is visible.
3823     *
3824     * @return The size in pixels of the vertical faded edge or 0 if vertical
3825     *         faded edges are not enabled for this view.
3826     * @attr ref android.R.styleable#View_fadingEdgeLength
3827     */
3828    public int getVerticalFadingEdgeLength() {
3829        if (isVerticalFadingEdgeEnabled()) {
3830            ScrollabilityCache cache = mScrollCache;
3831            if (cache != null) {
3832                return cache.fadingEdgeLength;
3833            }
3834        }
3835        return 0;
3836    }
3837
3838    /**
3839     * Set the size of the faded edge used to indicate that more content in this
3840     * view is available.  Will not change whether the fading edge is enabled; use
3841     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3842     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3843     * for the vertical or horizontal fading edges.
3844     *
3845     * @param length The size in pixels of the faded edge used to indicate that more
3846     *        content in this view is visible.
3847     */
3848    public void setFadingEdgeLength(int length) {
3849        initScrollCache();
3850        mScrollCache.fadingEdgeLength = length;
3851    }
3852
3853    /**
3854     * Returns the size of the horizontal faded edges used to indicate that more
3855     * content in this view is visible.
3856     *
3857     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3858     *         faded edges are not enabled for this view.
3859     * @attr ref android.R.styleable#View_fadingEdgeLength
3860     */
3861    public int getHorizontalFadingEdgeLength() {
3862        if (isHorizontalFadingEdgeEnabled()) {
3863            ScrollabilityCache cache = mScrollCache;
3864            if (cache != null) {
3865                return cache.fadingEdgeLength;
3866            }
3867        }
3868        return 0;
3869    }
3870
3871    /**
3872     * Returns the width of the vertical scrollbar.
3873     *
3874     * @return The width in pixels of the vertical scrollbar or 0 if there
3875     *         is no vertical scrollbar.
3876     */
3877    public int getVerticalScrollbarWidth() {
3878        ScrollabilityCache cache = mScrollCache;
3879        if (cache != null) {
3880            ScrollBarDrawable scrollBar = cache.scrollBar;
3881            if (scrollBar != null) {
3882                int size = scrollBar.getSize(true);
3883                if (size <= 0) {
3884                    size = cache.scrollBarSize;
3885                }
3886                return size;
3887            }
3888            return 0;
3889        }
3890        return 0;
3891    }
3892
3893    /**
3894     * Returns the height of the horizontal scrollbar.
3895     *
3896     * @return The height in pixels of the horizontal scrollbar or 0 if
3897     *         there is no horizontal scrollbar.
3898     */
3899    protected int getHorizontalScrollbarHeight() {
3900        ScrollabilityCache cache = mScrollCache;
3901        if (cache != null) {
3902            ScrollBarDrawable scrollBar = cache.scrollBar;
3903            if (scrollBar != null) {
3904                int size = scrollBar.getSize(false);
3905                if (size <= 0) {
3906                    size = cache.scrollBarSize;
3907                }
3908                return size;
3909            }
3910            return 0;
3911        }
3912        return 0;
3913    }
3914
3915    /**
3916     * <p>
3917     * Initializes the scrollbars from a given set of styled attributes. This
3918     * method should be called by subclasses that need scrollbars and when an
3919     * instance of these subclasses is created programmatically rather than
3920     * being inflated from XML. This method is automatically called when the XML
3921     * is inflated.
3922     * </p>
3923     *
3924     * @param a the styled attributes set to initialize the scrollbars from
3925     */
3926    protected void initializeScrollbars(TypedArray a) {
3927        initScrollCache();
3928
3929        final ScrollabilityCache scrollabilityCache = mScrollCache;
3930
3931        if (scrollabilityCache.scrollBar == null) {
3932            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3933        }
3934
3935        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3936
3937        if (!fadeScrollbars) {
3938            scrollabilityCache.state = ScrollabilityCache.ON;
3939        }
3940        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3941
3942
3943        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3944                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3945                        .getScrollBarFadeDuration());
3946        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3947                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3948                ViewConfiguration.getScrollDefaultDelay());
3949
3950
3951        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3952                com.android.internal.R.styleable.View_scrollbarSize,
3953                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3954
3955        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3956        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3957
3958        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3959        if (thumb != null) {
3960            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3961        }
3962
3963        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3964                false);
3965        if (alwaysDraw) {
3966            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3967        }
3968
3969        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3970        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3971
3972        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3973        if (thumb != null) {
3974            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3975        }
3976
3977        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3978                false);
3979        if (alwaysDraw) {
3980            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3981        }
3982
3983        // Apply layout direction to the new Drawables if needed
3984        final int layoutDirection = getLayoutDirection();
3985        if (track != null) {
3986            track.setLayoutDirection(layoutDirection);
3987        }
3988        if (thumb != null) {
3989            thumb.setLayoutDirection(layoutDirection);
3990        }
3991
3992        // Re-apply user/background padding so that scrollbar(s) get added
3993        resolvePadding();
3994    }
3995
3996    /**
3997     * <p>
3998     * Initalizes the scrollability cache if necessary.
3999     * </p>
4000     */
4001    private void initScrollCache() {
4002        if (mScrollCache == null) {
4003            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4004        }
4005    }
4006
4007    private ScrollabilityCache getScrollCache() {
4008        initScrollCache();
4009        return mScrollCache;
4010    }
4011
4012    /**
4013     * Set the position of the vertical scroll bar. Should be one of
4014     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4015     * {@link #SCROLLBAR_POSITION_RIGHT}.
4016     *
4017     * @param position Where the vertical scroll bar should be positioned.
4018     */
4019    public void setVerticalScrollbarPosition(int position) {
4020        if (mVerticalScrollbarPosition != position) {
4021            mVerticalScrollbarPosition = position;
4022            computeOpaqueFlags();
4023            resolvePadding();
4024        }
4025    }
4026
4027    /**
4028     * @return The position where the vertical scroll bar will show, if applicable.
4029     * @see #setVerticalScrollbarPosition(int)
4030     */
4031    public int getVerticalScrollbarPosition() {
4032        return mVerticalScrollbarPosition;
4033    }
4034
4035    ListenerInfo getListenerInfo() {
4036        if (mListenerInfo != null) {
4037            return mListenerInfo;
4038        }
4039        mListenerInfo = new ListenerInfo();
4040        return mListenerInfo;
4041    }
4042
4043    /**
4044     * Register a callback to be invoked when focus of this view changed.
4045     *
4046     * @param l The callback that will run.
4047     */
4048    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4049        getListenerInfo().mOnFocusChangeListener = l;
4050    }
4051
4052    /**
4053     * Add a listener that will be called when the bounds of the view change due to
4054     * layout processing.
4055     *
4056     * @param listener The listener that will be called when layout bounds change.
4057     */
4058    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4059        ListenerInfo li = getListenerInfo();
4060        if (li.mOnLayoutChangeListeners == null) {
4061            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4062        }
4063        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4064            li.mOnLayoutChangeListeners.add(listener);
4065        }
4066    }
4067
4068    /**
4069     * Remove a listener for layout changes.
4070     *
4071     * @param listener The listener for layout bounds change.
4072     */
4073    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4074        ListenerInfo li = mListenerInfo;
4075        if (li == null || li.mOnLayoutChangeListeners == null) {
4076            return;
4077        }
4078        li.mOnLayoutChangeListeners.remove(listener);
4079    }
4080
4081    /**
4082     * Add a listener for attach state changes.
4083     *
4084     * This listener will be called whenever this view is attached or detached
4085     * from a window. Remove the listener using
4086     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4087     *
4088     * @param listener Listener to attach
4089     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4090     */
4091    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4092        ListenerInfo li = getListenerInfo();
4093        if (li.mOnAttachStateChangeListeners == null) {
4094            li.mOnAttachStateChangeListeners
4095                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4096        }
4097        li.mOnAttachStateChangeListeners.add(listener);
4098    }
4099
4100    /**
4101     * Remove a listener for attach state changes. The listener will receive no further
4102     * notification of window attach/detach events.
4103     *
4104     * @param listener Listener to remove
4105     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4106     */
4107    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4108        ListenerInfo li = mListenerInfo;
4109        if (li == null || li.mOnAttachStateChangeListeners == null) {
4110            return;
4111        }
4112        li.mOnAttachStateChangeListeners.remove(listener);
4113    }
4114
4115    /**
4116     * Returns the focus-change callback registered for this view.
4117     *
4118     * @return The callback, or null if one is not registered.
4119     */
4120    public OnFocusChangeListener getOnFocusChangeListener() {
4121        ListenerInfo li = mListenerInfo;
4122        return li != null ? li.mOnFocusChangeListener : null;
4123    }
4124
4125    /**
4126     * Register a callback to be invoked when this view is clicked. If this view is not
4127     * clickable, it becomes clickable.
4128     *
4129     * @param l The callback that will run
4130     *
4131     * @see #setClickable(boolean)
4132     */
4133    public void setOnClickListener(OnClickListener l) {
4134        if (!isClickable()) {
4135            setClickable(true);
4136        }
4137        getListenerInfo().mOnClickListener = l;
4138    }
4139
4140    /**
4141     * Return whether this view has an attached OnClickListener.  Returns
4142     * true if there is a listener, false if there is none.
4143     */
4144    public boolean hasOnClickListeners() {
4145        ListenerInfo li = mListenerInfo;
4146        return (li != null && li.mOnClickListener != null);
4147    }
4148
4149    /**
4150     * Register a callback to be invoked when this view is clicked and held. If this view is not
4151     * long clickable, it becomes long clickable.
4152     *
4153     * @param l The callback that will run
4154     *
4155     * @see #setLongClickable(boolean)
4156     */
4157    public void setOnLongClickListener(OnLongClickListener l) {
4158        if (!isLongClickable()) {
4159            setLongClickable(true);
4160        }
4161        getListenerInfo().mOnLongClickListener = l;
4162    }
4163
4164    /**
4165     * Register a callback to be invoked when the context menu for this view is
4166     * being built. If this view is not long clickable, it becomes long clickable.
4167     *
4168     * @param l The callback that will run
4169     *
4170     */
4171    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4172        if (!isLongClickable()) {
4173            setLongClickable(true);
4174        }
4175        getListenerInfo().mOnCreateContextMenuListener = l;
4176    }
4177
4178    /**
4179     * Call this view's OnClickListener, if it is defined.  Performs all normal
4180     * actions associated with clicking: reporting accessibility event, playing
4181     * a sound, etc.
4182     *
4183     * @return True there was an assigned OnClickListener that was called, false
4184     *         otherwise is returned.
4185     */
4186    public boolean performClick() {
4187        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4188
4189        ListenerInfo li = mListenerInfo;
4190        if (li != null && li.mOnClickListener != null) {
4191            playSoundEffect(SoundEffectConstants.CLICK);
4192            li.mOnClickListener.onClick(this);
4193            return true;
4194        }
4195
4196        return false;
4197    }
4198
4199    /**
4200     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4201     * this only calls the listener, and does not do any associated clicking
4202     * actions like reporting an accessibility event.
4203     *
4204     * @return True there was an assigned OnClickListener that was called, false
4205     *         otherwise is returned.
4206     */
4207    public boolean callOnClick() {
4208        ListenerInfo li = mListenerInfo;
4209        if (li != null && li.mOnClickListener != null) {
4210            li.mOnClickListener.onClick(this);
4211            return true;
4212        }
4213        return false;
4214    }
4215
4216    /**
4217     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4218     * OnLongClickListener did not consume the event.
4219     *
4220     * @return True if one of the above receivers consumed the event, false otherwise.
4221     */
4222    public boolean performLongClick() {
4223        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4224
4225        boolean handled = false;
4226        ListenerInfo li = mListenerInfo;
4227        if (li != null && li.mOnLongClickListener != null) {
4228            handled = li.mOnLongClickListener.onLongClick(View.this);
4229        }
4230        if (!handled) {
4231            handled = showContextMenu();
4232        }
4233        if (handled) {
4234            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4235        }
4236        return handled;
4237    }
4238
4239    /**
4240     * Performs button-related actions during a touch down event.
4241     *
4242     * @param event The event.
4243     * @return True if the down was consumed.
4244     *
4245     * @hide
4246     */
4247    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4248        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4249            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4250                return true;
4251            }
4252        }
4253        return false;
4254    }
4255
4256    /**
4257     * Bring up the context menu for this view.
4258     *
4259     * @return Whether a context menu was displayed.
4260     */
4261    public boolean showContextMenu() {
4262        return getParent().showContextMenuForChild(this);
4263    }
4264
4265    /**
4266     * Bring up the context menu for this view, referring to the item under the specified point.
4267     *
4268     * @param x The referenced x coordinate.
4269     * @param y The referenced y coordinate.
4270     * @param metaState The keyboard modifiers that were pressed.
4271     * @return Whether a context menu was displayed.
4272     *
4273     * @hide
4274     */
4275    public boolean showContextMenu(float x, float y, int metaState) {
4276        return showContextMenu();
4277    }
4278
4279    /**
4280     * Start an action mode.
4281     *
4282     * @param callback Callback that will control the lifecycle of the action mode
4283     * @return The new action mode if it is started, null otherwise
4284     *
4285     * @see ActionMode
4286     */
4287    public ActionMode startActionMode(ActionMode.Callback callback) {
4288        ViewParent parent = getParent();
4289        if (parent == null) return null;
4290        return parent.startActionModeForChild(this, callback);
4291    }
4292
4293    /**
4294     * Register a callback to be invoked when a hardware key is pressed in this view.
4295     * Key presses in software input methods will generally not trigger the methods of
4296     * this listener.
4297     * @param l the key listener to attach to this view
4298     */
4299    public void setOnKeyListener(OnKeyListener l) {
4300        getListenerInfo().mOnKeyListener = l;
4301    }
4302
4303    /**
4304     * Register a callback to be invoked when a touch event is sent to this view.
4305     * @param l the touch listener to attach to this view
4306     */
4307    public void setOnTouchListener(OnTouchListener l) {
4308        getListenerInfo().mOnTouchListener = l;
4309    }
4310
4311    /**
4312     * Register a callback to be invoked when a generic motion event is sent to this view.
4313     * @param l the generic motion listener to attach to this view
4314     */
4315    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4316        getListenerInfo().mOnGenericMotionListener = l;
4317    }
4318
4319    /**
4320     * Register a callback to be invoked when a hover event is sent to this view.
4321     * @param l the hover listener to attach to this view
4322     */
4323    public void setOnHoverListener(OnHoverListener l) {
4324        getListenerInfo().mOnHoverListener = l;
4325    }
4326
4327    /**
4328     * Register a drag event listener callback object for this View. The parameter is
4329     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4330     * View, the system calls the
4331     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4332     * @param l An implementation of {@link android.view.View.OnDragListener}.
4333     */
4334    public void setOnDragListener(OnDragListener l) {
4335        getListenerInfo().mOnDragListener = l;
4336    }
4337
4338    /**
4339     * Give this view focus. This will cause
4340     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4341     *
4342     * Note: this does not check whether this {@link View} should get focus, it just
4343     * gives it focus no matter what.  It should only be called internally by framework
4344     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4345     *
4346     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4347     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4348     *        focus moved when requestFocus() is called. It may not always
4349     *        apply, in which case use the default View.FOCUS_DOWN.
4350     * @param previouslyFocusedRect The rectangle of the view that had focus
4351     *        prior in this View's coordinate system.
4352     */
4353    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4354        if (DBG) {
4355            System.out.println(this + " requestFocus()");
4356        }
4357
4358        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4359            mPrivateFlags |= PFLAG_FOCUSED;
4360
4361            if (mParent != null) {
4362                mParent.requestChildFocus(this, this);
4363            }
4364
4365            onFocusChanged(true, direction, previouslyFocusedRect);
4366            refreshDrawableState();
4367
4368            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4369                notifyAccessibilityStateChanged();
4370            }
4371        }
4372    }
4373
4374    /**
4375     * Request that a rectangle of this view be visible on the screen,
4376     * scrolling if necessary just enough.
4377     *
4378     * <p>A View should call this if it maintains some notion of which part
4379     * of its content is interesting.  For example, a text editing view
4380     * should call this when its cursor moves.
4381     *
4382     * @param rectangle The rectangle.
4383     * @return Whether any parent scrolled.
4384     */
4385    public boolean requestRectangleOnScreen(Rect rectangle) {
4386        return requestRectangleOnScreen(rectangle, false);
4387    }
4388
4389    /**
4390     * Request that a rectangle of this view be visible on the screen,
4391     * scrolling if necessary just enough.
4392     *
4393     * <p>A View should call this if it maintains some notion of which part
4394     * of its content is interesting.  For example, a text editing view
4395     * should call this when its cursor moves.
4396     *
4397     * <p>When <code>immediate</code> is set to true, scrolling will not be
4398     * animated.
4399     *
4400     * @param rectangle The rectangle.
4401     * @param immediate True to forbid animated scrolling, false otherwise
4402     * @return Whether any parent scrolled.
4403     */
4404    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4405        if (mParent == null) {
4406            return false;
4407        }
4408
4409        View child = this;
4410
4411        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4412        position.set(rectangle);
4413
4414        ViewParent parent = mParent;
4415        boolean scrolled = false;
4416        while (parent != null) {
4417            rectangle.set((int) position.left, (int) position.top,
4418                    (int) position.right, (int) position.bottom);
4419
4420            scrolled |= parent.requestChildRectangleOnScreen(child,
4421                    rectangle, immediate);
4422
4423            if (!child.hasIdentityMatrix()) {
4424                child.getMatrix().mapRect(position);
4425            }
4426
4427            position.offset(child.mLeft, child.mTop);
4428
4429            if (!(parent instanceof View)) {
4430                break;
4431            }
4432
4433            View parentView = (View) parent;
4434
4435            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4436
4437            child = parentView;
4438            parent = child.getParent();
4439        }
4440
4441        return scrolled;
4442    }
4443
4444    /**
4445     * Called when this view wants to give up focus. If focus is cleared
4446     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4447     * <p>
4448     * <strong>Note:</strong> When a View clears focus the framework is trying
4449     * to give focus to the first focusable View from the top. Hence, if this
4450     * View is the first from the top that can take focus, then all callbacks
4451     * related to clearing focus will be invoked after wich the framework will
4452     * give focus to this view.
4453     * </p>
4454     */
4455    public void clearFocus() {
4456        if (DBG) {
4457            System.out.println(this + " clearFocus()");
4458        }
4459
4460        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4461            mPrivateFlags &= ~PFLAG_FOCUSED;
4462
4463            if (mParent != null) {
4464                mParent.clearChildFocus(this);
4465            }
4466
4467            onFocusChanged(false, 0, null);
4468
4469            refreshDrawableState();
4470
4471            ensureInputFocusOnFirstFocusable();
4472
4473            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4474                notifyAccessibilityStateChanged();
4475            }
4476        }
4477    }
4478
4479    void ensureInputFocusOnFirstFocusable() {
4480        View root = getRootView();
4481        if (root != null) {
4482            root.requestFocus();
4483        }
4484    }
4485
4486    /**
4487     * Called internally by the view system when a new view is getting focus.
4488     * This is what clears the old focus.
4489     */
4490    void unFocus() {
4491        if (DBG) {
4492            System.out.println(this + " unFocus()");
4493        }
4494
4495        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4496            mPrivateFlags &= ~PFLAG_FOCUSED;
4497
4498            onFocusChanged(false, 0, null);
4499            refreshDrawableState();
4500
4501            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4502                notifyAccessibilityStateChanged();
4503            }
4504        }
4505    }
4506
4507    /**
4508     * Returns true if this view has focus iteself, or is the ancestor of the
4509     * view that has focus.
4510     *
4511     * @return True if this view has or contains focus, false otherwise.
4512     */
4513    @ViewDebug.ExportedProperty(category = "focus")
4514    public boolean hasFocus() {
4515        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4516    }
4517
4518    /**
4519     * Returns true if this view is focusable or if it contains a reachable View
4520     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4521     * is a View whose parents do not block descendants focus.
4522     *
4523     * Only {@link #VISIBLE} views are considered focusable.
4524     *
4525     * @return True if the view is focusable or if the view contains a focusable
4526     *         View, false otherwise.
4527     *
4528     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4529     */
4530    public boolean hasFocusable() {
4531        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4532    }
4533
4534    /**
4535     * Called by the view system when the focus state of this view changes.
4536     * When the focus change event is caused by directional navigation, direction
4537     * and previouslyFocusedRect provide insight into where the focus is coming from.
4538     * When overriding, be sure to call up through to the super class so that
4539     * the standard focus handling will occur.
4540     *
4541     * @param gainFocus True if the View has focus; false otherwise.
4542     * @param direction The direction focus has moved when requestFocus()
4543     *                  is called to give this view focus. Values are
4544     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4545     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4546     *                  It may not always apply, in which case use the default.
4547     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4548     *        system, of the previously focused view.  If applicable, this will be
4549     *        passed in as finer grained information about where the focus is coming
4550     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4551     */
4552    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4553        if (gainFocus) {
4554            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4555                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4556            }
4557        }
4558
4559        InputMethodManager imm = InputMethodManager.peekInstance();
4560        if (!gainFocus) {
4561            if (isPressed()) {
4562                setPressed(false);
4563            }
4564            if (imm != null && mAttachInfo != null
4565                    && mAttachInfo.mHasWindowFocus) {
4566                imm.focusOut(this);
4567            }
4568            onFocusLost();
4569        } else if (imm != null && mAttachInfo != null
4570                && mAttachInfo.mHasWindowFocus) {
4571            imm.focusIn(this);
4572        }
4573
4574        invalidate(true);
4575        ListenerInfo li = mListenerInfo;
4576        if (li != null && li.mOnFocusChangeListener != null) {
4577            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4578        }
4579
4580        if (mAttachInfo != null) {
4581            mAttachInfo.mKeyDispatchState.reset(this);
4582        }
4583    }
4584
4585    /**
4586     * Sends an accessibility event of the given type. If accessibility is
4587     * not enabled this method has no effect. The default implementation calls
4588     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4589     * to populate information about the event source (this View), then calls
4590     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4591     * populate the text content of the event source including its descendants,
4592     * and last calls
4593     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4594     * on its parent to resuest sending of the event to interested parties.
4595     * <p>
4596     * If an {@link AccessibilityDelegate} has been specified via calling
4597     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4598     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4599     * responsible for handling this call.
4600     * </p>
4601     *
4602     * @param eventType The type of the event to send, as defined by several types from
4603     * {@link android.view.accessibility.AccessibilityEvent}, such as
4604     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4605     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4606     *
4607     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4608     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4609     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4610     * @see AccessibilityDelegate
4611     */
4612    public void sendAccessibilityEvent(int eventType) {
4613        if (mAccessibilityDelegate != null) {
4614            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4615        } else {
4616            sendAccessibilityEventInternal(eventType);
4617        }
4618    }
4619
4620    /**
4621     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4622     * {@link AccessibilityEvent} to make an announcement which is related to some
4623     * sort of a context change for which none of the events representing UI transitions
4624     * is a good fit. For example, announcing a new page in a book. If accessibility
4625     * is not enabled this method does nothing.
4626     *
4627     * @param text The announcement text.
4628     */
4629    public void announceForAccessibility(CharSequence text) {
4630        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4631            AccessibilityEvent event = AccessibilityEvent.obtain(
4632                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4633            onInitializeAccessibilityEvent(event);
4634            event.getText().add(text);
4635            event.setContentDescription(null);
4636            mParent.requestSendAccessibilityEvent(this, event);
4637        }
4638    }
4639
4640    /**
4641     * @see #sendAccessibilityEvent(int)
4642     *
4643     * Note: Called from the default {@link AccessibilityDelegate}.
4644     */
4645    void sendAccessibilityEventInternal(int eventType) {
4646        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4647            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4648        }
4649    }
4650
4651    /**
4652     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4653     * takes as an argument an empty {@link AccessibilityEvent} and does not
4654     * perform a check whether accessibility is enabled.
4655     * <p>
4656     * If an {@link AccessibilityDelegate} has been specified via calling
4657     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4658     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4659     * is responsible for handling this call.
4660     * </p>
4661     *
4662     * @param event The event to send.
4663     *
4664     * @see #sendAccessibilityEvent(int)
4665     */
4666    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4667        if (mAccessibilityDelegate != null) {
4668            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4669        } else {
4670            sendAccessibilityEventUncheckedInternal(event);
4671        }
4672    }
4673
4674    /**
4675     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4676     *
4677     * Note: Called from the default {@link AccessibilityDelegate}.
4678     */
4679    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4680        if (!isShown()) {
4681            return;
4682        }
4683        onInitializeAccessibilityEvent(event);
4684        // Only a subset of accessibility events populates text content.
4685        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4686            dispatchPopulateAccessibilityEvent(event);
4687        }
4688        // In the beginning we called #isShown(), so we know that getParent() is not null.
4689        getParent().requestSendAccessibilityEvent(this, event);
4690    }
4691
4692    /**
4693     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4694     * to its children for adding their text content to the event. Note that the
4695     * event text is populated in a separate dispatch path since we add to the
4696     * event not only the text of the source but also the text of all its descendants.
4697     * A typical implementation will call
4698     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4699     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4700     * on each child. Override this method if custom population of the event text
4701     * content is required.
4702     * <p>
4703     * If an {@link AccessibilityDelegate} has been specified via calling
4704     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4705     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4706     * is responsible for handling this call.
4707     * </p>
4708     * <p>
4709     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4710     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4711     * </p>
4712     *
4713     * @param event The event.
4714     *
4715     * @return True if the event population was completed.
4716     */
4717    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4718        if (mAccessibilityDelegate != null) {
4719            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4720        } else {
4721            return dispatchPopulateAccessibilityEventInternal(event);
4722        }
4723    }
4724
4725    /**
4726     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4727     *
4728     * Note: Called from the default {@link AccessibilityDelegate}.
4729     */
4730    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4731        onPopulateAccessibilityEvent(event);
4732        return false;
4733    }
4734
4735    /**
4736     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4737     * giving a chance to this View to populate the accessibility event with its
4738     * text content. While this method is free to modify event
4739     * attributes other than text content, doing so should normally be performed in
4740     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4741     * <p>
4742     * Example: Adding formatted date string to an accessibility event in addition
4743     *          to the text added by the super implementation:
4744     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4745     *     super.onPopulateAccessibilityEvent(event);
4746     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4747     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4748     *         mCurrentDate.getTimeInMillis(), flags);
4749     *     event.getText().add(selectedDateUtterance);
4750     * }</pre>
4751     * <p>
4752     * If an {@link AccessibilityDelegate} has been specified via calling
4753     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4754     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4755     * is responsible for handling this call.
4756     * </p>
4757     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4758     * information to the event, in case the default implementation has basic information to add.
4759     * </p>
4760     *
4761     * @param event The accessibility event which to populate.
4762     *
4763     * @see #sendAccessibilityEvent(int)
4764     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4765     */
4766    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4767        if (mAccessibilityDelegate != null) {
4768            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4769        } else {
4770            onPopulateAccessibilityEventInternal(event);
4771        }
4772    }
4773
4774    /**
4775     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4776     *
4777     * Note: Called from the default {@link AccessibilityDelegate}.
4778     */
4779    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4780
4781    }
4782
4783    /**
4784     * Initializes an {@link AccessibilityEvent} with information about
4785     * this View which is the event source. In other words, the source of
4786     * an accessibility event is the view whose state change triggered firing
4787     * the event.
4788     * <p>
4789     * Example: Setting the password property of an event in addition
4790     *          to properties set by the super implementation:
4791     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4792     *     super.onInitializeAccessibilityEvent(event);
4793     *     event.setPassword(true);
4794     * }</pre>
4795     * <p>
4796     * If an {@link AccessibilityDelegate} has been specified via calling
4797     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4798     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4799     * is responsible for handling this call.
4800     * </p>
4801     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4802     * information to the event, in case the default implementation has basic information to add.
4803     * </p>
4804     * @param event The event to initialize.
4805     *
4806     * @see #sendAccessibilityEvent(int)
4807     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4808     */
4809    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4810        if (mAccessibilityDelegate != null) {
4811            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4812        } else {
4813            onInitializeAccessibilityEventInternal(event);
4814        }
4815    }
4816
4817    /**
4818     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4819     *
4820     * Note: Called from the default {@link AccessibilityDelegate}.
4821     */
4822    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4823        event.setSource(this);
4824        event.setClassName(View.class.getName());
4825        event.setPackageName(getContext().getPackageName());
4826        event.setEnabled(isEnabled());
4827        event.setContentDescription(mContentDescription);
4828
4829        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4830            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4831            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4832                    FOCUSABLES_ALL);
4833            event.setItemCount(focusablesTempList.size());
4834            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4835            focusablesTempList.clear();
4836        }
4837    }
4838
4839    /**
4840     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4841     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4842     * This method is responsible for obtaining an accessibility node info from a
4843     * pool of reusable instances and calling
4844     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4845     * initialize the former.
4846     * <p>
4847     * Note: The client is responsible for recycling the obtained instance by calling
4848     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4849     * </p>
4850     *
4851     * @return A populated {@link AccessibilityNodeInfo}.
4852     *
4853     * @see AccessibilityNodeInfo
4854     */
4855    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4856        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4857        if (provider != null) {
4858            return provider.createAccessibilityNodeInfo(View.NO_ID);
4859        } else {
4860            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4861            onInitializeAccessibilityNodeInfo(info);
4862            return info;
4863        }
4864    }
4865
4866    /**
4867     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4868     * The base implementation sets:
4869     * <ul>
4870     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4871     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4872     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4873     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4874     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4875     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4876     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4877     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4878     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4879     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4880     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4881     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4882     * </ul>
4883     * <p>
4884     * Subclasses should override this method, call the super implementation,
4885     * and set additional attributes.
4886     * </p>
4887     * <p>
4888     * If an {@link AccessibilityDelegate} has been specified via calling
4889     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4890     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4891     * is responsible for handling this call.
4892     * </p>
4893     *
4894     * @param info The instance to initialize.
4895     */
4896    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4897        if (mAccessibilityDelegate != null) {
4898            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4899        } else {
4900            onInitializeAccessibilityNodeInfoInternal(info);
4901        }
4902    }
4903
4904    /**
4905     * Gets the location of this view in screen coordintates.
4906     *
4907     * @param outRect The output location
4908     */
4909    private void getBoundsOnScreen(Rect outRect) {
4910        if (mAttachInfo == null) {
4911            return;
4912        }
4913
4914        RectF position = mAttachInfo.mTmpTransformRect;
4915        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4916
4917        if (!hasIdentityMatrix()) {
4918            getMatrix().mapRect(position);
4919        }
4920
4921        position.offset(mLeft, mTop);
4922
4923        ViewParent parent = mParent;
4924        while (parent instanceof View) {
4925            View parentView = (View) parent;
4926
4927            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4928
4929            if (!parentView.hasIdentityMatrix()) {
4930                parentView.getMatrix().mapRect(position);
4931            }
4932
4933            position.offset(parentView.mLeft, parentView.mTop);
4934
4935            parent = parentView.mParent;
4936        }
4937
4938        if (parent instanceof ViewRootImpl) {
4939            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4940            position.offset(0, -viewRootImpl.mCurScrollY);
4941        }
4942
4943        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4944
4945        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4946                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4947    }
4948
4949    /**
4950     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4951     *
4952     * Note: Called from the default {@link AccessibilityDelegate}.
4953     */
4954    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4955        Rect bounds = mAttachInfo.mTmpInvalRect;
4956
4957        getDrawingRect(bounds);
4958        info.setBoundsInParent(bounds);
4959
4960        getBoundsOnScreen(bounds);
4961        info.setBoundsInScreen(bounds);
4962
4963        ViewParent parent = getParentForAccessibility();
4964        if (parent instanceof View) {
4965            info.setParent((View) parent);
4966        }
4967
4968        if (mID != View.NO_ID) {
4969            View rootView = getRootView();
4970            if (rootView == null) {
4971                rootView = this;
4972            }
4973            View label = rootView.findLabelForView(this, mID);
4974            if (label != null) {
4975                info.setLabeledBy(label);
4976            }
4977        }
4978
4979        if (mLabelForId != View.NO_ID) {
4980            View rootView = getRootView();
4981            if (rootView == null) {
4982                rootView = this;
4983            }
4984            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
4985            if (labeled != null) {
4986                info.setLabelFor(labeled);
4987            }
4988        }
4989
4990        info.setVisibleToUser(isVisibleToUser());
4991
4992        info.setPackageName(mContext.getPackageName());
4993        info.setClassName(View.class.getName());
4994        info.setContentDescription(getContentDescription());
4995
4996        info.setEnabled(isEnabled());
4997        info.setClickable(isClickable());
4998        info.setFocusable(isFocusable());
4999        info.setFocused(isFocused());
5000        info.setAccessibilityFocused(isAccessibilityFocused());
5001        info.setSelected(isSelected());
5002        info.setLongClickable(isLongClickable());
5003
5004        // TODO: These make sense only if we are in an AdapterView but all
5005        // views can be selected. Maybe from accessibility perspective
5006        // we should report as selectable view in an AdapterView.
5007        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5008        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5009
5010        if (isFocusable()) {
5011            if (isFocused()) {
5012                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5013            } else {
5014                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5015            }
5016        }
5017
5018        if (!isAccessibilityFocused()) {
5019            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5020        } else {
5021            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5022        }
5023
5024        if (isClickable() && isEnabled()) {
5025            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5026        }
5027
5028        if (isLongClickable() && isEnabled()) {
5029            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5030        }
5031
5032        if (mContentDescription != null && mContentDescription.length() > 0) {
5033            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5034            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5035            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5036                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5037                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5038        }
5039    }
5040
5041    private View findLabelForView(View view, int labeledId) {
5042        if (mMatchLabelForPredicate == null) {
5043            mMatchLabelForPredicate = new MatchLabelForPredicate();
5044        }
5045        mMatchLabelForPredicate.mLabeledId = labeledId;
5046        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5047    }
5048
5049    /**
5050     * Computes whether this view is visible to the user. Such a view is
5051     * attached, visible, all its predecessors are visible, it is not clipped
5052     * entirely by its predecessors, and has an alpha greater than zero.
5053     *
5054     * @return Whether the view is visible on the screen.
5055     *
5056     * @hide
5057     */
5058    protected boolean isVisibleToUser() {
5059        return isVisibleToUser(null);
5060    }
5061
5062    /**
5063     * Computes whether the given portion of this view is visible to the user.
5064     * Such a view is attached, visible, all its predecessors are visible,
5065     * has an alpha greater than zero, and the specified portion is not
5066     * clipped entirely by its predecessors.
5067     *
5068     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5069     *                    <code>null</code>, and the entire view will be tested in this case.
5070     *                    When <code>true</code> is returned by the function, the actual visible
5071     *                    region will be stored in this parameter; that is, if boundInView is fully
5072     *                    contained within the view, no modification will be made, otherwise regions
5073     *                    outside of the visible area of the view will be clipped.
5074     *
5075     * @return Whether the specified portion of the view is visible on the screen.
5076     *
5077     * @hide
5078     */
5079    protected boolean isVisibleToUser(Rect boundInView) {
5080        if (mAttachInfo != null) {
5081            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5082            Point offset = mAttachInfo.mPoint;
5083            // The first two checks are made also made by isShown() which
5084            // however traverses the tree up to the parent to catch that.
5085            // Therefore, we do some fail fast check to minimize the up
5086            // tree traversal.
5087            boolean isVisible = mAttachInfo.mWindowVisibility == View.VISIBLE
5088                && getAlpha() > 0
5089                && isShown()
5090                && getGlobalVisibleRect(visibleRect, offset);
5091            if (isVisible && boundInView != null) {
5092                visibleRect.offset(-offset.x, -offset.y);
5093                // isVisible is always true here, use a simple assignment
5094                isVisible = boundInView.intersect(visibleRect);
5095            }
5096            return isVisible;
5097        }
5098
5099        return false;
5100    }
5101
5102    /**
5103     * Returns the delegate for implementing accessibility support via
5104     * composition. For more details see {@link AccessibilityDelegate}.
5105     *
5106     * @return The delegate, or null if none set.
5107     *
5108     * @hide
5109     */
5110    public AccessibilityDelegate getAccessibilityDelegate() {
5111        return mAccessibilityDelegate;
5112    }
5113
5114    /**
5115     * Sets a delegate for implementing accessibility support via composition as
5116     * opposed to inheritance. The delegate's primary use is for implementing
5117     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5118     *
5119     * @param delegate The delegate instance.
5120     *
5121     * @see AccessibilityDelegate
5122     */
5123    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5124        mAccessibilityDelegate = delegate;
5125    }
5126
5127    /**
5128     * Gets the provider for managing a virtual view hierarchy rooted at this View
5129     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5130     * that explore the window content.
5131     * <p>
5132     * If this method returns an instance, this instance is responsible for managing
5133     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5134     * View including the one representing the View itself. Similarly the returned
5135     * instance is responsible for performing accessibility actions on any virtual
5136     * view or the root view itself.
5137     * </p>
5138     * <p>
5139     * If an {@link AccessibilityDelegate} has been specified via calling
5140     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5141     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5142     * is responsible for handling this call.
5143     * </p>
5144     *
5145     * @return The provider.
5146     *
5147     * @see AccessibilityNodeProvider
5148     */
5149    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5150        if (mAccessibilityDelegate != null) {
5151            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5152        } else {
5153            return null;
5154        }
5155    }
5156
5157    /**
5158     * Gets the unique identifier of this view on the screen for accessibility purposes.
5159     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5160     *
5161     * @return The view accessibility id.
5162     *
5163     * @hide
5164     */
5165    public int getAccessibilityViewId() {
5166        if (mAccessibilityViewId == NO_ID) {
5167            mAccessibilityViewId = sNextAccessibilityViewId++;
5168        }
5169        return mAccessibilityViewId;
5170    }
5171
5172    /**
5173     * Gets the unique identifier of the window in which this View reseides.
5174     *
5175     * @return The window accessibility id.
5176     *
5177     * @hide
5178     */
5179    public int getAccessibilityWindowId() {
5180        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5181    }
5182
5183    /**
5184     * Gets the {@link View} description. It briefly describes the view and is
5185     * primarily used for accessibility support. Set this property to enable
5186     * better accessibility support for your application. This is especially
5187     * true for views that do not have textual representation (For example,
5188     * ImageButton).
5189     *
5190     * @return The content description.
5191     *
5192     * @attr ref android.R.styleable#View_contentDescription
5193     */
5194    @ViewDebug.ExportedProperty(category = "accessibility")
5195    public CharSequence getContentDescription() {
5196        return mContentDescription;
5197    }
5198
5199    /**
5200     * Sets the {@link View} description. It briefly describes the view and is
5201     * primarily used for accessibility support. Set this property to enable
5202     * better accessibility support for your application. This is especially
5203     * true for views that do not have textual representation (For example,
5204     * ImageButton).
5205     *
5206     * @param contentDescription The content description.
5207     *
5208     * @attr ref android.R.styleable#View_contentDescription
5209     */
5210    @RemotableViewMethod
5211    public void setContentDescription(CharSequence contentDescription) {
5212        if (mContentDescription == null) {
5213            if (contentDescription == null) {
5214                return;
5215            }
5216        } else if (mContentDescription.equals(contentDescription)) {
5217            return;
5218        }
5219        mContentDescription = contentDescription;
5220        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5221        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5222             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5223        }
5224        notifyAccessibilityStateChanged();
5225    }
5226
5227    /**
5228     * Gets the id of a view for which this view serves as a label for
5229     * accessibility purposes.
5230     *
5231     * @return The labeled view id.
5232     */
5233    @ViewDebug.ExportedProperty(category = "accessibility")
5234    public int getLabelFor() {
5235        return mLabelForId;
5236    }
5237
5238    /**
5239     * Sets the id of a view for which this view serves as a label for
5240     * accessibility purposes.
5241     *
5242     * @param id The labeled view id.
5243     */
5244    @RemotableViewMethod
5245    public void setLabelFor(int id) {
5246        mLabelForId = id;
5247        if (mLabelForId != View.NO_ID
5248                && mID == View.NO_ID) {
5249            mID = generateViewId();
5250        }
5251    }
5252
5253    /**
5254     * Invoked whenever this view loses focus, either by losing window focus or by losing
5255     * focus within its window. This method can be used to clear any state tied to the
5256     * focus. For instance, if a button is held pressed with the trackball and the window
5257     * loses focus, this method can be used to cancel the press.
5258     *
5259     * Subclasses of View overriding this method should always call super.onFocusLost().
5260     *
5261     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5262     * @see #onWindowFocusChanged(boolean)
5263     *
5264     * @hide pending API council approval
5265     */
5266    protected void onFocusLost() {
5267        resetPressedState();
5268    }
5269
5270    private void resetPressedState() {
5271        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5272            return;
5273        }
5274
5275        if (isPressed()) {
5276            setPressed(false);
5277
5278            if (!mHasPerformedLongPress) {
5279                removeLongPressCallback();
5280            }
5281        }
5282    }
5283
5284    /**
5285     * Returns true if this view has focus
5286     *
5287     * @return True if this view has focus, false otherwise.
5288     */
5289    @ViewDebug.ExportedProperty(category = "focus")
5290    public boolean isFocused() {
5291        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5292    }
5293
5294    /**
5295     * Find the view in the hierarchy rooted at this view that currently has
5296     * focus.
5297     *
5298     * @return The view that currently has focus, or null if no focused view can
5299     *         be found.
5300     */
5301    public View findFocus() {
5302        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5303    }
5304
5305    /**
5306     * Indicates whether this view is one of the set of scrollable containers in
5307     * its window.
5308     *
5309     * @return whether this view is one of the set of scrollable containers in
5310     * its window
5311     *
5312     * @attr ref android.R.styleable#View_isScrollContainer
5313     */
5314    public boolean isScrollContainer() {
5315        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5316    }
5317
5318    /**
5319     * Change whether this view is one of the set of scrollable containers in
5320     * its window.  This will be used to determine whether the window can
5321     * resize or must pan when a soft input area is open -- scrollable
5322     * containers allow the window to use resize mode since the container
5323     * will appropriately shrink.
5324     *
5325     * @attr ref android.R.styleable#View_isScrollContainer
5326     */
5327    public void setScrollContainer(boolean isScrollContainer) {
5328        if (isScrollContainer) {
5329            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5330                mAttachInfo.mScrollContainers.add(this);
5331                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5332            }
5333            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5334        } else {
5335            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5336                mAttachInfo.mScrollContainers.remove(this);
5337            }
5338            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5339        }
5340    }
5341
5342    /**
5343     * Returns the quality of the drawing cache.
5344     *
5345     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5346     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5347     *
5348     * @see #setDrawingCacheQuality(int)
5349     * @see #setDrawingCacheEnabled(boolean)
5350     * @see #isDrawingCacheEnabled()
5351     *
5352     * @attr ref android.R.styleable#View_drawingCacheQuality
5353     */
5354    public int getDrawingCacheQuality() {
5355        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5356    }
5357
5358    /**
5359     * Set the drawing cache quality of this view. This value is used only when the
5360     * drawing cache is enabled
5361     *
5362     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5363     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5364     *
5365     * @see #getDrawingCacheQuality()
5366     * @see #setDrawingCacheEnabled(boolean)
5367     * @see #isDrawingCacheEnabled()
5368     *
5369     * @attr ref android.R.styleable#View_drawingCacheQuality
5370     */
5371    public void setDrawingCacheQuality(int quality) {
5372        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5373    }
5374
5375    /**
5376     * Returns whether the screen should remain on, corresponding to the current
5377     * value of {@link #KEEP_SCREEN_ON}.
5378     *
5379     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5380     *
5381     * @see #setKeepScreenOn(boolean)
5382     *
5383     * @attr ref android.R.styleable#View_keepScreenOn
5384     */
5385    public boolean getKeepScreenOn() {
5386        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5387    }
5388
5389    /**
5390     * Controls whether the screen should remain on, modifying the
5391     * value of {@link #KEEP_SCREEN_ON}.
5392     *
5393     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5394     *
5395     * @see #getKeepScreenOn()
5396     *
5397     * @attr ref android.R.styleable#View_keepScreenOn
5398     */
5399    public void setKeepScreenOn(boolean keepScreenOn) {
5400        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5401    }
5402
5403    /**
5404     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5405     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5406     *
5407     * @attr ref android.R.styleable#View_nextFocusLeft
5408     */
5409    public int getNextFocusLeftId() {
5410        return mNextFocusLeftId;
5411    }
5412
5413    /**
5414     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5415     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5416     * decide automatically.
5417     *
5418     * @attr ref android.R.styleable#View_nextFocusLeft
5419     */
5420    public void setNextFocusLeftId(int nextFocusLeftId) {
5421        mNextFocusLeftId = nextFocusLeftId;
5422    }
5423
5424    /**
5425     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5426     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5427     *
5428     * @attr ref android.R.styleable#View_nextFocusRight
5429     */
5430    public int getNextFocusRightId() {
5431        return mNextFocusRightId;
5432    }
5433
5434    /**
5435     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5436     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5437     * decide automatically.
5438     *
5439     * @attr ref android.R.styleable#View_nextFocusRight
5440     */
5441    public void setNextFocusRightId(int nextFocusRightId) {
5442        mNextFocusRightId = nextFocusRightId;
5443    }
5444
5445    /**
5446     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5447     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5448     *
5449     * @attr ref android.R.styleable#View_nextFocusUp
5450     */
5451    public int getNextFocusUpId() {
5452        return mNextFocusUpId;
5453    }
5454
5455    /**
5456     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5457     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5458     * decide automatically.
5459     *
5460     * @attr ref android.R.styleable#View_nextFocusUp
5461     */
5462    public void setNextFocusUpId(int nextFocusUpId) {
5463        mNextFocusUpId = nextFocusUpId;
5464    }
5465
5466    /**
5467     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5468     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5469     *
5470     * @attr ref android.R.styleable#View_nextFocusDown
5471     */
5472    public int getNextFocusDownId() {
5473        return mNextFocusDownId;
5474    }
5475
5476    /**
5477     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5478     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5479     * decide automatically.
5480     *
5481     * @attr ref android.R.styleable#View_nextFocusDown
5482     */
5483    public void setNextFocusDownId(int nextFocusDownId) {
5484        mNextFocusDownId = nextFocusDownId;
5485    }
5486
5487    /**
5488     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5489     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5490     *
5491     * @attr ref android.R.styleable#View_nextFocusForward
5492     */
5493    public int getNextFocusForwardId() {
5494        return mNextFocusForwardId;
5495    }
5496
5497    /**
5498     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5499     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5500     * decide automatically.
5501     *
5502     * @attr ref android.R.styleable#View_nextFocusForward
5503     */
5504    public void setNextFocusForwardId(int nextFocusForwardId) {
5505        mNextFocusForwardId = nextFocusForwardId;
5506    }
5507
5508    /**
5509     * Returns the visibility of this view and all of its ancestors
5510     *
5511     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5512     */
5513    public boolean isShown() {
5514        View current = this;
5515        //noinspection ConstantConditions
5516        do {
5517            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5518                return false;
5519            }
5520            ViewParent parent = current.mParent;
5521            if (parent == null) {
5522                return false; // We are not attached to the view root
5523            }
5524            if (!(parent instanceof View)) {
5525                return true;
5526            }
5527            current = (View) parent;
5528        } while (current != null);
5529
5530        return false;
5531    }
5532
5533    /**
5534     * Called by the view hierarchy when the content insets for a window have
5535     * changed, to allow it to adjust its content to fit within those windows.
5536     * The content insets tell you the space that the status bar, input method,
5537     * and other system windows infringe on the application's window.
5538     *
5539     * <p>You do not normally need to deal with this function, since the default
5540     * window decoration given to applications takes care of applying it to the
5541     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5542     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5543     * and your content can be placed under those system elements.  You can then
5544     * use this method within your view hierarchy if you have parts of your UI
5545     * which you would like to ensure are not being covered.
5546     *
5547     * <p>The default implementation of this method simply applies the content
5548     * inset's to the view's padding, consuming that content (modifying the
5549     * insets to be 0), and returning true.  This behavior is off by default, but can
5550     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5551     *
5552     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5553     * insets object is propagated down the hierarchy, so any changes made to it will
5554     * be seen by all following views (including potentially ones above in
5555     * the hierarchy since this is a depth-first traversal).  The first view
5556     * that returns true will abort the entire traversal.
5557     *
5558     * <p>The default implementation works well for a situation where it is
5559     * used with a container that covers the entire window, allowing it to
5560     * apply the appropriate insets to its content on all edges.  If you need
5561     * a more complicated layout (such as two different views fitting system
5562     * windows, one on the top of the window, and one on the bottom),
5563     * you can override the method and handle the insets however you would like.
5564     * Note that the insets provided by the framework are always relative to the
5565     * far edges of the window, not accounting for the location of the called view
5566     * within that window.  (In fact when this method is called you do not yet know
5567     * where the layout will place the view, as it is done before layout happens.)
5568     *
5569     * <p>Note: unlike many View methods, there is no dispatch phase to this
5570     * call.  If you are overriding it in a ViewGroup and want to allow the
5571     * call to continue to your children, you must be sure to call the super
5572     * implementation.
5573     *
5574     * <p>Here is a sample layout that makes use of fitting system windows
5575     * to have controls for a video view placed inside of the window decorations
5576     * that it hides and shows.  This can be used with code like the second
5577     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5578     *
5579     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5580     *
5581     * @param insets Current content insets of the window.  Prior to
5582     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5583     * the insets or else you and Android will be unhappy.
5584     *
5585     * @return Return true if this view applied the insets and it should not
5586     * continue propagating further down the hierarchy, false otherwise.
5587     * @see #getFitsSystemWindows()
5588     * @see #setFitsSystemWindows(boolean)
5589     * @see #setSystemUiVisibility(int)
5590     */
5591    protected boolean fitSystemWindows(Rect insets) {
5592        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5593            mUserPaddingStart = UNDEFINED_PADDING;
5594            mUserPaddingEnd = UNDEFINED_PADDING;
5595            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5596                    || mAttachInfo == null
5597                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5598                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5599                return true;
5600            } else {
5601                internalSetPadding(0, 0, 0, 0);
5602                return false;
5603            }
5604        }
5605        return false;
5606    }
5607
5608    /**
5609     * Sets whether or not this view should account for system screen decorations
5610     * such as the status bar and inset its content; that is, controlling whether
5611     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5612     * executed.  See that method for more details.
5613     *
5614     * <p>Note that if you are providing your own implementation of
5615     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5616     * flag to true -- your implementation will be overriding the default
5617     * implementation that checks this flag.
5618     *
5619     * @param fitSystemWindows If true, then the default implementation of
5620     * {@link #fitSystemWindows(Rect)} will be executed.
5621     *
5622     * @attr ref android.R.styleable#View_fitsSystemWindows
5623     * @see #getFitsSystemWindows()
5624     * @see #fitSystemWindows(Rect)
5625     * @see #setSystemUiVisibility(int)
5626     */
5627    public void setFitsSystemWindows(boolean fitSystemWindows) {
5628        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5629    }
5630
5631    /**
5632     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5633     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5634     * will be executed.
5635     *
5636     * @return Returns true if the default implementation of
5637     * {@link #fitSystemWindows(Rect)} will be executed.
5638     *
5639     * @attr ref android.R.styleable#View_fitsSystemWindows
5640     * @see #setFitsSystemWindows()
5641     * @see #fitSystemWindows(Rect)
5642     * @see #setSystemUiVisibility(int)
5643     */
5644    public boolean getFitsSystemWindows() {
5645        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5646    }
5647
5648    /** @hide */
5649    public boolean fitsSystemWindows() {
5650        return getFitsSystemWindows();
5651    }
5652
5653    /**
5654     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5655     */
5656    public void requestFitSystemWindows() {
5657        if (mParent != null) {
5658            mParent.requestFitSystemWindows();
5659        }
5660    }
5661
5662    /**
5663     * For use by PhoneWindow to make its own system window fitting optional.
5664     * @hide
5665     */
5666    public void makeOptionalFitsSystemWindows() {
5667        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5668    }
5669
5670    /**
5671     * Returns the visibility status for this view.
5672     *
5673     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5674     * @attr ref android.R.styleable#View_visibility
5675     */
5676    @ViewDebug.ExportedProperty(mapping = {
5677        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5678        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5679        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5680    })
5681    public int getVisibility() {
5682        return mViewFlags & VISIBILITY_MASK;
5683    }
5684
5685    /**
5686     * Set the enabled state of this view.
5687     *
5688     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5689     * @attr ref android.R.styleable#View_visibility
5690     */
5691    @RemotableViewMethod
5692    public void setVisibility(int visibility) {
5693        setFlags(visibility, VISIBILITY_MASK);
5694        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5695    }
5696
5697    /**
5698     * Returns the enabled status for this view. The interpretation of the
5699     * enabled state varies by subclass.
5700     *
5701     * @return True if this view is enabled, false otherwise.
5702     */
5703    @ViewDebug.ExportedProperty
5704    public boolean isEnabled() {
5705        return (mViewFlags & ENABLED_MASK) == ENABLED;
5706    }
5707
5708    /**
5709     * Set the enabled state of this view. The interpretation of the enabled
5710     * state varies by subclass.
5711     *
5712     * @param enabled True if this view is enabled, false otherwise.
5713     */
5714    @RemotableViewMethod
5715    public void setEnabled(boolean enabled) {
5716        if (enabled == isEnabled()) return;
5717
5718        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5719
5720        /*
5721         * The View most likely has to change its appearance, so refresh
5722         * the drawable state.
5723         */
5724        refreshDrawableState();
5725
5726        // Invalidate too, since the default behavior for views is to be
5727        // be drawn at 50% alpha rather than to change the drawable.
5728        invalidate(true);
5729    }
5730
5731    /**
5732     * Set whether this view can receive the focus.
5733     *
5734     * Setting this to false will also ensure that this view is not focusable
5735     * in touch mode.
5736     *
5737     * @param focusable If true, this view can receive the focus.
5738     *
5739     * @see #setFocusableInTouchMode(boolean)
5740     * @attr ref android.R.styleable#View_focusable
5741     */
5742    public void setFocusable(boolean focusable) {
5743        if (!focusable) {
5744            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5745        }
5746        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5747    }
5748
5749    /**
5750     * Set whether this view can receive focus while in touch mode.
5751     *
5752     * Setting this to true will also ensure that this view is focusable.
5753     *
5754     * @param focusableInTouchMode If true, this view can receive the focus while
5755     *   in touch mode.
5756     *
5757     * @see #setFocusable(boolean)
5758     * @attr ref android.R.styleable#View_focusableInTouchMode
5759     */
5760    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5761        // Focusable in touch mode should always be set before the focusable flag
5762        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5763        // which, in touch mode, will not successfully request focus on this view
5764        // because the focusable in touch mode flag is not set
5765        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5766        if (focusableInTouchMode) {
5767            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5768        }
5769    }
5770
5771    /**
5772     * Set whether this view should have sound effects enabled for events such as
5773     * clicking and touching.
5774     *
5775     * <p>You may wish to disable sound effects for a view if you already play sounds,
5776     * for instance, a dial key that plays dtmf tones.
5777     *
5778     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5779     * @see #isSoundEffectsEnabled()
5780     * @see #playSoundEffect(int)
5781     * @attr ref android.R.styleable#View_soundEffectsEnabled
5782     */
5783    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5784        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5785    }
5786
5787    /**
5788     * @return whether this view should have sound effects enabled for events such as
5789     *     clicking and touching.
5790     *
5791     * @see #setSoundEffectsEnabled(boolean)
5792     * @see #playSoundEffect(int)
5793     * @attr ref android.R.styleable#View_soundEffectsEnabled
5794     */
5795    @ViewDebug.ExportedProperty
5796    public boolean isSoundEffectsEnabled() {
5797        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5798    }
5799
5800    /**
5801     * Set whether this view should have haptic feedback for events such as
5802     * long presses.
5803     *
5804     * <p>You may wish to disable haptic feedback if your view already controls
5805     * its own haptic feedback.
5806     *
5807     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5808     * @see #isHapticFeedbackEnabled()
5809     * @see #performHapticFeedback(int)
5810     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5811     */
5812    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5813        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5814    }
5815
5816    /**
5817     * @return whether this view should have haptic feedback enabled for events
5818     * long presses.
5819     *
5820     * @see #setHapticFeedbackEnabled(boolean)
5821     * @see #performHapticFeedback(int)
5822     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5823     */
5824    @ViewDebug.ExportedProperty
5825    public boolean isHapticFeedbackEnabled() {
5826        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5827    }
5828
5829    /**
5830     * Returns the layout direction for this view.
5831     *
5832     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5833     *   {@link #LAYOUT_DIRECTION_RTL},
5834     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5835     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5836     * @attr ref android.R.styleable#View_layoutDirection
5837     *
5838     * @hide
5839     */
5840    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5841        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5842        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5843        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5844        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5845    })
5846    public int getRawLayoutDirection() {
5847        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
5848    }
5849
5850    /**
5851     * Set the layout direction for this view. This will propagate a reset of layout direction
5852     * resolution to the view's children and resolve layout direction for this view.
5853     *
5854     * @param layoutDirection the layout direction to set. Should be one of:
5855     *
5856     * {@link #LAYOUT_DIRECTION_LTR},
5857     * {@link #LAYOUT_DIRECTION_RTL},
5858     * {@link #LAYOUT_DIRECTION_INHERIT},
5859     * {@link #LAYOUT_DIRECTION_LOCALE}.
5860     *
5861     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
5862     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
5863     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
5864     *
5865     * @attr ref android.R.styleable#View_layoutDirection
5866     */
5867    @RemotableViewMethod
5868    public void setLayoutDirection(int layoutDirection) {
5869        if (getRawLayoutDirection() != layoutDirection) {
5870            // Reset the current layout direction and the resolved one
5871            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
5872            resetRtlProperties();
5873            // Set the new layout direction (filtered)
5874            mPrivateFlags2 |=
5875                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
5876            // We need to resolve all RTL properties as they all depend on layout direction
5877            resolveRtlPropertiesIfNeeded();
5878            requestLayout();
5879            invalidate(true);
5880        }
5881    }
5882
5883    /**
5884     * Returns the resolved layout direction for this view.
5885     *
5886     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5887     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5888     *
5889     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
5890     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
5891     */
5892    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5893        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5894        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5895    })
5896    public int getLayoutDirection() {
5897        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
5898        if (targetSdkVersion < JELLY_BEAN_MR1) {
5899            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
5900            return LAYOUT_DIRECTION_LTR;
5901        }
5902        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
5903                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5904    }
5905
5906    /**
5907     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5908     * layout attribute and/or the inherited value from the parent
5909     *
5910     * @return true if the layout is right-to-left.
5911     *
5912     * @hide
5913     */
5914    @ViewDebug.ExportedProperty(category = "layout")
5915    public boolean isLayoutRtl() {
5916        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
5917    }
5918
5919    /**
5920     * Indicates whether the view is currently tracking transient state that the
5921     * app should not need to concern itself with saving and restoring, but that
5922     * the framework should take special note to preserve when possible.
5923     *
5924     * <p>A view with transient state cannot be trivially rebound from an external
5925     * data source, such as an adapter binding item views in a list. This may be
5926     * because the view is performing an animation, tracking user selection
5927     * of content, or similar.</p>
5928     *
5929     * @return true if the view has transient state
5930     */
5931    @ViewDebug.ExportedProperty(category = "layout")
5932    public boolean hasTransientState() {
5933        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
5934    }
5935
5936    /**
5937     * Set whether this view is currently tracking transient state that the
5938     * framework should attempt to preserve when possible. This flag is reference counted,
5939     * so every call to setHasTransientState(true) should be paired with a later call
5940     * to setHasTransientState(false).
5941     *
5942     * <p>A view with transient state cannot be trivially rebound from an external
5943     * data source, such as an adapter binding item views in a list. This may be
5944     * because the view is performing an animation, tracking user selection
5945     * of content, or similar.</p>
5946     *
5947     * @param hasTransientState true if this view has transient state
5948     */
5949    public void setHasTransientState(boolean hasTransientState) {
5950        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5951                mTransientStateCount - 1;
5952        if (mTransientStateCount < 0) {
5953            mTransientStateCount = 0;
5954            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5955                    "unmatched pair of setHasTransientState calls");
5956        }
5957        if ((hasTransientState && mTransientStateCount == 1) ||
5958                (!hasTransientState && mTransientStateCount == 0)) {
5959            // update flag if we've just incremented up from 0 or decremented down to 0
5960            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
5961                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
5962            if (mParent != null) {
5963                try {
5964                    mParent.childHasTransientStateChanged(this, hasTransientState);
5965                } catch (AbstractMethodError e) {
5966                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5967                            " does not fully implement ViewParent", e);
5968                }
5969            }
5970        }
5971    }
5972
5973    /**
5974     * If this view doesn't do any drawing on its own, set this flag to
5975     * allow further optimizations. By default, this flag is not set on
5976     * View, but could be set on some View subclasses such as ViewGroup.
5977     *
5978     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5979     * you should clear this flag.
5980     *
5981     * @param willNotDraw whether or not this View draw on its own
5982     */
5983    public void setWillNotDraw(boolean willNotDraw) {
5984        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5985    }
5986
5987    /**
5988     * Returns whether or not this View draws on its own.
5989     *
5990     * @return true if this view has nothing to draw, false otherwise
5991     */
5992    @ViewDebug.ExportedProperty(category = "drawing")
5993    public boolean willNotDraw() {
5994        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5995    }
5996
5997    /**
5998     * When a View's drawing cache is enabled, drawing is redirected to an
5999     * offscreen bitmap. Some views, like an ImageView, must be able to
6000     * bypass this mechanism if they already draw a single bitmap, to avoid
6001     * unnecessary usage of the memory.
6002     *
6003     * @param willNotCacheDrawing true if this view does not cache its
6004     *        drawing, false otherwise
6005     */
6006    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6007        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6008    }
6009
6010    /**
6011     * Returns whether or not this View can cache its drawing or not.
6012     *
6013     * @return true if this view does not cache its drawing, false otherwise
6014     */
6015    @ViewDebug.ExportedProperty(category = "drawing")
6016    public boolean willNotCacheDrawing() {
6017        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6018    }
6019
6020    /**
6021     * Indicates whether this view reacts to click events or not.
6022     *
6023     * @return true if the view is clickable, false otherwise
6024     *
6025     * @see #setClickable(boolean)
6026     * @attr ref android.R.styleable#View_clickable
6027     */
6028    @ViewDebug.ExportedProperty
6029    public boolean isClickable() {
6030        return (mViewFlags & CLICKABLE) == CLICKABLE;
6031    }
6032
6033    /**
6034     * Enables or disables click events for this view. When a view
6035     * is clickable it will change its state to "pressed" on every click.
6036     * Subclasses should set the view clickable to visually react to
6037     * user's clicks.
6038     *
6039     * @param clickable true to make the view clickable, false otherwise
6040     *
6041     * @see #isClickable()
6042     * @attr ref android.R.styleable#View_clickable
6043     */
6044    public void setClickable(boolean clickable) {
6045        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6046    }
6047
6048    /**
6049     * Indicates whether this view reacts to long click events or not.
6050     *
6051     * @return true if the view is long clickable, false otherwise
6052     *
6053     * @see #setLongClickable(boolean)
6054     * @attr ref android.R.styleable#View_longClickable
6055     */
6056    public boolean isLongClickable() {
6057        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6058    }
6059
6060    /**
6061     * Enables or disables long click events for this view. When a view is long
6062     * clickable it reacts to the user holding down the button for a longer
6063     * duration than a tap. This event can either launch the listener or a
6064     * context menu.
6065     *
6066     * @param longClickable true to make the view long clickable, false otherwise
6067     * @see #isLongClickable()
6068     * @attr ref android.R.styleable#View_longClickable
6069     */
6070    public void setLongClickable(boolean longClickable) {
6071        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6072    }
6073
6074    /**
6075     * Sets the pressed state for this view.
6076     *
6077     * @see #isClickable()
6078     * @see #setClickable(boolean)
6079     *
6080     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6081     *        the View's internal state from a previously set "pressed" state.
6082     */
6083    public void setPressed(boolean pressed) {
6084        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6085
6086        if (pressed) {
6087            mPrivateFlags |= PFLAG_PRESSED;
6088        } else {
6089            mPrivateFlags &= ~PFLAG_PRESSED;
6090        }
6091
6092        if (needsRefresh) {
6093            refreshDrawableState();
6094        }
6095        dispatchSetPressed(pressed);
6096    }
6097
6098    /**
6099     * Dispatch setPressed to all of this View's children.
6100     *
6101     * @see #setPressed(boolean)
6102     *
6103     * @param pressed The new pressed state
6104     */
6105    protected void dispatchSetPressed(boolean pressed) {
6106    }
6107
6108    /**
6109     * Indicates whether the view is currently in pressed state. Unless
6110     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6111     * the pressed state.
6112     *
6113     * @see #setPressed(boolean)
6114     * @see #isClickable()
6115     * @see #setClickable(boolean)
6116     *
6117     * @return true if the view is currently pressed, false otherwise
6118     */
6119    public boolean isPressed() {
6120        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6121    }
6122
6123    /**
6124     * Indicates whether this view will save its state (that is,
6125     * whether its {@link #onSaveInstanceState} method will be called).
6126     *
6127     * @return Returns true if the view state saving is enabled, else false.
6128     *
6129     * @see #setSaveEnabled(boolean)
6130     * @attr ref android.R.styleable#View_saveEnabled
6131     */
6132    public boolean isSaveEnabled() {
6133        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6134    }
6135
6136    /**
6137     * Controls whether the saving of this view's state is
6138     * enabled (that is, whether its {@link #onSaveInstanceState} method
6139     * will be called).  Note that even if freezing is enabled, the
6140     * view still must have an id assigned to it (via {@link #setId(int)})
6141     * for its state to be saved.  This flag can only disable the
6142     * saving of this view; any child views may still have their state saved.
6143     *
6144     * @param enabled Set to false to <em>disable</em> state saving, or true
6145     * (the default) to allow it.
6146     *
6147     * @see #isSaveEnabled()
6148     * @see #setId(int)
6149     * @see #onSaveInstanceState()
6150     * @attr ref android.R.styleable#View_saveEnabled
6151     */
6152    public void setSaveEnabled(boolean enabled) {
6153        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6154    }
6155
6156    /**
6157     * Gets whether the framework should discard touches when the view's
6158     * window is obscured by another visible window.
6159     * Refer to the {@link View} security documentation for more details.
6160     *
6161     * @return True if touch filtering is enabled.
6162     *
6163     * @see #setFilterTouchesWhenObscured(boolean)
6164     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6165     */
6166    @ViewDebug.ExportedProperty
6167    public boolean getFilterTouchesWhenObscured() {
6168        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6169    }
6170
6171    /**
6172     * Sets whether the framework should discard touches when the view's
6173     * window is obscured by another visible window.
6174     * Refer to the {@link View} security documentation for more details.
6175     *
6176     * @param enabled True if touch filtering should be enabled.
6177     *
6178     * @see #getFilterTouchesWhenObscured
6179     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6180     */
6181    public void setFilterTouchesWhenObscured(boolean enabled) {
6182        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6183                FILTER_TOUCHES_WHEN_OBSCURED);
6184    }
6185
6186    /**
6187     * Indicates whether the entire hierarchy under this view will save its
6188     * state when a state saving traversal occurs from its parent.  The default
6189     * is true; if false, these views will not be saved unless
6190     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6191     *
6192     * @return Returns true if the view state saving from parent is enabled, else false.
6193     *
6194     * @see #setSaveFromParentEnabled(boolean)
6195     */
6196    public boolean isSaveFromParentEnabled() {
6197        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6198    }
6199
6200    /**
6201     * Controls whether the entire hierarchy under this view will save its
6202     * state when a state saving traversal occurs from its parent.  The default
6203     * is true; if false, these views will not be saved unless
6204     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6205     *
6206     * @param enabled Set to false to <em>disable</em> state saving, or true
6207     * (the default) to allow it.
6208     *
6209     * @see #isSaveFromParentEnabled()
6210     * @see #setId(int)
6211     * @see #onSaveInstanceState()
6212     */
6213    public void setSaveFromParentEnabled(boolean enabled) {
6214        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6215    }
6216
6217
6218    /**
6219     * Returns whether this View is able to take focus.
6220     *
6221     * @return True if this view can take focus, or false otherwise.
6222     * @attr ref android.R.styleable#View_focusable
6223     */
6224    @ViewDebug.ExportedProperty(category = "focus")
6225    public final boolean isFocusable() {
6226        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6227    }
6228
6229    /**
6230     * When a view is focusable, it may not want to take focus when in touch mode.
6231     * For example, a button would like focus when the user is navigating via a D-pad
6232     * so that the user can click on it, but once the user starts touching the screen,
6233     * the button shouldn't take focus
6234     * @return Whether the view is focusable in touch mode.
6235     * @attr ref android.R.styleable#View_focusableInTouchMode
6236     */
6237    @ViewDebug.ExportedProperty
6238    public final boolean isFocusableInTouchMode() {
6239        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6240    }
6241
6242    /**
6243     * Find the nearest view in the specified direction that can take focus.
6244     * This does not actually give focus to that view.
6245     *
6246     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6247     *
6248     * @return The nearest focusable in the specified direction, or null if none
6249     *         can be found.
6250     */
6251    public View focusSearch(int direction) {
6252        if (mParent != null) {
6253            return mParent.focusSearch(this, direction);
6254        } else {
6255            return null;
6256        }
6257    }
6258
6259    /**
6260     * This method is the last chance for the focused view and its ancestors to
6261     * respond to an arrow key. This is called when the focused view did not
6262     * consume the key internally, nor could the view system find a new view in
6263     * the requested direction to give focus to.
6264     *
6265     * @param focused The currently focused view.
6266     * @param direction The direction focus wants to move. One of FOCUS_UP,
6267     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6268     * @return True if the this view consumed this unhandled move.
6269     */
6270    public boolean dispatchUnhandledMove(View focused, int direction) {
6271        return false;
6272    }
6273
6274    /**
6275     * If a user manually specified the next view id for a particular direction,
6276     * use the root to look up the view.
6277     * @param root The root view of the hierarchy containing this view.
6278     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6279     * or FOCUS_BACKWARD.
6280     * @return The user specified next view, or null if there is none.
6281     */
6282    View findUserSetNextFocus(View root, int direction) {
6283        switch (direction) {
6284            case FOCUS_LEFT:
6285                if (mNextFocusLeftId == View.NO_ID) return null;
6286                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6287            case FOCUS_RIGHT:
6288                if (mNextFocusRightId == View.NO_ID) return null;
6289                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6290            case FOCUS_UP:
6291                if (mNextFocusUpId == View.NO_ID) return null;
6292                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6293            case FOCUS_DOWN:
6294                if (mNextFocusDownId == View.NO_ID) return null;
6295                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6296            case FOCUS_FORWARD:
6297                if (mNextFocusForwardId == View.NO_ID) return null;
6298                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6299            case FOCUS_BACKWARD: {
6300                if (mID == View.NO_ID) return null;
6301                final int id = mID;
6302                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6303                    @Override
6304                    public boolean apply(View t) {
6305                        return t.mNextFocusForwardId == id;
6306                    }
6307                });
6308            }
6309        }
6310        return null;
6311    }
6312
6313    private View findViewInsideOutShouldExist(View root, int id) {
6314        if (mMatchIdPredicate == null) {
6315            mMatchIdPredicate = new MatchIdPredicate();
6316        }
6317        mMatchIdPredicate.mId = id;
6318        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6319        if (result == null) {
6320            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6321        }
6322        return result;
6323    }
6324
6325    /**
6326     * Find and return all focusable views that are descendants of this view,
6327     * possibly including this view if it is focusable itself.
6328     *
6329     * @param direction The direction of the focus
6330     * @return A list of focusable views
6331     */
6332    public ArrayList<View> getFocusables(int direction) {
6333        ArrayList<View> result = new ArrayList<View>(24);
6334        addFocusables(result, direction);
6335        return result;
6336    }
6337
6338    /**
6339     * Add any focusable views that are descendants of this view (possibly
6340     * including this view if it is focusable itself) to views.  If we are in touch mode,
6341     * only add views that are also focusable in touch mode.
6342     *
6343     * @param views Focusable views found so far
6344     * @param direction The direction of the focus
6345     */
6346    public void addFocusables(ArrayList<View> views, int direction) {
6347        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6348    }
6349
6350    /**
6351     * Adds any focusable views that are descendants of this view (possibly
6352     * including this view if it is focusable itself) to views. This method
6353     * adds all focusable views regardless if we are in touch mode or
6354     * only views focusable in touch mode if we are in touch mode or
6355     * only views that can take accessibility focus if accessibility is enabeld
6356     * depending on the focusable mode paramater.
6357     *
6358     * @param views Focusable views found so far or null if all we are interested is
6359     *        the number of focusables.
6360     * @param direction The direction of the focus.
6361     * @param focusableMode The type of focusables to be added.
6362     *
6363     * @see #FOCUSABLES_ALL
6364     * @see #FOCUSABLES_TOUCH_MODE
6365     */
6366    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6367        if (views == null) {
6368            return;
6369        }
6370        if (!isFocusable()) {
6371            return;
6372        }
6373        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6374                && isInTouchMode() && !isFocusableInTouchMode()) {
6375            return;
6376        }
6377        views.add(this);
6378    }
6379
6380    /**
6381     * Finds the Views that contain given text. The containment is case insensitive.
6382     * The search is performed by either the text that the View renders or the content
6383     * description that describes the view for accessibility purposes and the view does
6384     * not render or both. Clients can specify how the search is to be performed via
6385     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6386     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6387     *
6388     * @param outViews The output list of matching Views.
6389     * @param searched The text to match against.
6390     *
6391     * @see #FIND_VIEWS_WITH_TEXT
6392     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6393     * @see #setContentDescription(CharSequence)
6394     */
6395    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6396        if (getAccessibilityNodeProvider() != null) {
6397            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6398                outViews.add(this);
6399            }
6400        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6401                && (searched != null && searched.length() > 0)
6402                && (mContentDescription != null && mContentDescription.length() > 0)) {
6403            String searchedLowerCase = searched.toString().toLowerCase();
6404            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6405            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6406                outViews.add(this);
6407            }
6408        }
6409    }
6410
6411    /**
6412     * Find and return all touchable views that are descendants of this view,
6413     * possibly including this view if it is touchable itself.
6414     *
6415     * @return A list of touchable views
6416     */
6417    public ArrayList<View> getTouchables() {
6418        ArrayList<View> result = new ArrayList<View>();
6419        addTouchables(result);
6420        return result;
6421    }
6422
6423    /**
6424     * Add any touchable views that are descendants of this view (possibly
6425     * including this view if it is touchable itself) to views.
6426     *
6427     * @param views Touchable views found so far
6428     */
6429    public void addTouchables(ArrayList<View> views) {
6430        final int viewFlags = mViewFlags;
6431
6432        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6433                && (viewFlags & ENABLED_MASK) == ENABLED) {
6434            views.add(this);
6435        }
6436    }
6437
6438    /**
6439     * Returns whether this View is accessibility focused.
6440     *
6441     * @return True if this View is accessibility focused.
6442     */
6443    boolean isAccessibilityFocused() {
6444        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6445    }
6446
6447    /**
6448     * Call this to try to give accessibility focus to this view.
6449     *
6450     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6451     * returns false or the view is no visible or the view already has accessibility
6452     * focus.
6453     *
6454     * See also {@link #focusSearch(int)}, which is what you call to say that you
6455     * have focus, and you want your parent to look for the next one.
6456     *
6457     * @return Whether this view actually took accessibility focus.
6458     *
6459     * @hide
6460     */
6461    public boolean requestAccessibilityFocus() {
6462        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6463        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6464            return false;
6465        }
6466        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6467            return false;
6468        }
6469        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6470            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6471            ViewRootImpl viewRootImpl = getViewRootImpl();
6472            if (viewRootImpl != null) {
6473                viewRootImpl.setAccessibilityFocus(this, null);
6474            }
6475            invalidate();
6476            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6477            notifyAccessibilityStateChanged();
6478            return true;
6479        }
6480        return false;
6481    }
6482
6483    /**
6484     * Call this to try to clear accessibility focus of this view.
6485     *
6486     * See also {@link #focusSearch(int)}, which is what you call to say that you
6487     * have focus, and you want your parent to look for the next one.
6488     *
6489     * @hide
6490     */
6491    public void clearAccessibilityFocus() {
6492        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6493            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6494            invalidate();
6495            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6496            notifyAccessibilityStateChanged();
6497        }
6498        // Clear the global reference of accessibility focus if this
6499        // view or any of its descendants had accessibility focus.
6500        ViewRootImpl viewRootImpl = getViewRootImpl();
6501        if (viewRootImpl != null) {
6502            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6503            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6504                viewRootImpl.setAccessibilityFocus(null, null);
6505            }
6506        }
6507    }
6508
6509    private void sendAccessibilityHoverEvent(int eventType) {
6510        // Since we are not delivering to a client accessibility events from not
6511        // important views (unless the clinet request that) we need to fire the
6512        // event from the deepest view exposed to the client. As a consequence if
6513        // the user crosses a not exposed view the client will see enter and exit
6514        // of the exposed predecessor followed by and enter and exit of that same
6515        // predecessor when entering and exiting the not exposed descendant. This
6516        // is fine since the client has a clear idea which view is hovered at the
6517        // price of a couple more events being sent. This is a simple and
6518        // working solution.
6519        View source = this;
6520        while (true) {
6521            if (source.includeForAccessibility()) {
6522                source.sendAccessibilityEvent(eventType);
6523                return;
6524            }
6525            ViewParent parent = source.getParent();
6526            if (parent instanceof View) {
6527                source = (View) parent;
6528            } else {
6529                return;
6530            }
6531        }
6532    }
6533
6534    /**
6535     * Clears accessibility focus without calling any callback methods
6536     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6537     * is used for clearing accessibility focus when giving this focus to
6538     * another view.
6539     */
6540    void clearAccessibilityFocusNoCallbacks() {
6541        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6542            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6543            invalidate();
6544        }
6545    }
6546
6547    /**
6548     * Call this to try to give focus to a specific view or to one of its
6549     * descendants.
6550     *
6551     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6552     * false), or if it is focusable and it is not focusable in touch mode
6553     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6554     *
6555     * See also {@link #focusSearch(int)}, which is what you call to say that you
6556     * have focus, and you want your parent to look for the next one.
6557     *
6558     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6559     * {@link #FOCUS_DOWN} and <code>null</code>.
6560     *
6561     * @return Whether this view or one of its descendants actually took focus.
6562     */
6563    public final boolean requestFocus() {
6564        return requestFocus(View.FOCUS_DOWN);
6565    }
6566
6567    /**
6568     * Call this to try to give focus to a specific view or to one of its
6569     * descendants and give it a hint about what direction focus is heading.
6570     *
6571     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6572     * false), or if it is focusable and it is not focusable in touch mode
6573     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6574     *
6575     * See also {@link #focusSearch(int)}, which is what you call to say that you
6576     * have focus, and you want your parent to look for the next one.
6577     *
6578     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6579     * <code>null</code> set for the previously focused rectangle.
6580     *
6581     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6582     * @return Whether this view or one of its descendants actually took focus.
6583     */
6584    public final boolean requestFocus(int direction) {
6585        return requestFocus(direction, null);
6586    }
6587
6588    /**
6589     * Call this to try to give focus to a specific view or to one of its descendants
6590     * and give it hints about the direction and a specific rectangle that the focus
6591     * is coming from.  The rectangle can help give larger views a finer grained hint
6592     * about where focus is coming from, and therefore, where to show selection, or
6593     * forward focus change internally.
6594     *
6595     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6596     * false), or if it is focusable and it is not focusable in touch mode
6597     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6598     *
6599     * A View will not take focus if it is not visible.
6600     *
6601     * A View will not take focus if one of its parents has
6602     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6603     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6604     *
6605     * See also {@link #focusSearch(int)}, which is what you call to say that you
6606     * have focus, and you want your parent to look for the next one.
6607     *
6608     * You may wish to override this method if your custom {@link View} has an internal
6609     * {@link View} that it wishes to forward the request to.
6610     *
6611     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6612     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6613     *        to give a finer grained hint about where focus is coming from.  May be null
6614     *        if there is no hint.
6615     * @return Whether this view or one of its descendants actually took focus.
6616     */
6617    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6618        return requestFocusNoSearch(direction, previouslyFocusedRect);
6619    }
6620
6621    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6622        // need to be focusable
6623        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6624                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6625            return false;
6626        }
6627
6628        // need to be focusable in touch mode if in touch mode
6629        if (isInTouchMode() &&
6630            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6631               return false;
6632        }
6633
6634        // need to not have any parents blocking us
6635        if (hasAncestorThatBlocksDescendantFocus()) {
6636            return false;
6637        }
6638
6639        handleFocusGainInternal(direction, previouslyFocusedRect);
6640        return true;
6641    }
6642
6643    /**
6644     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6645     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6646     * touch mode to request focus when they are touched.
6647     *
6648     * @return Whether this view or one of its descendants actually took focus.
6649     *
6650     * @see #isInTouchMode()
6651     *
6652     */
6653    public final boolean requestFocusFromTouch() {
6654        // Leave touch mode if we need to
6655        if (isInTouchMode()) {
6656            ViewRootImpl viewRoot = getViewRootImpl();
6657            if (viewRoot != null) {
6658                viewRoot.ensureTouchMode(false);
6659            }
6660        }
6661        return requestFocus(View.FOCUS_DOWN);
6662    }
6663
6664    /**
6665     * @return Whether any ancestor of this view blocks descendant focus.
6666     */
6667    private boolean hasAncestorThatBlocksDescendantFocus() {
6668        ViewParent ancestor = mParent;
6669        while (ancestor instanceof ViewGroup) {
6670            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6671            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6672                return true;
6673            } else {
6674                ancestor = vgAncestor.getParent();
6675            }
6676        }
6677        return false;
6678    }
6679
6680    /**
6681     * Gets the mode for determining whether this View is important for accessibility
6682     * which is if it fires accessibility events and if it is reported to
6683     * accessibility services that query the screen.
6684     *
6685     * @return The mode for determining whether a View is important for accessibility.
6686     *
6687     * @attr ref android.R.styleable#View_importantForAccessibility
6688     *
6689     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6690     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6691     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6692     */
6693    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6694            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6695            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6696            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6697        })
6698    public int getImportantForAccessibility() {
6699        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6700                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6701    }
6702
6703    /**
6704     * Sets how to determine whether this view is important for accessibility
6705     * which is if it fires accessibility events and if it is reported to
6706     * accessibility services that query the screen.
6707     *
6708     * @param mode How to determine whether this view is important for accessibility.
6709     *
6710     * @attr ref android.R.styleable#View_importantForAccessibility
6711     *
6712     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6713     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6714     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6715     */
6716    public void setImportantForAccessibility(int mode) {
6717        if (mode != getImportantForAccessibility()) {
6718            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6719            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6720                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6721            notifyAccessibilityStateChanged();
6722        }
6723    }
6724
6725    /**
6726     * Gets whether this view should be exposed for accessibility.
6727     *
6728     * @return Whether the view is exposed for accessibility.
6729     *
6730     * @hide
6731     */
6732    public boolean isImportantForAccessibility() {
6733        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6734                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6735        switch (mode) {
6736            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6737                return true;
6738            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6739                return false;
6740            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6741                return isActionableForAccessibility() || hasListenersForAccessibility()
6742                        || getAccessibilityNodeProvider() != null;
6743            default:
6744                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6745                        + mode);
6746        }
6747    }
6748
6749    /**
6750     * Gets the parent for accessibility purposes. Note that the parent for
6751     * accessibility is not necessary the immediate parent. It is the first
6752     * predecessor that is important for accessibility.
6753     *
6754     * @return The parent for accessibility purposes.
6755     */
6756    public ViewParent getParentForAccessibility() {
6757        if (mParent instanceof View) {
6758            View parentView = (View) mParent;
6759            if (parentView.includeForAccessibility()) {
6760                return mParent;
6761            } else {
6762                return mParent.getParentForAccessibility();
6763            }
6764        }
6765        return null;
6766    }
6767
6768    /**
6769     * Adds the children of a given View for accessibility. Since some Views are
6770     * not important for accessibility the children for accessibility are not
6771     * necessarily direct children of the riew, rather they are the first level of
6772     * descendants important for accessibility.
6773     *
6774     * @param children The list of children for accessibility.
6775     */
6776    public void addChildrenForAccessibility(ArrayList<View> children) {
6777        if (includeForAccessibility()) {
6778            children.add(this);
6779        }
6780    }
6781
6782    /**
6783     * Whether to regard this view for accessibility. A view is regarded for
6784     * accessibility if it is important for accessibility or the querying
6785     * accessibility service has explicitly requested that view not
6786     * important for accessibility are regarded.
6787     *
6788     * @return Whether to regard the view for accessibility.
6789     *
6790     * @hide
6791     */
6792    public boolean includeForAccessibility() {
6793        if (mAttachInfo != null) {
6794            return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility();
6795        }
6796        return false;
6797    }
6798
6799    /**
6800     * Returns whether the View is considered actionable from
6801     * accessibility perspective. Such view are important for
6802     * accessibility.
6803     *
6804     * @return True if the view is actionable for accessibility.
6805     *
6806     * @hide
6807     */
6808    public boolean isActionableForAccessibility() {
6809        return (isClickable() || isLongClickable() || isFocusable());
6810    }
6811
6812    /**
6813     * Returns whether the View has registered callbacks wich makes it
6814     * important for accessibility.
6815     *
6816     * @return True if the view is actionable for accessibility.
6817     */
6818    private boolean hasListenersForAccessibility() {
6819        ListenerInfo info = getListenerInfo();
6820        return mTouchDelegate != null || info.mOnKeyListener != null
6821                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6822                || info.mOnHoverListener != null || info.mOnDragListener != null;
6823    }
6824
6825    /**
6826     * Notifies accessibility services that some view's important for
6827     * accessibility state has changed. Note that such notifications
6828     * are made at most once every
6829     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6830     * to avoid unnecessary load to the system. Also once a view has
6831     * made a notifucation this method is a NOP until the notification has
6832     * been sent to clients.
6833     *
6834     * @hide
6835     *
6836     * TODO: Makse sure this method is called for any view state change
6837     *       that is interesting for accessilility purposes.
6838     */
6839    public void notifyAccessibilityStateChanged() {
6840        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6841            return;
6842        }
6843        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) {
6844            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6845            if (mParent != null) {
6846                mParent.childAccessibilityStateChanged(this);
6847            }
6848        }
6849    }
6850
6851    /**
6852     * Reset the state indicating the this view has requested clients
6853     * interested in its accessibility state to be notified.
6854     *
6855     * @hide
6856     */
6857    public void resetAccessibilityStateChanged() {
6858        mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6859    }
6860
6861    /**
6862     * Performs the specified accessibility action on the view. For
6863     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6864     * <p>
6865     * If an {@link AccessibilityDelegate} has been specified via calling
6866     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6867     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6868     * is responsible for handling this call.
6869     * </p>
6870     *
6871     * @param action The action to perform.
6872     * @param arguments Optional action arguments.
6873     * @return Whether the action was performed.
6874     */
6875    public boolean performAccessibilityAction(int action, Bundle arguments) {
6876      if (mAccessibilityDelegate != null) {
6877          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6878      } else {
6879          return performAccessibilityActionInternal(action, arguments);
6880      }
6881    }
6882
6883   /**
6884    * @see #performAccessibilityAction(int, Bundle)
6885    *
6886    * Note: Called from the default {@link AccessibilityDelegate}.
6887    */
6888    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6889        switch (action) {
6890            case AccessibilityNodeInfo.ACTION_CLICK: {
6891                if (isClickable()) {
6892                    performClick();
6893                    return true;
6894                }
6895            } break;
6896            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6897                if (isLongClickable()) {
6898                    performLongClick();
6899                    return true;
6900                }
6901            } break;
6902            case AccessibilityNodeInfo.ACTION_FOCUS: {
6903                if (!hasFocus()) {
6904                    // Get out of touch mode since accessibility
6905                    // wants to move focus around.
6906                    getViewRootImpl().ensureTouchMode(false);
6907                    return requestFocus();
6908                }
6909            } break;
6910            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6911                if (hasFocus()) {
6912                    clearFocus();
6913                    return !isFocused();
6914                }
6915            } break;
6916            case AccessibilityNodeInfo.ACTION_SELECT: {
6917                if (!isSelected()) {
6918                    setSelected(true);
6919                    return isSelected();
6920                }
6921            } break;
6922            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6923                if (isSelected()) {
6924                    setSelected(false);
6925                    return !isSelected();
6926                }
6927            } break;
6928            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6929                if (!isAccessibilityFocused()) {
6930                    return requestAccessibilityFocus();
6931                }
6932            } break;
6933            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6934                if (isAccessibilityFocused()) {
6935                    clearAccessibilityFocus();
6936                    return true;
6937                }
6938            } break;
6939            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6940                if (arguments != null) {
6941                    final int granularity = arguments.getInt(
6942                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6943                    return nextAtGranularity(granularity);
6944                }
6945            } break;
6946            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6947                if (arguments != null) {
6948                    final int granularity = arguments.getInt(
6949                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6950                    return previousAtGranularity(granularity);
6951                }
6952            } break;
6953        }
6954        return false;
6955    }
6956
6957    private boolean nextAtGranularity(int granularity) {
6958        CharSequence text = getIterableTextForAccessibility();
6959        if (text == null || text.length() == 0) {
6960            return false;
6961        }
6962        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6963        if (iterator == null) {
6964            return false;
6965        }
6966        final int current = getAccessibilityCursorPosition();
6967        final int[] range = iterator.following(current);
6968        if (range == null) {
6969            return false;
6970        }
6971        final int start = range[0];
6972        final int end = range[1];
6973        setAccessibilityCursorPosition(end);
6974        sendViewTextTraversedAtGranularityEvent(
6975                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6976                granularity, start, end);
6977        return true;
6978    }
6979
6980    private boolean previousAtGranularity(int granularity) {
6981        CharSequence text = getIterableTextForAccessibility();
6982        if (text == null || text.length() == 0) {
6983            return false;
6984        }
6985        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6986        if (iterator == null) {
6987            return false;
6988        }
6989        int current = getAccessibilityCursorPosition();
6990        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
6991            current = text.length();
6992        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6993            // When traversing by character we always put the cursor after the character
6994            // to ease edit and have to compensate before asking the for previous segment.
6995            current--;
6996        }
6997        final int[] range = iterator.preceding(current);
6998        if (range == null) {
6999            return false;
7000        }
7001        final int start = range[0];
7002        final int end = range[1];
7003        // Always put the cursor after the character to ease edit.
7004        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
7005            setAccessibilityCursorPosition(end);
7006        } else {
7007            setAccessibilityCursorPosition(start);
7008        }
7009        sendViewTextTraversedAtGranularityEvent(
7010                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
7011                granularity, start, end);
7012        return true;
7013    }
7014
7015    /**
7016     * Gets the text reported for accessibility purposes.
7017     *
7018     * @return The accessibility text.
7019     *
7020     * @hide
7021     */
7022    public CharSequence getIterableTextForAccessibility() {
7023        return getContentDescription();
7024    }
7025
7026    /**
7027     * @hide
7028     */
7029    public int getAccessibilityCursorPosition() {
7030        return mAccessibilityCursorPosition;
7031    }
7032
7033    /**
7034     * @hide
7035     */
7036    public void setAccessibilityCursorPosition(int position) {
7037        mAccessibilityCursorPosition = position;
7038    }
7039
7040    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7041            int fromIndex, int toIndex) {
7042        if (mParent == null) {
7043            return;
7044        }
7045        AccessibilityEvent event = AccessibilityEvent.obtain(
7046                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7047        onInitializeAccessibilityEvent(event);
7048        onPopulateAccessibilityEvent(event);
7049        event.setFromIndex(fromIndex);
7050        event.setToIndex(toIndex);
7051        event.setAction(action);
7052        event.setMovementGranularity(granularity);
7053        mParent.requestSendAccessibilityEvent(this, event);
7054    }
7055
7056    /**
7057     * @hide
7058     */
7059    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7060        switch (granularity) {
7061            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7062                CharSequence text = getIterableTextForAccessibility();
7063                if (text != null && text.length() > 0) {
7064                    CharacterTextSegmentIterator iterator =
7065                        CharacterTextSegmentIterator.getInstance(
7066                                mContext.getResources().getConfiguration().locale);
7067                    iterator.initialize(text.toString());
7068                    return iterator;
7069                }
7070            } break;
7071            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7072                CharSequence text = getIterableTextForAccessibility();
7073                if (text != null && text.length() > 0) {
7074                    WordTextSegmentIterator iterator =
7075                        WordTextSegmentIterator.getInstance(
7076                                mContext.getResources().getConfiguration().locale);
7077                    iterator.initialize(text.toString());
7078                    return iterator;
7079                }
7080            } break;
7081            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7082                CharSequence text = getIterableTextForAccessibility();
7083                if (text != null && text.length() > 0) {
7084                    ParagraphTextSegmentIterator iterator =
7085                        ParagraphTextSegmentIterator.getInstance();
7086                    iterator.initialize(text.toString());
7087                    return iterator;
7088                }
7089            } break;
7090        }
7091        return null;
7092    }
7093
7094    /**
7095     * @hide
7096     */
7097    public void dispatchStartTemporaryDetach() {
7098        clearAccessibilityFocus();
7099        clearDisplayList();
7100
7101        onStartTemporaryDetach();
7102    }
7103
7104    /**
7105     * This is called when a container is going to temporarily detach a child, with
7106     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7107     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7108     * {@link #onDetachedFromWindow()} when the container is done.
7109     */
7110    public void onStartTemporaryDetach() {
7111        removeUnsetPressCallback();
7112        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7113    }
7114
7115    /**
7116     * @hide
7117     */
7118    public void dispatchFinishTemporaryDetach() {
7119        onFinishTemporaryDetach();
7120    }
7121
7122    /**
7123     * Called after {@link #onStartTemporaryDetach} when the container is done
7124     * changing the view.
7125     */
7126    public void onFinishTemporaryDetach() {
7127    }
7128
7129    /**
7130     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7131     * for this view's window.  Returns null if the view is not currently attached
7132     * to the window.  Normally you will not need to use this directly, but
7133     * just use the standard high-level event callbacks like
7134     * {@link #onKeyDown(int, KeyEvent)}.
7135     */
7136    public KeyEvent.DispatcherState getKeyDispatcherState() {
7137        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7138    }
7139
7140    /**
7141     * Dispatch a key event before it is processed by any input method
7142     * associated with the view hierarchy.  This can be used to intercept
7143     * key events in special situations before the IME consumes them; a
7144     * typical example would be handling the BACK key to update the application's
7145     * UI instead of allowing the IME to see it and close itself.
7146     *
7147     * @param event The key event to be dispatched.
7148     * @return True if the event was handled, false otherwise.
7149     */
7150    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7151        return onKeyPreIme(event.getKeyCode(), event);
7152    }
7153
7154    /**
7155     * Dispatch a key event to the next view on the focus path. This path runs
7156     * from the top of the view tree down to the currently focused view. If this
7157     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7158     * the next node down the focus path. This method also fires any key
7159     * listeners.
7160     *
7161     * @param event The key event to be dispatched.
7162     * @return True if the event was handled, false otherwise.
7163     */
7164    public boolean dispatchKeyEvent(KeyEvent event) {
7165        if (mInputEventConsistencyVerifier != null) {
7166            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7167        }
7168
7169        // Give any attached key listener a first crack at the event.
7170        //noinspection SimplifiableIfStatement
7171        ListenerInfo li = mListenerInfo;
7172        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7173                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7174            return true;
7175        }
7176
7177        if (event.dispatch(this, mAttachInfo != null
7178                ? mAttachInfo.mKeyDispatchState : null, this)) {
7179            return true;
7180        }
7181
7182        if (mInputEventConsistencyVerifier != null) {
7183            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7184        }
7185        return false;
7186    }
7187
7188    /**
7189     * Dispatches a key shortcut event.
7190     *
7191     * @param event The key event to be dispatched.
7192     * @return True if the event was handled by the view, false otherwise.
7193     */
7194    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7195        return onKeyShortcut(event.getKeyCode(), event);
7196    }
7197
7198    /**
7199     * Pass the touch screen motion event down to the target view, or this
7200     * view if it is the target.
7201     *
7202     * @param event The motion event to be dispatched.
7203     * @return True if the event was handled by the view, false otherwise.
7204     */
7205    public boolean dispatchTouchEvent(MotionEvent event) {
7206        if (mInputEventConsistencyVerifier != null) {
7207            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7208        }
7209
7210        if (onFilterTouchEventForSecurity(event)) {
7211            //noinspection SimplifiableIfStatement
7212            ListenerInfo li = mListenerInfo;
7213            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7214                    && li.mOnTouchListener.onTouch(this, event)) {
7215                return true;
7216            }
7217
7218            if (onTouchEvent(event)) {
7219                return true;
7220            }
7221        }
7222
7223        if (mInputEventConsistencyVerifier != null) {
7224            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7225        }
7226        return false;
7227    }
7228
7229    /**
7230     * Filter the touch event to apply security policies.
7231     *
7232     * @param event The motion event to be filtered.
7233     * @return True if the event should be dispatched, false if the event should be dropped.
7234     *
7235     * @see #getFilterTouchesWhenObscured
7236     */
7237    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7238        //noinspection RedundantIfStatement
7239        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7240                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7241            // Window is obscured, drop this touch.
7242            return false;
7243        }
7244        return true;
7245    }
7246
7247    /**
7248     * Pass a trackball motion event down to the focused view.
7249     *
7250     * @param event The motion event to be dispatched.
7251     * @return True if the event was handled by the view, false otherwise.
7252     */
7253    public boolean dispatchTrackballEvent(MotionEvent event) {
7254        if (mInputEventConsistencyVerifier != null) {
7255            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7256        }
7257
7258        return onTrackballEvent(event);
7259    }
7260
7261    /**
7262     * Dispatch a generic motion event.
7263     * <p>
7264     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7265     * are delivered to the view under the pointer.  All other generic motion events are
7266     * delivered to the focused view.  Hover events are handled specially and are delivered
7267     * to {@link #onHoverEvent(MotionEvent)}.
7268     * </p>
7269     *
7270     * @param event The motion event to be dispatched.
7271     * @return True if the event was handled by the view, false otherwise.
7272     */
7273    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7274        if (mInputEventConsistencyVerifier != null) {
7275            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7276        }
7277
7278        final int source = event.getSource();
7279        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7280            final int action = event.getAction();
7281            if (action == MotionEvent.ACTION_HOVER_ENTER
7282                    || action == MotionEvent.ACTION_HOVER_MOVE
7283                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7284                if (dispatchHoverEvent(event)) {
7285                    return true;
7286                }
7287            } else if (dispatchGenericPointerEvent(event)) {
7288                return true;
7289            }
7290        } else if (dispatchGenericFocusedEvent(event)) {
7291            return true;
7292        }
7293
7294        if (dispatchGenericMotionEventInternal(event)) {
7295            return true;
7296        }
7297
7298        if (mInputEventConsistencyVerifier != null) {
7299            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7300        }
7301        return false;
7302    }
7303
7304    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7305        //noinspection SimplifiableIfStatement
7306        ListenerInfo li = mListenerInfo;
7307        if (li != null && li.mOnGenericMotionListener != null
7308                && (mViewFlags & ENABLED_MASK) == ENABLED
7309                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7310            return true;
7311        }
7312
7313        if (onGenericMotionEvent(event)) {
7314            return true;
7315        }
7316
7317        if (mInputEventConsistencyVerifier != null) {
7318            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7319        }
7320        return false;
7321    }
7322
7323    /**
7324     * Dispatch a hover event.
7325     * <p>
7326     * Do not call this method directly.
7327     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7328     * </p>
7329     *
7330     * @param event The motion event to be dispatched.
7331     * @return True if the event was handled by the view, false otherwise.
7332     */
7333    protected boolean dispatchHoverEvent(MotionEvent event) {
7334        //noinspection SimplifiableIfStatement
7335        ListenerInfo li = mListenerInfo;
7336        if (li != null && li.mOnHoverListener != null
7337                && (mViewFlags & ENABLED_MASK) == ENABLED
7338                && li.mOnHoverListener.onHover(this, event)) {
7339            return true;
7340        }
7341
7342        return onHoverEvent(event);
7343    }
7344
7345    /**
7346     * Returns true if the view has a child to which it has recently sent
7347     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7348     * it does not have a hovered child, then it must be the innermost hovered view.
7349     * @hide
7350     */
7351    protected boolean hasHoveredChild() {
7352        return false;
7353    }
7354
7355    /**
7356     * Dispatch a generic motion event to the view under the first pointer.
7357     * <p>
7358     * Do not call this method directly.
7359     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7360     * </p>
7361     *
7362     * @param event The motion event to be dispatched.
7363     * @return True if the event was handled by the view, false otherwise.
7364     */
7365    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7366        return false;
7367    }
7368
7369    /**
7370     * Dispatch a generic motion event to the currently focused view.
7371     * <p>
7372     * Do not call this method directly.
7373     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7374     * </p>
7375     *
7376     * @param event The motion event to be dispatched.
7377     * @return True if the event was handled by the view, false otherwise.
7378     */
7379    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7380        return false;
7381    }
7382
7383    /**
7384     * Dispatch a pointer event.
7385     * <p>
7386     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7387     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7388     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7389     * and should not be expected to handle other pointing device features.
7390     * </p>
7391     *
7392     * @param event The motion event to be dispatched.
7393     * @return True if the event was handled by the view, false otherwise.
7394     * @hide
7395     */
7396    public final boolean dispatchPointerEvent(MotionEvent event) {
7397        if (event.isTouchEvent()) {
7398            return dispatchTouchEvent(event);
7399        } else {
7400            return dispatchGenericMotionEvent(event);
7401        }
7402    }
7403
7404    /**
7405     * Called when the window containing this view gains or loses window focus.
7406     * ViewGroups should override to route to their children.
7407     *
7408     * @param hasFocus True if the window containing this view now has focus,
7409     *        false otherwise.
7410     */
7411    public void dispatchWindowFocusChanged(boolean hasFocus) {
7412        onWindowFocusChanged(hasFocus);
7413    }
7414
7415    /**
7416     * Called when the window containing this view gains or loses focus.  Note
7417     * that this is separate from view focus: to receive key events, both
7418     * your view and its window must have focus.  If a window is displayed
7419     * on top of yours that takes input focus, then your own window will lose
7420     * focus but the view focus will remain unchanged.
7421     *
7422     * @param hasWindowFocus True if the window containing this view now has
7423     *        focus, false otherwise.
7424     */
7425    public void onWindowFocusChanged(boolean hasWindowFocus) {
7426        InputMethodManager imm = InputMethodManager.peekInstance();
7427        if (!hasWindowFocus) {
7428            if (isPressed()) {
7429                setPressed(false);
7430            }
7431            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7432                imm.focusOut(this);
7433            }
7434            removeLongPressCallback();
7435            removeTapCallback();
7436            onFocusLost();
7437        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7438            imm.focusIn(this);
7439        }
7440        refreshDrawableState();
7441    }
7442
7443    /**
7444     * Returns true if this view is in a window that currently has window focus.
7445     * Note that this is not the same as the view itself having focus.
7446     *
7447     * @return True if this view is in a window that currently has window focus.
7448     */
7449    public boolean hasWindowFocus() {
7450        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7451    }
7452
7453    /**
7454     * Dispatch a view visibility change down the view hierarchy.
7455     * ViewGroups should override to route to their children.
7456     * @param changedView The view whose visibility changed. Could be 'this' or
7457     * an ancestor view.
7458     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7459     * {@link #INVISIBLE} or {@link #GONE}.
7460     */
7461    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7462        onVisibilityChanged(changedView, visibility);
7463    }
7464
7465    /**
7466     * Called when the visibility of the view or an ancestor of the view is changed.
7467     * @param changedView The view whose visibility changed. Could be 'this' or
7468     * an ancestor view.
7469     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7470     * {@link #INVISIBLE} or {@link #GONE}.
7471     */
7472    protected void onVisibilityChanged(View changedView, int visibility) {
7473        if (visibility == VISIBLE) {
7474            if (mAttachInfo != null) {
7475                initialAwakenScrollBars();
7476            } else {
7477                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7478            }
7479        }
7480    }
7481
7482    /**
7483     * Dispatch a hint about whether this view is displayed. For instance, when
7484     * a View moves out of the screen, it might receives a display hint indicating
7485     * the view is not displayed. Applications should not <em>rely</em> on this hint
7486     * as there is no guarantee that they will receive one.
7487     *
7488     * @param hint A hint about whether or not this view is displayed:
7489     * {@link #VISIBLE} or {@link #INVISIBLE}.
7490     */
7491    public void dispatchDisplayHint(int hint) {
7492        onDisplayHint(hint);
7493    }
7494
7495    /**
7496     * Gives this view a hint about whether is displayed or not. For instance, when
7497     * a View moves out of the screen, it might receives a display hint indicating
7498     * the view is not displayed. Applications should not <em>rely</em> on this hint
7499     * as there is no guarantee that they will receive one.
7500     *
7501     * @param hint A hint about whether or not this view is displayed:
7502     * {@link #VISIBLE} or {@link #INVISIBLE}.
7503     */
7504    protected void onDisplayHint(int hint) {
7505    }
7506
7507    /**
7508     * Dispatch a window visibility change down the view hierarchy.
7509     * ViewGroups should override to route to their children.
7510     *
7511     * @param visibility The new visibility of the window.
7512     *
7513     * @see #onWindowVisibilityChanged(int)
7514     */
7515    public void dispatchWindowVisibilityChanged(int visibility) {
7516        onWindowVisibilityChanged(visibility);
7517    }
7518
7519    /**
7520     * Called when the window containing has change its visibility
7521     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7522     * that this tells you whether or not your window is being made visible
7523     * to the window manager; this does <em>not</em> tell you whether or not
7524     * your window is obscured by other windows on the screen, even if it
7525     * is itself visible.
7526     *
7527     * @param visibility The new visibility of the window.
7528     */
7529    protected void onWindowVisibilityChanged(int visibility) {
7530        if (visibility == VISIBLE) {
7531            initialAwakenScrollBars();
7532        }
7533    }
7534
7535    /**
7536     * Returns the current visibility of the window this view is attached to
7537     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7538     *
7539     * @return Returns the current visibility of the view's window.
7540     */
7541    public int getWindowVisibility() {
7542        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7543    }
7544
7545    /**
7546     * Retrieve the overall visible display size in which the window this view is
7547     * attached to has been positioned in.  This takes into account screen
7548     * decorations above the window, for both cases where the window itself
7549     * is being position inside of them or the window is being placed under
7550     * then and covered insets are used for the window to position its content
7551     * inside.  In effect, this tells you the available area where content can
7552     * be placed and remain visible to users.
7553     *
7554     * <p>This function requires an IPC back to the window manager to retrieve
7555     * the requested information, so should not be used in performance critical
7556     * code like drawing.
7557     *
7558     * @param outRect Filled in with the visible display frame.  If the view
7559     * is not attached to a window, this is simply the raw display size.
7560     */
7561    public void getWindowVisibleDisplayFrame(Rect outRect) {
7562        if (mAttachInfo != null) {
7563            try {
7564                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7565            } catch (RemoteException e) {
7566                return;
7567            }
7568            // XXX This is really broken, and probably all needs to be done
7569            // in the window manager, and we need to know more about whether
7570            // we want the area behind or in front of the IME.
7571            final Rect insets = mAttachInfo.mVisibleInsets;
7572            outRect.left += insets.left;
7573            outRect.top += insets.top;
7574            outRect.right -= insets.right;
7575            outRect.bottom -= insets.bottom;
7576            return;
7577        }
7578        // The view is not attached to a display so we don't have a context.
7579        // Make a best guess about the display size.
7580        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7581        d.getRectSize(outRect);
7582    }
7583
7584    /**
7585     * Dispatch a notification about a resource configuration change down
7586     * the view hierarchy.
7587     * ViewGroups should override to route to their children.
7588     *
7589     * @param newConfig The new resource configuration.
7590     *
7591     * @see #onConfigurationChanged(android.content.res.Configuration)
7592     */
7593    public void dispatchConfigurationChanged(Configuration newConfig) {
7594        onConfigurationChanged(newConfig);
7595    }
7596
7597    /**
7598     * Called when the current configuration of the resources being used
7599     * by the application have changed.  You can use this to decide when
7600     * to reload resources that can changed based on orientation and other
7601     * configuration characterstics.  You only need to use this if you are
7602     * not relying on the normal {@link android.app.Activity} mechanism of
7603     * recreating the activity instance upon a configuration change.
7604     *
7605     * @param newConfig The new resource configuration.
7606     */
7607    protected void onConfigurationChanged(Configuration newConfig) {
7608    }
7609
7610    /**
7611     * Private function to aggregate all per-view attributes in to the view
7612     * root.
7613     */
7614    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7615        performCollectViewAttributes(attachInfo, visibility);
7616    }
7617
7618    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7619        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7620            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7621                attachInfo.mKeepScreenOn = true;
7622            }
7623            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7624            ListenerInfo li = mListenerInfo;
7625            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7626                attachInfo.mHasSystemUiListeners = true;
7627            }
7628        }
7629    }
7630
7631    void needGlobalAttributesUpdate(boolean force) {
7632        final AttachInfo ai = mAttachInfo;
7633        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7634            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7635                    || ai.mHasSystemUiListeners) {
7636                ai.mRecomputeGlobalAttributes = true;
7637            }
7638        }
7639    }
7640
7641    /**
7642     * Returns whether the device is currently in touch mode.  Touch mode is entered
7643     * once the user begins interacting with the device by touch, and affects various
7644     * things like whether focus is always visible to the user.
7645     *
7646     * @return Whether the device is in touch mode.
7647     */
7648    @ViewDebug.ExportedProperty
7649    public boolean isInTouchMode() {
7650        if (mAttachInfo != null) {
7651            return mAttachInfo.mInTouchMode;
7652        } else {
7653            return ViewRootImpl.isInTouchMode();
7654        }
7655    }
7656
7657    /**
7658     * Returns the context the view is running in, through which it can
7659     * access the current theme, resources, etc.
7660     *
7661     * @return The view's Context.
7662     */
7663    @ViewDebug.CapturedViewProperty
7664    public final Context getContext() {
7665        return mContext;
7666    }
7667
7668    /**
7669     * Handle a key event before it is processed by any input method
7670     * associated with the view hierarchy.  This can be used to intercept
7671     * key events in special situations before the IME consumes them; a
7672     * typical example would be handling the BACK key to update the application's
7673     * UI instead of allowing the IME to see it and close itself.
7674     *
7675     * @param keyCode The value in event.getKeyCode().
7676     * @param event Description of the key event.
7677     * @return If you handled the event, return true. If you want to allow the
7678     *         event to be handled by the next receiver, return false.
7679     */
7680    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7681        return false;
7682    }
7683
7684    /**
7685     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7686     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7687     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7688     * is released, if the view is enabled and clickable.
7689     *
7690     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7691     * although some may elect to do so in some situations. Do not rely on this to
7692     * catch software key presses.
7693     *
7694     * @param keyCode A key code that represents the button pressed, from
7695     *                {@link android.view.KeyEvent}.
7696     * @param event   The KeyEvent object that defines the button action.
7697     */
7698    public boolean onKeyDown(int keyCode, KeyEvent event) {
7699        boolean result = false;
7700
7701        switch (keyCode) {
7702            case KeyEvent.KEYCODE_DPAD_CENTER:
7703            case KeyEvent.KEYCODE_ENTER: {
7704                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7705                    return true;
7706                }
7707                // Long clickable items don't necessarily have to be clickable
7708                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7709                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7710                        (event.getRepeatCount() == 0)) {
7711                    setPressed(true);
7712                    checkForLongClick(0);
7713                    return true;
7714                }
7715                break;
7716            }
7717        }
7718        return result;
7719    }
7720
7721    /**
7722     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7723     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7724     * the event).
7725     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7726     * although some may elect to do so in some situations. Do not rely on this to
7727     * catch software key presses.
7728     */
7729    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7730        return false;
7731    }
7732
7733    /**
7734     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7735     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7736     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7737     * {@link KeyEvent#KEYCODE_ENTER} is released.
7738     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7739     * although some may elect to do so in some situations. Do not rely on this to
7740     * catch software key presses.
7741     *
7742     * @param keyCode A key code that represents the button pressed, from
7743     *                {@link android.view.KeyEvent}.
7744     * @param event   The KeyEvent object that defines the button action.
7745     */
7746    public boolean onKeyUp(int keyCode, KeyEvent event) {
7747        boolean result = false;
7748
7749        switch (keyCode) {
7750            case KeyEvent.KEYCODE_DPAD_CENTER:
7751            case KeyEvent.KEYCODE_ENTER: {
7752                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7753                    return true;
7754                }
7755                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7756                    setPressed(false);
7757
7758                    if (!mHasPerformedLongPress) {
7759                        // This is a tap, so remove the longpress check
7760                        removeLongPressCallback();
7761
7762                        result = performClick();
7763                    }
7764                }
7765                break;
7766            }
7767        }
7768        return result;
7769    }
7770
7771    /**
7772     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7773     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7774     * the event).
7775     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7776     * although some may elect to do so in some situations. Do not rely on this to
7777     * catch software key presses.
7778     *
7779     * @param keyCode     A key code that represents the button pressed, from
7780     *                    {@link android.view.KeyEvent}.
7781     * @param repeatCount The number of times the action was made.
7782     * @param event       The KeyEvent object that defines the button action.
7783     */
7784    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7785        return false;
7786    }
7787
7788    /**
7789     * Called on the focused view when a key shortcut event is not handled.
7790     * Override this method to implement local key shortcuts for the View.
7791     * Key shortcuts can also be implemented by setting the
7792     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7793     *
7794     * @param keyCode The value in event.getKeyCode().
7795     * @param event Description of the key event.
7796     * @return If you handled the event, return true. If you want to allow the
7797     *         event to be handled by the next receiver, return false.
7798     */
7799    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7800        return false;
7801    }
7802
7803    /**
7804     * Check whether the called view is a text editor, in which case it
7805     * would make sense to automatically display a soft input window for
7806     * it.  Subclasses should override this if they implement
7807     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7808     * a call on that method would return a non-null InputConnection, and
7809     * they are really a first-class editor that the user would normally
7810     * start typing on when the go into a window containing your view.
7811     *
7812     * <p>The default implementation always returns false.  This does
7813     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7814     * will not be called or the user can not otherwise perform edits on your
7815     * view; it is just a hint to the system that this is not the primary
7816     * purpose of this view.
7817     *
7818     * @return Returns true if this view is a text editor, else false.
7819     */
7820    public boolean onCheckIsTextEditor() {
7821        return false;
7822    }
7823
7824    /**
7825     * Create a new InputConnection for an InputMethod to interact
7826     * with the view.  The default implementation returns null, since it doesn't
7827     * support input methods.  You can override this to implement such support.
7828     * This is only needed for views that take focus and text input.
7829     *
7830     * <p>When implementing this, you probably also want to implement
7831     * {@link #onCheckIsTextEditor()} to indicate you will return a
7832     * non-null InputConnection.
7833     *
7834     * @param outAttrs Fill in with attribute information about the connection.
7835     */
7836    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7837        return null;
7838    }
7839
7840    /**
7841     * Called by the {@link android.view.inputmethod.InputMethodManager}
7842     * when a view who is not the current
7843     * input connection target is trying to make a call on the manager.  The
7844     * default implementation returns false; you can override this to return
7845     * true for certain views if you are performing InputConnection proxying
7846     * to them.
7847     * @param view The View that is making the InputMethodManager call.
7848     * @return Return true to allow the call, false to reject.
7849     */
7850    public boolean checkInputConnectionProxy(View view) {
7851        return false;
7852    }
7853
7854    /**
7855     * Show the context menu for this view. It is not safe to hold on to the
7856     * menu after returning from this method.
7857     *
7858     * You should normally not overload this method. Overload
7859     * {@link #onCreateContextMenu(ContextMenu)} or define an
7860     * {@link OnCreateContextMenuListener} to add items to the context menu.
7861     *
7862     * @param menu The context menu to populate
7863     */
7864    public void createContextMenu(ContextMenu menu) {
7865        ContextMenuInfo menuInfo = getContextMenuInfo();
7866
7867        // Sets the current menu info so all items added to menu will have
7868        // my extra info set.
7869        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7870
7871        onCreateContextMenu(menu);
7872        ListenerInfo li = mListenerInfo;
7873        if (li != null && li.mOnCreateContextMenuListener != null) {
7874            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7875        }
7876
7877        // Clear the extra information so subsequent items that aren't mine don't
7878        // have my extra info.
7879        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7880
7881        if (mParent != null) {
7882            mParent.createContextMenu(menu);
7883        }
7884    }
7885
7886    /**
7887     * Views should implement this if they have extra information to associate
7888     * with the context menu. The return result is supplied as a parameter to
7889     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7890     * callback.
7891     *
7892     * @return Extra information about the item for which the context menu
7893     *         should be shown. This information will vary across different
7894     *         subclasses of View.
7895     */
7896    protected ContextMenuInfo getContextMenuInfo() {
7897        return null;
7898    }
7899
7900    /**
7901     * Views should implement this if the view itself is going to add items to
7902     * the context menu.
7903     *
7904     * @param menu the context menu to populate
7905     */
7906    protected void onCreateContextMenu(ContextMenu menu) {
7907    }
7908
7909    /**
7910     * Implement this method to handle trackball motion events.  The
7911     * <em>relative</em> movement of the trackball since the last event
7912     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7913     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7914     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7915     * they will often be fractional values, representing the more fine-grained
7916     * movement information available from a trackball).
7917     *
7918     * @param event The motion event.
7919     * @return True if the event was handled, false otherwise.
7920     */
7921    public boolean onTrackballEvent(MotionEvent event) {
7922        return false;
7923    }
7924
7925    /**
7926     * Implement this method to handle generic motion events.
7927     * <p>
7928     * Generic motion events describe joystick movements, mouse hovers, track pad
7929     * touches, scroll wheel movements and other input events.  The
7930     * {@link MotionEvent#getSource() source} of the motion event specifies
7931     * the class of input that was received.  Implementations of this method
7932     * must examine the bits in the source before processing the event.
7933     * The following code example shows how this is done.
7934     * </p><p>
7935     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7936     * are delivered to the view under the pointer.  All other generic motion events are
7937     * delivered to the focused view.
7938     * </p>
7939     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7940     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7941     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7942     *             // process the joystick movement...
7943     *             return true;
7944     *         }
7945     *     }
7946     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7947     *         switch (event.getAction()) {
7948     *             case MotionEvent.ACTION_HOVER_MOVE:
7949     *                 // process the mouse hover movement...
7950     *                 return true;
7951     *             case MotionEvent.ACTION_SCROLL:
7952     *                 // process the scroll wheel movement...
7953     *                 return true;
7954     *         }
7955     *     }
7956     *     return super.onGenericMotionEvent(event);
7957     * }</pre>
7958     *
7959     * @param event The generic motion event being processed.
7960     * @return True if the event was handled, false otherwise.
7961     */
7962    public boolean onGenericMotionEvent(MotionEvent event) {
7963        return false;
7964    }
7965
7966    /**
7967     * Implement this method to handle hover events.
7968     * <p>
7969     * This method is called whenever a pointer is hovering into, over, or out of the
7970     * bounds of a view and the view is not currently being touched.
7971     * Hover events are represented as pointer events with action
7972     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7973     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7974     * </p>
7975     * <ul>
7976     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7977     * when the pointer enters the bounds of the view.</li>
7978     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7979     * when the pointer has already entered the bounds of the view and has moved.</li>
7980     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7981     * when the pointer has exited the bounds of the view or when the pointer is
7982     * about to go down due to a button click, tap, or similar user action that
7983     * causes the view to be touched.</li>
7984     * </ul>
7985     * <p>
7986     * The view should implement this method to return true to indicate that it is
7987     * handling the hover event, such as by changing its drawable state.
7988     * </p><p>
7989     * The default implementation calls {@link #setHovered} to update the hovered state
7990     * of the view when a hover enter or hover exit event is received, if the view
7991     * is enabled and is clickable.  The default implementation also sends hover
7992     * accessibility events.
7993     * </p>
7994     *
7995     * @param event The motion event that describes the hover.
7996     * @return True if the view handled the hover event.
7997     *
7998     * @see #isHovered
7999     * @see #setHovered
8000     * @see #onHoverChanged
8001     */
8002    public boolean onHoverEvent(MotionEvent event) {
8003        // The root view may receive hover (or touch) events that are outside the bounds of
8004        // the window.  This code ensures that we only send accessibility events for
8005        // hovers that are actually within the bounds of the root view.
8006        final int action = event.getActionMasked();
8007        if (!mSendingHoverAccessibilityEvents) {
8008            if ((action == MotionEvent.ACTION_HOVER_ENTER
8009                    || action == MotionEvent.ACTION_HOVER_MOVE)
8010                    && !hasHoveredChild()
8011                    && pointInView(event.getX(), event.getY())) {
8012                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8013                mSendingHoverAccessibilityEvents = true;
8014            }
8015        } else {
8016            if (action == MotionEvent.ACTION_HOVER_EXIT
8017                    || (action == MotionEvent.ACTION_MOVE
8018                            && !pointInView(event.getX(), event.getY()))) {
8019                mSendingHoverAccessibilityEvents = false;
8020                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8021                // If the window does not have input focus we take away accessibility
8022                // focus as soon as the user stop hovering over the view.
8023                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8024                    getViewRootImpl().setAccessibilityFocus(null, null);
8025                }
8026            }
8027        }
8028
8029        if (isHoverable()) {
8030            switch (action) {
8031                case MotionEvent.ACTION_HOVER_ENTER:
8032                    setHovered(true);
8033                    break;
8034                case MotionEvent.ACTION_HOVER_EXIT:
8035                    setHovered(false);
8036                    break;
8037            }
8038
8039            // Dispatch the event to onGenericMotionEvent before returning true.
8040            // This is to provide compatibility with existing applications that
8041            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8042            // break because of the new default handling for hoverable views
8043            // in onHoverEvent.
8044            // Note that onGenericMotionEvent will be called by default when
8045            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8046            dispatchGenericMotionEventInternal(event);
8047            return true;
8048        }
8049
8050        return false;
8051    }
8052
8053    /**
8054     * Returns true if the view should handle {@link #onHoverEvent}
8055     * by calling {@link #setHovered} to change its hovered state.
8056     *
8057     * @return True if the view is hoverable.
8058     */
8059    private boolean isHoverable() {
8060        final int viewFlags = mViewFlags;
8061        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8062            return false;
8063        }
8064
8065        return (viewFlags & CLICKABLE) == CLICKABLE
8066                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8067    }
8068
8069    /**
8070     * Returns true if the view is currently hovered.
8071     *
8072     * @return True if the view is currently hovered.
8073     *
8074     * @see #setHovered
8075     * @see #onHoverChanged
8076     */
8077    @ViewDebug.ExportedProperty
8078    public boolean isHovered() {
8079        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8080    }
8081
8082    /**
8083     * Sets whether the view is currently hovered.
8084     * <p>
8085     * Calling this method also changes the drawable state of the view.  This
8086     * enables the view to react to hover by using different drawable resources
8087     * to change its appearance.
8088     * </p><p>
8089     * The {@link #onHoverChanged} method is called when the hovered state changes.
8090     * </p>
8091     *
8092     * @param hovered True if the view is hovered.
8093     *
8094     * @see #isHovered
8095     * @see #onHoverChanged
8096     */
8097    public void setHovered(boolean hovered) {
8098        if (hovered) {
8099            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8100                mPrivateFlags |= PFLAG_HOVERED;
8101                refreshDrawableState();
8102                onHoverChanged(true);
8103            }
8104        } else {
8105            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8106                mPrivateFlags &= ~PFLAG_HOVERED;
8107                refreshDrawableState();
8108                onHoverChanged(false);
8109            }
8110        }
8111    }
8112
8113    /**
8114     * Implement this method to handle hover state changes.
8115     * <p>
8116     * This method is called whenever the hover state changes as a result of a
8117     * call to {@link #setHovered}.
8118     * </p>
8119     *
8120     * @param hovered The current hover state, as returned by {@link #isHovered}.
8121     *
8122     * @see #isHovered
8123     * @see #setHovered
8124     */
8125    public void onHoverChanged(boolean hovered) {
8126    }
8127
8128    /**
8129     * Implement this method to handle touch screen motion events.
8130     *
8131     * @param event The motion event.
8132     * @return True if the event was handled, false otherwise.
8133     */
8134    public boolean onTouchEvent(MotionEvent event) {
8135        final int viewFlags = mViewFlags;
8136
8137        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8138            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8139                setPressed(false);
8140            }
8141            // A disabled view that is clickable still consumes the touch
8142            // events, it just doesn't respond to them.
8143            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8144                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8145        }
8146
8147        if (mTouchDelegate != null) {
8148            if (mTouchDelegate.onTouchEvent(event)) {
8149                return true;
8150            }
8151        }
8152
8153        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8154                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8155            switch (event.getAction()) {
8156                case MotionEvent.ACTION_UP:
8157                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8158                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8159                        // take focus if we don't have it already and we should in
8160                        // touch mode.
8161                        boolean focusTaken = false;
8162                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8163                            focusTaken = requestFocus();
8164                        }
8165
8166                        if (prepressed) {
8167                            // The button is being released before we actually
8168                            // showed it as pressed.  Make it show the pressed
8169                            // state now (before scheduling the click) to ensure
8170                            // the user sees it.
8171                            setPressed(true);
8172                       }
8173
8174                        if (!mHasPerformedLongPress) {
8175                            // This is a tap, so remove the longpress check
8176                            removeLongPressCallback();
8177
8178                            // Only perform take click actions if we were in the pressed state
8179                            if (!focusTaken) {
8180                                // Use a Runnable and post this rather than calling
8181                                // performClick directly. This lets other visual state
8182                                // of the view update before click actions start.
8183                                if (mPerformClick == null) {
8184                                    mPerformClick = new PerformClick();
8185                                }
8186                                if (!post(mPerformClick)) {
8187                                    performClick();
8188                                }
8189                            }
8190                        }
8191
8192                        if (mUnsetPressedState == null) {
8193                            mUnsetPressedState = new UnsetPressedState();
8194                        }
8195
8196                        if (prepressed) {
8197                            postDelayed(mUnsetPressedState,
8198                                    ViewConfiguration.getPressedStateDuration());
8199                        } else if (!post(mUnsetPressedState)) {
8200                            // If the post failed, unpress right now
8201                            mUnsetPressedState.run();
8202                        }
8203                        removeTapCallback();
8204                    }
8205                    break;
8206
8207                case MotionEvent.ACTION_DOWN:
8208                    mHasPerformedLongPress = false;
8209
8210                    if (performButtonActionOnTouchDown(event)) {
8211                        break;
8212                    }
8213
8214                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8215                    boolean isInScrollingContainer = isInScrollingContainer();
8216
8217                    // For views inside a scrolling container, delay the pressed feedback for
8218                    // a short period in case this is a scroll.
8219                    if (isInScrollingContainer) {
8220                        mPrivateFlags |= PFLAG_PREPRESSED;
8221                        if (mPendingCheckForTap == null) {
8222                            mPendingCheckForTap = new CheckForTap();
8223                        }
8224                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8225                    } else {
8226                        // Not inside a scrolling container, so show the feedback right away
8227                        setPressed(true);
8228                        checkForLongClick(0);
8229                    }
8230                    break;
8231
8232                case MotionEvent.ACTION_CANCEL:
8233                    setPressed(false);
8234                    removeTapCallback();
8235                    break;
8236
8237                case MotionEvent.ACTION_MOVE:
8238                    final int x = (int) event.getX();
8239                    final int y = (int) event.getY();
8240
8241                    // Be lenient about moving outside of buttons
8242                    if (!pointInView(x, y, mTouchSlop)) {
8243                        // Outside button
8244                        removeTapCallback();
8245                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8246                            // Remove any future long press/tap checks
8247                            removeLongPressCallback();
8248
8249                            setPressed(false);
8250                        }
8251                    }
8252                    break;
8253            }
8254            return true;
8255        }
8256
8257        return false;
8258    }
8259
8260    /**
8261     * @hide
8262     */
8263    public boolean isInScrollingContainer() {
8264        ViewParent p = getParent();
8265        while (p != null && p instanceof ViewGroup) {
8266            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8267                return true;
8268            }
8269            p = p.getParent();
8270        }
8271        return false;
8272    }
8273
8274    /**
8275     * Remove the longpress detection timer.
8276     */
8277    private void removeLongPressCallback() {
8278        if (mPendingCheckForLongPress != null) {
8279          removeCallbacks(mPendingCheckForLongPress);
8280        }
8281    }
8282
8283    /**
8284     * Remove the pending click action
8285     */
8286    private void removePerformClickCallback() {
8287        if (mPerformClick != null) {
8288            removeCallbacks(mPerformClick);
8289        }
8290    }
8291
8292    /**
8293     * Remove the prepress detection timer.
8294     */
8295    private void removeUnsetPressCallback() {
8296        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8297            setPressed(false);
8298            removeCallbacks(mUnsetPressedState);
8299        }
8300    }
8301
8302    /**
8303     * Remove the tap detection timer.
8304     */
8305    private void removeTapCallback() {
8306        if (mPendingCheckForTap != null) {
8307            mPrivateFlags &= ~PFLAG_PREPRESSED;
8308            removeCallbacks(mPendingCheckForTap);
8309        }
8310    }
8311
8312    /**
8313     * Cancels a pending long press.  Your subclass can use this if you
8314     * want the context menu to come up if the user presses and holds
8315     * at the same place, but you don't want it to come up if they press
8316     * and then move around enough to cause scrolling.
8317     */
8318    public void cancelLongPress() {
8319        removeLongPressCallback();
8320
8321        /*
8322         * The prepressed state handled by the tap callback is a display
8323         * construct, but the tap callback will post a long press callback
8324         * less its own timeout. Remove it here.
8325         */
8326        removeTapCallback();
8327    }
8328
8329    /**
8330     * Remove the pending callback for sending a
8331     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8332     */
8333    private void removeSendViewScrolledAccessibilityEventCallback() {
8334        if (mSendViewScrolledAccessibilityEvent != null) {
8335            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8336            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8337        }
8338    }
8339
8340    /**
8341     * Sets the TouchDelegate for this View.
8342     */
8343    public void setTouchDelegate(TouchDelegate delegate) {
8344        mTouchDelegate = delegate;
8345    }
8346
8347    /**
8348     * Gets the TouchDelegate for this View.
8349     */
8350    public TouchDelegate getTouchDelegate() {
8351        return mTouchDelegate;
8352    }
8353
8354    /**
8355     * Set flags controlling behavior of this view.
8356     *
8357     * @param flags Constant indicating the value which should be set
8358     * @param mask Constant indicating the bit range that should be changed
8359     */
8360    void setFlags(int flags, int mask) {
8361        int old = mViewFlags;
8362        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8363
8364        int changed = mViewFlags ^ old;
8365        if (changed == 0) {
8366            return;
8367        }
8368        int privateFlags = mPrivateFlags;
8369
8370        /* Check if the FOCUSABLE bit has changed */
8371        if (((changed & FOCUSABLE_MASK) != 0) &&
8372                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8373            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8374                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8375                /* Give up focus if we are no longer focusable */
8376                clearFocus();
8377            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8378                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8379                /*
8380                 * Tell the view system that we are now available to take focus
8381                 * if no one else already has it.
8382                 */
8383                if (mParent != null) mParent.focusableViewAvailable(this);
8384            }
8385            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8386                notifyAccessibilityStateChanged();
8387            }
8388        }
8389
8390        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8391            if ((changed & VISIBILITY_MASK) != 0) {
8392                /*
8393                 * If this view is becoming visible, invalidate it in case it changed while
8394                 * it was not visible. Marking it drawn ensures that the invalidation will
8395                 * go through.
8396                 */
8397                mPrivateFlags |= PFLAG_DRAWN;
8398                invalidate(true);
8399
8400                needGlobalAttributesUpdate(true);
8401
8402                // a view becoming visible is worth notifying the parent
8403                // about in case nothing has focus.  even if this specific view
8404                // isn't focusable, it may contain something that is, so let
8405                // the root view try to give this focus if nothing else does.
8406                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8407                    mParent.focusableViewAvailable(this);
8408                }
8409            }
8410        }
8411
8412        /* Check if the GONE bit has changed */
8413        if ((changed & GONE) != 0) {
8414            needGlobalAttributesUpdate(false);
8415            requestLayout();
8416
8417            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8418                if (hasFocus()) clearFocus();
8419                clearAccessibilityFocus();
8420                destroyDrawingCache();
8421                if (mParent instanceof View) {
8422                    // GONE views noop invalidation, so invalidate the parent
8423                    ((View) mParent).invalidate(true);
8424                }
8425                // Mark the view drawn to ensure that it gets invalidated properly the next
8426                // time it is visible and gets invalidated
8427                mPrivateFlags |= PFLAG_DRAWN;
8428            }
8429            if (mAttachInfo != null) {
8430                mAttachInfo.mViewVisibilityChanged = true;
8431            }
8432        }
8433
8434        /* Check if the VISIBLE bit has changed */
8435        if ((changed & INVISIBLE) != 0) {
8436            needGlobalAttributesUpdate(false);
8437            /*
8438             * If this view is becoming invisible, set the DRAWN flag so that
8439             * the next invalidate() will not be skipped.
8440             */
8441            mPrivateFlags |= PFLAG_DRAWN;
8442
8443            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8444                // root view becoming invisible shouldn't clear focus and accessibility focus
8445                if (getRootView() != this) {
8446                    clearFocus();
8447                    clearAccessibilityFocus();
8448                }
8449            }
8450            if (mAttachInfo != null) {
8451                mAttachInfo.mViewVisibilityChanged = true;
8452            }
8453        }
8454
8455        if ((changed & VISIBILITY_MASK) != 0) {
8456            if (mParent instanceof ViewGroup) {
8457                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8458                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8459                ((View) mParent).invalidate(true);
8460            } else if (mParent != null) {
8461                mParent.invalidateChild(this, null);
8462            }
8463            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8464        }
8465
8466        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8467            destroyDrawingCache();
8468        }
8469
8470        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8471            destroyDrawingCache();
8472            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8473            invalidateParentCaches();
8474        }
8475
8476        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8477            destroyDrawingCache();
8478            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8479        }
8480
8481        if ((changed & DRAW_MASK) != 0) {
8482            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8483                if (mBackground != null) {
8484                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8485                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8486                } else {
8487                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8488                }
8489            } else {
8490                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8491            }
8492            requestLayout();
8493            invalidate(true);
8494        }
8495
8496        if ((changed & KEEP_SCREEN_ON) != 0) {
8497            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8498                mParent.recomputeViewAttributes(this);
8499            }
8500        }
8501
8502        if (AccessibilityManager.getInstance(mContext).isEnabled()
8503                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8504                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8505            notifyAccessibilityStateChanged();
8506        }
8507    }
8508
8509    /**
8510     * Change the view's z order in the tree, so it's on top of other sibling
8511     * views
8512     */
8513    public void bringToFront() {
8514        if (mParent != null) {
8515            mParent.bringChildToFront(this);
8516        }
8517    }
8518
8519    /**
8520     * This is called in response to an internal scroll in this view (i.e., the
8521     * view scrolled its own contents). This is typically as a result of
8522     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8523     * called.
8524     *
8525     * @param l Current horizontal scroll origin.
8526     * @param t Current vertical scroll origin.
8527     * @param oldl Previous horizontal scroll origin.
8528     * @param oldt Previous vertical scroll origin.
8529     */
8530    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8531        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8532            postSendViewScrolledAccessibilityEventCallback();
8533        }
8534
8535        mBackgroundSizeChanged = true;
8536
8537        final AttachInfo ai = mAttachInfo;
8538        if (ai != null) {
8539            ai.mViewScrollChanged = true;
8540        }
8541    }
8542
8543    /**
8544     * Interface definition for a callback to be invoked when the layout bounds of a view
8545     * changes due to layout processing.
8546     */
8547    public interface OnLayoutChangeListener {
8548        /**
8549         * Called when the focus state of a view has changed.
8550         *
8551         * @param v The view whose state has changed.
8552         * @param left The new value of the view's left property.
8553         * @param top The new value of the view's top property.
8554         * @param right The new value of the view's right property.
8555         * @param bottom The new value of the view's bottom property.
8556         * @param oldLeft The previous value of the view's left property.
8557         * @param oldTop The previous value of the view's top property.
8558         * @param oldRight The previous value of the view's right property.
8559         * @param oldBottom The previous value of the view's bottom property.
8560         */
8561        void onLayoutChange(View v, int left, int top, int right, int bottom,
8562            int oldLeft, int oldTop, int oldRight, int oldBottom);
8563    }
8564
8565    /**
8566     * This is called during layout when the size of this view has changed. If
8567     * you were just added to the view hierarchy, you're called with the old
8568     * values of 0.
8569     *
8570     * @param w Current width of this view.
8571     * @param h Current height of this view.
8572     * @param oldw Old width of this view.
8573     * @param oldh Old height of this view.
8574     */
8575    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8576    }
8577
8578    /**
8579     * Called by draw to draw the child views. This may be overridden
8580     * by derived classes to gain control just before its children are drawn
8581     * (but after its own view has been drawn).
8582     * @param canvas the canvas on which to draw the view
8583     */
8584    protected void dispatchDraw(Canvas canvas) {
8585
8586    }
8587
8588    /**
8589     * Gets the parent of this view. Note that the parent is a
8590     * ViewParent and not necessarily a View.
8591     *
8592     * @return Parent of this view.
8593     */
8594    public final ViewParent getParent() {
8595        return mParent;
8596    }
8597
8598    /**
8599     * Set the horizontal scrolled position of your view. This will cause a call to
8600     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8601     * invalidated.
8602     * @param value the x position to scroll to
8603     */
8604    public void setScrollX(int value) {
8605        scrollTo(value, mScrollY);
8606    }
8607
8608    /**
8609     * Set the vertical scrolled position of your view. This will cause a call to
8610     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8611     * invalidated.
8612     * @param value the y position to scroll to
8613     */
8614    public void setScrollY(int value) {
8615        scrollTo(mScrollX, value);
8616    }
8617
8618    /**
8619     * Return the scrolled left position of this view. This is the left edge of
8620     * the displayed part of your view. You do not need to draw any pixels
8621     * farther left, since those are outside of the frame of your view on
8622     * screen.
8623     *
8624     * @return The left edge of the displayed part of your view, in pixels.
8625     */
8626    public final int getScrollX() {
8627        return mScrollX;
8628    }
8629
8630    /**
8631     * Return the scrolled top position of this view. This is the top edge of
8632     * the displayed part of your view. You do not need to draw any pixels above
8633     * it, since those are outside of the frame of your view on screen.
8634     *
8635     * @return The top edge of the displayed part of your view, in pixels.
8636     */
8637    public final int getScrollY() {
8638        return mScrollY;
8639    }
8640
8641    /**
8642     * Return the width of the your view.
8643     *
8644     * @return The width of your view, in pixels.
8645     */
8646    @ViewDebug.ExportedProperty(category = "layout")
8647    public final int getWidth() {
8648        return mRight - mLeft;
8649    }
8650
8651    /**
8652     * Return the height of your view.
8653     *
8654     * @return The height of your view, in pixels.
8655     */
8656    @ViewDebug.ExportedProperty(category = "layout")
8657    public final int getHeight() {
8658        return mBottom - mTop;
8659    }
8660
8661    /**
8662     * Return the visible drawing bounds of your view. Fills in the output
8663     * rectangle with the values from getScrollX(), getScrollY(),
8664     * getWidth(), and getHeight().
8665     *
8666     * @param outRect The (scrolled) drawing bounds of the view.
8667     */
8668    public void getDrawingRect(Rect outRect) {
8669        outRect.left = mScrollX;
8670        outRect.top = mScrollY;
8671        outRect.right = mScrollX + (mRight - mLeft);
8672        outRect.bottom = mScrollY + (mBottom - mTop);
8673    }
8674
8675    /**
8676     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8677     * raw width component (that is the result is masked by
8678     * {@link #MEASURED_SIZE_MASK}).
8679     *
8680     * @return The raw measured width of this view.
8681     */
8682    public final int getMeasuredWidth() {
8683        return mMeasuredWidth & MEASURED_SIZE_MASK;
8684    }
8685
8686    /**
8687     * Return the full width measurement information for this view as computed
8688     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8689     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8690     * This should be used during measurement and layout calculations only. Use
8691     * {@link #getWidth()} to see how wide a view is after layout.
8692     *
8693     * @return The measured width of this view as a bit mask.
8694     */
8695    public final int getMeasuredWidthAndState() {
8696        return mMeasuredWidth;
8697    }
8698
8699    /**
8700     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8701     * raw width component (that is the result is masked by
8702     * {@link #MEASURED_SIZE_MASK}).
8703     *
8704     * @return The raw measured height of this view.
8705     */
8706    public final int getMeasuredHeight() {
8707        return mMeasuredHeight & MEASURED_SIZE_MASK;
8708    }
8709
8710    /**
8711     * Return the full height measurement information for this view as computed
8712     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8713     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8714     * This should be used during measurement and layout calculations only. Use
8715     * {@link #getHeight()} to see how wide a view is after layout.
8716     *
8717     * @return The measured width of this view as a bit mask.
8718     */
8719    public final int getMeasuredHeightAndState() {
8720        return mMeasuredHeight;
8721    }
8722
8723    /**
8724     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8725     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8726     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8727     * and the height component is at the shifted bits
8728     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8729     */
8730    public final int getMeasuredState() {
8731        return (mMeasuredWidth&MEASURED_STATE_MASK)
8732                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8733                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8734    }
8735
8736    /**
8737     * The transform matrix of this view, which is calculated based on the current
8738     * roation, scale, and pivot properties.
8739     *
8740     * @see #getRotation()
8741     * @see #getScaleX()
8742     * @see #getScaleY()
8743     * @see #getPivotX()
8744     * @see #getPivotY()
8745     * @return The current transform matrix for the view
8746     */
8747    public Matrix getMatrix() {
8748        if (mTransformationInfo != null) {
8749            updateMatrix();
8750            return mTransformationInfo.mMatrix;
8751        }
8752        return Matrix.IDENTITY_MATRIX;
8753    }
8754
8755    /**
8756     * Utility function to determine if the value is far enough away from zero to be
8757     * considered non-zero.
8758     * @param value A floating point value to check for zero-ness
8759     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8760     */
8761    private static boolean nonzero(float value) {
8762        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8763    }
8764
8765    /**
8766     * Returns true if the transform matrix is the identity matrix.
8767     * Recomputes the matrix if necessary.
8768     *
8769     * @return True if the transform matrix is the identity matrix, false otherwise.
8770     */
8771    final boolean hasIdentityMatrix() {
8772        if (mTransformationInfo != null) {
8773            updateMatrix();
8774            return mTransformationInfo.mMatrixIsIdentity;
8775        }
8776        return true;
8777    }
8778
8779    void ensureTransformationInfo() {
8780        if (mTransformationInfo == null) {
8781            mTransformationInfo = new TransformationInfo();
8782        }
8783    }
8784
8785    /**
8786     * Recomputes the transform matrix if necessary.
8787     */
8788    private void updateMatrix() {
8789        final TransformationInfo info = mTransformationInfo;
8790        if (info == null) {
8791            return;
8792        }
8793        if (info.mMatrixDirty) {
8794            // transform-related properties have changed since the last time someone
8795            // asked for the matrix; recalculate it with the current values
8796
8797            // Figure out if we need to update the pivot point
8798            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
8799                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8800                    info.mPrevWidth = mRight - mLeft;
8801                    info.mPrevHeight = mBottom - mTop;
8802                    info.mPivotX = info.mPrevWidth / 2f;
8803                    info.mPivotY = info.mPrevHeight / 2f;
8804                }
8805            }
8806            info.mMatrix.reset();
8807            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8808                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8809                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8810                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8811            } else {
8812                if (info.mCamera == null) {
8813                    info.mCamera = new Camera();
8814                    info.matrix3D = new Matrix();
8815                }
8816                info.mCamera.save();
8817                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8818                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8819                info.mCamera.getMatrix(info.matrix3D);
8820                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8821                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8822                        info.mPivotY + info.mTranslationY);
8823                info.mMatrix.postConcat(info.matrix3D);
8824                info.mCamera.restore();
8825            }
8826            info.mMatrixDirty = false;
8827            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8828            info.mInverseMatrixDirty = true;
8829        }
8830    }
8831
8832   /**
8833     * Utility method to retrieve the inverse of the current mMatrix property.
8834     * We cache the matrix to avoid recalculating it when transform properties
8835     * have not changed.
8836     *
8837     * @return The inverse of the current matrix of this view.
8838     */
8839    final Matrix getInverseMatrix() {
8840        final TransformationInfo info = mTransformationInfo;
8841        if (info != null) {
8842            updateMatrix();
8843            if (info.mInverseMatrixDirty) {
8844                if (info.mInverseMatrix == null) {
8845                    info.mInverseMatrix = new Matrix();
8846                }
8847                info.mMatrix.invert(info.mInverseMatrix);
8848                info.mInverseMatrixDirty = false;
8849            }
8850            return info.mInverseMatrix;
8851        }
8852        return Matrix.IDENTITY_MATRIX;
8853    }
8854
8855    /**
8856     * Gets the distance along the Z axis from the camera to this view.
8857     *
8858     * @see #setCameraDistance(float)
8859     *
8860     * @return The distance along the Z axis.
8861     */
8862    public float getCameraDistance() {
8863        ensureTransformationInfo();
8864        final float dpi = mResources.getDisplayMetrics().densityDpi;
8865        final TransformationInfo info = mTransformationInfo;
8866        if (info.mCamera == null) {
8867            info.mCamera = new Camera();
8868            info.matrix3D = new Matrix();
8869        }
8870        return -(info.mCamera.getLocationZ() * dpi);
8871    }
8872
8873    /**
8874     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8875     * views are drawn) from the camera to this view. The camera's distance
8876     * affects 3D transformations, for instance rotations around the X and Y
8877     * axis. If the rotationX or rotationY properties are changed and this view is
8878     * large (more than half the size of the screen), it is recommended to always
8879     * use a camera distance that's greater than the height (X axis rotation) or
8880     * the width (Y axis rotation) of this view.</p>
8881     *
8882     * <p>The distance of the camera from the view plane can have an affect on the
8883     * perspective distortion of the view when it is rotated around the x or y axis.
8884     * For example, a large distance will result in a large viewing angle, and there
8885     * will not be much perspective distortion of the view as it rotates. A short
8886     * distance may cause much more perspective distortion upon rotation, and can
8887     * also result in some drawing artifacts if the rotated view ends up partially
8888     * behind the camera (which is why the recommendation is to use a distance at
8889     * least as far as the size of the view, if the view is to be rotated.)</p>
8890     *
8891     * <p>The distance is expressed in "depth pixels." The default distance depends
8892     * on the screen density. For instance, on a medium density display, the
8893     * default distance is 1280. On a high density display, the default distance
8894     * is 1920.</p>
8895     *
8896     * <p>If you want to specify a distance that leads to visually consistent
8897     * results across various densities, use the following formula:</p>
8898     * <pre>
8899     * float scale = context.getResources().getDisplayMetrics().density;
8900     * view.setCameraDistance(distance * scale);
8901     * </pre>
8902     *
8903     * <p>The density scale factor of a high density display is 1.5,
8904     * and 1920 = 1280 * 1.5.</p>
8905     *
8906     * @param distance The distance in "depth pixels", if negative the opposite
8907     *        value is used
8908     *
8909     * @see #setRotationX(float)
8910     * @see #setRotationY(float)
8911     */
8912    public void setCameraDistance(float distance) {
8913        invalidateViewProperty(true, false);
8914
8915        ensureTransformationInfo();
8916        final float dpi = mResources.getDisplayMetrics().densityDpi;
8917        final TransformationInfo info = mTransformationInfo;
8918        if (info.mCamera == null) {
8919            info.mCamera = new Camera();
8920            info.matrix3D = new Matrix();
8921        }
8922
8923        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8924        info.mMatrixDirty = true;
8925
8926        invalidateViewProperty(false, false);
8927        if (mDisplayList != null) {
8928            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8929        }
8930        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8931            // View was rejected last time it was drawn by its parent; this may have changed
8932            invalidateParentIfNeeded();
8933        }
8934    }
8935
8936    /**
8937     * The degrees that the view is rotated around the pivot point.
8938     *
8939     * @see #setRotation(float)
8940     * @see #getPivotX()
8941     * @see #getPivotY()
8942     *
8943     * @return The degrees of rotation.
8944     */
8945    @ViewDebug.ExportedProperty(category = "drawing")
8946    public float getRotation() {
8947        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8948    }
8949
8950    /**
8951     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8952     * result in clockwise rotation.
8953     *
8954     * @param rotation The degrees of rotation.
8955     *
8956     * @see #getRotation()
8957     * @see #getPivotX()
8958     * @see #getPivotY()
8959     * @see #setRotationX(float)
8960     * @see #setRotationY(float)
8961     *
8962     * @attr ref android.R.styleable#View_rotation
8963     */
8964    public void setRotation(float rotation) {
8965        ensureTransformationInfo();
8966        final TransformationInfo info = mTransformationInfo;
8967        if (info.mRotation != rotation) {
8968            // Double-invalidation is necessary to capture view's old and new areas
8969            invalidateViewProperty(true, false);
8970            info.mRotation = rotation;
8971            info.mMatrixDirty = true;
8972            invalidateViewProperty(false, true);
8973            if (mDisplayList != null) {
8974                mDisplayList.setRotation(rotation);
8975            }
8976            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
8977                // View was rejected last time it was drawn by its parent; this may have changed
8978                invalidateParentIfNeeded();
8979            }
8980        }
8981    }
8982
8983    /**
8984     * The degrees that the view is rotated around the vertical axis through the pivot point.
8985     *
8986     * @see #getPivotX()
8987     * @see #getPivotY()
8988     * @see #setRotationY(float)
8989     *
8990     * @return The degrees of Y rotation.
8991     */
8992    @ViewDebug.ExportedProperty(category = "drawing")
8993    public float getRotationY() {
8994        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8995    }
8996
8997    /**
8998     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8999     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9000     * down the y axis.
9001     *
9002     * When rotating large views, it is recommended to adjust the camera distance
9003     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9004     *
9005     * @param rotationY The degrees of Y rotation.
9006     *
9007     * @see #getRotationY()
9008     * @see #getPivotX()
9009     * @see #getPivotY()
9010     * @see #setRotation(float)
9011     * @see #setRotationX(float)
9012     * @see #setCameraDistance(float)
9013     *
9014     * @attr ref android.R.styleable#View_rotationY
9015     */
9016    public void setRotationY(float rotationY) {
9017        ensureTransformationInfo();
9018        final TransformationInfo info = mTransformationInfo;
9019        if (info.mRotationY != rotationY) {
9020            invalidateViewProperty(true, false);
9021            info.mRotationY = rotationY;
9022            info.mMatrixDirty = true;
9023            invalidateViewProperty(false, true);
9024            if (mDisplayList != null) {
9025                mDisplayList.setRotationY(rotationY);
9026            }
9027            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9028                // View was rejected last time it was drawn by its parent; this may have changed
9029                invalidateParentIfNeeded();
9030            }
9031        }
9032    }
9033
9034    /**
9035     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9036     *
9037     * @see #getPivotX()
9038     * @see #getPivotY()
9039     * @see #setRotationX(float)
9040     *
9041     * @return The degrees of X rotation.
9042     */
9043    @ViewDebug.ExportedProperty(category = "drawing")
9044    public float getRotationX() {
9045        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9046    }
9047
9048    /**
9049     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9050     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9051     * x axis.
9052     *
9053     * When rotating large views, it is recommended to adjust the camera distance
9054     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9055     *
9056     * @param rotationX The degrees of X rotation.
9057     *
9058     * @see #getRotationX()
9059     * @see #getPivotX()
9060     * @see #getPivotY()
9061     * @see #setRotation(float)
9062     * @see #setRotationY(float)
9063     * @see #setCameraDistance(float)
9064     *
9065     * @attr ref android.R.styleable#View_rotationX
9066     */
9067    public void setRotationX(float rotationX) {
9068        ensureTransformationInfo();
9069        final TransformationInfo info = mTransformationInfo;
9070        if (info.mRotationX != rotationX) {
9071            invalidateViewProperty(true, false);
9072            info.mRotationX = rotationX;
9073            info.mMatrixDirty = true;
9074            invalidateViewProperty(false, true);
9075            if (mDisplayList != null) {
9076                mDisplayList.setRotationX(rotationX);
9077            }
9078            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9079                // View was rejected last time it was drawn by its parent; this may have changed
9080                invalidateParentIfNeeded();
9081            }
9082        }
9083    }
9084
9085    /**
9086     * The amount that the view is scaled in x around the pivot point, as a proportion of
9087     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9088     *
9089     * <p>By default, this is 1.0f.
9090     *
9091     * @see #getPivotX()
9092     * @see #getPivotY()
9093     * @return The scaling factor.
9094     */
9095    @ViewDebug.ExportedProperty(category = "drawing")
9096    public float getScaleX() {
9097        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9098    }
9099
9100    /**
9101     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9102     * the view's unscaled width. A value of 1 means that no scaling is applied.
9103     *
9104     * @param scaleX The scaling factor.
9105     * @see #getPivotX()
9106     * @see #getPivotY()
9107     *
9108     * @attr ref android.R.styleable#View_scaleX
9109     */
9110    public void setScaleX(float scaleX) {
9111        ensureTransformationInfo();
9112        final TransformationInfo info = mTransformationInfo;
9113        if (info.mScaleX != scaleX) {
9114            invalidateViewProperty(true, false);
9115            info.mScaleX = scaleX;
9116            info.mMatrixDirty = true;
9117            invalidateViewProperty(false, true);
9118            if (mDisplayList != null) {
9119                mDisplayList.setScaleX(scaleX);
9120            }
9121            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9122                // View was rejected last time it was drawn by its parent; this may have changed
9123                invalidateParentIfNeeded();
9124            }
9125        }
9126    }
9127
9128    /**
9129     * The amount that the view is scaled in y around the pivot point, as a proportion of
9130     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9131     *
9132     * <p>By default, this is 1.0f.
9133     *
9134     * @see #getPivotX()
9135     * @see #getPivotY()
9136     * @return The scaling factor.
9137     */
9138    @ViewDebug.ExportedProperty(category = "drawing")
9139    public float getScaleY() {
9140        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9141    }
9142
9143    /**
9144     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9145     * the view's unscaled width. A value of 1 means that no scaling is applied.
9146     *
9147     * @param scaleY The scaling factor.
9148     * @see #getPivotX()
9149     * @see #getPivotY()
9150     *
9151     * @attr ref android.R.styleable#View_scaleY
9152     */
9153    public void setScaleY(float scaleY) {
9154        ensureTransformationInfo();
9155        final TransformationInfo info = mTransformationInfo;
9156        if (info.mScaleY != scaleY) {
9157            invalidateViewProperty(true, false);
9158            info.mScaleY = scaleY;
9159            info.mMatrixDirty = true;
9160            invalidateViewProperty(false, true);
9161            if (mDisplayList != null) {
9162                mDisplayList.setScaleY(scaleY);
9163            }
9164            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9165                // View was rejected last time it was drawn by its parent; this may have changed
9166                invalidateParentIfNeeded();
9167            }
9168        }
9169    }
9170
9171    /**
9172     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9173     * and {@link #setScaleX(float) scaled}.
9174     *
9175     * @see #getRotation()
9176     * @see #getScaleX()
9177     * @see #getScaleY()
9178     * @see #getPivotY()
9179     * @return The x location of the pivot point.
9180     *
9181     * @attr ref android.R.styleable#View_transformPivotX
9182     */
9183    @ViewDebug.ExportedProperty(category = "drawing")
9184    public float getPivotX() {
9185        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9186    }
9187
9188    /**
9189     * Sets the x location of the point around which the view is
9190     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9191     * By default, the pivot point is centered on the object.
9192     * Setting this property disables this behavior and causes the view to use only the
9193     * explicitly set pivotX and pivotY values.
9194     *
9195     * @param pivotX The x location of the pivot point.
9196     * @see #getRotation()
9197     * @see #getScaleX()
9198     * @see #getScaleY()
9199     * @see #getPivotY()
9200     *
9201     * @attr ref android.R.styleable#View_transformPivotX
9202     */
9203    public void setPivotX(float pivotX) {
9204        ensureTransformationInfo();
9205        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9206        final TransformationInfo info = mTransformationInfo;
9207        if (info.mPivotX != pivotX) {
9208            invalidateViewProperty(true, false);
9209            info.mPivotX = pivotX;
9210            info.mMatrixDirty = true;
9211            invalidateViewProperty(false, true);
9212            if (mDisplayList != null) {
9213                mDisplayList.setPivotX(pivotX);
9214            }
9215            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9216                // View was rejected last time it was drawn by its parent; this may have changed
9217                invalidateParentIfNeeded();
9218            }
9219        }
9220    }
9221
9222    /**
9223     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9224     * and {@link #setScaleY(float) scaled}.
9225     *
9226     * @see #getRotation()
9227     * @see #getScaleX()
9228     * @see #getScaleY()
9229     * @see #getPivotY()
9230     * @return The y location of the pivot point.
9231     *
9232     * @attr ref android.R.styleable#View_transformPivotY
9233     */
9234    @ViewDebug.ExportedProperty(category = "drawing")
9235    public float getPivotY() {
9236        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9237    }
9238
9239    /**
9240     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9241     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9242     * Setting this property disables this behavior and causes the view to use only the
9243     * explicitly set pivotX and pivotY values.
9244     *
9245     * @param pivotY The y location of the pivot point.
9246     * @see #getRotation()
9247     * @see #getScaleX()
9248     * @see #getScaleY()
9249     * @see #getPivotY()
9250     *
9251     * @attr ref android.R.styleable#View_transformPivotY
9252     */
9253    public void setPivotY(float pivotY) {
9254        ensureTransformationInfo();
9255        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9256        final TransformationInfo info = mTransformationInfo;
9257        if (info.mPivotY != pivotY) {
9258            invalidateViewProperty(true, false);
9259            info.mPivotY = pivotY;
9260            info.mMatrixDirty = true;
9261            invalidateViewProperty(false, true);
9262            if (mDisplayList != null) {
9263                mDisplayList.setPivotY(pivotY);
9264            }
9265            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9266                // View was rejected last time it was drawn by its parent; this may have changed
9267                invalidateParentIfNeeded();
9268            }
9269        }
9270    }
9271
9272    /**
9273     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9274     * completely transparent and 1 means the view is completely opaque.
9275     *
9276     * <p>By default this is 1.0f.
9277     * @return The opacity of the view.
9278     */
9279    @ViewDebug.ExportedProperty(category = "drawing")
9280    public float getAlpha() {
9281        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9282    }
9283
9284    /**
9285     * Returns whether this View has content which overlaps. This function, intended to be
9286     * overridden by specific View types, is an optimization when alpha is set on a view. If
9287     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9288     * and then composited it into place, which can be expensive. If the view has no overlapping
9289     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9290     * An example of overlapping rendering is a TextView with a background image, such as a
9291     * Button. An example of non-overlapping rendering is a TextView with no background, or
9292     * an ImageView with only the foreground image. The default implementation returns true;
9293     * subclasses should override if they have cases which can be optimized.
9294     *
9295     * @return true if the content in this view might overlap, false otherwise.
9296     */
9297    public boolean hasOverlappingRendering() {
9298        return true;
9299    }
9300
9301    /**
9302     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9303     * completely transparent and 1 means the view is completely opaque.</p>
9304     *
9305     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9306     * responsible for applying the opacity itself. Otherwise, calling this method is
9307     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
9308     * setting a hardware layer.</p>
9309     *
9310     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
9311     * performance implications. It is generally best to use the alpha property sparingly and
9312     * transiently, as in the case of fading animations.</p>
9313     *
9314     * @param alpha The opacity of the view.
9315     *
9316     * @see #setLayerType(int, android.graphics.Paint)
9317     *
9318     * @attr ref android.R.styleable#View_alpha
9319     */
9320    public void setAlpha(float alpha) {
9321        ensureTransformationInfo();
9322        if (mTransformationInfo.mAlpha != alpha) {
9323            mTransformationInfo.mAlpha = alpha;
9324            if (onSetAlpha((int) (alpha * 255))) {
9325                mPrivateFlags |= PFLAG_ALPHA_SET;
9326                // subclass is handling alpha - don't optimize rendering cache invalidation
9327                invalidateParentCaches();
9328                invalidate(true);
9329            } else {
9330                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9331                invalidateViewProperty(true, false);
9332                if (mDisplayList != null) {
9333                    mDisplayList.setAlpha(alpha);
9334                }
9335            }
9336        }
9337    }
9338
9339    /**
9340     * Faster version of setAlpha() which performs the same steps except there are
9341     * no calls to invalidate(). The caller of this function should perform proper invalidation
9342     * on the parent and this object. The return value indicates whether the subclass handles
9343     * alpha (the return value for onSetAlpha()).
9344     *
9345     * @param alpha The new value for the alpha property
9346     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9347     *         the new value for the alpha property is different from the old value
9348     */
9349    boolean setAlphaNoInvalidation(float alpha) {
9350        ensureTransformationInfo();
9351        if (mTransformationInfo.mAlpha != alpha) {
9352            mTransformationInfo.mAlpha = alpha;
9353            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9354            if (subclassHandlesAlpha) {
9355                mPrivateFlags |= PFLAG_ALPHA_SET;
9356                return true;
9357            } else {
9358                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9359                if (mDisplayList != null) {
9360                    mDisplayList.setAlpha(alpha);
9361                }
9362            }
9363        }
9364        return false;
9365    }
9366
9367    /**
9368     * Top position of this view relative to its parent.
9369     *
9370     * @return The top of this view, in pixels.
9371     */
9372    @ViewDebug.CapturedViewProperty
9373    public final int getTop() {
9374        return mTop;
9375    }
9376
9377    /**
9378     * Sets the top position of this view relative to its parent. This method is meant to be called
9379     * by the layout system and should not generally be called otherwise, because the property
9380     * may be changed at any time by the layout.
9381     *
9382     * @param top The top of this view, in pixels.
9383     */
9384    public final void setTop(int top) {
9385        if (top != mTop) {
9386            updateMatrix();
9387            final boolean matrixIsIdentity = mTransformationInfo == null
9388                    || mTransformationInfo.mMatrixIsIdentity;
9389            if (matrixIsIdentity) {
9390                if (mAttachInfo != null) {
9391                    int minTop;
9392                    int yLoc;
9393                    if (top < mTop) {
9394                        minTop = top;
9395                        yLoc = top - mTop;
9396                    } else {
9397                        minTop = mTop;
9398                        yLoc = 0;
9399                    }
9400                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9401                }
9402            } else {
9403                // Double-invalidation is necessary to capture view's old and new areas
9404                invalidate(true);
9405            }
9406
9407            int width = mRight - mLeft;
9408            int oldHeight = mBottom - mTop;
9409
9410            mTop = top;
9411            if (mDisplayList != null) {
9412                mDisplayList.setTop(mTop);
9413            }
9414
9415            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9416
9417            if (!matrixIsIdentity) {
9418                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9419                    // A change in dimension means an auto-centered pivot point changes, too
9420                    mTransformationInfo.mMatrixDirty = true;
9421                }
9422                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9423                invalidate(true);
9424            }
9425            mBackgroundSizeChanged = true;
9426            invalidateParentIfNeeded();
9427            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9428                // View was rejected last time it was drawn by its parent; this may have changed
9429                invalidateParentIfNeeded();
9430            }
9431        }
9432    }
9433
9434    /**
9435     * Bottom position of this view relative to its parent.
9436     *
9437     * @return The bottom of this view, in pixels.
9438     */
9439    @ViewDebug.CapturedViewProperty
9440    public final int getBottom() {
9441        return mBottom;
9442    }
9443
9444    /**
9445     * True if this view has changed since the last time being drawn.
9446     *
9447     * @return The dirty state of this view.
9448     */
9449    public boolean isDirty() {
9450        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9451    }
9452
9453    /**
9454     * Sets the bottom position of this view relative to its parent. This method is meant to be
9455     * called by the layout system and should not generally be called otherwise, because the
9456     * property may be changed at any time by the layout.
9457     *
9458     * @param bottom The bottom of this view, in pixels.
9459     */
9460    public final void setBottom(int bottom) {
9461        if (bottom != mBottom) {
9462            updateMatrix();
9463            final boolean matrixIsIdentity = mTransformationInfo == null
9464                    || mTransformationInfo.mMatrixIsIdentity;
9465            if (matrixIsIdentity) {
9466                if (mAttachInfo != null) {
9467                    int maxBottom;
9468                    if (bottom < mBottom) {
9469                        maxBottom = mBottom;
9470                    } else {
9471                        maxBottom = bottom;
9472                    }
9473                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9474                }
9475            } else {
9476                // Double-invalidation is necessary to capture view's old and new areas
9477                invalidate(true);
9478            }
9479
9480            int width = mRight - mLeft;
9481            int oldHeight = mBottom - mTop;
9482
9483            mBottom = bottom;
9484            if (mDisplayList != null) {
9485                mDisplayList.setBottom(mBottom);
9486            }
9487
9488            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9489
9490            if (!matrixIsIdentity) {
9491                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9492                    // A change in dimension means an auto-centered pivot point changes, too
9493                    mTransformationInfo.mMatrixDirty = true;
9494                }
9495                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9496                invalidate(true);
9497            }
9498            mBackgroundSizeChanged = true;
9499            invalidateParentIfNeeded();
9500            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9501                // View was rejected last time it was drawn by its parent; this may have changed
9502                invalidateParentIfNeeded();
9503            }
9504        }
9505    }
9506
9507    /**
9508     * Left position of this view relative to its parent.
9509     *
9510     * @return The left edge of this view, in pixels.
9511     */
9512    @ViewDebug.CapturedViewProperty
9513    public final int getLeft() {
9514        return mLeft;
9515    }
9516
9517    /**
9518     * Sets the left position of this view relative to its parent. This method is meant to be called
9519     * by the layout system and should not generally be called otherwise, because the property
9520     * may be changed at any time by the layout.
9521     *
9522     * @param left The bottom of this view, in pixels.
9523     */
9524    public final void setLeft(int left) {
9525        if (left != mLeft) {
9526            updateMatrix();
9527            final boolean matrixIsIdentity = mTransformationInfo == null
9528                    || mTransformationInfo.mMatrixIsIdentity;
9529            if (matrixIsIdentity) {
9530                if (mAttachInfo != null) {
9531                    int minLeft;
9532                    int xLoc;
9533                    if (left < mLeft) {
9534                        minLeft = left;
9535                        xLoc = left - mLeft;
9536                    } else {
9537                        minLeft = mLeft;
9538                        xLoc = 0;
9539                    }
9540                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9541                }
9542            } else {
9543                // Double-invalidation is necessary to capture view's old and new areas
9544                invalidate(true);
9545            }
9546
9547            int oldWidth = mRight - mLeft;
9548            int height = mBottom - mTop;
9549
9550            mLeft = left;
9551            if (mDisplayList != null) {
9552                mDisplayList.setLeft(left);
9553            }
9554
9555            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9556
9557            if (!matrixIsIdentity) {
9558                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9559                    // A change in dimension means an auto-centered pivot point changes, too
9560                    mTransformationInfo.mMatrixDirty = true;
9561                }
9562                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9563                invalidate(true);
9564            }
9565            mBackgroundSizeChanged = true;
9566            invalidateParentIfNeeded();
9567            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9568                // View was rejected last time it was drawn by its parent; this may have changed
9569                invalidateParentIfNeeded();
9570            }
9571        }
9572    }
9573
9574    /**
9575     * Right position of this view relative to its parent.
9576     *
9577     * @return The right edge of this view, in pixels.
9578     */
9579    @ViewDebug.CapturedViewProperty
9580    public final int getRight() {
9581        return mRight;
9582    }
9583
9584    /**
9585     * Sets the right position of this view relative to its parent. This method is meant to be called
9586     * by the layout system and should not generally be called otherwise, because the property
9587     * may be changed at any time by the layout.
9588     *
9589     * @param right The bottom of this view, in pixels.
9590     */
9591    public final void setRight(int right) {
9592        if (right != mRight) {
9593            updateMatrix();
9594            final boolean matrixIsIdentity = mTransformationInfo == null
9595                    || mTransformationInfo.mMatrixIsIdentity;
9596            if (matrixIsIdentity) {
9597                if (mAttachInfo != null) {
9598                    int maxRight;
9599                    if (right < mRight) {
9600                        maxRight = mRight;
9601                    } else {
9602                        maxRight = right;
9603                    }
9604                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9605                }
9606            } else {
9607                // Double-invalidation is necessary to capture view's old and new areas
9608                invalidate(true);
9609            }
9610
9611            int oldWidth = mRight - mLeft;
9612            int height = mBottom - mTop;
9613
9614            mRight = right;
9615            if (mDisplayList != null) {
9616                mDisplayList.setRight(mRight);
9617            }
9618
9619            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9620
9621            if (!matrixIsIdentity) {
9622                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9623                    // A change in dimension means an auto-centered pivot point changes, too
9624                    mTransformationInfo.mMatrixDirty = true;
9625                }
9626                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9627                invalidate(true);
9628            }
9629            mBackgroundSizeChanged = true;
9630            invalidateParentIfNeeded();
9631            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9632                // View was rejected last time it was drawn by its parent; this may have changed
9633                invalidateParentIfNeeded();
9634            }
9635        }
9636    }
9637
9638    /**
9639     * The visual x position of this view, in pixels. This is equivalent to the
9640     * {@link #setTranslationX(float) translationX} property plus the current
9641     * {@link #getLeft() left} property.
9642     *
9643     * @return The visual x position of this view, in pixels.
9644     */
9645    @ViewDebug.ExportedProperty(category = "drawing")
9646    public float getX() {
9647        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9648    }
9649
9650    /**
9651     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9652     * {@link #setTranslationX(float) translationX} property to be the difference between
9653     * the x value passed in and the current {@link #getLeft() left} property.
9654     *
9655     * @param x The visual x position of this view, in pixels.
9656     */
9657    public void setX(float x) {
9658        setTranslationX(x - mLeft);
9659    }
9660
9661    /**
9662     * The visual y position of this view, in pixels. This is equivalent to the
9663     * {@link #setTranslationY(float) translationY} property plus the current
9664     * {@link #getTop() top} property.
9665     *
9666     * @return The visual y position of this view, in pixels.
9667     */
9668    @ViewDebug.ExportedProperty(category = "drawing")
9669    public float getY() {
9670        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9671    }
9672
9673    /**
9674     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9675     * {@link #setTranslationY(float) translationY} property to be the difference between
9676     * the y value passed in and the current {@link #getTop() top} property.
9677     *
9678     * @param y The visual y position of this view, in pixels.
9679     */
9680    public void setY(float y) {
9681        setTranslationY(y - mTop);
9682    }
9683
9684
9685    /**
9686     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9687     * This position is post-layout, in addition to wherever the object's
9688     * layout placed it.
9689     *
9690     * @return The horizontal position of this view relative to its left position, in pixels.
9691     */
9692    @ViewDebug.ExportedProperty(category = "drawing")
9693    public float getTranslationX() {
9694        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9695    }
9696
9697    /**
9698     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9699     * This effectively positions the object post-layout, in addition to wherever the object's
9700     * layout placed it.
9701     *
9702     * @param translationX The horizontal position of this view relative to its left position,
9703     * in pixels.
9704     *
9705     * @attr ref android.R.styleable#View_translationX
9706     */
9707    public void setTranslationX(float translationX) {
9708        ensureTransformationInfo();
9709        final TransformationInfo info = mTransformationInfo;
9710        if (info.mTranslationX != translationX) {
9711            // Double-invalidation is necessary to capture view's old and new areas
9712            invalidateViewProperty(true, false);
9713            info.mTranslationX = translationX;
9714            info.mMatrixDirty = true;
9715            invalidateViewProperty(false, true);
9716            if (mDisplayList != null) {
9717                mDisplayList.setTranslationX(translationX);
9718            }
9719            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9720                // View was rejected last time it was drawn by its parent; this may have changed
9721                invalidateParentIfNeeded();
9722            }
9723        }
9724    }
9725
9726    /**
9727     * The horizontal location of this view relative to its {@link #getTop() top} position.
9728     * This position is post-layout, in addition to wherever the object's
9729     * layout placed it.
9730     *
9731     * @return The vertical position of this view relative to its top position,
9732     * in pixels.
9733     */
9734    @ViewDebug.ExportedProperty(category = "drawing")
9735    public float getTranslationY() {
9736        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9737    }
9738
9739    /**
9740     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9741     * This effectively positions the object post-layout, in addition to wherever the object's
9742     * layout placed it.
9743     *
9744     * @param translationY The vertical position of this view relative to its top position,
9745     * in pixels.
9746     *
9747     * @attr ref android.R.styleable#View_translationY
9748     */
9749    public void setTranslationY(float translationY) {
9750        ensureTransformationInfo();
9751        final TransformationInfo info = mTransformationInfo;
9752        if (info.mTranslationY != translationY) {
9753            invalidateViewProperty(true, false);
9754            info.mTranslationY = translationY;
9755            info.mMatrixDirty = true;
9756            invalidateViewProperty(false, true);
9757            if (mDisplayList != null) {
9758                mDisplayList.setTranslationY(translationY);
9759            }
9760            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9761                // View was rejected last time it was drawn by its parent; this may have changed
9762                invalidateParentIfNeeded();
9763            }
9764        }
9765    }
9766
9767    /**
9768     * Hit rectangle in parent's coordinates
9769     *
9770     * @param outRect The hit rectangle of the view.
9771     */
9772    public void getHitRect(Rect outRect) {
9773        updateMatrix();
9774        final TransformationInfo info = mTransformationInfo;
9775        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9776            outRect.set(mLeft, mTop, mRight, mBottom);
9777        } else {
9778            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9779            tmpRect.set(-info.mPivotX, -info.mPivotY,
9780                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9781            info.mMatrix.mapRect(tmpRect);
9782            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9783                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9784        }
9785    }
9786
9787    /**
9788     * Determines whether the given point, in local coordinates is inside the view.
9789     */
9790    /*package*/ final boolean pointInView(float localX, float localY) {
9791        return localX >= 0 && localX < (mRight - mLeft)
9792                && localY >= 0 && localY < (mBottom - mTop);
9793    }
9794
9795    /**
9796     * Utility method to determine whether the given point, in local coordinates,
9797     * is inside the view, where the area of the view is expanded by the slop factor.
9798     * This method is called while processing touch-move events to determine if the event
9799     * is still within the view.
9800     */
9801    private boolean pointInView(float localX, float localY, float slop) {
9802        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9803                localY < ((mBottom - mTop) + slop);
9804    }
9805
9806    /**
9807     * When a view has focus and the user navigates away from it, the next view is searched for
9808     * starting from the rectangle filled in by this method.
9809     *
9810     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
9811     * of the view.  However, if your view maintains some idea of internal selection,
9812     * such as a cursor, or a selected row or column, you should override this method and
9813     * fill in a more specific rectangle.
9814     *
9815     * @param r The rectangle to fill in, in this view's coordinates.
9816     */
9817    public void getFocusedRect(Rect r) {
9818        getDrawingRect(r);
9819    }
9820
9821    /**
9822     * If some part of this view is not clipped by any of its parents, then
9823     * return that area in r in global (root) coordinates. To convert r to local
9824     * coordinates (without taking possible View rotations into account), offset
9825     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9826     * If the view is completely clipped or translated out, return false.
9827     *
9828     * @param r If true is returned, r holds the global coordinates of the
9829     *        visible portion of this view.
9830     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9831     *        between this view and its root. globalOffet may be null.
9832     * @return true if r is non-empty (i.e. part of the view is visible at the
9833     *         root level.
9834     */
9835    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9836        int width = mRight - mLeft;
9837        int height = mBottom - mTop;
9838        if (width > 0 && height > 0) {
9839            r.set(0, 0, width, height);
9840            if (globalOffset != null) {
9841                globalOffset.set(-mScrollX, -mScrollY);
9842            }
9843            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9844        }
9845        return false;
9846    }
9847
9848    public final boolean getGlobalVisibleRect(Rect r) {
9849        return getGlobalVisibleRect(r, null);
9850    }
9851
9852    public final boolean getLocalVisibleRect(Rect r) {
9853        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9854        if (getGlobalVisibleRect(r, offset)) {
9855            r.offset(-offset.x, -offset.y); // make r local
9856            return true;
9857        }
9858        return false;
9859    }
9860
9861    /**
9862     * Offset this view's vertical location by the specified number of pixels.
9863     *
9864     * @param offset the number of pixels to offset the view by
9865     */
9866    public void offsetTopAndBottom(int offset) {
9867        if (offset != 0) {
9868            updateMatrix();
9869            final boolean matrixIsIdentity = mTransformationInfo == null
9870                    || mTransformationInfo.mMatrixIsIdentity;
9871            if (matrixIsIdentity) {
9872                if (mDisplayList != null) {
9873                    invalidateViewProperty(false, false);
9874                } else {
9875                    final ViewParent p = mParent;
9876                    if (p != null && mAttachInfo != null) {
9877                        final Rect r = mAttachInfo.mTmpInvalRect;
9878                        int minTop;
9879                        int maxBottom;
9880                        int yLoc;
9881                        if (offset < 0) {
9882                            minTop = mTop + offset;
9883                            maxBottom = mBottom;
9884                            yLoc = offset;
9885                        } else {
9886                            minTop = mTop;
9887                            maxBottom = mBottom + offset;
9888                            yLoc = 0;
9889                        }
9890                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9891                        p.invalidateChild(this, r);
9892                    }
9893                }
9894            } else {
9895                invalidateViewProperty(false, false);
9896            }
9897
9898            mTop += offset;
9899            mBottom += offset;
9900            if (mDisplayList != null) {
9901                mDisplayList.offsetTopBottom(offset);
9902                invalidateViewProperty(false, false);
9903            } else {
9904                if (!matrixIsIdentity) {
9905                    invalidateViewProperty(false, true);
9906                }
9907                invalidateParentIfNeeded();
9908            }
9909        }
9910    }
9911
9912    /**
9913     * Offset this view's horizontal location by the specified amount of pixels.
9914     *
9915     * @param offset the numer of pixels to offset the view by
9916     */
9917    public void offsetLeftAndRight(int offset) {
9918        if (offset != 0) {
9919            updateMatrix();
9920            final boolean matrixIsIdentity = mTransformationInfo == null
9921                    || mTransformationInfo.mMatrixIsIdentity;
9922            if (matrixIsIdentity) {
9923                if (mDisplayList != null) {
9924                    invalidateViewProperty(false, false);
9925                } else {
9926                    final ViewParent p = mParent;
9927                    if (p != null && mAttachInfo != null) {
9928                        final Rect r = mAttachInfo.mTmpInvalRect;
9929                        int minLeft;
9930                        int maxRight;
9931                        if (offset < 0) {
9932                            minLeft = mLeft + offset;
9933                            maxRight = mRight;
9934                        } else {
9935                            minLeft = mLeft;
9936                            maxRight = mRight + offset;
9937                        }
9938                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9939                        p.invalidateChild(this, r);
9940                    }
9941                }
9942            } else {
9943                invalidateViewProperty(false, false);
9944            }
9945
9946            mLeft += offset;
9947            mRight += offset;
9948            if (mDisplayList != null) {
9949                mDisplayList.offsetLeftRight(offset);
9950                invalidateViewProperty(false, false);
9951            } else {
9952                if (!matrixIsIdentity) {
9953                    invalidateViewProperty(false, true);
9954                }
9955                invalidateParentIfNeeded();
9956            }
9957        }
9958    }
9959
9960    /**
9961     * Get the LayoutParams associated with this view. All views should have
9962     * layout parameters. These supply parameters to the <i>parent</i> of this
9963     * view specifying how it should be arranged. There are many subclasses of
9964     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9965     * of ViewGroup that are responsible for arranging their children.
9966     *
9967     * This method may return null if this View is not attached to a parent
9968     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9969     * was not invoked successfully. When a View is attached to a parent
9970     * ViewGroup, this method must not return null.
9971     *
9972     * @return The LayoutParams associated with this view, or null if no
9973     *         parameters have been set yet
9974     */
9975    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9976    public ViewGroup.LayoutParams getLayoutParams() {
9977        return mLayoutParams;
9978    }
9979
9980    /**
9981     * Set the layout parameters associated with this view. These supply
9982     * parameters to the <i>parent</i> of this view specifying how it should be
9983     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9984     * correspond to the different subclasses of ViewGroup that are responsible
9985     * for arranging their children.
9986     *
9987     * @param params The layout parameters for this view, cannot be null
9988     */
9989    public void setLayoutParams(ViewGroup.LayoutParams params) {
9990        if (params == null) {
9991            throw new NullPointerException("Layout parameters cannot be null");
9992        }
9993        mLayoutParams = params;
9994        resolveLayoutParams();
9995        if (mParent instanceof ViewGroup) {
9996            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9997        }
9998        requestLayout();
9999    }
10000
10001    /**
10002     * Resolve the layout parameters depending on the resolved layout direction
10003     */
10004    private void resolveLayoutParams() {
10005        if (mLayoutParams != null) {
10006            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10007        }
10008    }
10009
10010    /**
10011     * Set the scrolled position of your view. This will cause a call to
10012     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10013     * invalidated.
10014     * @param x the x position to scroll to
10015     * @param y the y position to scroll to
10016     */
10017    public void scrollTo(int x, int y) {
10018        if (mScrollX != x || mScrollY != y) {
10019            int oldX = mScrollX;
10020            int oldY = mScrollY;
10021            mScrollX = x;
10022            mScrollY = y;
10023            invalidateParentCaches();
10024            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10025            if (!awakenScrollBars()) {
10026                postInvalidateOnAnimation();
10027            }
10028        }
10029    }
10030
10031    /**
10032     * Move the scrolled position of your view. This will cause a call to
10033     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10034     * invalidated.
10035     * @param x the amount of pixels to scroll by horizontally
10036     * @param y the amount of pixels to scroll by vertically
10037     */
10038    public void scrollBy(int x, int y) {
10039        scrollTo(mScrollX + x, mScrollY + y);
10040    }
10041
10042    /**
10043     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10044     * animation to fade the scrollbars out after a default delay. If a subclass
10045     * provides animated scrolling, the start delay should equal the duration
10046     * of the scrolling animation.</p>
10047     *
10048     * <p>The animation starts only if at least one of the scrollbars is
10049     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10050     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10051     * this method returns true, and false otherwise. If the animation is
10052     * started, this method calls {@link #invalidate()}; in that case the
10053     * caller should not call {@link #invalidate()}.</p>
10054     *
10055     * <p>This method should be invoked every time a subclass directly updates
10056     * the scroll parameters.</p>
10057     *
10058     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10059     * and {@link #scrollTo(int, int)}.</p>
10060     *
10061     * @return true if the animation is played, false otherwise
10062     *
10063     * @see #awakenScrollBars(int)
10064     * @see #scrollBy(int, int)
10065     * @see #scrollTo(int, int)
10066     * @see #isHorizontalScrollBarEnabled()
10067     * @see #isVerticalScrollBarEnabled()
10068     * @see #setHorizontalScrollBarEnabled(boolean)
10069     * @see #setVerticalScrollBarEnabled(boolean)
10070     */
10071    protected boolean awakenScrollBars() {
10072        return mScrollCache != null &&
10073                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10074    }
10075
10076    /**
10077     * Trigger the scrollbars to draw.
10078     * This method differs from awakenScrollBars() only in its default duration.
10079     * initialAwakenScrollBars() will show the scroll bars for longer than
10080     * usual to give the user more of a chance to notice them.
10081     *
10082     * @return true if the animation is played, false otherwise.
10083     */
10084    private boolean initialAwakenScrollBars() {
10085        return mScrollCache != null &&
10086                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10087    }
10088
10089    /**
10090     * <p>
10091     * Trigger the scrollbars to draw. When invoked this method starts an
10092     * animation to fade the scrollbars out after a fixed delay. If a subclass
10093     * provides animated scrolling, the start delay should equal the duration of
10094     * the scrolling animation.
10095     * </p>
10096     *
10097     * <p>
10098     * The animation starts only if at least one of the scrollbars is enabled,
10099     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10100     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10101     * this method returns true, and false otherwise. If the animation is
10102     * started, this method calls {@link #invalidate()}; in that case the caller
10103     * should not call {@link #invalidate()}.
10104     * </p>
10105     *
10106     * <p>
10107     * This method should be invoked everytime a subclass directly updates the
10108     * scroll parameters.
10109     * </p>
10110     *
10111     * @param startDelay the delay, in milliseconds, after which the animation
10112     *        should start; when the delay is 0, the animation starts
10113     *        immediately
10114     * @return true if the animation is played, false otherwise
10115     *
10116     * @see #scrollBy(int, int)
10117     * @see #scrollTo(int, int)
10118     * @see #isHorizontalScrollBarEnabled()
10119     * @see #isVerticalScrollBarEnabled()
10120     * @see #setHorizontalScrollBarEnabled(boolean)
10121     * @see #setVerticalScrollBarEnabled(boolean)
10122     */
10123    protected boolean awakenScrollBars(int startDelay) {
10124        return awakenScrollBars(startDelay, true);
10125    }
10126
10127    /**
10128     * <p>
10129     * Trigger the scrollbars to draw. When invoked this method starts an
10130     * animation to fade the scrollbars out after a fixed delay. If a subclass
10131     * provides animated scrolling, the start delay should equal the duration of
10132     * the scrolling animation.
10133     * </p>
10134     *
10135     * <p>
10136     * The animation starts only if at least one of the scrollbars is enabled,
10137     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10138     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10139     * this method returns true, and false otherwise. If the animation is
10140     * started, this method calls {@link #invalidate()} if the invalidate parameter
10141     * is set to true; in that case the caller
10142     * should not call {@link #invalidate()}.
10143     * </p>
10144     *
10145     * <p>
10146     * This method should be invoked everytime a subclass directly updates the
10147     * scroll parameters.
10148     * </p>
10149     *
10150     * @param startDelay the delay, in milliseconds, after which the animation
10151     *        should start; when the delay is 0, the animation starts
10152     *        immediately
10153     *
10154     * @param invalidate Wheter this method should call invalidate
10155     *
10156     * @return true if the animation is played, false otherwise
10157     *
10158     * @see #scrollBy(int, int)
10159     * @see #scrollTo(int, int)
10160     * @see #isHorizontalScrollBarEnabled()
10161     * @see #isVerticalScrollBarEnabled()
10162     * @see #setHorizontalScrollBarEnabled(boolean)
10163     * @see #setVerticalScrollBarEnabled(boolean)
10164     */
10165    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10166        final ScrollabilityCache scrollCache = mScrollCache;
10167
10168        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10169            return false;
10170        }
10171
10172        if (scrollCache.scrollBar == null) {
10173            scrollCache.scrollBar = new ScrollBarDrawable();
10174        }
10175
10176        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10177
10178            if (invalidate) {
10179                // Invalidate to show the scrollbars
10180                postInvalidateOnAnimation();
10181            }
10182
10183            if (scrollCache.state == ScrollabilityCache.OFF) {
10184                // FIXME: this is copied from WindowManagerService.
10185                // We should get this value from the system when it
10186                // is possible to do so.
10187                final int KEY_REPEAT_FIRST_DELAY = 750;
10188                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10189            }
10190
10191            // Tell mScrollCache when we should start fading. This may
10192            // extend the fade start time if one was already scheduled
10193            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10194            scrollCache.fadeStartTime = fadeStartTime;
10195            scrollCache.state = ScrollabilityCache.ON;
10196
10197            // Schedule our fader to run, unscheduling any old ones first
10198            if (mAttachInfo != null) {
10199                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10200                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10201            }
10202
10203            return true;
10204        }
10205
10206        return false;
10207    }
10208
10209    /**
10210     * Do not invalidate views which are not visible and which are not running an animation. They
10211     * will not get drawn and they should not set dirty flags as if they will be drawn
10212     */
10213    private boolean skipInvalidate() {
10214        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10215                (!(mParent instanceof ViewGroup) ||
10216                        !((ViewGroup) mParent).isViewTransitioning(this));
10217    }
10218    /**
10219     * Mark the area defined by dirty as needing to be drawn. If the view is
10220     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10221     * in the future. This must be called from a UI thread. To call from a non-UI
10222     * thread, call {@link #postInvalidate()}.
10223     *
10224     * WARNING: This method is destructive to dirty.
10225     * @param dirty the rectangle representing the bounds of the dirty region
10226     */
10227    public void invalidate(Rect dirty) {
10228        if (skipInvalidate()) {
10229            return;
10230        }
10231        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10232                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10233                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10234            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10235            mPrivateFlags |= PFLAG_INVALIDATED;
10236            mPrivateFlags |= PFLAG_DIRTY;
10237            final ViewParent p = mParent;
10238            final AttachInfo ai = mAttachInfo;
10239            //noinspection PointlessBooleanExpression,ConstantConditions
10240            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10241                if (p != null && ai != null && ai.mHardwareAccelerated) {
10242                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10243                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10244                    p.invalidateChild(this, null);
10245                    return;
10246                }
10247            }
10248            if (p != null && ai != null) {
10249                final int scrollX = mScrollX;
10250                final int scrollY = mScrollY;
10251                final Rect r = ai.mTmpInvalRect;
10252                r.set(dirty.left - scrollX, dirty.top - scrollY,
10253                        dirty.right - scrollX, dirty.bottom - scrollY);
10254                mParent.invalidateChild(this, r);
10255            }
10256        }
10257    }
10258
10259    /**
10260     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10261     * The coordinates of the dirty rect are relative to the view.
10262     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10263     * will be called at some point in the future. This must be called from
10264     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10265     * @param l the left position of the dirty region
10266     * @param t the top position of the dirty region
10267     * @param r the right position of the dirty region
10268     * @param b the bottom position of the dirty region
10269     */
10270    public void invalidate(int l, int t, int r, int b) {
10271        if (skipInvalidate()) {
10272            return;
10273        }
10274        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10275                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10276                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10277            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10278            mPrivateFlags |= PFLAG_INVALIDATED;
10279            mPrivateFlags |= PFLAG_DIRTY;
10280            final ViewParent p = mParent;
10281            final AttachInfo ai = mAttachInfo;
10282            //noinspection PointlessBooleanExpression,ConstantConditions
10283            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10284                if (p != null && ai != null && ai.mHardwareAccelerated) {
10285                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10286                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10287                    p.invalidateChild(this, null);
10288                    return;
10289                }
10290            }
10291            if (p != null && ai != null && l < r && t < b) {
10292                final int scrollX = mScrollX;
10293                final int scrollY = mScrollY;
10294                final Rect tmpr = ai.mTmpInvalRect;
10295                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10296                p.invalidateChild(this, tmpr);
10297            }
10298        }
10299    }
10300
10301    /**
10302     * Invalidate the whole view. If the view is visible,
10303     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10304     * the future. This must be called from a UI thread. To call from a non-UI thread,
10305     * call {@link #postInvalidate()}.
10306     */
10307    public void invalidate() {
10308        invalidate(true);
10309    }
10310
10311    /**
10312     * This is where the invalidate() work actually happens. A full invalidate()
10313     * causes the drawing cache to be invalidated, but this function can be called with
10314     * invalidateCache set to false to skip that invalidation step for cases that do not
10315     * need it (for example, a component that remains at the same dimensions with the same
10316     * content).
10317     *
10318     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10319     * well. This is usually true for a full invalidate, but may be set to false if the
10320     * View's contents or dimensions have not changed.
10321     */
10322    void invalidate(boolean invalidateCache) {
10323        if (skipInvalidate()) {
10324            return;
10325        }
10326        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10327                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10328                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10329            mLastIsOpaque = isOpaque();
10330            mPrivateFlags &= ~PFLAG_DRAWN;
10331            mPrivateFlags |= PFLAG_DIRTY;
10332            if (invalidateCache) {
10333                mPrivateFlags |= PFLAG_INVALIDATED;
10334                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10335            }
10336            final AttachInfo ai = mAttachInfo;
10337            final ViewParent p = mParent;
10338            //noinspection PointlessBooleanExpression,ConstantConditions
10339            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10340                if (p != null && ai != null && ai.mHardwareAccelerated) {
10341                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10342                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10343                    p.invalidateChild(this, null);
10344                    return;
10345                }
10346            }
10347
10348            if (p != null && ai != null) {
10349                final Rect r = ai.mTmpInvalRect;
10350                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10351                // Don't call invalidate -- we don't want to internally scroll
10352                // our own bounds
10353                p.invalidateChild(this, r);
10354            }
10355        }
10356    }
10357
10358    /**
10359     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10360     * set any flags or handle all of the cases handled by the default invalidation methods.
10361     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10362     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10363     * walk up the hierarchy, transforming the dirty rect as necessary.
10364     *
10365     * The method also handles normal invalidation logic if display list properties are not
10366     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10367     * backup approach, to handle these cases used in the various property-setting methods.
10368     *
10369     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10370     * are not being used in this view
10371     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10372     * list properties are not being used in this view
10373     */
10374    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10375        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10376            if (invalidateParent) {
10377                invalidateParentCaches();
10378            }
10379            if (forceRedraw) {
10380                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10381            }
10382            invalidate(false);
10383        } else {
10384            final AttachInfo ai = mAttachInfo;
10385            final ViewParent p = mParent;
10386            if (p != null && ai != null) {
10387                final Rect r = ai.mTmpInvalRect;
10388                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10389                if (mParent instanceof ViewGroup) {
10390                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10391                } else {
10392                    mParent.invalidateChild(this, r);
10393                }
10394            }
10395        }
10396    }
10397
10398    /**
10399     * Utility method to transform a given Rect by the current matrix of this view.
10400     */
10401    void transformRect(final Rect rect) {
10402        if (!getMatrix().isIdentity()) {
10403            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10404            boundingRect.set(rect);
10405            getMatrix().mapRect(boundingRect);
10406            rect.set((int) (boundingRect.left - 0.5f),
10407                    (int) (boundingRect.top - 0.5f),
10408                    (int) (boundingRect.right + 0.5f),
10409                    (int) (boundingRect.bottom + 0.5f));
10410        }
10411    }
10412
10413    /**
10414     * Used to indicate that the parent of this view should clear its caches. This functionality
10415     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10416     * which is necessary when various parent-managed properties of the view change, such as
10417     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10418     * clears the parent caches and does not causes an invalidate event.
10419     *
10420     * @hide
10421     */
10422    protected void invalidateParentCaches() {
10423        if (mParent instanceof View) {
10424            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10425        }
10426    }
10427
10428    /**
10429     * Used to indicate that the parent of this view should be invalidated. This functionality
10430     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10431     * which is necessary when various parent-managed properties of the view change, such as
10432     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10433     * an invalidation event to the parent.
10434     *
10435     * @hide
10436     */
10437    protected void invalidateParentIfNeeded() {
10438        if (isHardwareAccelerated() && mParent instanceof View) {
10439            ((View) mParent).invalidate(true);
10440        }
10441    }
10442
10443    /**
10444     * Indicates whether this View is opaque. An opaque View guarantees that it will
10445     * draw all the pixels overlapping its bounds using a fully opaque color.
10446     *
10447     * Subclasses of View should override this method whenever possible to indicate
10448     * whether an instance is opaque. Opaque Views are treated in a special way by
10449     * the View hierarchy, possibly allowing it to perform optimizations during
10450     * invalidate/draw passes.
10451     *
10452     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10453     */
10454    @ViewDebug.ExportedProperty(category = "drawing")
10455    public boolean isOpaque() {
10456        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10457                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10458    }
10459
10460    /**
10461     * @hide
10462     */
10463    protected void computeOpaqueFlags() {
10464        // Opaque if:
10465        //   - Has a background
10466        //   - Background is opaque
10467        //   - Doesn't have scrollbars or scrollbars are inside overlay
10468
10469        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10470            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10471        } else {
10472            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10473        }
10474
10475        final int flags = mViewFlags;
10476        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10477                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10478            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10479        } else {
10480            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10481        }
10482    }
10483
10484    /**
10485     * @hide
10486     */
10487    protected boolean hasOpaqueScrollbars() {
10488        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10489    }
10490
10491    /**
10492     * @return A handler associated with the thread running the View. This
10493     * handler can be used to pump events in the UI events queue.
10494     */
10495    public Handler getHandler() {
10496        if (mAttachInfo != null) {
10497            return mAttachInfo.mHandler;
10498        }
10499        return null;
10500    }
10501
10502    /**
10503     * Gets the view root associated with the View.
10504     * @return The view root, or null if none.
10505     * @hide
10506     */
10507    public ViewRootImpl getViewRootImpl() {
10508        if (mAttachInfo != null) {
10509            return mAttachInfo.mViewRootImpl;
10510        }
10511        return null;
10512    }
10513
10514    /**
10515     * <p>Causes the Runnable to be added to the message queue.
10516     * The runnable will be run on the user interface thread.</p>
10517     *
10518     * <p>This method can be invoked from outside of the UI thread
10519     * only when this View is attached to a window.</p>
10520     *
10521     * @param action The Runnable that will be executed.
10522     *
10523     * @return Returns true if the Runnable was successfully placed in to the
10524     *         message queue.  Returns false on failure, usually because the
10525     *         looper processing the message queue is exiting.
10526     *
10527     * @see #postDelayed
10528     * @see #removeCallbacks
10529     */
10530    public boolean post(Runnable action) {
10531        final AttachInfo attachInfo = mAttachInfo;
10532        if (attachInfo != null) {
10533            return attachInfo.mHandler.post(action);
10534        }
10535        // Assume that post will succeed later
10536        ViewRootImpl.getRunQueue().post(action);
10537        return true;
10538    }
10539
10540    /**
10541     * <p>Causes the Runnable to be added to the message queue, to be run
10542     * after the specified amount of time elapses.
10543     * The runnable will be run on the user interface thread.</p>
10544     *
10545     * <p>This method can be invoked from outside of the UI thread
10546     * only when this View is attached to a window.</p>
10547     *
10548     * @param action The Runnable that will be executed.
10549     * @param delayMillis The delay (in milliseconds) until the Runnable
10550     *        will be executed.
10551     *
10552     * @return true if the Runnable was successfully placed in to the
10553     *         message queue.  Returns false on failure, usually because the
10554     *         looper processing the message queue is exiting.  Note that a
10555     *         result of true does not mean the Runnable will be processed --
10556     *         if the looper is quit before the delivery time of the message
10557     *         occurs then the message will be dropped.
10558     *
10559     * @see #post
10560     * @see #removeCallbacks
10561     */
10562    public boolean postDelayed(Runnable action, long delayMillis) {
10563        final AttachInfo attachInfo = mAttachInfo;
10564        if (attachInfo != null) {
10565            return attachInfo.mHandler.postDelayed(action, delayMillis);
10566        }
10567        // Assume that post will succeed later
10568        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10569        return true;
10570    }
10571
10572    /**
10573     * <p>Causes the Runnable to execute on the next animation time step.
10574     * The runnable will be run on the user interface thread.</p>
10575     *
10576     * <p>This method can be invoked from outside of the UI thread
10577     * only when this View is attached to a window.</p>
10578     *
10579     * @param action The Runnable that will be executed.
10580     *
10581     * @see #postOnAnimationDelayed
10582     * @see #removeCallbacks
10583     */
10584    public void postOnAnimation(Runnable action) {
10585        final AttachInfo attachInfo = mAttachInfo;
10586        if (attachInfo != null) {
10587            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10588                    Choreographer.CALLBACK_ANIMATION, action, null);
10589        } else {
10590            // Assume that post will succeed later
10591            ViewRootImpl.getRunQueue().post(action);
10592        }
10593    }
10594
10595    /**
10596     * <p>Causes the Runnable to execute on the next animation time step,
10597     * after the specified amount of time elapses.
10598     * The runnable will be run on the user interface thread.</p>
10599     *
10600     * <p>This method can be invoked from outside of the UI thread
10601     * only when this View is attached to a window.</p>
10602     *
10603     * @param action The Runnable that will be executed.
10604     * @param delayMillis The delay (in milliseconds) until the Runnable
10605     *        will be executed.
10606     *
10607     * @see #postOnAnimation
10608     * @see #removeCallbacks
10609     */
10610    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10611        final AttachInfo attachInfo = mAttachInfo;
10612        if (attachInfo != null) {
10613            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10614                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10615        } else {
10616            // Assume that post will succeed later
10617            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10618        }
10619    }
10620
10621    /**
10622     * <p>Removes the specified Runnable from the message queue.</p>
10623     *
10624     * <p>This method can be invoked from outside of the UI thread
10625     * only when this View is attached to a window.</p>
10626     *
10627     * @param action The Runnable to remove from the message handling queue
10628     *
10629     * @return true if this view could ask the Handler to remove the Runnable,
10630     *         false otherwise. When the returned value is true, the Runnable
10631     *         may or may not have been actually removed from the message queue
10632     *         (for instance, if the Runnable was not in the queue already.)
10633     *
10634     * @see #post
10635     * @see #postDelayed
10636     * @see #postOnAnimation
10637     * @see #postOnAnimationDelayed
10638     */
10639    public boolean removeCallbacks(Runnable action) {
10640        if (action != null) {
10641            final AttachInfo attachInfo = mAttachInfo;
10642            if (attachInfo != null) {
10643                attachInfo.mHandler.removeCallbacks(action);
10644                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10645                        Choreographer.CALLBACK_ANIMATION, action, null);
10646            } else {
10647                // Assume that post will succeed later
10648                ViewRootImpl.getRunQueue().removeCallbacks(action);
10649            }
10650        }
10651        return true;
10652    }
10653
10654    /**
10655     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10656     * Use this to invalidate the View from a non-UI thread.</p>
10657     *
10658     * <p>This method can be invoked from outside of the UI thread
10659     * only when this View is attached to a window.</p>
10660     *
10661     * @see #invalidate()
10662     * @see #postInvalidateDelayed(long)
10663     */
10664    public void postInvalidate() {
10665        postInvalidateDelayed(0);
10666    }
10667
10668    /**
10669     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10670     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10671     *
10672     * <p>This method can be invoked from outside of the UI thread
10673     * only when this View is attached to a window.</p>
10674     *
10675     * @param left The left coordinate of the rectangle to invalidate.
10676     * @param top The top coordinate of the rectangle to invalidate.
10677     * @param right The right coordinate of the rectangle to invalidate.
10678     * @param bottom The bottom coordinate of the rectangle to invalidate.
10679     *
10680     * @see #invalidate(int, int, int, int)
10681     * @see #invalidate(Rect)
10682     * @see #postInvalidateDelayed(long, int, int, int, int)
10683     */
10684    public void postInvalidate(int left, int top, int right, int bottom) {
10685        postInvalidateDelayed(0, left, top, right, bottom);
10686    }
10687
10688    /**
10689     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10690     * loop. Waits for the specified amount of time.</p>
10691     *
10692     * <p>This method can be invoked from outside of the UI thread
10693     * only when this View is attached to a window.</p>
10694     *
10695     * @param delayMilliseconds the duration in milliseconds to delay the
10696     *         invalidation by
10697     *
10698     * @see #invalidate()
10699     * @see #postInvalidate()
10700     */
10701    public void postInvalidateDelayed(long delayMilliseconds) {
10702        // We try only with the AttachInfo because there's no point in invalidating
10703        // if we are not attached to our window
10704        final AttachInfo attachInfo = mAttachInfo;
10705        if (attachInfo != null) {
10706            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10707        }
10708    }
10709
10710    /**
10711     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10712     * through the event loop. Waits for the specified amount of time.</p>
10713     *
10714     * <p>This method can be invoked from outside of the UI thread
10715     * only when this View is attached to a window.</p>
10716     *
10717     * @param delayMilliseconds the duration in milliseconds to delay the
10718     *         invalidation by
10719     * @param left The left coordinate of the rectangle to invalidate.
10720     * @param top The top coordinate of the rectangle to invalidate.
10721     * @param right The right coordinate of the rectangle to invalidate.
10722     * @param bottom The bottom coordinate of the rectangle to invalidate.
10723     *
10724     * @see #invalidate(int, int, int, int)
10725     * @see #invalidate(Rect)
10726     * @see #postInvalidate(int, int, int, int)
10727     */
10728    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10729            int right, int bottom) {
10730
10731        // We try only with the AttachInfo because there's no point in invalidating
10732        // if we are not attached to our window
10733        final AttachInfo attachInfo = mAttachInfo;
10734        if (attachInfo != null) {
10735            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10736            info.target = this;
10737            info.left = left;
10738            info.top = top;
10739            info.right = right;
10740            info.bottom = bottom;
10741
10742            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10743        }
10744    }
10745
10746    /**
10747     * <p>Cause an invalidate to happen on the next animation time step, typically the
10748     * next display frame.</p>
10749     *
10750     * <p>This method can be invoked from outside of the UI thread
10751     * only when this View is attached to a window.</p>
10752     *
10753     * @see #invalidate()
10754     */
10755    public void postInvalidateOnAnimation() {
10756        // We try only with the AttachInfo because there's no point in invalidating
10757        // if we are not attached to our window
10758        final AttachInfo attachInfo = mAttachInfo;
10759        if (attachInfo != null) {
10760            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10761        }
10762    }
10763
10764    /**
10765     * <p>Cause an invalidate of the specified area to happen on the next animation
10766     * time step, typically the next display frame.</p>
10767     *
10768     * <p>This method can be invoked from outside of the UI thread
10769     * only when this View is attached to a window.</p>
10770     *
10771     * @param left The left coordinate of the rectangle to invalidate.
10772     * @param top The top coordinate of the rectangle to invalidate.
10773     * @param right The right coordinate of the rectangle to invalidate.
10774     * @param bottom The bottom coordinate of the rectangle to invalidate.
10775     *
10776     * @see #invalidate(int, int, int, int)
10777     * @see #invalidate(Rect)
10778     */
10779    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10780        // We try only with the AttachInfo because there's no point in invalidating
10781        // if we are not attached to our window
10782        final AttachInfo attachInfo = mAttachInfo;
10783        if (attachInfo != null) {
10784            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10785            info.target = this;
10786            info.left = left;
10787            info.top = top;
10788            info.right = right;
10789            info.bottom = bottom;
10790
10791            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10792        }
10793    }
10794
10795    /**
10796     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10797     * This event is sent at most once every
10798     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10799     */
10800    private void postSendViewScrolledAccessibilityEventCallback() {
10801        if (mSendViewScrolledAccessibilityEvent == null) {
10802            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10803        }
10804        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10805            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10806            postDelayed(mSendViewScrolledAccessibilityEvent,
10807                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10808        }
10809    }
10810
10811    /**
10812     * Called by a parent to request that a child update its values for mScrollX
10813     * and mScrollY if necessary. This will typically be done if the child is
10814     * animating a scroll using a {@link android.widget.Scroller Scroller}
10815     * object.
10816     */
10817    public void computeScroll() {
10818    }
10819
10820    /**
10821     * <p>Indicate whether the horizontal edges are faded when the view is
10822     * scrolled horizontally.</p>
10823     *
10824     * @return true if the horizontal edges should are faded on scroll, false
10825     *         otherwise
10826     *
10827     * @see #setHorizontalFadingEdgeEnabled(boolean)
10828     *
10829     * @attr ref android.R.styleable#View_requiresFadingEdge
10830     */
10831    public boolean isHorizontalFadingEdgeEnabled() {
10832        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10833    }
10834
10835    /**
10836     * <p>Define whether the horizontal edges should be faded when this view
10837     * is scrolled horizontally.</p>
10838     *
10839     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10840     *                                    be faded when the view is scrolled
10841     *                                    horizontally
10842     *
10843     * @see #isHorizontalFadingEdgeEnabled()
10844     *
10845     * @attr ref android.R.styleable#View_requiresFadingEdge
10846     */
10847    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10848        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10849            if (horizontalFadingEdgeEnabled) {
10850                initScrollCache();
10851            }
10852
10853            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10854        }
10855    }
10856
10857    /**
10858     * <p>Indicate whether the vertical edges are faded when the view is
10859     * scrolled horizontally.</p>
10860     *
10861     * @return true if the vertical edges should are faded on scroll, false
10862     *         otherwise
10863     *
10864     * @see #setVerticalFadingEdgeEnabled(boolean)
10865     *
10866     * @attr ref android.R.styleable#View_requiresFadingEdge
10867     */
10868    public boolean isVerticalFadingEdgeEnabled() {
10869        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10870    }
10871
10872    /**
10873     * <p>Define whether the vertical edges should be faded when this view
10874     * is scrolled vertically.</p>
10875     *
10876     * @param verticalFadingEdgeEnabled true if the vertical edges should
10877     *                                  be faded when the view is scrolled
10878     *                                  vertically
10879     *
10880     * @see #isVerticalFadingEdgeEnabled()
10881     *
10882     * @attr ref android.R.styleable#View_requiresFadingEdge
10883     */
10884    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10885        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10886            if (verticalFadingEdgeEnabled) {
10887                initScrollCache();
10888            }
10889
10890            mViewFlags ^= FADING_EDGE_VERTICAL;
10891        }
10892    }
10893
10894    /**
10895     * Returns the strength, or intensity, of the top faded edge. The strength is
10896     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10897     * returns 0.0 or 1.0 but no value in between.
10898     *
10899     * Subclasses should override this method to provide a smoother fade transition
10900     * when scrolling occurs.
10901     *
10902     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10903     */
10904    protected float getTopFadingEdgeStrength() {
10905        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10906    }
10907
10908    /**
10909     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10910     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10911     * returns 0.0 or 1.0 but no value in between.
10912     *
10913     * Subclasses should override this method to provide a smoother fade transition
10914     * when scrolling occurs.
10915     *
10916     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10917     */
10918    protected float getBottomFadingEdgeStrength() {
10919        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10920                computeVerticalScrollRange() ? 1.0f : 0.0f;
10921    }
10922
10923    /**
10924     * Returns the strength, or intensity, of the left faded edge. The strength is
10925     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10926     * returns 0.0 or 1.0 but no value in between.
10927     *
10928     * Subclasses should override this method to provide a smoother fade transition
10929     * when scrolling occurs.
10930     *
10931     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10932     */
10933    protected float getLeftFadingEdgeStrength() {
10934        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10935    }
10936
10937    /**
10938     * Returns the strength, or intensity, of the right faded edge. The strength is
10939     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10940     * returns 0.0 or 1.0 but no value in between.
10941     *
10942     * Subclasses should override this method to provide a smoother fade transition
10943     * when scrolling occurs.
10944     *
10945     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10946     */
10947    protected float getRightFadingEdgeStrength() {
10948        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10949                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10950    }
10951
10952    /**
10953     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10954     * scrollbar is not drawn by default.</p>
10955     *
10956     * @return true if the horizontal scrollbar should be painted, false
10957     *         otherwise
10958     *
10959     * @see #setHorizontalScrollBarEnabled(boolean)
10960     */
10961    public boolean isHorizontalScrollBarEnabled() {
10962        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10963    }
10964
10965    /**
10966     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10967     * scrollbar is not drawn by default.</p>
10968     *
10969     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10970     *                                   be painted
10971     *
10972     * @see #isHorizontalScrollBarEnabled()
10973     */
10974    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10975        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10976            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10977            computeOpaqueFlags();
10978            resolvePadding();
10979        }
10980    }
10981
10982    /**
10983     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10984     * scrollbar is not drawn by default.</p>
10985     *
10986     * @return true if the vertical scrollbar should be painted, false
10987     *         otherwise
10988     *
10989     * @see #setVerticalScrollBarEnabled(boolean)
10990     */
10991    public boolean isVerticalScrollBarEnabled() {
10992        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10993    }
10994
10995    /**
10996     * <p>Define whether the vertical scrollbar should be drawn or not. The
10997     * scrollbar is not drawn by default.</p>
10998     *
10999     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11000     *                                 be painted
11001     *
11002     * @see #isVerticalScrollBarEnabled()
11003     */
11004    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11005        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11006            mViewFlags ^= SCROLLBARS_VERTICAL;
11007            computeOpaqueFlags();
11008            resolvePadding();
11009        }
11010    }
11011
11012    /**
11013     * @hide
11014     */
11015    protected void recomputePadding() {
11016        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11017    }
11018
11019    /**
11020     * Define whether scrollbars will fade when the view is not scrolling.
11021     *
11022     * @param fadeScrollbars wheter to enable fading
11023     *
11024     * @attr ref android.R.styleable#View_fadeScrollbars
11025     */
11026    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11027        initScrollCache();
11028        final ScrollabilityCache scrollabilityCache = mScrollCache;
11029        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11030        if (fadeScrollbars) {
11031            scrollabilityCache.state = ScrollabilityCache.OFF;
11032        } else {
11033            scrollabilityCache.state = ScrollabilityCache.ON;
11034        }
11035    }
11036
11037    /**
11038     *
11039     * Returns true if scrollbars will fade when this view is not scrolling
11040     *
11041     * @return true if scrollbar fading is enabled
11042     *
11043     * @attr ref android.R.styleable#View_fadeScrollbars
11044     */
11045    public boolean isScrollbarFadingEnabled() {
11046        return mScrollCache != null && mScrollCache.fadeScrollBars;
11047    }
11048
11049    /**
11050     *
11051     * Returns the delay before scrollbars fade.
11052     *
11053     * @return the delay before scrollbars fade
11054     *
11055     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11056     */
11057    public int getScrollBarDefaultDelayBeforeFade() {
11058        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11059                mScrollCache.scrollBarDefaultDelayBeforeFade;
11060    }
11061
11062    /**
11063     * Define the delay before scrollbars fade.
11064     *
11065     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11066     *
11067     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11068     */
11069    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11070        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11071    }
11072
11073    /**
11074     *
11075     * Returns the scrollbar fade duration.
11076     *
11077     * @return the scrollbar fade duration
11078     *
11079     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11080     */
11081    public int getScrollBarFadeDuration() {
11082        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11083                mScrollCache.scrollBarFadeDuration;
11084    }
11085
11086    /**
11087     * Define the scrollbar fade duration.
11088     *
11089     * @param scrollBarFadeDuration - the scrollbar fade duration
11090     *
11091     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11092     */
11093    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11094        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11095    }
11096
11097    /**
11098     *
11099     * Returns the scrollbar size.
11100     *
11101     * @return the scrollbar size
11102     *
11103     * @attr ref android.R.styleable#View_scrollbarSize
11104     */
11105    public int getScrollBarSize() {
11106        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11107                mScrollCache.scrollBarSize;
11108    }
11109
11110    /**
11111     * Define the scrollbar size.
11112     *
11113     * @param scrollBarSize - the scrollbar size
11114     *
11115     * @attr ref android.R.styleable#View_scrollbarSize
11116     */
11117    public void setScrollBarSize(int scrollBarSize) {
11118        getScrollCache().scrollBarSize = scrollBarSize;
11119    }
11120
11121    /**
11122     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11123     * inset. When inset, they add to the padding of the view. And the scrollbars
11124     * can be drawn inside the padding area or on the edge of the view. For example,
11125     * if a view has a background drawable and you want to draw the scrollbars
11126     * inside the padding specified by the drawable, you can use
11127     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11128     * appear at the edge of the view, ignoring the padding, then you can use
11129     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11130     * @param style the style of the scrollbars. Should be one of
11131     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11132     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11133     * @see #SCROLLBARS_INSIDE_OVERLAY
11134     * @see #SCROLLBARS_INSIDE_INSET
11135     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11136     * @see #SCROLLBARS_OUTSIDE_INSET
11137     *
11138     * @attr ref android.R.styleable#View_scrollbarStyle
11139     */
11140    public void setScrollBarStyle(int style) {
11141        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11142            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11143            computeOpaqueFlags();
11144            resolvePadding();
11145        }
11146    }
11147
11148    /**
11149     * <p>Returns the current scrollbar style.</p>
11150     * @return the current scrollbar style
11151     * @see #SCROLLBARS_INSIDE_OVERLAY
11152     * @see #SCROLLBARS_INSIDE_INSET
11153     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11154     * @see #SCROLLBARS_OUTSIDE_INSET
11155     *
11156     * @attr ref android.R.styleable#View_scrollbarStyle
11157     */
11158    @ViewDebug.ExportedProperty(mapping = {
11159            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11160            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11161            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11162            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11163    })
11164    public int getScrollBarStyle() {
11165        return mViewFlags & SCROLLBARS_STYLE_MASK;
11166    }
11167
11168    /**
11169     * <p>Compute the horizontal range that the horizontal scrollbar
11170     * represents.</p>
11171     *
11172     * <p>The range is expressed in arbitrary units that must be the same as the
11173     * units used by {@link #computeHorizontalScrollExtent()} and
11174     * {@link #computeHorizontalScrollOffset()}.</p>
11175     *
11176     * <p>The default range is the drawing width of this view.</p>
11177     *
11178     * @return the total horizontal range represented by the horizontal
11179     *         scrollbar
11180     *
11181     * @see #computeHorizontalScrollExtent()
11182     * @see #computeHorizontalScrollOffset()
11183     * @see android.widget.ScrollBarDrawable
11184     */
11185    protected int computeHorizontalScrollRange() {
11186        return getWidth();
11187    }
11188
11189    /**
11190     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11191     * within the horizontal range. This value is used to compute the position
11192     * of the thumb within the scrollbar's track.</p>
11193     *
11194     * <p>The range is expressed in arbitrary units that must be the same as the
11195     * units used by {@link #computeHorizontalScrollRange()} and
11196     * {@link #computeHorizontalScrollExtent()}.</p>
11197     *
11198     * <p>The default offset is the scroll offset of this view.</p>
11199     *
11200     * @return the horizontal offset of the scrollbar's thumb
11201     *
11202     * @see #computeHorizontalScrollRange()
11203     * @see #computeHorizontalScrollExtent()
11204     * @see android.widget.ScrollBarDrawable
11205     */
11206    protected int computeHorizontalScrollOffset() {
11207        return mScrollX;
11208    }
11209
11210    /**
11211     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11212     * within the horizontal range. This value is used to compute the length
11213     * of the thumb within the scrollbar's track.</p>
11214     *
11215     * <p>The range is expressed in arbitrary units that must be the same as the
11216     * units used by {@link #computeHorizontalScrollRange()} and
11217     * {@link #computeHorizontalScrollOffset()}.</p>
11218     *
11219     * <p>The default extent is the drawing width of this view.</p>
11220     *
11221     * @return the horizontal extent of the scrollbar's thumb
11222     *
11223     * @see #computeHorizontalScrollRange()
11224     * @see #computeHorizontalScrollOffset()
11225     * @see android.widget.ScrollBarDrawable
11226     */
11227    protected int computeHorizontalScrollExtent() {
11228        return getWidth();
11229    }
11230
11231    /**
11232     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11233     *
11234     * <p>The range is expressed in arbitrary units that must be the same as the
11235     * units used by {@link #computeVerticalScrollExtent()} and
11236     * {@link #computeVerticalScrollOffset()}.</p>
11237     *
11238     * @return the total vertical range represented by the vertical scrollbar
11239     *
11240     * <p>The default range is the drawing height of this view.</p>
11241     *
11242     * @see #computeVerticalScrollExtent()
11243     * @see #computeVerticalScrollOffset()
11244     * @see android.widget.ScrollBarDrawable
11245     */
11246    protected int computeVerticalScrollRange() {
11247        return getHeight();
11248    }
11249
11250    /**
11251     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11252     * within the horizontal range. This value is used to compute the position
11253     * of the thumb within the scrollbar's track.</p>
11254     *
11255     * <p>The range is expressed in arbitrary units that must be the same as the
11256     * units used by {@link #computeVerticalScrollRange()} and
11257     * {@link #computeVerticalScrollExtent()}.</p>
11258     *
11259     * <p>The default offset is the scroll offset of this view.</p>
11260     *
11261     * @return the vertical offset of the scrollbar's thumb
11262     *
11263     * @see #computeVerticalScrollRange()
11264     * @see #computeVerticalScrollExtent()
11265     * @see android.widget.ScrollBarDrawable
11266     */
11267    protected int computeVerticalScrollOffset() {
11268        return mScrollY;
11269    }
11270
11271    /**
11272     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11273     * within the vertical range. This value is used to compute the length
11274     * of the thumb within the scrollbar's track.</p>
11275     *
11276     * <p>The range is expressed in arbitrary units that must be the same as the
11277     * units used by {@link #computeVerticalScrollRange()} and
11278     * {@link #computeVerticalScrollOffset()}.</p>
11279     *
11280     * <p>The default extent is the drawing height of this view.</p>
11281     *
11282     * @return the vertical extent of the scrollbar's thumb
11283     *
11284     * @see #computeVerticalScrollRange()
11285     * @see #computeVerticalScrollOffset()
11286     * @see android.widget.ScrollBarDrawable
11287     */
11288    protected int computeVerticalScrollExtent() {
11289        return getHeight();
11290    }
11291
11292    /**
11293     * Check if this view can be scrolled horizontally in a certain direction.
11294     *
11295     * @param direction Negative to check scrolling left, positive to check scrolling right.
11296     * @return true if this view can be scrolled in the specified direction, false otherwise.
11297     */
11298    public boolean canScrollHorizontally(int direction) {
11299        final int offset = computeHorizontalScrollOffset();
11300        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11301        if (range == 0) return false;
11302        if (direction < 0) {
11303            return offset > 0;
11304        } else {
11305            return offset < range - 1;
11306        }
11307    }
11308
11309    /**
11310     * Check if this view can be scrolled vertically in a certain direction.
11311     *
11312     * @param direction Negative to check scrolling up, positive to check scrolling down.
11313     * @return true if this view can be scrolled in the specified direction, false otherwise.
11314     */
11315    public boolean canScrollVertically(int direction) {
11316        final int offset = computeVerticalScrollOffset();
11317        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11318        if (range == 0) return false;
11319        if (direction < 0) {
11320            return offset > 0;
11321        } else {
11322            return offset < range - 1;
11323        }
11324    }
11325
11326    /**
11327     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11328     * scrollbars are painted only if they have been awakened first.</p>
11329     *
11330     * @param canvas the canvas on which to draw the scrollbars
11331     *
11332     * @see #awakenScrollBars(int)
11333     */
11334    protected final void onDrawScrollBars(Canvas canvas) {
11335        // scrollbars are drawn only when the animation is running
11336        final ScrollabilityCache cache = mScrollCache;
11337        if (cache != null) {
11338
11339            int state = cache.state;
11340
11341            if (state == ScrollabilityCache.OFF) {
11342                return;
11343            }
11344
11345            boolean invalidate = false;
11346
11347            if (state == ScrollabilityCache.FADING) {
11348                // We're fading -- get our fade interpolation
11349                if (cache.interpolatorValues == null) {
11350                    cache.interpolatorValues = new float[1];
11351                }
11352
11353                float[] values = cache.interpolatorValues;
11354
11355                // Stops the animation if we're done
11356                if (cache.scrollBarInterpolator.timeToValues(values) ==
11357                        Interpolator.Result.FREEZE_END) {
11358                    cache.state = ScrollabilityCache.OFF;
11359                } else {
11360                    cache.scrollBar.setAlpha(Math.round(values[0]));
11361                }
11362
11363                // This will make the scroll bars inval themselves after
11364                // drawing. We only want this when we're fading so that
11365                // we prevent excessive redraws
11366                invalidate = true;
11367            } else {
11368                // We're just on -- but we may have been fading before so
11369                // reset alpha
11370                cache.scrollBar.setAlpha(255);
11371            }
11372
11373
11374            final int viewFlags = mViewFlags;
11375
11376            final boolean drawHorizontalScrollBar =
11377                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11378            final boolean drawVerticalScrollBar =
11379                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11380                && !isVerticalScrollBarHidden();
11381
11382            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11383                final int width = mRight - mLeft;
11384                final int height = mBottom - mTop;
11385
11386                final ScrollBarDrawable scrollBar = cache.scrollBar;
11387
11388                final int scrollX = mScrollX;
11389                final int scrollY = mScrollY;
11390                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11391
11392                int left, top, right, bottom;
11393
11394                if (drawHorizontalScrollBar) {
11395                    int size = scrollBar.getSize(false);
11396                    if (size <= 0) {
11397                        size = cache.scrollBarSize;
11398                    }
11399
11400                    scrollBar.setParameters(computeHorizontalScrollRange(),
11401                                            computeHorizontalScrollOffset(),
11402                                            computeHorizontalScrollExtent(), false);
11403                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11404                            getVerticalScrollbarWidth() : 0;
11405                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11406                    left = scrollX + (mPaddingLeft & inside);
11407                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11408                    bottom = top + size;
11409                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11410                    if (invalidate) {
11411                        invalidate(left, top, right, bottom);
11412                    }
11413                }
11414
11415                if (drawVerticalScrollBar) {
11416                    int size = scrollBar.getSize(true);
11417                    if (size <= 0) {
11418                        size = cache.scrollBarSize;
11419                    }
11420
11421                    scrollBar.setParameters(computeVerticalScrollRange(),
11422                                            computeVerticalScrollOffset(),
11423                                            computeVerticalScrollExtent(), true);
11424                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11425                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11426                        verticalScrollbarPosition = isLayoutRtl() ?
11427                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11428                    }
11429                    switch (verticalScrollbarPosition) {
11430                        default:
11431                        case SCROLLBAR_POSITION_RIGHT:
11432                            left = scrollX + width - size - (mUserPaddingRight & inside);
11433                            break;
11434                        case SCROLLBAR_POSITION_LEFT:
11435                            left = scrollX + (mUserPaddingLeft & inside);
11436                            break;
11437                    }
11438                    top = scrollY + (mPaddingTop & inside);
11439                    right = left + size;
11440                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11441                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11442                    if (invalidate) {
11443                        invalidate(left, top, right, bottom);
11444                    }
11445                }
11446            }
11447        }
11448    }
11449
11450    /**
11451     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11452     * FastScroller is visible.
11453     * @return whether to temporarily hide the vertical scrollbar
11454     * @hide
11455     */
11456    protected boolean isVerticalScrollBarHidden() {
11457        return false;
11458    }
11459
11460    /**
11461     * <p>Draw the horizontal scrollbar if
11462     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11463     *
11464     * @param canvas the canvas on which to draw the scrollbar
11465     * @param scrollBar the scrollbar's drawable
11466     *
11467     * @see #isHorizontalScrollBarEnabled()
11468     * @see #computeHorizontalScrollRange()
11469     * @see #computeHorizontalScrollExtent()
11470     * @see #computeHorizontalScrollOffset()
11471     * @see android.widget.ScrollBarDrawable
11472     * @hide
11473     */
11474    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11475            int l, int t, int r, int b) {
11476        scrollBar.setBounds(l, t, r, b);
11477        scrollBar.draw(canvas);
11478    }
11479
11480    /**
11481     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11482     * returns true.</p>
11483     *
11484     * @param canvas the canvas on which to draw the scrollbar
11485     * @param scrollBar the scrollbar's drawable
11486     *
11487     * @see #isVerticalScrollBarEnabled()
11488     * @see #computeVerticalScrollRange()
11489     * @see #computeVerticalScrollExtent()
11490     * @see #computeVerticalScrollOffset()
11491     * @see android.widget.ScrollBarDrawable
11492     * @hide
11493     */
11494    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11495            int l, int t, int r, int b) {
11496        scrollBar.setBounds(l, t, r, b);
11497        scrollBar.draw(canvas);
11498    }
11499
11500    /**
11501     * Implement this to do your drawing.
11502     *
11503     * @param canvas the canvas on which the background will be drawn
11504     */
11505    protected void onDraw(Canvas canvas) {
11506    }
11507
11508    /*
11509     * Caller is responsible for calling requestLayout if necessary.
11510     * (This allows addViewInLayout to not request a new layout.)
11511     */
11512    void assignParent(ViewParent parent) {
11513        if (mParent == null) {
11514            mParent = parent;
11515        } else if (parent == null) {
11516            mParent = null;
11517        } else {
11518            throw new RuntimeException("view " + this + " being added, but"
11519                    + " it already has a parent");
11520        }
11521    }
11522
11523    /**
11524     * This is called when the view is attached to a window.  At this point it
11525     * has a Surface and will start drawing.  Note that this function is
11526     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11527     * however it may be called any time before the first onDraw -- including
11528     * before or after {@link #onMeasure(int, int)}.
11529     *
11530     * @see #onDetachedFromWindow()
11531     */
11532    protected void onAttachedToWindow() {
11533        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11534            mParent.requestTransparentRegion(this);
11535        }
11536
11537        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11538            initialAwakenScrollBars();
11539            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11540        }
11541
11542        jumpDrawablesToCurrentState();
11543
11544        clearAccessibilityFocus();
11545        if (isFocused()) {
11546            InputMethodManager imm = InputMethodManager.peekInstance();
11547            imm.focusIn(this);
11548        }
11549
11550        if (mAttachInfo != null && mDisplayList != null) {
11551            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11552        }
11553    }
11554
11555    /**
11556     * Resolve all RTL related properties.
11557     *
11558     * @hide
11559     */
11560    public void resolveRtlPropertiesIfNeeded() {
11561        if (!needRtlPropertiesResolution()) return;
11562
11563        // Order is important here: LayoutDirection MUST be resolved first
11564        if (!isLayoutDirectionResolved()) {
11565            resolveLayoutDirection();
11566            resolveLayoutParams();
11567        }
11568        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11569        if (!isTextDirectionResolved()) {
11570            resolveTextDirection();
11571        }
11572        if (!isTextAlignmentResolved()) {
11573            resolveTextAlignment();
11574        }
11575        if (!isPaddingResolved()) {
11576            resolvePadding();
11577        }
11578        if (!isDrawablesResolved()) {
11579            resolveDrawables();
11580        }
11581        onRtlPropertiesChanged(getLayoutDirection());
11582    }
11583
11584    /**
11585     * Reset resolution of all RTL related properties.
11586     *
11587     * @hide
11588     */
11589    public void resetRtlProperties() {
11590        resetResolvedLayoutDirection();
11591        resetResolvedTextDirection();
11592        resetResolvedTextAlignment();
11593        resetResolvedPadding();
11594        resetResolvedDrawables();
11595    }
11596
11597    /**
11598     * @see #onScreenStateChanged(int)
11599     */
11600    void dispatchScreenStateChanged(int screenState) {
11601        onScreenStateChanged(screenState);
11602    }
11603
11604    /**
11605     * This method is called whenever the state of the screen this view is
11606     * attached to changes. A state change will usually occurs when the screen
11607     * turns on or off (whether it happens automatically or the user does it
11608     * manually.)
11609     *
11610     * @param screenState The new state of the screen. Can be either
11611     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11612     */
11613    public void onScreenStateChanged(int screenState) {
11614    }
11615
11616    /**
11617     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11618     */
11619    private boolean hasRtlSupport() {
11620        return mContext.getApplicationInfo().hasRtlSupport();
11621    }
11622
11623    /**
11624     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11625     * RTL not supported)
11626     */
11627    private boolean isRtlCompatibilityMode() {
11628        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11629        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11630    }
11631
11632    /**
11633     * @return true if RTL properties need resolution.
11634     */
11635    private boolean needRtlPropertiesResolution() {
11636        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11637    }
11638
11639    /**
11640     * Called when any RTL property (layout direction or text direction or text alignment) has
11641     * been changed.
11642     *
11643     * Subclasses need to override this method to take care of cached information that depends on the
11644     * resolved layout direction, or to inform child views that inherit their layout direction.
11645     *
11646     * The default implementation does nothing.
11647     *
11648     * @param layoutDirection the direction of the layout
11649     *
11650     * @see #LAYOUT_DIRECTION_LTR
11651     * @see #LAYOUT_DIRECTION_RTL
11652     */
11653    public void onRtlPropertiesChanged(int layoutDirection) {
11654    }
11655
11656    /**
11657     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11658     * that the parent directionality can and will be resolved before its children.
11659     *
11660     * @return true if resolution has been done, false otherwise.
11661     *
11662     * @hide
11663     */
11664    public boolean resolveLayoutDirection() {
11665        // Clear any previous layout direction resolution
11666        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11667
11668        if (hasRtlSupport()) {
11669            // Set resolved depending on layout direction
11670            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11671                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11672                case LAYOUT_DIRECTION_INHERIT:
11673                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11674                    // later to get the correct resolved value
11675                    if (!canResolveLayoutDirection()) return false;
11676
11677                    View parent = ((View) mParent);
11678                    // Parent has not yet resolved, LTR is still the default
11679                    if (!parent.isLayoutDirectionResolved()) return false;
11680
11681                    if (parent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11682                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11683                    }
11684                    break;
11685                case LAYOUT_DIRECTION_RTL:
11686                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11687                    break;
11688                case LAYOUT_DIRECTION_LOCALE:
11689                    if((LAYOUT_DIRECTION_RTL ==
11690                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11691                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11692                    }
11693                    break;
11694                default:
11695                    // Nothing to do, LTR by default
11696            }
11697        }
11698
11699        // Set to resolved
11700        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11701        return true;
11702    }
11703
11704    /**
11705     * Check if layout direction resolution can be done.
11706     *
11707     * @return true if layout direction resolution can be done otherwise return false.
11708     *
11709     * @hide
11710     */
11711    public boolean canResolveLayoutDirection() {
11712        switch (getRawLayoutDirection()) {
11713            case LAYOUT_DIRECTION_INHERIT:
11714                return (mParent != null) && (mParent instanceof ViewGroup) &&
11715                       ((ViewGroup) mParent).canResolveLayoutDirection();
11716            default:
11717                return true;
11718        }
11719    }
11720
11721    /**
11722     * Reset the resolved layout direction. Layout direction will be resolved during a call to
11723     * {@link #onMeasure(int, int)}.
11724     *
11725     * @hide
11726     */
11727    public void resetResolvedLayoutDirection() {
11728        // Reset the current resolved bits
11729        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11730    }
11731
11732    /**
11733     * @return true if the layout direction is inherited.
11734     *
11735     * @hide
11736     */
11737    public boolean isLayoutDirectionInherited() {
11738        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
11739    }
11740
11741    /**
11742     * @return true if layout direction has been resolved.
11743     */
11744    private boolean isLayoutDirectionResolved() {
11745        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11746    }
11747
11748    /**
11749     * Return if padding has been resolved
11750     *
11751     * @hide
11752     */
11753    boolean isPaddingResolved() {
11754        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
11755    }
11756
11757    /**
11758     * Resolve padding depending on layout direction.
11759     *
11760     * @hide
11761     */
11762    public void resolvePadding() {
11763        if (!isRtlCompatibilityMode()) {
11764            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
11765            // If start / end padding are defined, they will be resolved (hence overriding) to
11766            // left / right or right / left depending on the resolved layout direction.
11767            // If start / end padding are not defined, use the left / right ones.
11768            int resolvedLayoutDirection = getLayoutDirection();
11769            // Set user padding to initial values ...
11770            mUserPaddingLeft = mUserPaddingLeftInitial;
11771            mUserPaddingRight = mUserPaddingRightInitial;
11772            // ... then resolve it.
11773            switch (resolvedLayoutDirection) {
11774                case LAYOUT_DIRECTION_RTL:
11775                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11776                        mUserPaddingRight = mUserPaddingStart;
11777                    }
11778                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11779                        mUserPaddingLeft = mUserPaddingEnd;
11780                    }
11781                    break;
11782                case LAYOUT_DIRECTION_LTR:
11783                default:
11784                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11785                        mUserPaddingLeft = mUserPaddingStart;
11786                    }
11787                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11788                        mUserPaddingRight = mUserPaddingEnd;
11789                    }
11790            }
11791
11792            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11793
11794            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11795                    mUserPaddingBottom);
11796            onRtlPropertiesChanged(resolvedLayoutDirection);
11797        }
11798
11799        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
11800    }
11801
11802    /**
11803     * Reset the resolved layout direction.
11804     *
11805     * @hide
11806     */
11807    public void resetResolvedPadding() {
11808        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
11809    }
11810
11811    /**
11812     * This is called when the view is detached from a window.  At this point it
11813     * no longer has a surface for drawing.
11814     *
11815     * @see #onAttachedToWindow()
11816     */
11817    protected void onDetachedFromWindow() {
11818        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
11819
11820        removeUnsetPressCallback();
11821        removeLongPressCallback();
11822        removePerformClickCallback();
11823        removeSendViewScrolledAccessibilityEventCallback();
11824
11825        destroyDrawingCache();
11826
11827        destroyLayer(false);
11828
11829        if (mAttachInfo != null) {
11830            if (mDisplayList != null) {
11831                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11832            }
11833            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11834        } else {
11835            // Should never happen
11836            clearDisplayList();
11837        }
11838
11839        mCurrentAnimation = null;
11840
11841        resetRtlProperties();
11842        onRtlPropertiesChanged(LAYOUT_DIRECTION_DEFAULT);
11843        resetAccessibilityStateChanged();
11844    }
11845
11846    /**
11847     * @return The number of times this view has been attached to a window
11848     */
11849    protected int getWindowAttachCount() {
11850        return mWindowAttachCount;
11851    }
11852
11853    /**
11854     * Retrieve a unique token identifying the window this view is attached to.
11855     * @return Return the window's token for use in
11856     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11857     */
11858    public IBinder getWindowToken() {
11859        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11860    }
11861
11862    /**
11863     * Retrieve a unique token identifying the top-level "real" window of
11864     * the window that this view is attached to.  That is, this is like
11865     * {@link #getWindowToken}, except if the window this view in is a panel
11866     * window (attached to another containing window), then the token of
11867     * the containing window is returned instead.
11868     *
11869     * @return Returns the associated window token, either
11870     * {@link #getWindowToken()} or the containing window's token.
11871     */
11872    public IBinder getApplicationWindowToken() {
11873        AttachInfo ai = mAttachInfo;
11874        if (ai != null) {
11875            IBinder appWindowToken = ai.mPanelParentWindowToken;
11876            if (appWindowToken == null) {
11877                appWindowToken = ai.mWindowToken;
11878            }
11879            return appWindowToken;
11880        }
11881        return null;
11882    }
11883
11884    /**
11885     * Gets the logical display to which the view's window has been attached.
11886     *
11887     * @return The logical display, or null if the view is not currently attached to a window.
11888     */
11889    public Display getDisplay() {
11890        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
11891    }
11892
11893    /**
11894     * Retrieve private session object this view hierarchy is using to
11895     * communicate with the window manager.
11896     * @return the session object to communicate with the window manager
11897     */
11898    /*package*/ IWindowSession getWindowSession() {
11899        return mAttachInfo != null ? mAttachInfo.mSession : null;
11900    }
11901
11902    /**
11903     * @param info the {@link android.view.View.AttachInfo} to associated with
11904     *        this view
11905     */
11906    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11907        //System.out.println("Attached! " + this);
11908        mAttachInfo = info;
11909        mWindowAttachCount++;
11910        // We will need to evaluate the drawable state at least once.
11911        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
11912        if (mFloatingTreeObserver != null) {
11913            info.mTreeObserver.merge(mFloatingTreeObserver);
11914            mFloatingTreeObserver = null;
11915        }
11916        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
11917            mAttachInfo.mScrollContainers.add(this);
11918            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
11919        }
11920        performCollectViewAttributes(mAttachInfo, visibility);
11921        onAttachedToWindow();
11922
11923        ListenerInfo li = mListenerInfo;
11924        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11925                li != null ? li.mOnAttachStateChangeListeners : null;
11926        if (listeners != null && listeners.size() > 0) {
11927            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11928            // perform the dispatching. The iterator is a safe guard against listeners that
11929            // could mutate the list by calling the various add/remove methods. This prevents
11930            // the array from being modified while we iterate it.
11931            for (OnAttachStateChangeListener listener : listeners) {
11932                listener.onViewAttachedToWindow(this);
11933            }
11934        }
11935
11936        int vis = info.mWindowVisibility;
11937        if (vis != GONE) {
11938            onWindowVisibilityChanged(vis);
11939        }
11940        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
11941            // If nobody has evaluated the drawable state yet, then do it now.
11942            refreshDrawableState();
11943        }
11944        needGlobalAttributesUpdate(false);
11945    }
11946
11947    void dispatchDetachedFromWindow() {
11948        AttachInfo info = mAttachInfo;
11949        if (info != null) {
11950            int vis = info.mWindowVisibility;
11951            if (vis != GONE) {
11952                onWindowVisibilityChanged(GONE);
11953            }
11954        }
11955
11956        onDetachedFromWindow();
11957
11958        ListenerInfo li = mListenerInfo;
11959        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11960                li != null ? li.mOnAttachStateChangeListeners : null;
11961        if (listeners != null && listeners.size() > 0) {
11962            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11963            // perform the dispatching. The iterator is a safe guard against listeners that
11964            // could mutate the list by calling the various add/remove methods. This prevents
11965            // the array from being modified while we iterate it.
11966            for (OnAttachStateChangeListener listener : listeners) {
11967                listener.onViewDetachedFromWindow(this);
11968            }
11969        }
11970
11971        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
11972            mAttachInfo.mScrollContainers.remove(this);
11973            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
11974        }
11975
11976        mAttachInfo = null;
11977    }
11978
11979    /**
11980     * Store this view hierarchy's frozen state into the given container.
11981     *
11982     * @param container The SparseArray in which to save the view's state.
11983     *
11984     * @see #restoreHierarchyState(android.util.SparseArray)
11985     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11986     * @see #onSaveInstanceState()
11987     */
11988    public void saveHierarchyState(SparseArray<Parcelable> container) {
11989        dispatchSaveInstanceState(container);
11990    }
11991
11992    /**
11993     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11994     * this view and its children. May be overridden to modify how freezing happens to a
11995     * view's children; for example, some views may want to not store state for their children.
11996     *
11997     * @param container The SparseArray in which to save the view's state.
11998     *
11999     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12000     * @see #saveHierarchyState(android.util.SparseArray)
12001     * @see #onSaveInstanceState()
12002     */
12003    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12004        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12005            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12006            Parcelable state = onSaveInstanceState();
12007            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12008                throw new IllegalStateException(
12009                        "Derived class did not call super.onSaveInstanceState()");
12010            }
12011            if (state != null) {
12012                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12013                // + ": " + state);
12014                container.put(mID, state);
12015            }
12016        }
12017    }
12018
12019    /**
12020     * Hook allowing a view to generate a representation of its internal state
12021     * that can later be used to create a new instance with that same state.
12022     * This state should only contain information that is not persistent or can
12023     * not be reconstructed later. For example, you will never store your
12024     * current position on screen because that will be computed again when a
12025     * new instance of the view is placed in its view hierarchy.
12026     * <p>
12027     * Some examples of things you may store here: the current cursor position
12028     * in a text view (but usually not the text itself since that is stored in a
12029     * content provider or other persistent storage), the currently selected
12030     * item in a list view.
12031     *
12032     * @return Returns a Parcelable object containing the view's current dynamic
12033     *         state, or null if there is nothing interesting to save. The
12034     *         default implementation returns null.
12035     * @see #onRestoreInstanceState(android.os.Parcelable)
12036     * @see #saveHierarchyState(android.util.SparseArray)
12037     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12038     * @see #setSaveEnabled(boolean)
12039     */
12040    protected Parcelable onSaveInstanceState() {
12041        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12042        return BaseSavedState.EMPTY_STATE;
12043    }
12044
12045    /**
12046     * Restore this view hierarchy's frozen state from the given container.
12047     *
12048     * @param container The SparseArray which holds previously frozen states.
12049     *
12050     * @see #saveHierarchyState(android.util.SparseArray)
12051     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12052     * @see #onRestoreInstanceState(android.os.Parcelable)
12053     */
12054    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12055        dispatchRestoreInstanceState(container);
12056    }
12057
12058    /**
12059     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12060     * state for this view and its children. May be overridden to modify how restoring
12061     * happens to a view's children; for example, some views may want to not store state
12062     * for their children.
12063     *
12064     * @param container The SparseArray which holds previously saved state.
12065     *
12066     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12067     * @see #restoreHierarchyState(android.util.SparseArray)
12068     * @see #onRestoreInstanceState(android.os.Parcelable)
12069     */
12070    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12071        if (mID != NO_ID) {
12072            Parcelable state = container.get(mID);
12073            if (state != null) {
12074                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12075                // + ": " + state);
12076                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12077                onRestoreInstanceState(state);
12078                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12079                    throw new IllegalStateException(
12080                            "Derived class did not call super.onRestoreInstanceState()");
12081                }
12082            }
12083        }
12084    }
12085
12086    /**
12087     * Hook allowing a view to re-apply a representation of its internal state that had previously
12088     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12089     * null state.
12090     *
12091     * @param state The frozen state that had previously been returned by
12092     *        {@link #onSaveInstanceState}.
12093     *
12094     * @see #onSaveInstanceState()
12095     * @see #restoreHierarchyState(android.util.SparseArray)
12096     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12097     */
12098    protected void onRestoreInstanceState(Parcelable state) {
12099        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12100        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12101            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12102                    + "received " + state.getClass().toString() + " instead. This usually happens "
12103                    + "when two views of different type have the same id in the same hierarchy. "
12104                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12105                    + "other views do not use the same id.");
12106        }
12107    }
12108
12109    /**
12110     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12111     *
12112     * @return the drawing start time in milliseconds
12113     */
12114    public long getDrawingTime() {
12115        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12116    }
12117
12118    /**
12119     * <p>Enables or disables the duplication of the parent's state into this view. When
12120     * duplication is enabled, this view gets its drawable state from its parent rather
12121     * than from its own internal properties.</p>
12122     *
12123     * <p>Note: in the current implementation, setting this property to true after the
12124     * view was added to a ViewGroup might have no effect at all. This property should
12125     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12126     *
12127     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12128     * property is enabled, an exception will be thrown.</p>
12129     *
12130     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12131     * parent, these states should not be affected by this method.</p>
12132     *
12133     * @param enabled True to enable duplication of the parent's drawable state, false
12134     *                to disable it.
12135     *
12136     * @see #getDrawableState()
12137     * @see #isDuplicateParentStateEnabled()
12138     */
12139    public void setDuplicateParentStateEnabled(boolean enabled) {
12140        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12141    }
12142
12143    /**
12144     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12145     *
12146     * @return True if this view's drawable state is duplicated from the parent,
12147     *         false otherwise
12148     *
12149     * @see #getDrawableState()
12150     * @see #setDuplicateParentStateEnabled(boolean)
12151     */
12152    public boolean isDuplicateParentStateEnabled() {
12153        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12154    }
12155
12156    /**
12157     * <p>Specifies the type of layer backing this view. The layer can be
12158     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
12159     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
12160     *
12161     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12162     * instance that controls how the layer is composed on screen. The following
12163     * properties of the paint are taken into account when composing the layer:</p>
12164     * <ul>
12165     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12166     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12167     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12168     * </ul>
12169     *
12170     * <p>If this view has an alpha value set to < 1.0 by calling
12171     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12172     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12173     * equivalent to setting a hardware layer on this view and providing a paint with
12174     * the desired alpha value.</p>
12175     *
12176     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
12177     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
12178     * for more information on when and how to use layers.</p>
12179     *
12180     * @param layerType The type of layer to use with this view, must be one of
12181     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12182     *        {@link #LAYER_TYPE_HARDWARE}
12183     * @param paint The paint used to compose the layer. This argument is optional
12184     *        and can be null. It is ignored when the layer type is
12185     *        {@link #LAYER_TYPE_NONE}
12186     *
12187     * @see #getLayerType()
12188     * @see #LAYER_TYPE_NONE
12189     * @see #LAYER_TYPE_SOFTWARE
12190     * @see #LAYER_TYPE_HARDWARE
12191     * @see #setAlpha(float)
12192     *
12193     * @attr ref android.R.styleable#View_layerType
12194     */
12195    public void setLayerType(int layerType, Paint paint) {
12196        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12197            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12198                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12199        }
12200
12201        if (layerType == mLayerType) {
12202            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12203                mLayerPaint = paint == null ? new Paint() : paint;
12204                invalidateParentCaches();
12205                invalidate(true);
12206            }
12207            return;
12208        }
12209
12210        // Destroy any previous software drawing cache if needed
12211        switch (mLayerType) {
12212            case LAYER_TYPE_HARDWARE:
12213                destroyLayer(false);
12214                // fall through - non-accelerated views may use software layer mechanism instead
12215            case LAYER_TYPE_SOFTWARE:
12216                destroyDrawingCache();
12217                break;
12218            default:
12219                break;
12220        }
12221
12222        mLayerType = layerType;
12223        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12224        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12225        mLocalDirtyRect = layerDisabled ? null : new Rect();
12226
12227        invalidateParentCaches();
12228        invalidate(true);
12229    }
12230
12231    /**
12232     * Updates the {@link Paint} object used with the current layer (used only if the current
12233     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12234     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12235     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12236     * ensure that the view gets redrawn immediately.
12237     *
12238     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12239     * instance that controls how the layer is composed on screen. The following
12240     * properties of the paint are taken into account when composing the layer:</p>
12241     * <ul>
12242     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12243     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12244     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12245     * </ul>
12246     *
12247     * <p>If this view has an alpha value set to < 1.0 by calling
12248     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12249     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12250     * equivalent to setting a hardware layer on this view and providing a paint with
12251     * the desired alpha value.</p>
12252     *
12253     * @param paint The paint used to compose the layer. This argument is optional
12254     *        and can be null. It is ignored when the layer type is
12255     *        {@link #LAYER_TYPE_NONE}
12256     *
12257     * @see #setLayerType(int, android.graphics.Paint)
12258     */
12259    public void setLayerPaint(Paint paint) {
12260        int layerType = getLayerType();
12261        if (layerType != LAYER_TYPE_NONE) {
12262            mLayerPaint = paint == null ? new Paint() : paint;
12263            if (layerType == LAYER_TYPE_HARDWARE) {
12264                HardwareLayer layer = getHardwareLayer();
12265                if (layer != null) {
12266                    layer.setLayerPaint(paint);
12267                }
12268                invalidateViewProperty(false, false);
12269            } else {
12270                invalidate();
12271            }
12272        }
12273    }
12274
12275    /**
12276     * Indicates whether this view has a static layer. A view with layer type
12277     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12278     * dynamic.
12279     */
12280    boolean hasStaticLayer() {
12281        return true;
12282    }
12283
12284    /**
12285     * Indicates what type of layer is currently associated with this view. By default
12286     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12287     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12288     * for more information on the different types of layers.
12289     *
12290     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12291     *         {@link #LAYER_TYPE_HARDWARE}
12292     *
12293     * @see #setLayerType(int, android.graphics.Paint)
12294     * @see #buildLayer()
12295     * @see #LAYER_TYPE_NONE
12296     * @see #LAYER_TYPE_SOFTWARE
12297     * @see #LAYER_TYPE_HARDWARE
12298     */
12299    public int getLayerType() {
12300        return mLayerType;
12301    }
12302
12303    /**
12304     * Forces this view's layer to be created and this view to be rendered
12305     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12306     * invoking this method will have no effect.
12307     *
12308     * This method can for instance be used to render a view into its layer before
12309     * starting an animation. If this view is complex, rendering into the layer
12310     * before starting the animation will avoid skipping frames.
12311     *
12312     * @throws IllegalStateException If this view is not attached to a window
12313     *
12314     * @see #setLayerType(int, android.graphics.Paint)
12315     */
12316    public void buildLayer() {
12317        if (mLayerType == LAYER_TYPE_NONE) return;
12318
12319        if (mAttachInfo == null) {
12320            throw new IllegalStateException("This view must be attached to a window first");
12321        }
12322
12323        switch (mLayerType) {
12324            case LAYER_TYPE_HARDWARE:
12325                if (mAttachInfo.mHardwareRenderer != null &&
12326                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12327                        mAttachInfo.mHardwareRenderer.validate()) {
12328                    getHardwareLayer();
12329                }
12330                break;
12331            case LAYER_TYPE_SOFTWARE:
12332                buildDrawingCache(true);
12333                break;
12334        }
12335    }
12336
12337    /**
12338     * <p>Returns a hardware layer that can be used to draw this view again
12339     * without executing its draw method.</p>
12340     *
12341     * @return A HardwareLayer ready to render, or null if an error occurred.
12342     */
12343    HardwareLayer getHardwareLayer() {
12344        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12345                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12346            return null;
12347        }
12348
12349        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12350
12351        final int width = mRight - mLeft;
12352        final int height = mBottom - mTop;
12353
12354        if (width == 0 || height == 0) {
12355            return null;
12356        }
12357
12358        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12359            if (mHardwareLayer == null) {
12360                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12361                        width, height, isOpaque());
12362                mLocalDirtyRect.set(0, 0, width, height);
12363            } else {
12364                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12365                    if (mHardwareLayer.resize(width, height)) {
12366                        mLocalDirtyRect.set(0, 0, width, height);
12367                    }
12368                }
12369
12370                // This should not be necessary but applications that change
12371                // the parameters of their background drawable without calling
12372                // this.setBackground(Drawable) can leave the view in a bad state
12373                // (for instance isOpaque() returns true, but the background is
12374                // not opaque.)
12375                computeOpaqueFlags();
12376
12377                final boolean opaque = isOpaque();
12378                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12379                    mHardwareLayer.setOpaque(opaque);
12380                    mLocalDirtyRect.set(0, 0, width, height);
12381                }
12382            }
12383
12384            // The layer is not valid if the underlying GPU resources cannot be allocated
12385            if (!mHardwareLayer.isValid()) {
12386                return null;
12387            }
12388
12389            mHardwareLayer.setLayerPaint(mLayerPaint);
12390            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12391            ViewRootImpl viewRoot = getViewRootImpl();
12392            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12393
12394            mLocalDirtyRect.setEmpty();
12395        }
12396
12397        return mHardwareLayer;
12398    }
12399
12400    /**
12401     * Destroys this View's hardware layer if possible.
12402     *
12403     * @return True if the layer was destroyed, false otherwise.
12404     *
12405     * @see #setLayerType(int, android.graphics.Paint)
12406     * @see #LAYER_TYPE_HARDWARE
12407     */
12408    boolean destroyLayer(boolean valid) {
12409        if (mHardwareLayer != null) {
12410            AttachInfo info = mAttachInfo;
12411            if (info != null && info.mHardwareRenderer != null &&
12412                    info.mHardwareRenderer.isEnabled() &&
12413                    (valid || info.mHardwareRenderer.validate())) {
12414                mHardwareLayer.destroy();
12415                mHardwareLayer = null;
12416
12417                if (mDisplayList != null) {
12418                    mDisplayList.reset();
12419                }
12420                invalidate(true);
12421                invalidateParentCaches();
12422            }
12423            return true;
12424        }
12425        return false;
12426    }
12427
12428    /**
12429     * Destroys all hardware rendering resources. This method is invoked
12430     * when the system needs to reclaim resources. Upon execution of this
12431     * method, you should free any OpenGL resources created by the view.
12432     *
12433     * Note: you <strong>must</strong> call
12434     * <code>super.destroyHardwareResources()</code> when overriding
12435     * this method.
12436     *
12437     * @hide
12438     */
12439    protected void destroyHardwareResources() {
12440        destroyLayer(true);
12441    }
12442
12443    /**
12444     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12445     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12446     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12447     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12448     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12449     * null.</p>
12450     *
12451     * <p>Enabling the drawing cache is similar to
12452     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12453     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12454     * drawing cache has no effect on rendering because the system uses a different mechanism
12455     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12456     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12457     * for information on how to enable software and hardware layers.</p>
12458     *
12459     * <p>This API can be used to manually generate
12460     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12461     * {@link #getDrawingCache()}.</p>
12462     *
12463     * @param enabled true to enable the drawing cache, false otherwise
12464     *
12465     * @see #isDrawingCacheEnabled()
12466     * @see #getDrawingCache()
12467     * @see #buildDrawingCache()
12468     * @see #setLayerType(int, android.graphics.Paint)
12469     */
12470    public void setDrawingCacheEnabled(boolean enabled) {
12471        mCachingFailed = false;
12472        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12473    }
12474
12475    /**
12476     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12477     *
12478     * @return true if the drawing cache is enabled
12479     *
12480     * @see #setDrawingCacheEnabled(boolean)
12481     * @see #getDrawingCache()
12482     */
12483    @ViewDebug.ExportedProperty(category = "drawing")
12484    public boolean isDrawingCacheEnabled() {
12485        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12486    }
12487
12488    /**
12489     * Debugging utility which recursively outputs the dirty state of a view and its
12490     * descendants.
12491     *
12492     * @hide
12493     */
12494    @SuppressWarnings({"UnusedDeclaration"})
12495    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12496        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12497                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12498                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12499                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12500        if (clear) {
12501            mPrivateFlags &= clearMask;
12502        }
12503        if (this instanceof ViewGroup) {
12504            ViewGroup parent = (ViewGroup) this;
12505            final int count = parent.getChildCount();
12506            for (int i = 0; i < count; i++) {
12507                final View child = parent.getChildAt(i);
12508                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12509            }
12510        }
12511    }
12512
12513    /**
12514     * This method is used by ViewGroup to cause its children to restore or recreate their
12515     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12516     * to recreate its own display list, which would happen if it went through the normal
12517     * draw/dispatchDraw mechanisms.
12518     *
12519     * @hide
12520     */
12521    protected void dispatchGetDisplayList() {}
12522
12523    /**
12524     * A view that is not attached or hardware accelerated cannot create a display list.
12525     * This method checks these conditions and returns the appropriate result.
12526     *
12527     * @return true if view has the ability to create a display list, false otherwise.
12528     *
12529     * @hide
12530     */
12531    public boolean canHaveDisplayList() {
12532        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12533    }
12534
12535    /**
12536     * @return The HardwareRenderer associated with that view or null if hardware rendering
12537     * is not supported or this this has not been attached to a window.
12538     *
12539     * @hide
12540     */
12541    public HardwareRenderer getHardwareRenderer() {
12542        if (mAttachInfo != null) {
12543            return mAttachInfo.mHardwareRenderer;
12544        }
12545        return null;
12546    }
12547
12548    /**
12549     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12550     * Otherwise, the same display list will be returned (after having been rendered into
12551     * along the way, depending on the invalidation state of the view).
12552     *
12553     * @param displayList The previous version of this displayList, could be null.
12554     * @param isLayer Whether the requester of the display list is a layer. If so,
12555     * the view will avoid creating a layer inside the resulting display list.
12556     * @return A new or reused DisplayList object.
12557     */
12558    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12559        if (!canHaveDisplayList()) {
12560            return null;
12561        }
12562
12563        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12564                displayList == null || !displayList.isValid() ||
12565                (!isLayer && mRecreateDisplayList))) {
12566            // Don't need to recreate the display list, just need to tell our
12567            // children to restore/recreate theirs
12568            if (displayList != null && displayList.isValid() &&
12569                    !isLayer && !mRecreateDisplayList) {
12570                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12571                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12572                dispatchGetDisplayList();
12573
12574                return displayList;
12575            }
12576
12577            if (!isLayer) {
12578                // If we got here, we're recreating it. Mark it as such to ensure that
12579                // we copy in child display lists into ours in drawChild()
12580                mRecreateDisplayList = true;
12581            }
12582            if (displayList == null) {
12583                final String name = getClass().getSimpleName();
12584                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12585                // If we're creating a new display list, make sure our parent gets invalidated
12586                // since they will need to recreate their display list to account for this
12587                // new child display list.
12588                invalidateParentCaches();
12589            }
12590
12591            boolean caching = false;
12592            final HardwareCanvas canvas = displayList.start();
12593            int width = mRight - mLeft;
12594            int height = mBottom - mTop;
12595
12596            try {
12597                canvas.setViewport(width, height);
12598                // The dirty rect should always be null for a display list
12599                canvas.onPreDraw(null);
12600                int layerType = getLayerType();
12601                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12602                    if (layerType == LAYER_TYPE_HARDWARE) {
12603                        final HardwareLayer layer = getHardwareLayer();
12604                        if (layer != null && layer.isValid()) {
12605                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12606                        } else {
12607                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12608                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12609                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12610                        }
12611                        caching = true;
12612                    } else {
12613                        buildDrawingCache(true);
12614                        Bitmap cache = getDrawingCache(true);
12615                        if (cache != null) {
12616                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12617                            caching = true;
12618                        }
12619                    }
12620                } else {
12621
12622                    computeScroll();
12623
12624                    canvas.translate(-mScrollX, -mScrollY);
12625                    if (!isLayer) {
12626                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12627                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12628                    }
12629
12630                    // Fast path for layouts with no backgrounds
12631                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12632                        dispatchDraw(canvas);
12633                    } else {
12634                        draw(canvas);
12635                    }
12636                }
12637            } finally {
12638                canvas.onPostDraw();
12639
12640                displayList.end();
12641                displayList.setCaching(caching);
12642                if (isLayer) {
12643                    displayList.setLeftTopRightBottom(0, 0, width, height);
12644                } else {
12645                    setDisplayListProperties(displayList);
12646                }
12647            }
12648        } else if (!isLayer) {
12649            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12650            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12651        }
12652
12653        return displayList;
12654    }
12655
12656    /**
12657     * Get the DisplayList for the HardwareLayer
12658     *
12659     * @param layer The HardwareLayer whose DisplayList we want
12660     * @return A DisplayList fopr the specified HardwareLayer
12661     */
12662    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12663        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12664        layer.setDisplayList(displayList);
12665        return displayList;
12666    }
12667
12668
12669    /**
12670     * <p>Returns a display list that can be used to draw this view again
12671     * without executing its draw method.</p>
12672     *
12673     * @return A DisplayList ready to replay, or null if caching is not enabled.
12674     *
12675     * @hide
12676     */
12677    public DisplayList getDisplayList() {
12678        mDisplayList = getDisplayList(mDisplayList, false);
12679        return mDisplayList;
12680    }
12681
12682    private void clearDisplayList() {
12683        if (mDisplayList != null) {
12684            mDisplayList.invalidate();
12685            mDisplayList.clear();
12686        }
12687    }
12688
12689    /**
12690     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12691     *
12692     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12693     *
12694     * @see #getDrawingCache(boolean)
12695     */
12696    public Bitmap getDrawingCache() {
12697        return getDrawingCache(false);
12698    }
12699
12700    /**
12701     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12702     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12703     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12704     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12705     * request the drawing cache by calling this method and draw it on screen if the
12706     * returned bitmap is not null.</p>
12707     *
12708     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12709     * this method will create a bitmap of the same size as this view. Because this bitmap
12710     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12711     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12712     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12713     * size than the view. This implies that your application must be able to handle this
12714     * size.</p>
12715     *
12716     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12717     *        the current density of the screen when the application is in compatibility
12718     *        mode.
12719     *
12720     * @return A bitmap representing this view or null if cache is disabled.
12721     *
12722     * @see #setDrawingCacheEnabled(boolean)
12723     * @see #isDrawingCacheEnabled()
12724     * @see #buildDrawingCache(boolean)
12725     * @see #destroyDrawingCache()
12726     */
12727    public Bitmap getDrawingCache(boolean autoScale) {
12728        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12729            return null;
12730        }
12731        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12732            buildDrawingCache(autoScale);
12733        }
12734        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12735    }
12736
12737    /**
12738     * <p>Frees the resources used by the drawing cache. If you call
12739     * {@link #buildDrawingCache()} manually without calling
12740     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12741     * should cleanup the cache with this method afterwards.</p>
12742     *
12743     * @see #setDrawingCacheEnabled(boolean)
12744     * @see #buildDrawingCache()
12745     * @see #getDrawingCache()
12746     */
12747    public void destroyDrawingCache() {
12748        if (mDrawingCache != null) {
12749            mDrawingCache.recycle();
12750            mDrawingCache = null;
12751        }
12752        if (mUnscaledDrawingCache != null) {
12753            mUnscaledDrawingCache.recycle();
12754            mUnscaledDrawingCache = null;
12755        }
12756    }
12757
12758    /**
12759     * Setting a solid background color for the drawing cache's bitmaps will improve
12760     * performance and memory usage. Note, though that this should only be used if this
12761     * view will always be drawn on top of a solid color.
12762     *
12763     * @param color The background color to use for the drawing cache's bitmap
12764     *
12765     * @see #setDrawingCacheEnabled(boolean)
12766     * @see #buildDrawingCache()
12767     * @see #getDrawingCache()
12768     */
12769    public void setDrawingCacheBackgroundColor(int color) {
12770        if (color != mDrawingCacheBackgroundColor) {
12771            mDrawingCacheBackgroundColor = color;
12772            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12773        }
12774    }
12775
12776    /**
12777     * @see #setDrawingCacheBackgroundColor(int)
12778     *
12779     * @return The background color to used for the drawing cache's bitmap
12780     */
12781    public int getDrawingCacheBackgroundColor() {
12782        return mDrawingCacheBackgroundColor;
12783    }
12784
12785    /**
12786     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12787     *
12788     * @see #buildDrawingCache(boolean)
12789     */
12790    public void buildDrawingCache() {
12791        buildDrawingCache(false);
12792    }
12793
12794    /**
12795     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12796     *
12797     * <p>If you call {@link #buildDrawingCache()} manually without calling
12798     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12799     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12800     *
12801     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12802     * this method will create a bitmap of the same size as this view. Because this bitmap
12803     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12804     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12805     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12806     * size than the view. This implies that your application must be able to handle this
12807     * size.</p>
12808     *
12809     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12810     * you do not need the drawing cache bitmap, calling this method will increase memory
12811     * usage and cause the view to be rendered in software once, thus negatively impacting
12812     * performance.</p>
12813     *
12814     * @see #getDrawingCache()
12815     * @see #destroyDrawingCache()
12816     */
12817    public void buildDrawingCache(boolean autoScale) {
12818        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
12819                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12820            mCachingFailed = false;
12821
12822            int width = mRight - mLeft;
12823            int height = mBottom - mTop;
12824
12825            final AttachInfo attachInfo = mAttachInfo;
12826            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12827
12828            if (autoScale && scalingRequired) {
12829                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12830                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12831            }
12832
12833            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12834            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12835            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12836
12837            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
12838            final long drawingCacheSize =
12839                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
12840            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
12841                if (width > 0 && height > 0) {
12842                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
12843                            + projectedBitmapSize + " bytes, only "
12844                            + drawingCacheSize + " available");
12845                }
12846                destroyDrawingCache();
12847                mCachingFailed = true;
12848                return;
12849            }
12850
12851            boolean clear = true;
12852            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12853
12854            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12855                Bitmap.Config quality;
12856                if (!opaque) {
12857                    // Never pick ARGB_4444 because it looks awful
12858                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12859                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12860                        case DRAWING_CACHE_QUALITY_AUTO:
12861                            quality = Bitmap.Config.ARGB_8888;
12862                            break;
12863                        case DRAWING_CACHE_QUALITY_LOW:
12864                            quality = Bitmap.Config.ARGB_8888;
12865                            break;
12866                        case DRAWING_CACHE_QUALITY_HIGH:
12867                            quality = Bitmap.Config.ARGB_8888;
12868                            break;
12869                        default:
12870                            quality = Bitmap.Config.ARGB_8888;
12871                            break;
12872                    }
12873                } else {
12874                    // Optimization for translucent windows
12875                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12876                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12877                }
12878
12879                // Try to cleanup memory
12880                if (bitmap != null) bitmap.recycle();
12881
12882                try {
12883                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
12884                            width, height, quality);
12885                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12886                    if (autoScale) {
12887                        mDrawingCache = bitmap;
12888                    } else {
12889                        mUnscaledDrawingCache = bitmap;
12890                    }
12891                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12892                } catch (OutOfMemoryError e) {
12893                    // If there is not enough memory to create the bitmap cache, just
12894                    // ignore the issue as bitmap caches are not required to draw the
12895                    // view hierarchy
12896                    if (autoScale) {
12897                        mDrawingCache = null;
12898                    } else {
12899                        mUnscaledDrawingCache = null;
12900                    }
12901                    mCachingFailed = true;
12902                    return;
12903                }
12904
12905                clear = drawingCacheBackgroundColor != 0;
12906            }
12907
12908            Canvas canvas;
12909            if (attachInfo != null) {
12910                canvas = attachInfo.mCanvas;
12911                if (canvas == null) {
12912                    canvas = new Canvas();
12913                }
12914                canvas.setBitmap(bitmap);
12915                // Temporarily clobber the cached Canvas in case one of our children
12916                // is also using a drawing cache. Without this, the children would
12917                // steal the canvas by attaching their own bitmap to it and bad, bad
12918                // thing would happen (invisible views, corrupted drawings, etc.)
12919                attachInfo.mCanvas = null;
12920            } else {
12921                // This case should hopefully never or seldom happen
12922                canvas = new Canvas(bitmap);
12923            }
12924
12925            if (clear) {
12926                bitmap.eraseColor(drawingCacheBackgroundColor);
12927            }
12928
12929            computeScroll();
12930            final int restoreCount = canvas.save();
12931
12932            if (autoScale && scalingRequired) {
12933                final float scale = attachInfo.mApplicationScale;
12934                canvas.scale(scale, scale);
12935            }
12936
12937            canvas.translate(-mScrollX, -mScrollY);
12938
12939            mPrivateFlags |= PFLAG_DRAWN;
12940            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12941                    mLayerType != LAYER_TYPE_NONE) {
12942                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
12943            }
12944
12945            // Fast path for layouts with no backgrounds
12946            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12947                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12948                dispatchDraw(canvas);
12949            } else {
12950                draw(canvas);
12951            }
12952
12953            canvas.restoreToCount(restoreCount);
12954            canvas.setBitmap(null);
12955
12956            if (attachInfo != null) {
12957                // Restore the cached Canvas for our siblings
12958                attachInfo.mCanvas = canvas;
12959            }
12960        }
12961    }
12962
12963    /**
12964     * Create a snapshot of the view into a bitmap.  We should probably make
12965     * some form of this public, but should think about the API.
12966     */
12967    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12968        int width = mRight - mLeft;
12969        int height = mBottom - mTop;
12970
12971        final AttachInfo attachInfo = mAttachInfo;
12972        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12973        width = (int) ((width * scale) + 0.5f);
12974        height = (int) ((height * scale) + 0.5f);
12975
12976        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
12977                width > 0 ? width : 1, height > 0 ? height : 1, quality);
12978        if (bitmap == null) {
12979            throw new OutOfMemoryError();
12980        }
12981
12982        Resources resources = getResources();
12983        if (resources != null) {
12984            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12985        }
12986
12987        Canvas canvas;
12988        if (attachInfo != null) {
12989            canvas = attachInfo.mCanvas;
12990            if (canvas == null) {
12991                canvas = new Canvas();
12992            }
12993            canvas.setBitmap(bitmap);
12994            // Temporarily clobber the cached Canvas in case one of our children
12995            // is also using a drawing cache. Without this, the children would
12996            // steal the canvas by attaching their own bitmap to it and bad, bad
12997            // things would happen (invisible views, corrupted drawings, etc.)
12998            attachInfo.mCanvas = null;
12999        } else {
13000            // This case should hopefully never or seldom happen
13001            canvas = new Canvas(bitmap);
13002        }
13003
13004        if ((backgroundColor & 0xff000000) != 0) {
13005            bitmap.eraseColor(backgroundColor);
13006        }
13007
13008        computeScroll();
13009        final int restoreCount = canvas.save();
13010        canvas.scale(scale, scale);
13011        canvas.translate(-mScrollX, -mScrollY);
13012
13013        // Temporarily remove the dirty mask
13014        int flags = mPrivateFlags;
13015        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13016
13017        // Fast path for layouts with no backgrounds
13018        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13019            dispatchDraw(canvas);
13020        } else {
13021            draw(canvas);
13022        }
13023
13024        mPrivateFlags = flags;
13025
13026        canvas.restoreToCount(restoreCount);
13027        canvas.setBitmap(null);
13028
13029        if (attachInfo != null) {
13030            // Restore the cached Canvas for our siblings
13031            attachInfo.mCanvas = canvas;
13032        }
13033
13034        return bitmap;
13035    }
13036
13037    /**
13038     * Indicates whether this View is currently in edit mode. A View is usually
13039     * in edit mode when displayed within a developer tool. For instance, if
13040     * this View is being drawn by a visual user interface builder, this method
13041     * should return true.
13042     *
13043     * Subclasses should check the return value of this method to provide
13044     * different behaviors if their normal behavior might interfere with the
13045     * host environment. For instance: the class spawns a thread in its
13046     * constructor, the drawing code relies on device-specific features, etc.
13047     *
13048     * This method is usually checked in the drawing code of custom widgets.
13049     *
13050     * @return True if this View is in edit mode, false otherwise.
13051     */
13052    public boolean isInEditMode() {
13053        return false;
13054    }
13055
13056    /**
13057     * If the View draws content inside its padding and enables fading edges,
13058     * it needs to support padding offsets. Padding offsets are added to the
13059     * fading edges to extend the length of the fade so that it covers pixels
13060     * drawn inside the padding.
13061     *
13062     * Subclasses of this class should override this method if they need
13063     * to draw content inside the padding.
13064     *
13065     * @return True if padding offset must be applied, false otherwise.
13066     *
13067     * @see #getLeftPaddingOffset()
13068     * @see #getRightPaddingOffset()
13069     * @see #getTopPaddingOffset()
13070     * @see #getBottomPaddingOffset()
13071     *
13072     * @since CURRENT
13073     */
13074    protected boolean isPaddingOffsetRequired() {
13075        return false;
13076    }
13077
13078    /**
13079     * Amount by which to extend the left fading region. Called only when
13080     * {@link #isPaddingOffsetRequired()} returns true.
13081     *
13082     * @return The left padding offset in pixels.
13083     *
13084     * @see #isPaddingOffsetRequired()
13085     *
13086     * @since CURRENT
13087     */
13088    protected int getLeftPaddingOffset() {
13089        return 0;
13090    }
13091
13092    /**
13093     * Amount by which to extend the right fading region. Called only when
13094     * {@link #isPaddingOffsetRequired()} returns true.
13095     *
13096     * @return The right padding offset in pixels.
13097     *
13098     * @see #isPaddingOffsetRequired()
13099     *
13100     * @since CURRENT
13101     */
13102    protected int getRightPaddingOffset() {
13103        return 0;
13104    }
13105
13106    /**
13107     * Amount by which to extend the top fading region. Called only when
13108     * {@link #isPaddingOffsetRequired()} returns true.
13109     *
13110     * @return The top padding offset in pixels.
13111     *
13112     * @see #isPaddingOffsetRequired()
13113     *
13114     * @since CURRENT
13115     */
13116    protected int getTopPaddingOffset() {
13117        return 0;
13118    }
13119
13120    /**
13121     * Amount by which to extend the bottom fading region. Called only when
13122     * {@link #isPaddingOffsetRequired()} returns true.
13123     *
13124     * @return The bottom padding offset in pixels.
13125     *
13126     * @see #isPaddingOffsetRequired()
13127     *
13128     * @since CURRENT
13129     */
13130    protected int getBottomPaddingOffset() {
13131        return 0;
13132    }
13133
13134    /**
13135     * @hide
13136     * @param offsetRequired
13137     */
13138    protected int getFadeTop(boolean offsetRequired) {
13139        int top = mPaddingTop;
13140        if (offsetRequired) top += getTopPaddingOffset();
13141        return top;
13142    }
13143
13144    /**
13145     * @hide
13146     * @param offsetRequired
13147     */
13148    protected int getFadeHeight(boolean offsetRequired) {
13149        int padding = mPaddingTop;
13150        if (offsetRequired) padding += getTopPaddingOffset();
13151        return mBottom - mTop - mPaddingBottom - padding;
13152    }
13153
13154    /**
13155     * <p>Indicates whether this view is attached to a hardware accelerated
13156     * window or not.</p>
13157     *
13158     * <p>Even if this method returns true, it does not mean that every call
13159     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13160     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13161     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13162     * window is hardware accelerated,
13163     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13164     * return false, and this method will return true.</p>
13165     *
13166     * @return True if the view is attached to a window and the window is
13167     *         hardware accelerated; false in any other case.
13168     */
13169    public boolean isHardwareAccelerated() {
13170        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13171    }
13172
13173    /**
13174     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13175     * case of an active Animation being run on the view.
13176     */
13177    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13178            Animation a, boolean scalingRequired) {
13179        Transformation invalidationTransform;
13180        final int flags = parent.mGroupFlags;
13181        final boolean initialized = a.isInitialized();
13182        if (!initialized) {
13183            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13184            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13185            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13186            onAnimationStart();
13187        }
13188
13189        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
13190        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13191            if (parent.mInvalidationTransformation == null) {
13192                parent.mInvalidationTransformation = new Transformation();
13193            }
13194            invalidationTransform = parent.mInvalidationTransformation;
13195            a.getTransformation(drawingTime, invalidationTransform, 1f);
13196        } else {
13197            invalidationTransform = parent.mChildTransformation;
13198        }
13199
13200        if (more) {
13201            if (!a.willChangeBounds()) {
13202                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13203                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13204                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13205                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13206                    // The child need to draw an animation, potentially offscreen, so
13207                    // make sure we do not cancel invalidate requests
13208                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13209                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13210                }
13211            } else {
13212                if (parent.mInvalidateRegion == null) {
13213                    parent.mInvalidateRegion = new RectF();
13214                }
13215                final RectF region = parent.mInvalidateRegion;
13216                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13217                        invalidationTransform);
13218
13219                // The child need to draw an animation, potentially offscreen, so
13220                // make sure we do not cancel invalidate requests
13221                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13222
13223                final int left = mLeft + (int) region.left;
13224                final int top = mTop + (int) region.top;
13225                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13226                        top + (int) (region.height() + .5f));
13227            }
13228        }
13229        return more;
13230    }
13231
13232    /**
13233     * This method is called by getDisplayList() when a display list is created or re-rendered.
13234     * It sets or resets the current value of all properties on that display list (resetting is
13235     * necessary when a display list is being re-created, because we need to make sure that
13236     * previously-set transform values
13237     */
13238    void setDisplayListProperties(DisplayList displayList) {
13239        if (displayList != null) {
13240            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13241            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13242            if (mParent instanceof ViewGroup) {
13243                displayList.setClipChildren(
13244                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13245            }
13246            float alpha = 1;
13247            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13248                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13249                ViewGroup parentVG = (ViewGroup) mParent;
13250                final boolean hasTransform =
13251                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13252                if (hasTransform) {
13253                    Transformation transform = parentVG.mChildTransformation;
13254                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13255                    if (transformType != Transformation.TYPE_IDENTITY) {
13256                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13257                            alpha = transform.getAlpha();
13258                        }
13259                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13260                            displayList.setStaticMatrix(transform.getMatrix());
13261                        }
13262                    }
13263                }
13264            }
13265            if (mTransformationInfo != null) {
13266                alpha *= mTransformationInfo.mAlpha;
13267                if (alpha < 1) {
13268                    final int multipliedAlpha = (int) (255 * alpha);
13269                    if (onSetAlpha(multipliedAlpha)) {
13270                        alpha = 1;
13271                    }
13272                }
13273                displayList.setTransformationInfo(alpha,
13274                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13275                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13276                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13277                        mTransformationInfo.mScaleY);
13278                if (mTransformationInfo.mCamera == null) {
13279                    mTransformationInfo.mCamera = new Camera();
13280                    mTransformationInfo.matrix3D = new Matrix();
13281                }
13282                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13283                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13284                    displayList.setPivotX(getPivotX());
13285                    displayList.setPivotY(getPivotY());
13286                }
13287            } else if (alpha < 1) {
13288                displayList.setAlpha(alpha);
13289            }
13290        }
13291    }
13292
13293    /**
13294     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13295     * This draw() method is an implementation detail and is not intended to be overridden or
13296     * to be called from anywhere else other than ViewGroup.drawChild().
13297     */
13298    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13299        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13300        boolean more = false;
13301        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13302        final int flags = parent.mGroupFlags;
13303
13304        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13305            parent.mChildTransformation.clear();
13306            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13307        }
13308
13309        Transformation transformToApply = null;
13310        boolean concatMatrix = false;
13311
13312        boolean scalingRequired = false;
13313        boolean caching;
13314        int layerType = getLayerType();
13315
13316        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13317        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13318                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13319            caching = true;
13320            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13321            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13322        } else {
13323            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13324        }
13325
13326        final Animation a = getAnimation();
13327        if (a != null) {
13328            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13329            concatMatrix = a.willChangeTransformationMatrix();
13330            if (concatMatrix) {
13331                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13332            }
13333            transformToApply = parent.mChildTransformation;
13334        } else {
13335            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == PFLAG3_VIEW_IS_ANIMATING_TRANSFORM &&
13336                    mDisplayList != null) {
13337                // No longer animating: clear out old animation matrix
13338                mDisplayList.setAnimationMatrix(null);
13339                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13340            }
13341            if (!useDisplayListProperties &&
13342                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13343                final boolean hasTransform =
13344                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13345                if (hasTransform) {
13346                    final int transformType = parent.mChildTransformation.getTransformationType();
13347                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13348                            parent.mChildTransformation : null;
13349                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13350                }
13351            }
13352        }
13353
13354        concatMatrix |= !childHasIdentityMatrix;
13355
13356        // Sets the flag as early as possible to allow draw() implementations
13357        // to call invalidate() successfully when doing animations
13358        mPrivateFlags |= PFLAG_DRAWN;
13359
13360        if (!concatMatrix &&
13361                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13362                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13363                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13364                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13365            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13366            return more;
13367        }
13368        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13369
13370        if (hardwareAccelerated) {
13371            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13372            // retain the flag's value temporarily in the mRecreateDisplayList flag
13373            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13374            mPrivateFlags &= ~PFLAG_INVALIDATED;
13375        }
13376
13377        DisplayList displayList = null;
13378        Bitmap cache = null;
13379        boolean hasDisplayList = false;
13380        if (caching) {
13381            if (!hardwareAccelerated) {
13382                if (layerType != LAYER_TYPE_NONE) {
13383                    layerType = LAYER_TYPE_SOFTWARE;
13384                    buildDrawingCache(true);
13385                }
13386                cache = getDrawingCache(true);
13387            } else {
13388                switch (layerType) {
13389                    case LAYER_TYPE_SOFTWARE:
13390                        if (useDisplayListProperties) {
13391                            hasDisplayList = canHaveDisplayList();
13392                        } else {
13393                            buildDrawingCache(true);
13394                            cache = getDrawingCache(true);
13395                        }
13396                        break;
13397                    case LAYER_TYPE_HARDWARE:
13398                        if (useDisplayListProperties) {
13399                            hasDisplayList = canHaveDisplayList();
13400                        }
13401                        break;
13402                    case LAYER_TYPE_NONE:
13403                        // Delay getting the display list until animation-driven alpha values are
13404                        // set up and possibly passed on to the view
13405                        hasDisplayList = canHaveDisplayList();
13406                        break;
13407                }
13408            }
13409        }
13410        useDisplayListProperties &= hasDisplayList;
13411        if (useDisplayListProperties) {
13412            displayList = getDisplayList();
13413            if (!displayList.isValid()) {
13414                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13415                // to getDisplayList(), the display list will be marked invalid and we should not
13416                // try to use it again.
13417                displayList = null;
13418                hasDisplayList = false;
13419                useDisplayListProperties = false;
13420            }
13421        }
13422
13423        int sx = 0;
13424        int sy = 0;
13425        if (!hasDisplayList) {
13426            computeScroll();
13427            sx = mScrollX;
13428            sy = mScrollY;
13429        }
13430
13431        final boolean hasNoCache = cache == null || hasDisplayList;
13432        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13433                layerType != LAYER_TYPE_HARDWARE;
13434
13435        int restoreTo = -1;
13436        if (!useDisplayListProperties || transformToApply != null) {
13437            restoreTo = canvas.save();
13438        }
13439        if (offsetForScroll) {
13440            canvas.translate(mLeft - sx, mTop - sy);
13441        } else {
13442            if (!useDisplayListProperties) {
13443                canvas.translate(mLeft, mTop);
13444            }
13445            if (scalingRequired) {
13446                if (useDisplayListProperties) {
13447                    // TODO: Might not need this if we put everything inside the DL
13448                    restoreTo = canvas.save();
13449                }
13450                // mAttachInfo cannot be null, otherwise scalingRequired == false
13451                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13452                canvas.scale(scale, scale);
13453            }
13454        }
13455
13456        float alpha = useDisplayListProperties ? 1 : getAlpha();
13457        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13458                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13459            if (transformToApply != null || !childHasIdentityMatrix) {
13460                int transX = 0;
13461                int transY = 0;
13462
13463                if (offsetForScroll) {
13464                    transX = -sx;
13465                    transY = -sy;
13466                }
13467
13468                if (transformToApply != null) {
13469                    if (concatMatrix) {
13470                        if (useDisplayListProperties) {
13471                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13472                        } else {
13473                            // Undo the scroll translation, apply the transformation matrix,
13474                            // then redo the scroll translate to get the correct result.
13475                            canvas.translate(-transX, -transY);
13476                            canvas.concat(transformToApply.getMatrix());
13477                            canvas.translate(transX, transY);
13478                        }
13479                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13480                    }
13481
13482                    float transformAlpha = transformToApply.getAlpha();
13483                    if (transformAlpha < 1) {
13484                        alpha *= transformAlpha;
13485                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13486                    }
13487                }
13488
13489                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13490                    canvas.translate(-transX, -transY);
13491                    canvas.concat(getMatrix());
13492                    canvas.translate(transX, transY);
13493                }
13494            }
13495
13496            // Deal with alpha if it is or used to be <1
13497            if (alpha < 1 ||
13498                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13499                if (alpha < 1) {
13500                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13501                } else {
13502                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13503                }
13504                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13505                if (hasNoCache) {
13506                    final int multipliedAlpha = (int) (255 * alpha);
13507                    if (!onSetAlpha(multipliedAlpha)) {
13508                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13509                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13510                                layerType != LAYER_TYPE_NONE) {
13511                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13512                        }
13513                        if (useDisplayListProperties) {
13514                            displayList.setAlpha(alpha * getAlpha());
13515                        } else  if (layerType == LAYER_TYPE_NONE) {
13516                            final int scrollX = hasDisplayList ? 0 : sx;
13517                            final int scrollY = hasDisplayList ? 0 : sy;
13518                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13519                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13520                        }
13521                    } else {
13522                        // Alpha is handled by the child directly, clobber the layer's alpha
13523                        mPrivateFlags |= PFLAG_ALPHA_SET;
13524                    }
13525                }
13526            }
13527        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13528            onSetAlpha(255);
13529            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13530        }
13531
13532        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13533                !useDisplayListProperties) {
13534            if (offsetForScroll) {
13535                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13536            } else {
13537                if (!scalingRequired || cache == null) {
13538                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13539                } else {
13540                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13541                }
13542            }
13543        }
13544
13545        if (!useDisplayListProperties && hasDisplayList) {
13546            displayList = getDisplayList();
13547            if (!displayList.isValid()) {
13548                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13549                // to getDisplayList(), the display list will be marked invalid and we should not
13550                // try to use it again.
13551                displayList = null;
13552                hasDisplayList = false;
13553            }
13554        }
13555
13556        if (hasNoCache) {
13557            boolean layerRendered = false;
13558            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13559                final HardwareLayer layer = getHardwareLayer();
13560                if (layer != null && layer.isValid()) {
13561                    mLayerPaint.setAlpha((int) (alpha * 255));
13562                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13563                    layerRendered = true;
13564                } else {
13565                    final int scrollX = hasDisplayList ? 0 : sx;
13566                    final int scrollY = hasDisplayList ? 0 : sy;
13567                    canvas.saveLayer(scrollX, scrollY,
13568                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13569                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13570                }
13571            }
13572
13573            if (!layerRendered) {
13574                if (!hasDisplayList) {
13575                    // Fast path for layouts with no backgrounds
13576                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13577                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13578                        dispatchDraw(canvas);
13579                    } else {
13580                        draw(canvas);
13581                    }
13582                } else {
13583                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13584                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13585                }
13586            }
13587        } else if (cache != null) {
13588            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13589            Paint cachePaint;
13590
13591            if (layerType == LAYER_TYPE_NONE) {
13592                cachePaint = parent.mCachePaint;
13593                if (cachePaint == null) {
13594                    cachePaint = new Paint();
13595                    cachePaint.setDither(false);
13596                    parent.mCachePaint = cachePaint;
13597                }
13598                if (alpha < 1) {
13599                    cachePaint.setAlpha((int) (alpha * 255));
13600                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13601                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13602                    cachePaint.setAlpha(255);
13603                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13604                }
13605            } else {
13606                cachePaint = mLayerPaint;
13607                cachePaint.setAlpha((int) (alpha * 255));
13608            }
13609            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13610        }
13611
13612        if (restoreTo >= 0) {
13613            canvas.restoreToCount(restoreTo);
13614        }
13615
13616        if (a != null && !more) {
13617            if (!hardwareAccelerated && !a.getFillAfter()) {
13618                onSetAlpha(255);
13619            }
13620            parent.finishAnimatingView(this, a);
13621        }
13622
13623        if (more && hardwareAccelerated) {
13624            // invalidation is the trigger to recreate display lists, so if we're using
13625            // display lists to render, force an invalidate to allow the animation to
13626            // continue drawing another frame
13627            parent.invalidate(true);
13628            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13629                // alpha animations should cause the child to recreate its display list
13630                invalidate(true);
13631            }
13632        }
13633
13634        mRecreateDisplayList = false;
13635
13636        return more;
13637    }
13638
13639    /**
13640     * Manually render this view (and all of its children) to the given Canvas.
13641     * The view must have already done a full layout before this function is
13642     * called.  When implementing a view, implement
13643     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13644     * If you do need to override this method, call the superclass version.
13645     *
13646     * @param canvas The Canvas to which the View is rendered.
13647     */
13648    public void draw(Canvas canvas) {
13649        final int privateFlags = mPrivateFlags;
13650        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13651                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13652        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13653
13654        /*
13655         * Draw traversal performs several drawing steps which must be executed
13656         * in the appropriate order:
13657         *
13658         *      1. Draw the background
13659         *      2. If necessary, save the canvas' layers to prepare for fading
13660         *      3. Draw view's content
13661         *      4. Draw children
13662         *      5. If necessary, draw the fading edges and restore layers
13663         *      6. Draw decorations (scrollbars for instance)
13664         */
13665
13666        // Step 1, draw the background, if needed
13667        int saveCount;
13668
13669        if (!dirtyOpaque) {
13670            final Drawable background = mBackground;
13671            if (background != null) {
13672                final int scrollX = mScrollX;
13673                final int scrollY = mScrollY;
13674
13675                if (mBackgroundSizeChanged) {
13676                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13677                    mBackgroundSizeChanged = false;
13678                }
13679
13680                if ((scrollX | scrollY) == 0) {
13681                    background.draw(canvas);
13682                } else {
13683                    canvas.translate(scrollX, scrollY);
13684                    background.draw(canvas);
13685                    canvas.translate(-scrollX, -scrollY);
13686                }
13687            }
13688        }
13689
13690        // skip step 2 & 5 if possible (common case)
13691        final int viewFlags = mViewFlags;
13692        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13693        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13694        if (!verticalEdges && !horizontalEdges) {
13695            // Step 3, draw the content
13696            if (!dirtyOpaque) onDraw(canvas);
13697
13698            // Step 4, draw the children
13699            dispatchDraw(canvas);
13700
13701            // Step 6, draw decorations (scrollbars)
13702            onDrawScrollBars(canvas);
13703
13704            // we're done...
13705            return;
13706        }
13707
13708        /*
13709         * Here we do the full fledged routine...
13710         * (this is an uncommon case where speed matters less,
13711         * this is why we repeat some of the tests that have been
13712         * done above)
13713         */
13714
13715        boolean drawTop = false;
13716        boolean drawBottom = false;
13717        boolean drawLeft = false;
13718        boolean drawRight = false;
13719
13720        float topFadeStrength = 0.0f;
13721        float bottomFadeStrength = 0.0f;
13722        float leftFadeStrength = 0.0f;
13723        float rightFadeStrength = 0.0f;
13724
13725        // Step 2, save the canvas' layers
13726        int paddingLeft = mPaddingLeft;
13727
13728        final boolean offsetRequired = isPaddingOffsetRequired();
13729        if (offsetRequired) {
13730            paddingLeft += getLeftPaddingOffset();
13731        }
13732
13733        int left = mScrollX + paddingLeft;
13734        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13735        int top = mScrollY + getFadeTop(offsetRequired);
13736        int bottom = top + getFadeHeight(offsetRequired);
13737
13738        if (offsetRequired) {
13739            right += getRightPaddingOffset();
13740            bottom += getBottomPaddingOffset();
13741        }
13742
13743        final ScrollabilityCache scrollabilityCache = mScrollCache;
13744        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13745        int length = (int) fadeHeight;
13746
13747        // clip the fade length if top and bottom fades overlap
13748        // overlapping fades produce odd-looking artifacts
13749        if (verticalEdges && (top + length > bottom - length)) {
13750            length = (bottom - top) / 2;
13751        }
13752
13753        // also clip horizontal fades if necessary
13754        if (horizontalEdges && (left + length > right - length)) {
13755            length = (right - left) / 2;
13756        }
13757
13758        if (verticalEdges) {
13759            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13760            drawTop = topFadeStrength * fadeHeight > 1.0f;
13761            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13762            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13763        }
13764
13765        if (horizontalEdges) {
13766            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13767            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13768            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13769            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13770        }
13771
13772        saveCount = canvas.getSaveCount();
13773
13774        int solidColor = getSolidColor();
13775        if (solidColor == 0) {
13776            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13777
13778            if (drawTop) {
13779                canvas.saveLayer(left, top, right, top + length, null, flags);
13780            }
13781
13782            if (drawBottom) {
13783                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13784            }
13785
13786            if (drawLeft) {
13787                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13788            }
13789
13790            if (drawRight) {
13791                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13792            }
13793        } else {
13794            scrollabilityCache.setFadeColor(solidColor);
13795        }
13796
13797        // Step 3, draw the content
13798        if (!dirtyOpaque) onDraw(canvas);
13799
13800        // Step 4, draw the children
13801        dispatchDraw(canvas);
13802
13803        // Step 5, draw the fade effect and restore layers
13804        final Paint p = scrollabilityCache.paint;
13805        final Matrix matrix = scrollabilityCache.matrix;
13806        final Shader fade = scrollabilityCache.shader;
13807
13808        if (drawTop) {
13809            matrix.setScale(1, fadeHeight * topFadeStrength);
13810            matrix.postTranslate(left, top);
13811            fade.setLocalMatrix(matrix);
13812            canvas.drawRect(left, top, right, top + length, p);
13813        }
13814
13815        if (drawBottom) {
13816            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13817            matrix.postRotate(180);
13818            matrix.postTranslate(left, bottom);
13819            fade.setLocalMatrix(matrix);
13820            canvas.drawRect(left, bottom - length, right, bottom, p);
13821        }
13822
13823        if (drawLeft) {
13824            matrix.setScale(1, fadeHeight * leftFadeStrength);
13825            matrix.postRotate(-90);
13826            matrix.postTranslate(left, top);
13827            fade.setLocalMatrix(matrix);
13828            canvas.drawRect(left, top, left + length, bottom, p);
13829        }
13830
13831        if (drawRight) {
13832            matrix.setScale(1, fadeHeight * rightFadeStrength);
13833            matrix.postRotate(90);
13834            matrix.postTranslate(right, top);
13835            fade.setLocalMatrix(matrix);
13836            canvas.drawRect(right - length, top, right, bottom, p);
13837        }
13838
13839        canvas.restoreToCount(saveCount);
13840
13841        // Step 6, draw decorations (scrollbars)
13842        onDrawScrollBars(canvas);
13843    }
13844
13845    /**
13846     * Override this if your view is known to always be drawn on top of a solid color background,
13847     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13848     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13849     * should be set to 0xFF.
13850     *
13851     * @see #setVerticalFadingEdgeEnabled(boolean)
13852     * @see #setHorizontalFadingEdgeEnabled(boolean)
13853     *
13854     * @return The known solid color background for this view, or 0 if the color may vary
13855     */
13856    @ViewDebug.ExportedProperty(category = "drawing")
13857    public int getSolidColor() {
13858        return 0;
13859    }
13860
13861    /**
13862     * Build a human readable string representation of the specified view flags.
13863     *
13864     * @param flags the view flags to convert to a string
13865     * @return a String representing the supplied flags
13866     */
13867    private static String printFlags(int flags) {
13868        String output = "";
13869        int numFlags = 0;
13870        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13871            output += "TAKES_FOCUS";
13872            numFlags++;
13873        }
13874
13875        switch (flags & VISIBILITY_MASK) {
13876        case INVISIBLE:
13877            if (numFlags > 0) {
13878                output += " ";
13879            }
13880            output += "INVISIBLE";
13881            // USELESS HERE numFlags++;
13882            break;
13883        case GONE:
13884            if (numFlags > 0) {
13885                output += " ";
13886            }
13887            output += "GONE";
13888            // USELESS HERE numFlags++;
13889            break;
13890        default:
13891            break;
13892        }
13893        return output;
13894    }
13895
13896    /**
13897     * Build a human readable string representation of the specified private
13898     * view flags.
13899     *
13900     * @param privateFlags the private view flags to convert to a string
13901     * @return a String representing the supplied flags
13902     */
13903    private static String printPrivateFlags(int privateFlags) {
13904        String output = "";
13905        int numFlags = 0;
13906
13907        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
13908            output += "WANTS_FOCUS";
13909            numFlags++;
13910        }
13911
13912        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
13913            if (numFlags > 0) {
13914                output += " ";
13915            }
13916            output += "FOCUSED";
13917            numFlags++;
13918        }
13919
13920        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
13921            if (numFlags > 0) {
13922                output += " ";
13923            }
13924            output += "SELECTED";
13925            numFlags++;
13926        }
13927
13928        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
13929            if (numFlags > 0) {
13930                output += " ";
13931            }
13932            output += "IS_ROOT_NAMESPACE";
13933            numFlags++;
13934        }
13935
13936        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
13937            if (numFlags > 0) {
13938                output += " ";
13939            }
13940            output += "HAS_BOUNDS";
13941            numFlags++;
13942        }
13943
13944        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
13945            if (numFlags > 0) {
13946                output += " ";
13947            }
13948            output += "DRAWN";
13949            // USELESS HERE numFlags++;
13950        }
13951        return output;
13952    }
13953
13954    /**
13955     * <p>Indicates whether or not this view's layout will be requested during
13956     * the next hierarchy layout pass.</p>
13957     *
13958     * @return true if the layout will be forced during next layout pass
13959     */
13960    public boolean isLayoutRequested() {
13961        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
13962    }
13963
13964    /**
13965     * Assign a size and position to a view and all of its
13966     * descendants
13967     *
13968     * <p>This is the second phase of the layout mechanism.
13969     * (The first is measuring). In this phase, each parent calls
13970     * layout on all of its children to position them.
13971     * This is typically done using the child measurements
13972     * that were stored in the measure pass().</p>
13973     *
13974     * <p>Derived classes should not override this method.
13975     * Derived classes with children should override
13976     * onLayout. In that method, they should
13977     * call layout on each of their children.</p>
13978     *
13979     * @param l Left position, relative to parent
13980     * @param t Top position, relative to parent
13981     * @param r Right position, relative to parent
13982     * @param b Bottom position, relative to parent
13983     */
13984    @SuppressWarnings({"unchecked"})
13985    public void layout(int l, int t, int r, int b) {
13986        int oldL = mLeft;
13987        int oldT = mTop;
13988        int oldB = mBottom;
13989        int oldR = mRight;
13990        boolean changed = setFrame(l, t, r, b);
13991        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
13992            onLayout(changed, l, t, r, b);
13993            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
13994
13995            ListenerInfo li = mListenerInfo;
13996            if (li != null && li.mOnLayoutChangeListeners != null) {
13997                ArrayList<OnLayoutChangeListener> listenersCopy =
13998                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13999                int numListeners = listenersCopy.size();
14000                for (int i = 0; i < numListeners; ++i) {
14001                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14002                }
14003            }
14004        }
14005        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14006    }
14007
14008    /**
14009     * Called from layout when this view should
14010     * assign a size and position to each of its children.
14011     *
14012     * Derived classes with children should override
14013     * this method and call layout on each of
14014     * their children.
14015     * @param changed This is a new size or position for this view
14016     * @param left Left position, relative to parent
14017     * @param top Top position, relative to parent
14018     * @param right Right position, relative to parent
14019     * @param bottom Bottom position, relative to parent
14020     */
14021    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14022    }
14023
14024    /**
14025     * Assign a size and position to this view.
14026     *
14027     * This is called from layout.
14028     *
14029     * @param left Left position, relative to parent
14030     * @param top Top position, relative to parent
14031     * @param right Right position, relative to parent
14032     * @param bottom Bottom position, relative to parent
14033     * @return true if the new size and position are different than the
14034     *         previous ones
14035     * {@hide}
14036     */
14037    protected boolean setFrame(int left, int top, int right, int bottom) {
14038        boolean changed = false;
14039
14040        if (DBG) {
14041            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14042                    + right + "," + bottom + ")");
14043        }
14044
14045        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14046            changed = true;
14047
14048            // Remember our drawn bit
14049            int drawn = mPrivateFlags & PFLAG_DRAWN;
14050
14051            int oldWidth = mRight - mLeft;
14052            int oldHeight = mBottom - mTop;
14053            int newWidth = right - left;
14054            int newHeight = bottom - top;
14055            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14056
14057            // Invalidate our old position
14058            invalidate(sizeChanged);
14059
14060            mLeft = left;
14061            mTop = top;
14062            mRight = right;
14063            mBottom = bottom;
14064            if (mDisplayList != null) {
14065                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14066            }
14067
14068            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14069
14070
14071            if (sizeChanged) {
14072                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14073                    // A change in dimension means an auto-centered pivot point changes, too
14074                    if (mTransformationInfo != null) {
14075                        mTransformationInfo.mMatrixDirty = true;
14076                    }
14077                }
14078                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14079            }
14080
14081            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14082                // If we are visible, force the DRAWN bit to on so that
14083                // this invalidate will go through (at least to our parent).
14084                // This is because someone may have invalidated this view
14085                // before this call to setFrame came in, thereby clearing
14086                // the DRAWN bit.
14087                mPrivateFlags |= PFLAG_DRAWN;
14088                invalidate(sizeChanged);
14089                // parent display list may need to be recreated based on a change in the bounds
14090                // of any child
14091                invalidateParentCaches();
14092            }
14093
14094            // Reset drawn bit to original value (invalidate turns it off)
14095            mPrivateFlags |= drawn;
14096
14097            mBackgroundSizeChanged = true;
14098        }
14099        return changed;
14100    }
14101
14102    /**
14103     * Finalize inflating a view from XML.  This is called as the last phase
14104     * of inflation, after all child views have been added.
14105     *
14106     * <p>Even if the subclass overrides onFinishInflate, they should always be
14107     * sure to call the super method, so that we get called.
14108     */
14109    protected void onFinishInflate() {
14110    }
14111
14112    /**
14113     * Returns the resources associated with this view.
14114     *
14115     * @return Resources object.
14116     */
14117    public Resources getResources() {
14118        return mResources;
14119    }
14120
14121    /**
14122     * Invalidates the specified Drawable.
14123     *
14124     * @param drawable the drawable to invalidate
14125     */
14126    public void invalidateDrawable(Drawable drawable) {
14127        if (verifyDrawable(drawable)) {
14128            final Rect dirty = drawable.getBounds();
14129            final int scrollX = mScrollX;
14130            final int scrollY = mScrollY;
14131
14132            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14133                    dirty.right + scrollX, dirty.bottom + scrollY);
14134        }
14135    }
14136
14137    /**
14138     * Schedules an action on a drawable to occur at a specified time.
14139     *
14140     * @param who the recipient of the action
14141     * @param what the action to run on the drawable
14142     * @param when the time at which the action must occur. Uses the
14143     *        {@link SystemClock#uptimeMillis} timebase.
14144     */
14145    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14146        if (verifyDrawable(who) && what != null) {
14147            final long delay = when - SystemClock.uptimeMillis();
14148            if (mAttachInfo != null) {
14149                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14150                        Choreographer.CALLBACK_ANIMATION, what, who,
14151                        Choreographer.subtractFrameDelay(delay));
14152            } else {
14153                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14154            }
14155        }
14156    }
14157
14158    /**
14159     * Cancels a scheduled action on a drawable.
14160     *
14161     * @param who the recipient of the action
14162     * @param what the action to cancel
14163     */
14164    public void unscheduleDrawable(Drawable who, Runnable what) {
14165        if (verifyDrawable(who) && what != null) {
14166            if (mAttachInfo != null) {
14167                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14168                        Choreographer.CALLBACK_ANIMATION, what, who);
14169            } else {
14170                ViewRootImpl.getRunQueue().removeCallbacks(what);
14171            }
14172        }
14173    }
14174
14175    /**
14176     * Unschedule any events associated with the given Drawable.  This can be
14177     * used when selecting a new Drawable into a view, so that the previous
14178     * one is completely unscheduled.
14179     *
14180     * @param who The Drawable to unschedule.
14181     *
14182     * @see #drawableStateChanged
14183     */
14184    public void unscheduleDrawable(Drawable who) {
14185        if (mAttachInfo != null && who != null) {
14186            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14187                    Choreographer.CALLBACK_ANIMATION, null, who);
14188        }
14189    }
14190
14191    /**
14192     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14193     * that the View directionality can and will be resolved before its Drawables.
14194     *
14195     * Will call {@link View#onResolveDrawables} when resolution is done.
14196     *
14197     * @hide
14198     */
14199    protected void resolveDrawables() {
14200        if (mBackground != null) {
14201            mBackground.setLayoutDirection(getLayoutDirection());
14202        }
14203        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14204        onResolveDrawables(getLayoutDirection());
14205    }
14206
14207    /**
14208     * Called when layout direction has been resolved.
14209     *
14210     * The default implementation does nothing.
14211     *
14212     * @param layoutDirection The resolved layout direction.
14213     *
14214     * @see #LAYOUT_DIRECTION_LTR
14215     * @see #LAYOUT_DIRECTION_RTL
14216     *
14217     * @hide
14218     */
14219    public void onResolveDrawables(int layoutDirection) {
14220    }
14221
14222    /**
14223     * @hide
14224     */
14225    protected void resetResolvedDrawables() {
14226        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14227    }
14228
14229    private boolean isDrawablesResolved() {
14230        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14231    }
14232
14233    /**
14234     * If your view subclass is displaying its own Drawable objects, it should
14235     * override this function and return true for any Drawable it is
14236     * displaying.  This allows animations for those drawables to be
14237     * scheduled.
14238     *
14239     * <p>Be sure to call through to the super class when overriding this
14240     * function.
14241     *
14242     * @param who The Drawable to verify.  Return true if it is one you are
14243     *            displaying, else return the result of calling through to the
14244     *            super class.
14245     *
14246     * @return boolean If true than the Drawable is being displayed in the
14247     *         view; else false and it is not allowed to animate.
14248     *
14249     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14250     * @see #drawableStateChanged()
14251     */
14252    protected boolean verifyDrawable(Drawable who) {
14253        return who == mBackground;
14254    }
14255
14256    /**
14257     * This function is called whenever the state of the view changes in such
14258     * a way that it impacts the state of drawables being shown.
14259     *
14260     * <p>Be sure to call through to the superclass when overriding this
14261     * function.
14262     *
14263     * @see Drawable#setState(int[])
14264     */
14265    protected void drawableStateChanged() {
14266        Drawable d = mBackground;
14267        if (d != null && d.isStateful()) {
14268            d.setState(getDrawableState());
14269        }
14270    }
14271
14272    /**
14273     * Call this to force a view to update its drawable state. This will cause
14274     * drawableStateChanged to be called on this view. Views that are interested
14275     * in the new state should call getDrawableState.
14276     *
14277     * @see #drawableStateChanged
14278     * @see #getDrawableState
14279     */
14280    public void refreshDrawableState() {
14281        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14282        drawableStateChanged();
14283
14284        ViewParent parent = mParent;
14285        if (parent != null) {
14286            parent.childDrawableStateChanged(this);
14287        }
14288    }
14289
14290    /**
14291     * Return an array of resource IDs of the drawable states representing the
14292     * current state of the view.
14293     *
14294     * @return The current drawable state
14295     *
14296     * @see Drawable#setState(int[])
14297     * @see #drawableStateChanged()
14298     * @see #onCreateDrawableState(int)
14299     */
14300    public final int[] getDrawableState() {
14301        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14302            return mDrawableState;
14303        } else {
14304            mDrawableState = onCreateDrawableState(0);
14305            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14306            return mDrawableState;
14307        }
14308    }
14309
14310    /**
14311     * Generate the new {@link android.graphics.drawable.Drawable} state for
14312     * this view. This is called by the view
14313     * system when the cached Drawable state is determined to be invalid.  To
14314     * retrieve the current state, you should use {@link #getDrawableState}.
14315     *
14316     * @param extraSpace if non-zero, this is the number of extra entries you
14317     * would like in the returned array in which you can place your own
14318     * states.
14319     *
14320     * @return Returns an array holding the current {@link Drawable} state of
14321     * the view.
14322     *
14323     * @see #mergeDrawableStates(int[], int[])
14324     */
14325    protected int[] onCreateDrawableState(int extraSpace) {
14326        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14327                mParent instanceof View) {
14328            return ((View) mParent).onCreateDrawableState(extraSpace);
14329        }
14330
14331        int[] drawableState;
14332
14333        int privateFlags = mPrivateFlags;
14334
14335        int viewStateIndex = 0;
14336        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14337        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14338        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14339        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14340        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14341        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14342        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14343                HardwareRenderer.isAvailable()) {
14344            // This is set if HW acceleration is requested, even if the current
14345            // process doesn't allow it.  This is just to allow app preview
14346            // windows to better match their app.
14347            viewStateIndex |= VIEW_STATE_ACCELERATED;
14348        }
14349        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14350
14351        final int privateFlags2 = mPrivateFlags2;
14352        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14353        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14354
14355        drawableState = VIEW_STATE_SETS[viewStateIndex];
14356
14357        //noinspection ConstantIfStatement
14358        if (false) {
14359            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14360            Log.i("View", toString()
14361                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14362                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14363                    + " fo=" + hasFocus()
14364                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14365                    + " wf=" + hasWindowFocus()
14366                    + ": " + Arrays.toString(drawableState));
14367        }
14368
14369        if (extraSpace == 0) {
14370            return drawableState;
14371        }
14372
14373        final int[] fullState;
14374        if (drawableState != null) {
14375            fullState = new int[drawableState.length + extraSpace];
14376            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14377        } else {
14378            fullState = new int[extraSpace];
14379        }
14380
14381        return fullState;
14382    }
14383
14384    /**
14385     * Merge your own state values in <var>additionalState</var> into the base
14386     * state values <var>baseState</var> that were returned by
14387     * {@link #onCreateDrawableState(int)}.
14388     *
14389     * @param baseState The base state values returned by
14390     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14391     * own additional state values.
14392     *
14393     * @param additionalState The additional state values you would like
14394     * added to <var>baseState</var>; this array is not modified.
14395     *
14396     * @return As a convenience, the <var>baseState</var> array you originally
14397     * passed into the function is returned.
14398     *
14399     * @see #onCreateDrawableState(int)
14400     */
14401    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14402        final int N = baseState.length;
14403        int i = N - 1;
14404        while (i >= 0 && baseState[i] == 0) {
14405            i--;
14406        }
14407        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14408        return baseState;
14409    }
14410
14411    /**
14412     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14413     * on all Drawable objects associated with this view.
14414     */
14415    public void jumpDrawablesToCurrentState() {
14416        if (mBackground != null) {
14417            mBackground.jumpToCurrentState();
14418        }
14419    }
14420
14421    /**
14422     * Sets the background color for this view.
14423     * @param color the color of the background
14424     */
14425    @RemotableViewMethod
14426    public void setBackgroundColor(int color) {
14427        if (mBackground instanceof ColorDrawable) {
14428            ((ColorDrawable) mBackground.mutate()).setColor(color);
14429            computeOpaqueFlags();
14430        } else {
14431            setBackground(new ColorDrawable(color));
14432        }
14433    }
14434
14435    /**
14436     * Set the background to a given resource. The resource should refer to
14437     * a Drawable object or 0 to remove the background.
14438     * @param resid The identifier of the resource.
14439     *
14440     * @attr ref android.R.styleable#View_background
14441     */
14442    @RemotableViewMethod
14443    public void setBackgroundResource(int resid) {
14444        if (resid != 0 && resid == mBackgroundResource) {
14445            return;
14446        }
14447
14448        Drawable d= null;
14449        if (resid != 0) {
14450            d = mResources.getDrawable(resid);
14451        }
14452        setBackground(d);
14453
14454        mBackgroundResource = resid;
14455    }
14456
14457    /**
14458     * Set the background to a given Drawable, or remove the background. If the
14459     * background has padding, this View's padding is set to the background's
14460     * padding. However, when a background is removed, this View's padding isn't
14461     * touched. If setting the padding is desired, please use
14462     * {@link #setPadding(int, int, int, int)}.
14463     *
14464     * @param background The Drawable to use as the background, or null to remove the
14465     *        background
14466     */
14467    public void setBackground(Drawable background) {
14468        //noinspection deprecation
14469        setBackgroundDrawable(background);
14470    }
14471
14472    /**
14473     * @deprecated use {@link #setBackground(Drawable)} instead
14474     */
14475    @Deprecated
14476    public void setBackgroundDrawable(Drawable background) {
14477        computeOpaqueFlags();
14478
14479        if (background == mBackground) {
14480            return;
14481        }
14482
14483        boolean requestLayout = false;
14484
14485        mBackgroundResource = 0;
14486
14487        /*
14488         * Regardless of whether we're setting a new background or not, we want
14489         * to clear the previous drawable.
14490         */
14491        if (mBackground != null) {
14492            mBackground.setCallback(null);
14493            unscheduleDrawable(mBackground);
14494        }
14495
14496        if (background != null) {
14497            Rect padding = sThreadLocal.get();
14498            if (padding == null) {
14499                padding = new Rect();
14500                sThreadLocal.set(padding);
14501            }
14502            resetResolvedDrawables();
14503            background.setLayoutDirection(getLayoutDirection());
14504            if (background.getPadding(padding)) {
14505                resetResolvedPadding();
14506                switch (background.getLayoutDirection()) {
14507                    case LAYOUT_DIRECTION_RTL:
14508                        mUserPaddingLeftInitial = padding.right;
14509                        mUserPaddingRightInitial = padding.left;
14510                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14511                        break;
14512                    case LAYOUT_DIRECTION_LTR:
14513                    default:
14514                        mUserPaddingLeftInitial = padding.left;
14515                        mUserPaddingRightInitial = padding.right;
14516                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14517                }
14518            }
14519
14520            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14521            // if it has a different minimum size, we should layout again
14522            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14523                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14524                requestLayout = true;
14525            }
14526
14527            background.setCallback(this);
14528            if (background.isStateful()) {
14529                background.setState(getDrawableState());
14530            }
14531            background.setVisible(getVisibility() == VISIBLE, false);
14532            mBackground = background;
14533
14534            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14535                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14536                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14537                requestLayout = true;
14538            }
14539        } else {
14540            /* Remove the background */
14541            mBackground = null;
14542
14543            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14544                /*
14545                 * This view ONLY drew the background before and we're removing
14546                 * the background, so now it won't draw anything
14547                 * (hence we SKIP_DRAW)
14548                 */
14549                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14550                mPrivateFlags |= PFLAG_SKIP_DRAW;
14551            }
14552
14553            /*
14554             * When the background is set, we try to apply its padding to this
14555             * View. When the background is removed, we don't touch this View's
14556             * padding. This is noted in the Javadocs. Hence, we don't need to
14557             * requestLayout(), the invalidate() below is sufficient.
14558             */
14559
14560            // The old background's minimum size could have affected this
14561            // View's layout, so let's requestLayout
14562            requestLayout = true;
14563        }
14564
14565        computeOpaqueFlags();
14566
14567        if (requestLayout) {
14568            requestLayout();
14569        }
14570
14571        mBackgroundSizeChanged = true;
14572        invalidate(true);
14573    }
14574
14575    /**
14576     * Gets the background drawable
14577     *
14578     * @return The drawable used as the background for this view, if any.
14579     *
14580     * @see #setBackground(Drawable)
14581     *
14582     * @attr ref android.R.styleable#View_background
14583     */
14584    public Drawable getBackground() {
14585        return mBackground;
14586    }
14587
14588    /**
14589     * Sets the padding. The view may add on the space required to display
14590     * the scrollbars, depending on the style and visibility of the scrollbars.
14591     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14592     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14593     * from the values set in this call.
14594     *
14595     * @attr ref android.R.styleable#View_padding
14596     * @attr ref android.R.styleable#View_paddingBottom
14597     * @attr ref android.R.styleable#View_paddingLeft
14598     * @attr ref android.R.styleable#View_paddingRight
14599     * @attr ref android.R.styleable#View_paddingTop
14600     * @param left the left padding in pixels
14601     * @param top the top padding in pixels
14602     * @param right the right padding in pixels
14603     * @param bottom the bottom padding in pixels
14604     */
14605    public void setPadding(int left, int top, int right, int bottom) {
14606        resetResolvedPadding();
14607
14608        mUserPaddingStart = UNDEFINED_PADDING;
14609        mUserPaddingEnd = UNDEFINED_PADDING;
14610
14611        mUserPaddingLeftInitial = left;
14612        mUserPaddingRightInitial = right;
14613
14614        internalSetPadding(left, top, right, bottom);
14615    }
14616
14617    /**
14618     * @hide
14619     */
14620    protected void internalSetPadding(int left, int top, int right, int bottom) {
14621        mUserPaddingLeft = left;
14622        mUserPaddingRight = right;
14623        mUserPaddingBottom = bottom;
14624
14625        final int viewFlags = mViewFlags;
14626        boolean changed = false;
14627
14628        // Common case is there are no scroll bars.
14629        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14630            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14631                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14632                        ? 0 : getVerticalScrollbarWidth();
14633                switch (mVerticalScrollbarPosition) {
14634                    case SCROLLBAR_POSITION_DEFAULT:
14635                        if (isLayoutRtl()) {
14636                            left += offset;
14637                        } else {
14638                            right += offset;
14639                        }
14640                        break;
14641                    case SCROLLBAR_POSITION_RIGHT:
14642                        right += offset;
14643                        break;
14644                    case SCROLLBAR_POSITION_LEFT:
14645                        left += offset;
14646                        break;
14647                }
14648            }
14649            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14650                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14651                        ? 0 : getHorizontalScrollbarHeight();
14652            }
14653        }
14654
14655        if (mPaddingLeft != left) {
14656            changed = true;
14657            mPaddingLeft = left;
14658        }
14659        if (mPaddingTop != top) {
14660            changed = true;
14661            mPaddingTop = top;
14662        }
14663        if (mPaddingRight != right) {
14664            changed = true;
14665            mPaddingRight = right;
14666        }
14667        if (mPaddingBottom != bottom) {
14668            changed = true;
14669            mPaddingBottom = bottom;
14670        }
14671
14672        if (changed) {
14673            requestLayout();
14674        }
14675    }
14676
14677    /**
14678     * Sets the relative padding. The view may add on the space required to display
14679     * the scrollbars, depending on the style and visibility of the scrollbars.
14680     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14681     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14682     * from the values set in this call.
14683     *
14684     * @attr ref android.R.styleable#View_padding
14685     * @attr ref android.R.styleable#View_paddingBottom
14686     * @attr ref android.R.styleable#View_paddingStart
14687     * @attr ref android.R.styleable#View_paddingEnd
14688     * @attr ref android.R.styleable#View_paddingTop
14689     * @param start the start padding in pixels
14690     * @param top the top padding in pixels
14691     * @param end the end padding in pixels
14692     * @param bottom the bottom padding in pixels
14693     */
14694    public void setPaddingRelative(int start, int top, int end, int bottom) {
14695        resetResolvedPadding();
14696
14697        mUserPaddingStart = start;
14698        mUserPaddingEnd = end;
14699
14700        switch(getLayoutDirection()) {
14701            case LAYOUT_DIRECTION_RTL:
14702                mUserPaddingLeftInitial = end;
14703                mUserPaddingRightInitial = start;
14704                internalSetPadding(end, top, start, bottom);
14705                break;
14706            case LAYOUT_DIRECTION_LTR:
14707            default:
14708                mUserPaddingLeftInitial = start;
14709                mUserPaddingRightInitial = end;
14710                internalSetPadding(start, top, end, bottom);
14711        }
14712    }
14713
14714    /**
14715     * Returns the top padding of this view.
14716     *
14717     * @return the top padding in pixels
14718     */
14719    public int getPaddingTop() {
14720        return mPaddingTop;
14721    }
14722
14723    /**
14724     * Returns the bottom padding of this view. If there are inset and enabled
14725     * scrollbars, this value may include the space required to display the
14726     * scrollbars as well.
14727     *
14728     * @return the bottom padding in pixels
14729     */
14730    public int getPaddingBottom() {
14731        return mPaddingBottom;
14732    }
14733
14734    /**
14735     * Returns the left padding of this view. If there are inset and enabled
14736     * scrollbars, this value may include the space required to display the
14737     * scrollbars as well.
14738     *
14739     * @return the left padding in pixels
14740     */
14741    public int getPaddingLeft() {
14742        if (!isPaddingResolved()) {
14743            resolvePadding();
14744        }
14745        return mPaddingLeft;
14746    }
14747
14748    /**
14749     * Returns the start padding of this view depending on its resolved layout direction.
14750     * If there are inset and enabled scrollbars, this value may include the space
14751     * required to display the scrollbars as well.
14752     *
14753     * @return the start padding in pixels
14754     */
14755    public int getPaddingStart() {
14756        if (!isPaddingResolved()) {
14757            resolvePadding();
14758        }
14759        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14760                mPaddingRight : mPaddingLeft;
14761    }
14762
14763    /**
14764     * Returns the right padding of this view. If there are inset and enabled
14765     * scrollbars, this value may include the space required to display the
14766     * scrollbars as well.
14767     *
14768     * @return the right padding in pixels
14769     */
14770    public int getPaddingRight() {
14771        if (!isPaddingResolved()) {
14772            resolvePadding();
14773        }
14774        return mPaddingRight;
14775    }
14776
14777    /**
14778     * Returns the end padding of this view depending on its resolved layout direction.
14779     * If there are inset and enabled scrollbars, this value may include the space
14780     * required to display the scrollbars as well.
14781     *
14782     * @return the end padding in pixels
14783     */
14784    public int getPaddingEnd() {
14785        if (!isPaddingResolved()) {
14786            resolvePadding();
14787        }
14788        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14789                mPaddingLeft : mPaddingRight;
14790    }
14791
14792    /**
14793     * Return if the padding as been set thru relative values
14794     * {@link #setPaddingRelative(int, int, int, int)} or thru
14795     * @attr ref android.R.styleable#View_paddingStart or
14796     * @attr ref android.R.styleable#View_paddingEnd
14797     *
14798     * @return true if the padding is relative or false if it is not.
14799     */
14800    public boolean isPaddingRelative() {
14801        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
14802    }
14803
14804    /**
14805     * @hide
14806     */
14807    public void resetPaddingToInitialValues() {
14808        if (isRtlCompatibilityMode()) {
14809            mPaddingLeft = mUserPaddingLeftInitial;
14810            mPaddingRight = mUserPaddingRightInitial;
14811            return;
14812        }
14813        if (isLayoutRtl()) {
14814            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
14815            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
14816        } else {
14817            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
14818            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
14819        }
14820    }
14821
14822    /**
14823     * @hide
14824     */
14825    public Insets getOpticalInsets() {
14826        if (mLayoutInsets == null) {
14827            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14828        }
14829        return mLayoutInsets;
14830    }
14831
14832    /**
14833     * @hide
14834     */
14835    public void setLayoutInsets(Insets layoutInsets) {
14836        mLayoutInsets = layoutInsets;
14837    }
14838
14839    /**
14840     * Changes the selection state of this view. A view can be selected or not.
14841     * Note that selection is not the same as focus. Views are typically
14842     * selected in the context of an AdapterView like ListView or GridView;
14843     * the selected view is the view that is highlighted.
14844     *
14845     * @param selected true if the view must be selected, false otherwise
14846     */
14847    public void setSelected(boolean selected) {
14848        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
14849            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
14850            if (!selected) resetPressedState();
14851            invalidate(true);
14852            refreshDrawableState();
14853            dispatchSetSelected(selected);
14854            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14855                notifyAccessibilityStateChanged();
14856            }
14857        }
14858    }
14859
14860    /**
14861     * Dispatch setSelected to all of this View's children.
14862     *
14863     * @see #setSelected(boolean)
14864     *
14865     * @param selected The new selected state
14866     */
14867    protected void dispatchSetSelected(boolean selected) {
14868    }
14869
14870    /**
14871     * Indicates the selection state of this view.
14872     *
14873     * @return true if the view is selected, false otherwise
14874     */
14875    @ViewDebug.ExportedProperty
14876    public boolean isSelected() {
14877        return (mPrivateFlags & PFLAG_SELECTED) != 0;
14878    }
14879
14880    /**
14881     * Changes the activated state of this view. A view can be activated or not.
14882     * Note that activation is not the same as selection.  Selection is
14883     * a transient property, representing the view (hierarchy) the user is
14884     * currently interacting with.  Activation is a longer-term state that the
14885     * user can move views in and out of.  For example, in a list view with
14886     * single or multiple selection enabled, the views in the current selection
14887     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14888     * here.)  The activated state is propagated down to children of the view it
14889     * is set on.
14890     *
14891     * @param activated true if the view must be activated, false otherwise
14892     */
14893    public void setActivated(boolean activated) {
14894        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
14895            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
14896            invalidate(true);
14897            refreshDrawableState();
14898            dispatchSetActivated(activated);
14899        }
14900    }
14901
14902    /**
14903     * Dispatch setActivated to all of this View's children.
14904     *
14905     * @see #setActivated(boolean)
14906     *
14907     * @param activated The new activated state
14908     */
14909    protected void dispatchSetActivated(boolean activated) {
14910    }
14911
14912    /**
14913     * Indicates the activation state of this view.
14914     *
14915     * @return true if the view is activated, false otherwise
14916     */
14917    @ViewDebug.ExportedProperty
14918    public boolean isActivated() {
14919        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
14920    }
14921
14922    /**
14923     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14924     * observer can be used to get notifications when global events, like
14925     * layout, happen.
14926     *
14927     * The returned ViewTreeObserver observer is not guaranteed to remain
14928     * valid for the lifetime of this View. If the caller of this method keeps
14929     * a long-lived reference to ViewTreeObserver, it should always check for
14930     * the return value of {@link ViewTreeObserver#isAlive()}.
14931     *
14932     * @return The ViewTreeObserver for this view's hierarchy.
14933     */
14934    public ViewTreeObserver getViewTreeObserver() {
14935        if (mAttachInfo != null) {
14936            return mAttachInfo.mTreeObserver;
14937        }
14938        if (mFloatingTreeObserver == null) {
14939            mFloatingTreeObserver = new ViewTreeObserver();
14940        }
14941        return mFloatingTreeObserver;
14942    }
14943
14944    /**
14945     * <p>Finds the topmost view in the current view hierarchy.</p>
14946     *
14947     * @return the topmost view containing this view
14948     */
14949    public View getRootView() {
14950        if (mAttachInfo != null) {
14951            final View v = mAttachInfo.mRootView;
14952            if (v != null) {
14953                return v;
14954            }
14955        }
14956
14957        View parent = this;
14958
14959        while (parent.mParent != null && parent.mParent instanceof View) {
14960            parent = (View) parent.mParent;
14961        }
14962
14963        return parent;
14964    }
14965
14966    /**
14967     * <p>Computes the coordinates of this view on the screen. The argument
14968     * must be an array of two integers. After the method returns, the array
14969     * contains the x and y location in that order.</p>
14970     *
14971     * @param location an array of two integers in which to hold the coordinates
14972     */
14973    public void getLocationOnScreen(int[] location) {
14974        getLocationInWindow(location);
14975
14976        final AttachInfo info = mAttachInfo;
14977        if (info != null) {
14978            location[0] += info.mWindowLeft;
14979            location[1] += info.mWindowTop;
14980        }
14981    }
14982
14983    /**
14984     * <p>Computes the coordinates of this view in its window. The argument
14985     * must be an array of two integers. After the method returns, the array
14986     * contains the x and y location in that order.</p>
14987     *
14988     * @param location an array of two integers in which to hold the coordinates
14989     */
14990    public void getLocationInWindow(int[] location) {
14991        if (location == null || location.length < 2) {
14992            throw new IllegalArgumentException("location must be an array of two integers");
14993        }
14994
14995        if (mAttachInfo == null) {
14996            // When the view is not attached to a window, this method does not make sense
14997            location[0] = location[1] = 0;
14998            return;
14999        }
15000
15001        float[] position = mAttachInfo.mTmpTransformLocation;
15002        position[0] = position[1] = 0.0f;
15003
15004        if (!hasIdentityMatrix()) {
15005            getMatrix().mapPoints(position);
15006        }
15007
15008        position[0] += mLeft;
15009        position[1] += mTop;
15010
15011        ViewParent viewParent = mParent;
15012        while (viewParent instanceof View) {
15013            final View view = (View) viewParent;
15014
15015            position[0] -= view.mScrollX;
15016            position[1] -= view.mScrollY;
15017
15018            if (!view.hasIdentityMatrix()) {
15019                view.getMatrix().mapPoints(position);
15020            }
15021
15022            position[0] += view.mLeft;
15023            position[1] += view.mTop;
15024
15025            viewParent = view.mParent;
15026         }
15027
15028        if (viewParent instanceof ViewRootImpl) {
15029            // *cough*
15030            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15031            position[1] -= vr.mCurScrollY;
15032        }
15033
15034        location[0] = (int) (position[0] + 0.5f);
15035        location[1] = (int) (position[1] + 0.5f);
15036    }
15037
15038    /**
15039     * {@hide}
15040     * @param id the id of the view to be found
15041     * @return the view of the specified id, null if cannot be found
15042     */
15043    protected View findViewTraversal(int id) {
15044        if (id == mID) {
15045            return this;
15046        }
15047        return null;
15048    }
15049
15050    /**
15051     * {@hide}
15052     * @param tag the tag of the view to be found
15053     * @return the view of specified tag, null if cannot be found
15054     */
15055    protected View findViewWithTagTraversal(Object tag) {
15056        if (tag != null && tag.equals(mTag)) {
15057            return this;
15058        }
15059        return null;
15060    }
15061
15062    /**
15063     * {@hide}
15064     * @param predicate The predicate to evaluate.
15065     * @param childToSkip If not null, ignores this child during the recursive traversal.
15066     * @return The first view that matches the predicate or null.
15067     */
15068    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15069        if (predicate.apply(this)) {
15070            return this;
15071        }
15072        return null;
15073    }
15074
15075    /**
15076     * Look for a child view with the given id.  If this view has the given
15077     * id, return this view.
15078     *
15079     * @param id The id to search for.
15080     * @return The view that has the given id in the hierarchy or null
15081     */
15082    public final View findViewById(int id) {
15083        if (id < 0) {
15084            return null;
15085        }
15086        return findViewTraversal(id);
15087    }
15088
15089    /**
15090     * Finds a view by its unuque and stable accessibility id.
15091     *
15092     * @param accessibilityId The searched accessibility id.
15093     * @return The found view.
15094     */
15095    final View findViewByAccessibilityId(int accessibilityId) {
15096        if (accessibilityId < 0) {
15097            return null;
15098        }
15099        return findViewByAccessibilityIdTraversal(accessibilityId);
15100    }
15101
15102    /**
15103     * Performs the traversal to find a view by its unuque and stable accessibility id.
15104     *
15105     * <strong>Note:</strong>This method does not stop at the root namespace
15106     * boundary since the user can touch the screen at an arbitrary location
15107     * potentially crossing the root namespace bounday which will send an
15108     * accessibility event to accessibility services and they should be able
15109     * to obtain the event source. Also accessibility ids are guaranteed to be
15110     * unique in the window.
15111     *
15112     * @param accessibilityId The accessibility id.
15113     * @return The found view.
15114     */
15115    View findViewByAccessibilityIdTraversal(int accessibilityId) {
15116        if (getAccessibilityViewId() == accessibilityId) {
15117            return this;
15118        }
15119        return null;
15120    }
15121
15122    /**
15123     * Look for a child view with the given tag.  If this view has the given
15124     * tag, return this view.
15125     *
15126     * @param tag The tag to search for, using "tag.equals(getTag())".
15127     * @return The View that has the given tag in the hierarchy or null
15128     */
15129    public final View findViewWithTag(Object tag) {
15130        if (tag == null) {
15131            return null;
15132        }
15133        return findViewWithTagTraversal(tag);
15134    }
15135
15136    /**
15137     * {@hide}
15138     * Look for a child view that matches the specified predicate.
15139     * If this view matches the predicate, return this view.
15140     *
15141     * @param predicate The predicate to evaluate.
15142     * @return The first view that matches the predicate or null.
15143     */
15144    public final View findViewByPredicate(Predicate<View> predicate) {
15145        return findViewByPredicateTraversal(predicate, null);
15146    }
15147
15148    /**
15149     * {@hide}
15150     * Look for a child view that matches the specified predicate,
15151     * starting with the specified view and its descendents and then
15152     * recusively searching the ancestors and siblings of that view
15153     * until this view is reached.
15154     *
15155     * This method is useful in cases where the predicate does not match
15156     * a single unique view (perhaps multiple views use the same id)
15157     * and we are trying to find the view that is "closest" in scope to the
15158     * starting view.
15159     *
15160     * @param start The view to start from.
15161     * @param predicate The predicate to evaluate.
15162     * @return The first view that matches the predicate or null.
15163     */
15164    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15165        View childToSkip = null;
15166        for (;;) {
15167            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15168            if (view != null || start == this) {
15169                return view;
15170            }
15171
15172            ViewParent parent = start.getParent();
15173            if (parent == null || !(parent instanceof View)) {
15174                return null;
15175            }
15176
15177            childToSkip = start;
15178            start = (View) parent;
15179        }
15180    }
15181
15182    /**
15183     * Sets the identifier for this view. The identifier does not have to be
15184     * unique in this view's hierarchy. The identifier should be a positive
15185     * number.
15186     *
15187     * @see #NO_ID
15188     * @see #getId()
15189     * @see #findViewById(int)
15190     *
15191     * @param id a number used to identify the view
15192     *
15193     * @attr ref android.R.styleable#View_id
15194     */
15195    public void setId(int id) {
15196        mID = id;
15197        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15198            mID = generateViewId();
15199        }
15200    }
15201
15202    /**
15203     * {@hide}
15204     *
15205     * @param isRoot true if the view belongs to the root namespace, false
15206     *        otherwise
15207     */
15208    public void setIsRootNamespace(boolean isRoot) {
15209        if (isRoot) {
15210            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15211        } else {
15212            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15213        }
15214    }
15215
15216    /**
15217     * {@hide}
15218     *
15219     * @return true if the view belongs to the root namespace, false otherwise
15220     */
15221    public boolean isRootNamespace() {
15222        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15223    }
15224
15225    /**
15226     * Returns this view's identifier.
15227     *
15228     * @return a positive integer used to identify the view or {@link #NO_ID}
15229     *         if the view has no ID
15230     *
15231     * @see #setId(int)
15232     * @see #findViewById(int)
15233     * @attr ref android.R.styleable#View_id
15234     */
15235    @ViewDebug.CapturedViewProperty
15236    public int getId() {
15237        return mID;
15238    }
15239
15240    /**
15241     * Returns this view's tag.
15242     *
15243     * @return the Object stored in this view as a tag
15244     *
15245     * @see #setTag(Object)
15246     * @see #getTag(int)
15247     */
15248    @ViewDebug.ExportedProperty
15249    public Object getTag() {
15250        return mTag;
15251    }
15252
15253    /**
15254     * Sets the tag associated with this view. A tag can be used to mark
15255     * a view in its hierarchy and does not have to be unique within the
15256     * hierarchy. Tags can also be used to store data within a view without
15257     * resorting to another data structure.
15258     *
15259     * @param tag an Object to tag the view with
15260     *
15261     * @see #getTag()
15262     * @see #setTag(int, Object)
15263     */
15264    public void setTag(final Object tag) {
15265        mTag = tag;
15266    }
15267
15268    /**
15269     * Returns the tag associated with this view and the specified key.
15270     *
15271     * @param key The key identifying the tag
15272     *
15273     * @return the Object stored in this view as a tag
15274     *
15275     * @see #setTag(int, Object)
15276     * @see #getTag()
15277     */
15278    public Object getTag(int key) {
15279        if (mKeyedTags != null) return mKeyedTags.get(key);
15280        return null;
15281    }
15282
15283    /**
15284     * Sets a tag associated with this view and a key. A tag can be used
15285     * to mark a view in its hierarchy and does not have to be unique within
15286     * the hierarchy. Tags can also be used to store data within a view
15287     * without resorting to another data structure.
15288     *
15289     * The specified key should be an id declared in the resources of the
15290     * application to ensure it is unique (see the <a
15291     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15292     * Keys identified as belonging to
15293     * the Android framework or not associated with any package will cause
15294     * an {@link IllegalArgumentException} to be thrown.
15295     *
15296     * @param key The key identifying the tag
15297     * @param tag An Object to tag the view with
15298     *
15299     * @throws IllegalArgumentException If they specified key is not valid
15300     *
15301     * @see #setTag(Object)
15302     * @see #getTag(int)
15303     */
15304    public void setTag(int key, final Object tag) {
15305        // If the package id is 0x00 or 0x01, it's either an undefined package
15306        // or a framework id
15307        if ((key >>> 24) < 2) {
15308            throw new IllegalArgumentException("The key must be an application-specific "
15309                    + "resource id.");
15310        }
15311
15312        setKeyedTag(key, tag);
15313    }
15314
15315    /**
15316     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15317     * framework id.
15318     *
15319     * @hide
15320     */
15321    public void setTagInternal(int key, Object tag) {
15322        if ((key >>> 24) != 0x1) {
15323            throw new IllegalArgumentException("The key must be a framework-specific "
15324                    + "resource id.");
15325        }
15326
15327        setKeyedTag(key, tag);
15328    }
15329
15330    private void setKeyedTag(int key, Object tag) {
15331        if (mKeyedTags == null) {
15332            mKeyedTags = new SparseArray<Object>();
15333        }
15334
15335        mKeyedTags.put(key, tag);
15336    }
15337
15338    /**
15339     * Prints information about this view in the log output, with the tag
15340     * {@link #VIEW_LOG_TAG}.
15341     *
15342     * @hide
15343     */
15344    public void debug() {
15345        debug(0);
15346    }
15347
15348    /**
15349     * Prints information about this view in the log output, with the tag
15350     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15351     * indentation defined by the <code>depth</code>.
15352     *
15353     * @param depth the indentation level
15354     *
15355     * @hide
15356     */
15357    protected void debug(int depth) {
15358        String output = debugIndent(depth - 1);
15359
15360        output += "+ " + this;
15361        int id = getId();
15362        if (id != -1) {
15363            output += " (id=" + id + ")";
15364        }
15365        Object tag = getTag();
15366        if (tag != null) {
15367            output += " (tag=" + tag + ")";
15368        }
15369        Log.d(VIEW_LOG_TAG, output);
15370
15371        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15372            output = debugIndent(depth) + " FOCUSED";
15373            Log.d(VIEW_LOG_TAG, output);
15374        }
15375
15376        output = debugIndent(depth);
15377        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15378                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15379                + "} ";
15380        Log.d(VIEW_LOG_TAG, output);
15381
15382        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15383                || mPaddingBottom != 0) {
15384            output = debugIndent(depth);
15385            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15386                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15387            Log.d(VIEW_LOG_TAG, output);
15388        }
15389
15390        output = debugIndent(depth);
15391        output += "mMeasureWidth=" + mMeasuredWidth +
15392                " mMeasureHeight=" + mMeasuredHeight;
15393        Log.d(VIEW_LOG_TAG, output);
15394
15395        output = debugIndent(depth);
15396        if (mLayoutParams == null) {
15397            output += "BAD! no layout params";
15398        } else {
15399            output = mLayoutParams.debug(output);
15400        }
15401        Log.d(VIEW_LOG_TAG, output);
15402
15403        output = debugIndent(depth);
15404        output += "flags={";
15405        output += View.printFlags(mViewFlags);
15406        output += "}";
15407        Log.d(VIEW_LOG_TAG, output);
15408
15409        output = debugIndent(depth);
15410        output += "privateFlags={";
15411        output += View.printPrivateFlags(mPrivateFlags);
15412        output += "}";
15413        Log.d(VIEW_LOG_TAG, output);
15414    }
15415
15416    /**
15417     * Creates a string of whitespaces used for indentation.
15418     *
15419     * @param depth the indentation level
15420     * @return a String containing (depth * 2 + 3) * 2 white spaces
15421     *
15422     * @hide
15423     */
15424    protected static String debugIndent(int depth) {
15425        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15426        for (int i = 0; i < (depth * 2) + 3; i++) {
15427            spaces.append(' ').append(' ');
15428        }
15429        return spaces.toString();
15430    }
15431
15432    /**
15433     * <p>Return the offset of the widget's text baseline from the widget's top
15434     * boundary. If this widget does not support baseline alignment, this
15435     * method returns -1. </p>
15436     *
15437     * @return the offset of the baseline within the widget's bounds or -1
15438     *         if baseline alignment is not supported
15439     */
15440    @ViewDebug.ExportedProperty(category = "layout")
15441    public int getBaseline() {
15442        return -1;
15443    }
15444
15445    /**
15446     * Call this when something has changed which has invalidated the
15447     * layout of this view. This will schedule a layout pass of the view
15448     * tree.
15449     */
15450    public void requestLayout() {
15451        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15452        mPrivateFlags |= PFLAG_INVALIDATED;
15453
15454        if (mParent != null && !mParent.isLayoutRequested()) {
15455            mParent.requestLayout();
15456        }
15457    }
15458
15459    /**
15460     * Forces this view to be laid out during the next layout pass.
15461     * This method does not call requestLayout() or forceLayout()
15462     * on the parent.
15463     */
15464    public void forceLayout() {
15465        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15466        mPrivateFlags |= PFLAG_INVALIDATED;
15467    }
15468
15469    /**
15470     * <p>
15471     * This is called to find out how big a view should be. The parent
15472     * supplies constraint information in the width and height parameters.
15473     * </p>
15474     *
15475     * <p>
15476     * The actual measurement work of a view is performed in
15477     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15478     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15479     * </p>
15480     *
15481     *
15482     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15483     *        parent
15484     * @param heightMeasureSpec Vertical space requirements as imposed by the
15485     *        parent
15486     *
15487     * @see #onMeasure(int, int)
15488     */
15489    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15490        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15491                widthMeasureSpec != mOldWidthMeasureSpec ||
15492                heightMeasureSpec != mOldHeightMeasureSpec) {
15493
15494            // first clears the measured dimension flag
15495            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15496
15497            resolveRtlPropertiesIfNeeded();
15498
15499            // measure ourselves, this should set the measured dimension flag back
15500            onMeasure(widthMeasureSpec, heightMeasureSpec);
15501
15502            // flag not set, setMeasuredDimension() was not invoked, we raise
15503            // an exception to warn the developer
15504            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15505                throw new IllegalStateException("onMeasure() did not set the"
15506                        + " measured dimension by calling"
15507                        + " setMeasuredDimension()");
15508            }
15509
15510            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15511        }
15512
15513        mOldWidthMeasureSpec = widthMeasureSpec;
15514        mOldHeightMeasureSpec = heightMeasureSpec;
15515    }
15516
15517    /**
15518     * <p>
15519     * Measure the view and its content to determine the measured width and the
15520     * measured height. This method is invoked by {@link #measure(int, int)} and
15521     * should be overriden by subclasses to provide accurate and efficient
15522     * measurement of their contents.
15523     * </p>
15524     *
15525     * <p>
15526     * <strong>CONTRACT:</strong> When overriding this method, you
15527     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15528     * measured width and height of this view. Failure to do so will trigger an
15529     * <code>IllegalStateException</code>, thrown by
15530     * {@link #measure(int, int)}. Calling the superclass'
15531     * {@link #onMeasure(int, int)} is a valid use.
15532     * </p>
15533     *
15534     * <p>
15535     * The base class implementation of measure defaults to the background size,
15536     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15537     * override {@link #onMeasure(int, int)} to provide better measurements of
15538     * their content.
15539     * </p>
15540     *
15541     * <p>
15542     * If this method is overridden, it is the subclass's responsibility to make
15543     * sure the measured height and width are at least the view's minimum height
15544     * and width ({@link #getSuggestedMinimumHeight()} and
15545     * {@link #getSuggestedMinimumWidth()}).
15546     * </p>
15547     *
15548     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15549     *                         The requirements are encoded with
15550     *                         {@link android.view.View.MeasureSpec}.
15551     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15552     *                         The requirements are encoded with
15553     *                         {@link android.view.View.MeasureSpec}.
15554     *
15555     * @see #getMeasuredWidth()
15556     * @see #getMeasuredHeight()
15557     * @see #setMeasuredDimension(int, int)
15558     * @see #getSuggestedMinimumHeight()
15559     * @see #getSuggestedMinimumWidth()
15560     * @see android.view.View.MeasureSpec#getMode(int)
15561     * @see android.view.View.MeasureSpec#getSize(int)
15562     */
15563    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15564        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15565                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15566    }
15567
15568    /**
15569     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15570     * measured width and measured height. Failing to do so will trigger an
15571     * exception at measurement time.</p>
15572     *
15573     * @param measuredWidth The measured width of this view.  May be a complex
15574     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15575     * {@link #MEASURED_STATE_TOO_SMALL}.
15576     * @param measuredHeight The measured height of this view.  May be a complex
15577     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15578     * {@link #MEASURED_STATE_TOO_SMALL}.
15579     */
15580    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15581        mMeasuredWidth = measuredWidth;
15582        mMeasuredHeight = measuredHeight;
15583
15584        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
15585    }
15586
15587    /**
15588     * Merge two states as returned by {@link #getMeasuredState()}.
15589     * @param curState The current state as returned from a view or the result
15590     * of combining multiple views.
15591     * @param newState The new view state to combine.
15592     * @return Returns a new integer reflecting the combination of the two
15593     * states.
15594     */
15595    public static int combineMeasuredStates(int curState, int newState) {
15596        return curState | newState;
15597    }
15598
15599    /**
15600     * Version of {@link #resolveSizeAndState(int, int, int)}
15601     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15602     */
15603    public static int resolveSize(int size, int measureSpec) {
15604        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15605    }
15606
15607    /**
15608     * Utility to reconcile a desired size and state, with constraints imposed
15609     * by a MeasureSpec.  Will take the desired size, unless a different size
15610     * is imposed by the constraints.  The returned value is a compound integer,
15611     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15612     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15613     * size is smaller than the size the view wants to be.
15614     *
15615     * @param size How big the view wants to be
15616     * @param measureSpec Constraints imposed by the parent
15617     * @return Size information bit mask as defined by
15618     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15619     */
15620    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15621        int result = size;
15622        int specMode = MeasureSpec.getMode(measureSpec);
15623        int specSize =  MeasureSpec.getSize(measureSpec);
15624        switch (specMode) {
15625        case MeasureSpec.UNSPECIFIED:
15626            result = size;
15627            break;
15628        case MeasureSpec.AT_MOST:
15629            if (specSize < size) {
15630                result = specSize | MEASURED_STATE_TOO_SMALL;
15631            } else {
15632                result = size;
15633            }
15634            break;
15635        case MeasureSpec.EXACTLY:
15636            result = specSize;
15637            break;
15638        }
15639        return result | (childMeasuredState&MEASURED_STATE_MASK);
15640    }
15641
15642    /**
15643     * Utility to return a default size. Uses the supplied size if the
15644     * MeasureSpec imposed no constraints. Will get larger if allowed
15645     * by the MeasureSpec.
15646     *
15647     * @param size Default size for this view
15648     * @param measureSpec Constraints imposed by the parent
15649     * @return The size this view should be.
15650     */
15651    public static int getDefaultSize(int size, int measureSpec) {
15652        int result = size;
15653        int specMode = MeasureSpec.getMode(measureSpec);
15654        int specSize = MeasureSpec.getSize(measureSpec);
15655
15656        switch (specMode) {
15657        case MeasureSpec.UNSPECIFIED:
15658            result = size;
15659            break;
15660        case MeasureSpec.AT_MOST:
15661        case MeasureSpec.EXACTLY:
15662            result = specSize;
15663            break;
15664        }
15665        return result;
15666    }
15667
15668    /**
15669     * Returns the suggested minimum height that the view should use. This
15670     * returns the maximum of the view's minimum height
15671     * and the background's minimum height
15672     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15673     * <p>
15674     * When being used in {@link #onMeasure(int, int)}, the caller should still
15675     * ensure the returned height is within the requirements of the parent.
15676     *
15677     * @return The suggested minimum height of the view.
15678     */
15679    protected int getSuggestedMinimumHeight() {
15680        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15681
15682    }
15683
15684    /**
15685     * Returns the suggested minimum width that the view should use. This
15686     * returns the maximum of the view's minimum width)
15687     * and the background's minimum width
15688     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15689     * <p>
15690     * When being used in {@link #onMeasure(int, int)}, the caller should still
15691     * ensure the returned width is within the requirements of the parent.
15692     *
15693     * @return The suggested minimum width of the view.
15694     */
15695    protected int getSuggestedMinimumWidth() {
15696        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15697    }
15698
15699    /**
15700     * Returns the minimum height of the view.
15701     *
15702     * @return the minimum height the view will try to be.
15703     *
15704     * @see #setMinimumHeight(int)
15705     *
15706     * @attr ref android.R.styleable#View_minHeight
15707     */
15708    public int getMinimumHeight() {
15709        return mMinHeight;
15710    }
15711
15712    /**
15713     * Sets the minimum height of the view. It is not guaranteed the view will
15714     * be able to achieve this minimum height (for example, if its parent layout
15715     * constrains it with less available height).
15716     *
15717     * @param minHeight The minimum height the view will try to be.
15718     *
15719     * @see #getMinimumHeight()
15720     *
15721     * @attr ref android.R.styleable#View_minHeight
15722     */
15723    public void setMinimumHeight(int minHeight) {
15724        mMinHeight = minHeight;
15725        requestLayout();
15726    }
15727
15728    /**
15729     * Returns the minimum width of the view.
15730     *
15731     * @return the minimum width the view will try to be.
15732     *
15733     * @see #setMinimumWidth(int)
15734     *
15735     * @attr ref android.R.styleable#View_minWidth
15736     */
15737    public int getMinimumWidth() {
15738        return mMinWidth;
15739    }
15740
15741    /**
15742     * Sets the minimum width of the view. It is not guaranteed the view will
15743     * be able to achieve this minimum width (for example, if its parent layout
15744     * constrains it with less available width).
15745     *
15746     * @param minWidth The minimum width the view will try to be.
15747     *
15748     * @see #getMinimumWidth()
15749     *
15750     * @attr ref android.R.styleable#View_minWidth
15751     */
15752    public void setMinimumWidth(int minWidth) {
15753        mMinWidth = minWidth;
15754        requestLayout();
15755
15756    }
15757
15758    /**
15759     * Get the animation currently associated with this view.
15760     *
15761     * @return The animation that is currently playing or
15762     *         scheduled to play for this view.
15763     */
15764    public Animation getAnimation() {
15765        return mCurrentAnimation;
15766    }
15767
15768    /**
15769     * Start the specified animation now.
15770     *
15771     * @param animation the animation to start now
15772     */
15773    public void startAnimation(Animation animation) {
15774        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15775        setAnimation(animation);
15776        invalidateParentCaches();
15777        invalidate(true);
15778    }
15779
15780    /**
15781     * Cancels any animations for this view.
15782     */
15783    public void clearAnimation() {
15784        if (mCurrentAnimation != null) {
15785            mCurrentAnimation.detach();
15786        }
15787        mCurrentAnimation = null;
15788        invalidateParentIfNeeded();
15789    }
15790
15791    /**
15792     * Sets the next animation to play for this view.
15793     * If you want the animation to play immediately, use
15794     * {@link #startAnimation(android.view.animation.Animation)} instead.
15795     * This method provides allows fine-grained
15796     * control over the start time and invalidation, but you
15797     * must make sure that 1) the animation has a start time set, and
15798     * 2) the view's parent (which controls animations on its children)
15799     * will be invalidated when the animation is supposed to
15800     * start.
15801     *
15802     * @param animation The next animation, or null.
15803     */
15804    public void setAnimation(Animation animation) {
15805        mCurrentAnimation = animation;
15806
15807        if (animation != null) {
15808            // If the screen is off assume the animation start time is now instead of
15809            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15810            // would cause the animation to start when the screen turns back on
15811            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15812                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15813                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15814            }
15815            animation.reset();
15816        }
15817    }
15818
15819    /**
15820     * Invoked by a parent ViewGroup to notify the start of the animation
15821     * currently associated with this view. If you override this method,
15822     * always call super.onAnimationStart();
15823     *
15824     * @see #setAnimation(android.view.animation.Animation)
15825     * @see #getAnimation()
15826     */
15827    protected void onAnimationStart() {
15828        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
15829    }
15830
15831    /**
15832     * Invoked by a parent ViewGroup to notify the end of the animation
15833     * currently associated with this view. If you override this method,
15834     * always call super.onAnimationEnd();
15835     *
15836     * @see #setAnimation(android.view.animation.Animation)
15837     * @see #getAnimation()
15838     */
15839    protected void onAnimationEnd() {
15840        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
15841    }
15842
15843    /**
15844     * Invoked if there is a Transform that involves alpha. Subclass that can
15845     * draw themselves with the specified alpha should return true, and then
15846     * respect that alpha when their onDraw() is called. If this returns false
15847     * then the view may be redirected to draw into an offscreen buffer to
15848     * fulfill the request, which will look fine, but may be slower than if the
15849     * subclass handles it internally. The default implementation returns false.
15850     *
15851     * @param alpha The alpha (0..255) to apply to the view's drawing
15852     * @return true if the view can draw with the specified alpha.
15853     */
15854    protected boolean onSetAlpha(int alpha) {
15855        return false;
15856    }
15857
15858    /**
15859     * This is used by the RootView to perform an optimization when
15860     * the view hierarchy contains one or several SurfaceView.
15861     * SurfaceView is always considered transparent, but its children are not,
15862     * therefore all View objects remove themselves from the global transparent
15863     * region (passed as a parameter to this function).
15864     *
15865     * @param region The transparent region for this ViewAncestor (window).
15866     *
15867     * @return Returns true if the effective visibility of the view at this
15868     * point is opaque, regardless of the transparent region; returns false
15869     * if it is possible for underlying windows to be seen behind the view.
15870     *
15871     * {@hide}
15872     */
15873    public boolean gatherTransparentRegion(Region region) {
15874        final AttachInfo attachInfo = mAttachInfo;
15875        if (region != null && attachInfo != null) {
15876            final int pflags = mPrivateFlags;
15877            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
15878                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15879                // remove it from the transparent region.
15880                final int[] location = attachInfo.mTransparentLocation;
15881                getLocationInWindow(location);
15882                region.op(location[0], location[1], location[0] + mRight - mLeft,
15883                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15884            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15885                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15886                // exists, so we remove the background drawable's non-transparent
15887                // parts from this transparent region.
15888                applyDrawableToTransparentRegion(mBackground, region);
15889            }
15890        }
15891        return true;
15892    }
15893
15894    /**
15895     * Play a sound effect for this view.
15896     *
15897     * <p>The framework will play sound effects for some built in actions, such as
15898     * clicking, but you may wish to play these effects in your widget,
15899     * for instance, for internal navigation.
15900     *
15901     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15902     * {@link #isSoundEffectsEnabled()} is true.
15903     *
15904     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15905     */
15906    public void playSoundEffect(int soundConstant) {
15907        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15908            return;
15909        }
15910        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15911    }
15912
15913    /**
15914     * BZZZTT!!1!
15915     *
15916     * <p>Provide haptic feedback to the user for this view.
15917     *
15918     * <p>The framework will provide haptic feedback for some built in actions,
15919     * such as long presses, but you may wish to provide feedback for your
15920     * own widget.
15921     *
15922     * <p>The feedback will only be performed if
15923     * {@link #isHapticFeedbackEnabled()} is true.
15924     *
15925     * @param feedbackConstant One of the constants defined in
15926     * {@link HapticFeedbackConstants}
15927     */
15928    public boolean performHapticFeedback(int feedbackConstant) {
15929        return performHapticFeedback(feedbackConstant, 0);
15930    }
15931
15932    /**
15933     * BZZZTT!!1!
15934     *
15935     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15936     *
15937     * @param feedbackConstant One of the constants defined in
15938     * {@link HapticFeedbackConstants}
15939     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15940     */
15941    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15942        if (mAttachInfo == null) {
15943            return false;
15944        }
15945        //noinspection SimplifiableIfStatement
15946        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15947                && !isHapticFeedbackEnabled()) {
15948            return false;
15949        }
15950        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15951                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15952    }
15953
15954    /**
15955     * Request that the visibility of the status bar or other screen/window
15956     * decorations be changed.
15957     *
15958     * <p>This method is used to put the over device UI into temporary modes
15959     * where the user's attention is focused more on the application content,
15960     * by dimming or hiding surrounding system affordances.  This is typically
15961     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15962     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15963     * to be placed behind the action bar (and with these flags other system
15964     * affordances) so that smooth transitions between hiding and showing them
15965     * can be done.
15966     *
15967     * <p>Two representative examples of the use of system UI visibility is
15968     * implementing a content browsing application (like a magazine reader)
15969     * and a video playing application.
15970     *
15971     * <p>The first code shows a typical implementation of a View in a content
15972     * browsing application.  In this implementation, the application goes
15973     * into a content-oriented mode by hiding the status bar and action bar,
15974     * and putting the navigation elements into lights out mode.  The user can
15975     * then interact with content while in this mode.  Such an application should
15976     * provide an easy way for the user to toggle out of the mode (such as to
15977     * check information in the status bar or access notifications).  In the
15978     * implementation here, this is done simply by tapping on the content.
15979     *
15980     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15981     *      content}
15982     *
15983     * <p>This second code sample shows a typical implementation of a View
15984     * in a video playing application.  In this situation, while the video is
15985     * playing the application would like to go into a complete full-screen mode,
15986     * to use as much of the display as possible for the video.  When in this state
15987     * the user can not interact with the application; the system intercepts
15988     * touching on the screen to pop the UI out of full screen mode.  See
15989     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15990     *
15991     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15992     *      content}
15993     *
15994     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15995     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15996     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15997     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15998     */
15999    public void setSystemUiVisibility(int visibility) {
16000        if (visibility != mSystemUiVisibility) {
16001            mSystemUiVisibility = visibility;
16002            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16003                mParent.recomputeViewAttributes(this);
16004            }
16005        }
16006    }
16007
16008    /**
16009     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16010     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16011     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16012     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16013     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16014     */
16015    public int getSystemUiVisibility() {
16016        return mSystemUiVisibility;
16017    }
16018
16019    /**
16020     * Returns the current system UI visibility that is currently set for
16021     * the entire window.  This is the combination of the
16022     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16023     * views in the window.
16024     */
16025    public int getWindowSystemUiVisibility() {
16026        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16027    }
16028
16029    /**
16030     * Override to find out when the window's requested system UI visibility
16031     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16032     * This is different from the callbacks recieved through
16033     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16034     * in that this is only telling you about the local request of the window,
16035     * not the actual values applied by the system.
16036     */
16037    public void onWindowSystemUiVisibilityChanged(int visible) {
16038    }
16039
16040    /**
16041     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16042     * the view hierarchy.
16043     */
16044    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16045        onWindowSystemUiVisibilityChanged(visible);
16046    }
16047
16048    /**
16049     * Set a listener to receive callbacks when the visibility of the system bar changes.
16050     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16051     */
16052    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16053        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16054        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16055            mParent.recomputeViewAttributes(this);
16056        }
16057    }
16058
16059    /**
16060     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16061     * the view hierarchy.
16062     */
16063    public void dispatchSystemUiVisibilityChanged(int visibility) {
16064        ListenerInfo li = mListenerInfo;
16065        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16066            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16067                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16068        }
16069    }
16070
16071    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16072        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16073        if (val != mSystemUiVisibility) {
16074            setSystemUiVisibility(val);
16075            return true;
16076        }
16077        return false;
16078    }
16079
16080    /** @hide */
16081    public void setDisabledSystemUiVisibility(int flags) {
16082        if (mAttachInfo != null) {
16083            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16084                mAttachInfo.mDisabledSystemUiVisibility = flags;
16085                if (mParent != null) {
16086                    mParent.recomputeViewAttributes(this);
16087                }
16088            }
16089        }
16090    }
16091
16092    /**
16093     * Creates an image that the system displays during the drag and drop
16094     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16095     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16096     * appearance as the given View. The default also positions the center of the drag shadow
16097     * directly under the touch point. If no View is provided (the constructor with no parameters
16098     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16099     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16100     * default is an invisible drag shadow.
16101     * <p>
16102     * You are not required to use the View you provide to the constructor as the basis of the
16103     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16104     * anything you want as the drag shadow.
16105     * </p>
16106     * <p>
16107     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16108     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16109     *  size and position of the drag shadow. It uses this data to construct a
16110     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16111     *  so that your application can draw the shadow image in the Canvas.
16112     * </p>
16113     *
16114     * <div class="special reference">
16115     * <h3>Developer Guides</h3>
16116     * <p>For a guide to implementing drag and drop features, read the
16117     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16118     * </div>
16119     */
16120    public static class DragShadowBuilder {
16121        private final WeakReference<View> mView;
16122
16123        /**
16124         * Constructs a shadow image builder based on a View. By default, the resulting drag
16125         * shadow will have the same appearance and dimensions as the View, with the touch point
16126         * over the center of the View.
16127         * @param view A View. Any View in scope can be used.
16128         */
16129        public DragShadowBuilder(View view) {
16130            mView = new WeakReference<View>(view);
16131        }
16132
16133        /**
16134         * Construct a shadow builder object with no associated View.  This
16135         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16136         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16137         * to supply the drag shadow's dimensions and appearance without
16138         * reference to any View object. If they are not overridden, then the result is an
16139         * invisible drag shadow.
16140         */
16141        public DragShadowBuilder() {
16142            mView = new WeakReference<View>(null);
16143        }
16144
16145        /**
16146         * Returns the View object that had been passed to the
16147         * {@link #View.DragShadowBuilder(View)}
16148         * constructor.  If that View parameter was {@code null} or if the
16149         * {@link #View.DragShadowBuilder()}
16150         * constructor was used to instantiate the builder object, this method will return
16151         * null.
16152         *
16153         * @return The View object associate with this builder object.
16154         */
16155        @SuppressWarnings({"JavadocReference"})
16156        final public View getView() {
16157            return mView.get();
16158        }
16159
16160        /**
16161         * Provides the metrics for the shadow image. These include the dimensions of
16162         * the shadow image, and the point within that shadow that should
16163         * be centered under the touch location while dragging.
16164         * <p>
16165         * The default implementation sets the dimensions of the shadow to be the
16166         * same as the dimensions of the View itself and centers the shadow under
16167         * the touch point.
16168         * </p>
16169         *
16170         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16171         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16172         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16173         * image.
16174         *
16175         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16176         * shadow image that should be underneath the touch point during the drag and drop
16177         * operation. Your application must set {@link android.graphics.Point#x} to the
16178         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16179         */
16180        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16181            final View view = mView.get();
16182            if (view != null) {
16183                shadowSize.set(view.getWidth(), view.getHeight());
16184                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16185            } else {
16186                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16187            }
16188        }
16189
16190        /**
16191         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16192         * based on the dimensions it received from the
16193         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16194         *
16195         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16196         */
16197        public void onDrawShadow(Canvas canvas) {
16198            final View view = mView.get();
16199            if (view != null) {
16200                view.draw(canvas);
16201            } else {
16202                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16203            }
16204        }
16205    }
16206
16207    /**
16208     * Starts a drag and drop operation. When your application calls this method, it passes a
16209     * {@link android.view.View.DragShadowBuilder} object to the system. The
16210     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16211     * to get metrics for the drag shadow, and then calls the object's
16212     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16213     * <p>
16214     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16215     *  drag events to all the View objects in your application that are currently visible. It does
16216     *  this either by calling the View object's drag listener (an implementation of
16217     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16218     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16219     *  Both are passed a {@link android.view.DragEvent} object that has a
16220     *  {@link android.view.DragEvent#getAction()} value of
16221     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16222     * </p>
16223     * <p>
16224     * Your application can invoke startDrag() on any attached View object. The View object does not
16225     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16226     * be related to the View the user selected for dragging.
16227     * </p>
16228     * @param data A {@link android.content.ClipData} object pointing to the data to be
16229     * transferred by the drag and drop operation.
16230     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16231     * drag shadow.
16232     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16233     * drop operation. This Object is put into every DragEvent object sent by the system during the
16234     * current drag.
16235     * <p>
16236     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16237     * to the target Views. For example, it can contain flags that differentiate between a
16238     * a copy operation and a move operation.
16239     * </p>
16240     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16241     * so the parameter should be set to 0.
16242     * @return {@code true} if the method completes successfully, or
16243     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16244     * do a drag, and so no drag operation is in progress.
16245     */
16246    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16247            Object myLocalState, int flags) {
16248        if (ViewDebug.DEBUG_DRAG) {
16249            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16250        }
16251        boolean okay = false;
16252
16253        Point shadowSize = new Point();
16254        Point shadowTouchPoint = new Point();
16255        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16256
16257        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16258                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16259            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16260        }
16261
16262        if (ViewDebug.DEBUG_DRAG) {
16263            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16264                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16265        }
16266        Surface surface = new Surface();
16267        try {
16268            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16269                    flags, shadowSize.x, shadowSize.y, surface);
16270            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16271                    + " surface=" + surface);
16272            if (token != null) {
16273                Canvas canvas = surface.lockCanvas(null);
16274                try {
16275                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16276                    shadowBuilder.onDrawShadow(canvas);
16277                } finally {
16278                    surface.unlockCanvasAndPost(canvas);
16279                }
16280
16281                final ViewRootImpl root = getViewRootImpl();
16282
16283                // Cache the local state object for delivery with DragEvents
16284                root.setLocalDragState(myLocalState);
16285
16286                // repurpose 'shadowSize' for the last touch point
16287                root.getLastTouchPoint(shadowSize);
16288
16289                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16290                        shadowSize.x, shadowSize.y,
16291                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16292                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16293
16294                // Off and running!  Release our local surface instance; the drag
16295                // shadow surface is now managed by the system process.
16296                surface.release();
16297            }
16298        } catch (Exception e) {
16299            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16300            surface.destroy();
16301        }
16302
16303        return okay;
16304    }
16305
16306    /**
16307     * Handles drag events sent by the system following a call to
16308     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16309     *<p>
16310     * When the system calls this method, it passes a
16311     * {@link android.view.DragEvent} object. A call to
16312     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16313     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16314     * operation.
16315     * @param event The {@link android.view.DragEvent} sent by the system.
16316     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16317     * in DragEvent, indicating the type of drag event represented by this object.
16318     * @return {@code true} if the method was successful, otherwise {@code false}.
16319     * <p>
16320     *  The method should return {@code true} in response to an action type of
16321     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16322     *  operation.
16323     * </p>
16324     * <p>
16325     *  The method should also return {@code true} in response to an action type of
16326     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16327     *  {@code false} if it didn't.
16328     * </p>
16329     */
16330    public boolean onDragEvent(DragEvent event) {
16331        return false;
16332    }
16333
16334    /**
16335     * Detects if this View is enabled and has a drag event listener.
16336     * If both are true, then it calls the drag event listener with the
16337     * {@link android.view.DragEvent} it received. If the drag event listener returns
16338     * {@code true}, then dispatchDragEvent() returns {@code true}.
16339     * <p>
16340     * For all other cases, the method calls the
16341     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16342     * method and returns its result.
16343     * </p>
16344     * <p>
16345     * This ensures that a drag event is always consumed, even if the View does not have a drag
16346     * event listener. However, if the View has a listener and the listener returns true, then
16347     * onDragEvent() is not called.
16348     * </p>
16349     */
16350    public boolean dispatchDragEvent(DragEvent event) {
16351        //noinspection SimplifiableIfStatement
16352        ListenerInfo li = mListenerInfo;
16353        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16354                && li.mOnDragListener.onDrag(this, event)) {
16355            return true;
16356        }
16357        return onDragEvent(event);
16358    }
16359
16360    boolean canAcceptDrag() {
16361        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16362    }
16363
16364    /**
16365     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16366     * it is ever exposed at all.
16367     * @hide
16368     */
16369    public void onCloseSystemDialogs(String reason) {
16370    }
16371
16372    /**
16373     * Given a Drawable whose bounds have been set to draw into this view,
16374     * update a Region being computed for
16375     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16376     * that any non-transparent parts of the Drawable are removed from the
16377     * given transparent region.
16378     *
16379     * @param dr The Drawable whose transparency is to be applied to the region.
16380     * @param region A Region holding the current transparency information,
16381     * where any parts of the region that are set are considered to be
16382     * transparent.  On return, this region will be modified to have the
16383     * transparency information reduced by the corresponding parts of the
16384     * Drawable that are not transparent.
16385     * {@hide}
16386     */
16387    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16388        if (DBG) {
16389            Log.i("View", "Getting transparent region for: " + this);
16390        }
16391        final Region r = dr.getTransparentRegion();
16392        final Rect db = dr.getBounds();
16393        final AttachInfo attachInfo = mAttachInfo;
16394        if (r != null && attachInfo != null) {
16395            final int w = getRight()-getLeft();
16396            final int h = getBottom()-getTop();
16397            if (db.left > 0) {
16398                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16399                r.op(0, 0, db.left, h, Region.Op.UNION);
16400            }
16401            if (db.right < w) {
16402                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16403                r.op(db.right, 0, w, h, Region.Op.UNION);
16404            }
16405            if (db.top > 0) {
16406                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16407                r.op(0, 0, w, db.top, Region.Op.UNION);
16408            }
16409            if (db.bottom < h) {
16410                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16411                r.op(0, db.bottom, w, h, Region.Op.UNION);
16412            }
16413            final int[] location = attachInfo.mTransparentLocation;
16414            getLocationInWindow(location);
16415            r.translate(location[0], location[1]);
16416            region.op(r, Region.Op.INTERSECT);
16417        } else {
16418            region.op(db, Region.Op.DIFFERENCE);
16419        }
16420    }
16421
16422    private void checkForLongClick(int delayOffset) {
16423        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16424            mHasPerformedLongPress = false;
16425
16426            if (mPendingCheckForLongPress == null) {
16427                mPendingCheckForLongPress = new CheckForLongPress();
16428            }
16429            mPendingCheckForLongPress.rememberWindowAttachCount();
16430            postDelayed(mPendingCheckForLongPress,
16431                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16432        }
16433    }
16434
16435    /**
16436     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16437     * LayoutInflater} class, which provides a full range of options for view inflation.
16438     *
16439     * @param context The Context object for your activity or application.
16440     * @param resource The resource ID to inflate
16441     * @param root A view group that will be the parent.  Used to properly inflate the
16442     * layout_* parameters.
16443     * @see LayoutInflater
16444     */
16445    public static View inflate(Context context, int resource, ViewGroup root) {
16446        LayoutInflater factory = LayoutInflater.from(context);
16447        return factory.inflate(resource, root);
16448    }
16449
16450    /**
16451     * Scroll the view with standard behavior for scrolling beyond the normal
16452     * content boundaries. Views that call this method should override
16453     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16454     * results of an over-scroll operation.
16455     *
16456     * Views can use this method to handle any touch or fling-based scrolling.
16457     *
16458     * @param deltaX Change in X in pixels
16459     * @param deltaY Change in Y in pixels
16460     * @param scrollX Current X scroll value in pixels before applying deltaX
16461     * @param scrollY Current Y scroll value in pixels before applying deltaY
16462     * @param scrollRangeX Maximum content scroll range along the X axis
16463     * @param scrollRangeY Maximum content scroll range along the Y axis
16464     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16465     *          along the X axis.
16466     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16467     *          along the Y axis.
16468     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16469     * @return true if scrolling was clamped to an over-scroll boundary along either
16470     *          axis, false otherwise.
16471     */
16472    @SuppressWarnings({"UnusedParameters"})
16473    protected boolean overScrollBy(int deltaX, int deltaY,
16474            int scrollX, int scrollY,
16475            int scrollRangeX, int scrollRangeY,
16476            int maxOverScrollX, int maxOverScrollY,
16477            boolean isTouchEvent) {
16478        final int overScrollMode = mOverScrollMode;
16479        final boolean canScrollHorizontal =
16480                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16481        final boolean canScrollVertical =
16482                computeVerticalScrollRange() > computeVerticalScrollExtent();
16483        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16484                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16485        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16486                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16487
16488        int newScrollX = scrollX + deltaX;
16489        if (!overScrollHorizontal) {
16490            maxOverScrollX = 0;
16491        }
16492
16493        int newScrollY = scrollY + deltaY;
16494        if (!overScrollVertical) {
16495            maxOverScrollY = 0;
16496        }
16497
16498        // Clamp values if at the limits and record
16499        final int left = -maxOverScrollX;
16500        final int right = maxOverScrollX + scrollRangeX;
16501        final int top = -maxOverScrollY;
16502        final int bottom = maxOverScrollY + scrollRangeY;
16503
16504        boolean clampedX = false;
16505        if (newScrollX > right) {
16506            newScrollX = right;
16507            clampedX = true;
16508        } else if (newScrollX < left) {
16509            newScrollX = left;
16510            clampedX = true;
16511        }
16512
16513        boolean clampedY = false;
16514        if (newScrollY > bottom) {
16515            newScrollY = bottom;
16516            clampedY = true;
16517        } else if (newScrollY < top) {
16518            newScrollY = top;
16519            clampedY = true;
16520        }
16521
16522        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16523
16524        return clampedX || clampedY;
16525    }
16526
16527    /**
16528     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16529     * respond to the results of an over-scroll operation.
16530     *
16531     * @param scrollX New X scroll value in pixels
16532     * @param scrollY New Y scroll value in pixels
16533     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16534     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16535     */
16536    protected void onOverScrolled(int scrollX, int scrollY,
16537            boolean clampedX, boolean clampedY) {
16538        // Intentionally empty.
16539    }
16540
16541    /**
16542     * Returns the over-scroll mode for this view. The result will be
16543     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16544     * (allow over-scrolling only if the view content is larger than the container),
16545     * or {@link #OVER_SCROLL_NEVER}.
16546     *
16547     * @return This view's over-scroll mode.
16548     */
16549    public int getOverScrollMode() {
16550        return mOverScrollMode;
16551    }
16552
16553    /**
16554     * Set the over-scroll mode for this view. Valid over-scroll modes are
16555     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16556     * (allow over-scrolling only if the view content is larger than the container),
16557     * or {@link #OVER_SCROLL_NEVER}.
16558     *
16559     * Setting the over-scroll mode of a view will have an effect only if the
16560     * view is capable of scrolling.
16561     *
16562     * @param overScrollMode The new over-scroll mode for this view.
16563     */
16564    public void setOverScrollMode(int overScrollMode) {
16565        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16566                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16567                overScrollMode != OVER_SCROLL_NEVER) {
16568            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16569        }
16570        mOverScrollMode = overScrollMode;
16571    }
16572
16573    /**
16574     * Gets a scale factor that determines the distance the view should scroll
16575     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16576     * @return The vertical scroll scale factor.
16577     * @hide
16578     */
16579    protected float getVerticalScrollFactor() {
16580        if (mVerticalScrollFactor == 0) {
16581            TypedValue outValue = new TypedValue();
16582            if (!mContext.getTheme().resolveAttribute(
16583                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16584                throw new IllegalStateException(
16585                        "Expected theme to define listPreferredItemHeight.");
16586            }
16587            mVerticalScrollFactor = outValue.getDimension(
16588                    mContext.getResources().getDisplayMetrics());
16589        }
16590        return mVerticalScrollFactor;
16591    }
16592
16593    /**
16594     * Gets a scale factor that determines the distance the view should scroll
16595     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16596     * @return The horizontal scroll scale factor.
16597     * @hide
16598     */
16599    protected float getHorizontalScrollFactor() {
16600        // TODO: Should use something else.
16601        return getVerticalScrollFactor();
16602    }
16603
16604    /**
16605     * Return the value specifying the text direction or policy that was set with
16606     * {@link #setTextDirection(int)}.
16607     *
16608     * @return the defined text direction. It can be one of:
16609     *
16610     * {@link #TEXT_DIRECTION_INHERIT},
16611     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16612     * {@link #TEXT_DIRECTION_ANY_RTL},
16613     * {@link #TEXT_DIRECTION_LTR},
16614     * {@link #TEXT_DIRECTION_RTL},
16615     * {@link #TEXT_DIRECTION_LOCALE}
16616     *
16617     * @hide
16618     */
16619    @ViewDebug.ExportedProperty(category = "text", mapping = {
16620            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16621            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16622            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16623            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16624            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16625            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16626    })
16627    public int getRawTextDirection() {
16628        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
16629    }
16630
16631    /**
16632     * Set the text direction.
16633     *
16634     * @param textDirection the direction to set. Should be one of:
16635     *
16636     * {@link #TEXT_DIRECTION_INHERIT},
16637     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16638     * {@link #TEXT_DIRECTION_ANY_RTL},
16639     * {@link #TEXT_DIRECTION_LTR},
16640     * {@link #TEXT_DIRECTION_RTL},
16641     * {@link #TEXT_DIRECTION_LOCALE}
16642     *
16643     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
16644     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
16645     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
16646     */
16647    public void setTextDirection(int textDirection) {
16648        if (getRawTextDirection() != textDirection) {
16649            // Reset the current text direction and the resolved one
16650            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
16651            resetResolvedTextDirection();
16652            // Set the new text direction
16653            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
16654            // Do resolution
16655            resolveTextDirection();
16656            // Notify change
16657            onRtlPropertiesChanged(getLayoutDirection());
16658            // Refresh
16659            requestLayout();
16660            invalidate(true);
16661        }
16662    }
16663
16664    /**
16665     * Return the resolved text direction.
16666     *
16667     * @return the resolved text direction. Returns one of:
16668     *
16669     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16670     * {@link #TEXT_DIRECTION_ANY_RTL},
16671     * {@link #TEXT_DIRECTION_LTR},
16672     * {@link #TEXT_DIRECTION_RTL},
16673     * {@link #TEXT_DIRECTION_LOCALE}
16674     */
16675    public int getTextDirection() {
16676        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16677    }
16678
16679    /**
16680     * Resolve the text direction.
16681     *
16682     * @return true if resolution has been done, false otherwise.
16683     *
16684     * @hide
16685     */
16686    public boolean resolveTextDirection() {
16687        // Reset any previous text direction resolution
16688        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
16689
16690        if (hasRtlSupport()) {
16691            // Set resolved text direction flag depending on text direction flag
16692            final int textDirection = getRawTextDirection();
16693            switch(textDirection) {
16694                case TEXT_DIRECTION_INHERIT:
16695                    if (!canResolveTextDirection()) {
16696                        // We cannot do the resolution if there is no parent, so use the default one
16697                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16698                        // Resolution will need to happen again later
16699                        return false;
16700                    }
16701
16702                    View parent = ((View) mParent);
16703                    // Parent has not yet resolved, so we still return the default
16704                    if (!parent.isTextDirectionResolved()) {
16705                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16706                        // Resolution will need to happen again later
16707                        return false;
16708                    }
16709
16710                    // Set current resolved direction to the same value as the parent's one
16711                    final int parentResolvedDirection = parent.getTextDirection();
16712                    switch (parentResolvedDirection) {
16713                        case TEXT_DIRECTION_FIRST_STRONG:
16714                        case TEXT_DIRECTION_ANY_RTL:
16715                        case TEXT_DIRECTION_LTR:
16716                        case TEXT_DIRECTION_RTL:
16717                        case TEXT_DIRECTION_LOCALE:
16718                            mPrivateFlags2 |=
16719                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16720                            break;
16721                        default:
16722                            // Default resolved direction is "first strong" heuristic
16723                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16724                    }
16725                    break;
16726                case TEXT_DIRECTION_FIRST_STRONG:
16727                case TEXT_DIRECTION_ANY_RTL:
16728                case TEXT_DIRECTION_LTR:
16729                case TEXT_DIRECTION_RTL:
16730                case TEXT_DIRECTION_LOCALE:
16731                    // Resolved direction is the same as text direction
16732                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16733                    break;
16734                default:
16735                    // Default resolved direction is "first strong" heuristic
16736                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16737            }
16738        } else {
16739            // Default resolved direction is "first strong" heuristic
16740            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16741        }
16742
16743        // Set to resolved
16744        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
16745        return true;
16746    }
16747
16748    /**
16749     * Check if text direction resolution can be done.
16750     *
16751     * @return true if text direction resolution can be done otherwise return false.
16752     */
16753    private boolean canResolveTextDirection() {
16754        switch (getRawTextDirection()) {
16755            case TEXT_DIRECTION_INHERIT:
16756                return (mParent != null) && (mParent instanceof View) &&
16757                       ((View) mParent).canResolveTextDirection();
16758            default:
16759                return true;
16760        }
16761    }
16762
16763    /**
16764     * Reset resolved text direction. Text direction will be resolved during a call to
16765     * {@link #onMeasure(int, int)}.
16766     *
16767     * @hide
16768     */
16769    public void resetResolvedTextDirection() {
16770        // Reset any previous text direction resolution
16771        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
16772        // Set to default value
16773        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16774    }
16775
16776    /**
16777     * @return true if text direction is inherited.
16778     *
16779     * @hide
16780     */
16781    public boolean isTextDirectionInherited() {
16782        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
16783    }
16784
16785    /**
16786     * @return true if text direction is resolved.
16787     */
16788    private boolean isTextDirectionResolved() {
16789        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
16790    }
16791
16792    /**
16793     * Return the value specifying the text alignment or policy that was set with
16794     * {@link #setTextAlignment(int)}.
16795     *
16796     * @return the defined text alignment. It can be one of:
16797     *
16798     * {@link #TEXT_ALIGNMENT_INHERIT},
16799     * {@link #TEXT_ALIGNMENT_GRAVITY},
16800     * {@link #TEXT_ALIGNMENT_CENTER},
16801     * {@link #TEXT_ALIGNMENT_TEXT_START},
16802     * {@link #TEXT_ALIGNMENT_TEXT_END},
16803     * {@link #TEXT_ALIGNMENT_VIEW_START},
16804     * {@link #TEXT_ALIGNMENT_VIEW_END}
16805     *
16806     * @hide
16807     */
16808    @ViewDebug.ExportedProperty(category = "text", mapping = {
16809            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16810            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16811            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16812            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16813            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16814            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16815            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16816    })
16817    public int getRawTextAlignment() {
16818        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
16819    }
16820
16821    /**
16822     * Set the text alignment.
16823     *
16824     * @param textAlignment The text alignment to set. Should be one of
16825     *
16826     * {@link #TEXT_ALIGNMENT_INHERIT},
16827     * {@link #TEXT_ALIGNMENT_GRAVITY},
16828     * {@link #TEXT_ALIGNMENT_CENTER},
16829     * {@link #TEXT_ALIGNMENT_TEXT_START},
16830     * {@link #TEXT_ALIGNMENT_TEXT_END},
16831     * {@link #TEXT_ALIGNMENT_VIEW_START},
16832     * {@link #TEXT_ALIGNMENT_VIEW_END}
16833     *
16834     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
16835     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
16836     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
16837     *
16838     * @attr ref android.R.styleable#View_textAlignment
16839     */
16840    public void setTextAlignment(int textAlignment) {
16841        if (textAlignment != getRawTextAlignment()) {
16842            // Reset the current and resolved text alignment
16843            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
16844            resetResolvedTextAlignment();
16845            // Set the new text alignment
16846            mPrivateFlags2 |=
16847                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
16848            // Do resolution
16849            resolveTextAlignment();
16850            // Notify change
16851            onRtlPropertiesChanged(getLayoutDirection());
16852            // Refresh
16853            requestLayout();
16854            invalidate(true);
16855        }
16856    }
16857
16858    /**
16859     * Return the resolved text alignment.
16860     *
16861     * @return the resolved text alignment. Returns one of:
16862     *
16863     * {@link #TEXT_ALIGNMENT_GRAVITY},
16864     * {@link #TEXT_ALIGNMENT_CENTER},
16865     * {@link #TEXT_ALIGNMENT_TEXT_START},
16866     * {@link #TEXT_ALIGNMENT_TEXT_END},
16867     * {@link #TEXT_ALIGNMENT_VIEW_START},
16868     * {@link #TEXT_ALIGNMENT_VIEW_END}
16869     */
16870    @ViewDebug.ExportedProperty(category = "text", mapping = {
16871            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16872            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16873            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16874            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16875            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16876            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16877            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16878    })
16879    public int getTextAlignment() {
16880        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
16881                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16882    }
16883
16884    /**
16885     * Resolve the text alignment.
16886     *
16887     * @return true if resolution has been done, false otherwise.
16888     *
16889     * @hide
16890     */
16891    public boolean resolveTextAlignment() {
16892        // Reset any previous text alignment resolution
16893        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
16894
16895        if (hasRtlSupport()) {
16896            // Set resolved text alignment flag depending on text alignment flag
16897            final int textAlignment = getRawTextAlignment();
16898            switch (textAlignment) {
16899                case TEXT_ALIGNMENT_INHERIT:
16900                    // Check if we can resolve the text alignment
16901                    if (!canResolveTextAlignment()) {
16902                        // We cannot do the resolution if there is no parent so use the default
16903                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16904                        // Resolution will need to happen again later
16905                        return false;
16906                    }
16907                    View parent = (View) mParent;
16908
16909                    // Parent has not yet resolved, so we still return the default
16910                    if (!parent.isTextAlignmentResolved()) {
16911                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16912                        // Resolution will need to happen again later
16913                        return false;
16914                    }
16915
16916                    final int parentResolvedTextAlignment = parent.getTextAlignment();
16917                    switch (parentResolvedTextAlignment) {
16918                        case TEXT_ALIGNMENT_GRAVITY:
16919                        case TEXT_ALIGNMENT_TEXT_START:
16920                        case TEXT_ALIGNMENT_TEXT_END:
16921                        case TEXT_ALIGNMENT_CENTER:
16922                        case TEXT_ALIGNMENT_VIEW_START:
16923                        case TEXT_ALIGNMENT_VIEW_END:
16924                            // Resolved text alignment is the same as the parent resolved
16925                            // text alignment
16926                            mPrivateFlags2 |=
16927                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16928                            break;
16929                        default:
16930                            // Use default resolved text alignment
16931                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16932                    }
16933                    break;
16934                case TEXT_ALIGNMENT_GRAVITY:
16935                case TEXT_ALIGNMENT_TEXT_START:
16936                case TEXT_ALIGNMENT_TEXT_END:
16937                case TEXT_ALIGNMENT_CENTER:
16938                case TEXT_ALIGNMENT_VIEW_START:
16939                case TEXT_ALIGNMENT_VIEW_END:
16940                    // Resolved text alignment is the same as text alignment
16941                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16942                    break;
16943                default:
16944                    // Use default resolved text alignment
16945                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16946            }
16947        } else {
16948            // Use default resolved text alignment
16949            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16950        }
16951
16952        // Set the resolved
16953        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
16954        return true;
16955    }
16956
16957    /**
16958     * Check if text alignment resolution can be done.
16959     *
16960     * @return true if text alignment resolution can be done otherwise return false.
16961     */
16962    private boolean canResolveTextAlignment() {
16963        switch (getRawTextAlignment()) {
16964            case TEXT_DIRECTION_INHERIT:
16965                return (mParent != null) && (mParent instanceof View) &&
16966                       ((View) mParent).canResolveTextAlignment();
16967            default:
16968                return true;
16969        }
16970    }
16971
16972    /**
16973     * Reset resolved text alignment. Text alignment will be resolved during a call to
16974     * {@link #onMeasure(int, int)}.
16975     *
16976     * @hide
16977     */
16978    public void resetResolvedTextAlignment() {
16979        // Reset any previous text alignment resolution
16980        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
16981        // Set to default
16982        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16983    }
16984
16985    /**
16986     * @return true if text alignment is inherited.
16987     *
16988     * @hide
16989     */
16990    public boolean isTextAlignmentInherited() {
16991        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
16992    }
16993
16994    /**
16995     * @return true if text alignment is resolved.
16996     */
16997    private boolean isTextAlignmentResolved() {
16998        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
16999    }
17000
17001    /**
17002     * Generate a value suitable for use in {@link #setId(int)}.
17003     * This value will not collide with ID values generated at build time by aapt for R.id.
17004     *
17005     * @return a generated ID value
17006     */
17007    public static int generateViewId() {
17008        for (;;) {
17009            final int result = sNextGeneratedId.get();
17010            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17011            int newValue = result + 1;
17012            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17013            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17014                return result;
17015            }
17016        }
17017    }
17018
17019    //
17020    // Properties
17021    //
17022    /**
17023     * A Property wrapper around the <code>alpha</code> functionality handled by the
17024     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17025     */
17026    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17027        @Override
17028        public void setValue(View object, float value) {
17029            object.setAlpha(value);
17030        }
17031
17032        @Override
17033        public Float get(View object) {
17034            return object.getAlpha();
17035        }
17036    };
17037
17038    /**
17039     * A Property wrapper around the <code>translationX</code> functionality handled by the
17040     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17041     */
17042    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17043        @Override
17044        public void setValue(View object, float value) {
17045            object.setTranslationX(value);
17046        }
17047
17048                @Override
17049        public Float get(View object) {
17050            return object.getTranslationX();
17051        }
17052    };
17053
17054    /**
17055     * A Property wrapper around the <code>translationY</code> functionality handled by the
17056     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17057     */
17058    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17059        @Override
17060        public void setValue(View object, float value) {
17061            object.setTranslationY(value);
17062        }
17063
17064        @Override
17065        public Float get(View object) {
17066            return object.getTranslationY();
17067        }
17068    };
17069
17070    /**
17071     * A Property wrapper around the <code>x</code> functionality handled by the
17072     * {@link View#setX(float)} and {@link View#getX()} methods.
17073     */
17074    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17075        @Override
17076        public void setValue(View object, float value) {
17077            object.setX(value);
17078        }
17079
17080        @Override
17081        public Float get(View object) {
17082            return object.getX();
17083        }
17084    };
17085
17086    /**
17087     * A Property wrapper around the <code>y</code> functionality handled by the
17088     * {@link View#setY(float)} and {@link View#getY()} methods.
17089     */
17090    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17091        @Override
17092        public void setValue(View object, float value) {
17093            object.setY(value);
17094        }
17095
17096        @Override
17097        public Float get(View object) {
17098            return object.getY();
17099        }
17100    };
17101
17102    /**
17103     * A Property wrapper around the <code>rotation</code> functionality handled by the
17104     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17105     */
17106    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17107        @Override
17108        public void setValue(View object, float value) {
17109            object.setRotation(value);
17110        }
17111
17112        @Override
17113        public Float get(View object) {
17114            return object.getRotation();
17115        }
17116    };
17117
17118    /**
17119     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17120     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17121     */
17122    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17123        @Override
17124        public void setValue(View object, float value) {
17125            object.setRotationX(value);
17126        }
17127
17128        @Override
17129        public Float get(View object) {
17130            return object.getRotationX();
17131        }
17132    };
17133
17134    /**
17135     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17136     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17137     */
17138    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17139        @Override
17140        public void setValue(View object, float value) {
17141            object.setRotationY(value);
17142        }
17143
17144        @Override
17145        public Float get(View object) {
17146            return object.getRotationY();
17147        }
17148    };
17149
17150    /**
17151     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17152     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17153     */
17154    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17155        @Override
17156        public void setValue(View object, float value) {
17157            object.setScaleX(value);
17158        }
17159
17160        @Override
17161        public Float get(View object) {
17162            return object.getScaleX();
17163        }
17164    };
17165
17166    /**
17167     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17168     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17169     */
17170    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17171        @Override
17172        public void setValue(View object, float value) {
17173            object.setScaleY(value);
17174        }
17175
17176        @Override
17177        public Float get(View object) {
17178            return object.getScaleY();
17179        }
17180    };
17181
17182    /**
17183     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17184     * Each MeasureSpec represents a requirement for either the width or the height.
17185     * A MeasureSpec is comprised of a size and a mode. There are three possible
17186     * modes:
17187     * <dl>
17188     * <dt>UNSPECIFIED</dt>
17189     * <dd>
17190     * The parent has not imposed any constraint on the child. It can be whatever size
17191     * it wants.
17192     * </dd>
17193     *
17194     * <dt>EXACTLY</dt>
17195     * <dd>
17196     * The parent has determined an exact size for the child. The child is going to be
17197     * given those bounds regardless of how big it wants to be.
17198     * </dd>
17199     *
17200     * <dt>AT_MOST</dt>
17201     * <dd>
17202     * The child can be as large as it wants up to the specified size.
17203     * </dd>
17204     * </dl>
17205     *
17206     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17207     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17208     */
17209    public static class MeasureSpec {
17210        private static final int MODE_SHIFT = 30;
17211        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17212
17213        /**
17214         * Measure specification mode: The parent has not imposed any constraint
17215         * on the child. It can be whatever size it wants.
17216         */
17217        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17218
17219        /**
17220         * Measure specification mode: The parent has determined an exact size
17221         * for the child. The child is going to be given those bounds regardless
17222         * of how big it wants to be.
17223         */
17224        public static final int EXACTLY     = 1 << MODE_SHIFT;
17225
17226        /**
17227         * Measure specification mode: The child can be as large as it wants up
17228         * to the specified size.
17229         */
17230        public static final int AT_MOST     = 2 << MODE_SHIFT;
17231
17232        /**
17233         * Creates a measure specification based on the supplied size and mode.
17234         *
17235         * The mode must always be one of the following:
17236         * <ul>
17237         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17238         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17239         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17240         * </ul>
17241         *
17242         * @param size the size of the measure specification
17243         * @param mode the mode of the measure specification
17244         * @return the measure specification based on size and mode
17245         */
17246        public static int makeMeasureSpec(int size, int mode) {
17247            return size + mode;
17248        }
17249
17250        /**
17251         * Extracts the mode from the supplied measure specification.
17252         *
17253         * @param measureSpec the measure specification to extract the mode from
17254         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17255         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17256         *         {@link android.view.View.MeasureSpec#EXACTLY}
17257         */
17258        public static int getMode(int measureSpec) {
17259            return (measureSpec & MODE_MASK);
17260        }
17261
17262        /**
17263         * Extracts the size from the supplied measure specification.
17264         *
17265         * @param measureSpec the measure specification to extract the size from
17266         * @return the size in pixels defined in the supplied measure specification
17267         */
17268        public static int getSize(int measureSpec) {
17269            return (measureSpec & ~MODE_MASK);
17270        }
17271
17272        /**
17273         * Returns a String representation of the specified measure
17274         * specification.
17275         *
17276         * @param measureSpec the measure specification to convert to a String
17277         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17278         */
17279        public static String toString(int measureSpec) {
17280            int mode = getMode(measureSpec);
17281            int size = getSize(measureSpec);
17282
17283            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17284
17285            if (mode == UNSPECIFIED)
17286                sb.append("UNSPECIFIED ");
17287            else if (mode == EXACTLY)
17288                sb.append("EXACTLY ");
17289            else if (mode == AT_MOST)
17290                sb.append("AT_MOST ");
17291            else
17292                sb.append(mode).append(" ");
17293
17294            sb.append(size);
17295            return sb.toString();
17296        }
17297    }
17298
17299    class CheckForLongPress implements Runnable {
17300
17301        private int mOriginalWindowAttachCount;
17302
17303        public void run() {
17304            if (isPressed() && (mParent != null)
17305                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17306                if (performLongClick()) {
17307                    mHasPerformedLongPress = true;
17308                }
17309            }
17310        }
17311
17312        public void rememberWindowAttachCount() {
17313            mOriginalWindowAttachCount = mWindowAttachCount;
17314        }
17315    }
17316
17317    private final class CheckForTap implements Runnable {
17318        public void run() {
17319            mPrivateFlags &= ~PFLAG_PREPRESSED;
17320            setPressed(true);
17321            checkForLongClick(ViewConfiguration.getTapTimeout());
17322        }
17323    }
17324
17325    private final class PerformClick implements Runnable {
17326        public void run() {
17327            performClick();
17328        }
17329    }
17330
17331    /** @hide */
17332    public void hackTurnOffWindowResizeAnim(boolean off) {
17333        mAttachInfo.mTurnOffWindowResizeAnim = off;
17334    }
17335
17336    /**
17337     * This method returns a ViewPropertyAnimator object, which can be used to animate
17338     * specific properties on this View.
17339     *
17340     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17341     */
17342    public ViewPropertyAnimator animate() {
17343        if (mAnimator == null) {
17344            mAnimator = new ViewPropertyAnimator(this);
17345        }
17346        return mAnimator;
17347    }
17348
17349    /**
17350     * Interface definition for a callback to be invoked when a hardware key event is
17351     * dispatched to this view. The callback will be invoked before the key event is
17352     * given to the view. This is only useful for hardware keyboards; a software input
17353     * method has no obligation to trigger this listener.
17354     */
17355    public interface OnKeyListener {
17356        /**
17357         * Called when a hardware key is dispatched to a view. This allows listeners to
17358         * get a chance to respond before the target view.
17359         * <p>Key presses in software keyboards will generally NOT trigger this method,
17360         * although some may elect to do so in some situations. Do not assume a
17361         * software input method has to be key-based; even if it is, it may use key presses
17362         * in a different way than you expect, so there is no way to reliably catch soft
17363         * input key presses.
17364         *
17365         * @param v The view the key has been dispatched to.
17366         * @param keyCode The code for the physical key that was pressed
17367         * @param event The KeyEvent object containing full information about
17368         *        the event.
17369         * @return True if the listener has consumed the event, false otherwise.
17370         */
17371        boolean onKey(View v, int keyCode, KeyEvent event);
17372    }
17373
17374    /**
17375     * Interface definition for a callback to be invoked when a touch event is
17376     * dispatched to this view. The callback will be invoked before the touch
17377     * event is given to the view.
17378     */
17379    public interface OnTouchListener {
17380        /**
17381         * Called when a touch event is dispatched to a view. This allows listeners to
17382         * get a chance to respond before the target view.
17383         *
17384         * @param v The view the touch event has been dispatched to.
17385         * @param event The MotionEvent object containing full information about
17386         *        the event.
17387         * @return True if the listener has consumed the event, false otherwise.
17388         */
17389        boolean onTouch(View v, MotionEvent event);
17390    }
17391
17392    /**
17393     * Interface definition for a callback to be invoked when a hover event is
17394     * dispatched to this view. The callback will be invoked before the hover
17395     * event is given to the view.
17396     */
17397    public interface OnHoverListener {
17398        /**
17399         * Called when a hover event is dispatched to a view. This allows listeners to
17400         * get a chance to respond before the target view.
17401         *
17402         * @param v The view the hover event has been dispatched to.
17403         * @param event The MotionEvent object containing full information about
17404         *        the event.
17405         * @return True if the listener has consumed the event, false otherwise.
17406         */
17407        boolean onHover(View v, MotionEvent event);
17408    }
17409
17410    /**
17411     * Interface definition for a callback to be invoked when a generic motion event is
17412     * dispatched to this view. The callback will be invoked before the generic motion
17413     * event is given to the view.
17414     */
17415    public interface OnGenericMotionListener {
17416        /**
17417         * Called when a generic motion event is dispatched to a view. This allows listeners to
17418         * get a chance to respond before the target view.
17419         *
17420         * @param v The view the generic motion event has been dispatched to.
17421         * @param event The MotionEvent object containing full information about
17422         *        the event.
17423         * @return True if the listener has consumed the event, false otherwise.
17424         */
17425        boolean onGenericMotion(View v, MotionEvent event);
17426    }
17427
17428    /**
17429     * Interface definition for a callback to be invoked when a view has been clicked and held.
17430     */
17431    public interface OnLongClickListener {
17432        /**
17433         * Called when a view has been clicked and held.
17434         *
17435         * @param v The view that was clicked and held.
17436         *
17437         * @return true if the callback consumed the long click, false otherwise.
17438         */
17439        boolean onLongClick(View v);
17440    }
17441
17442    /**
17443     * Interface definition for a callback to be invoked when a drag is being dispatched
17444     * to this view.  The callback will be invoked before the hosting view's own
17445     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17446     * onDrag(event) behavior, it should return 'false' from this callback.
17447     *
17448     * <div class="special reference">
17449     * <h3>Developer Guides</h3>
17450     * <p>For a guide to implementing drag and drop features, read the
17451     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17452     * </div>
17453     */
17454    public interface OnDragListener {
17455        /**
17456         * Called when a drag event is dispatched to a view. This allows listeners
17457         * to get a chance to override base View behavior.
17458         *
17459         * @param v The View that received the drag event.
17460         * @param event The {@link android.view.DragEvent} object for the drag event.
17461         * @return {@code true} if the drag event was handled successfully, or {@code false}
17462         * if the drag event was not handled. Note that {@code false} will trigger the View
17463         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17464         */
17465        boolean onDrag(View v, DragEvent event);
17466    }
17467
17468    /**
17469     * Interface definition for a callback to be invoked when the focus state of
17470     * a view changed.
17471     */
17472    public interface OnFocusChangeListener {
17473        /**
17474         * Called when the focus state of a view has changed.
17475         *
17476         * @param v The view whose state has changed.
17477         * @param hasFocus The new focus state of v.
17478         */
17479        void onFocusChange(View v, boolean hasFocus);
17480    }
17481
17482    /**
17483     * Interface definition for a callback to be invoked when a view is clicked.
17484     */
17485    public interface OnClickListener {
17486        /**
17487         * Called when a view has been clicked.
17488         *
17489         * @param v The view that was clicked.
17490         */
17491        void onClick(View v);
17492    }
17493
17494    /**
17495     * Interface definition for a callback to be invoked when the context menu
17496     * for this view is being built.
17497     */
17498    public interface OnCreateContextMenuListener {
17499        /**
17500         * Called when the context menu for this view is being built. It is not
17501         * safe to hold onto the menu after this method returns.
17502         *
17503         * @param menu The context menu that is being built
17504         * @param v The view for which the context menu is being built
17505         * @param menuInfo Extra information about the item for which the
17506         *            context menu should be shown. This information will vary
17507         *            depending on the class of v.
17508         */
17509        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17510    }
17511
17512    /**
17513     * Interface definition for a callback to be invoked when the status bar changes
17514     * visibility.  This reports <strong>global</strong> changes to the system UI
17515     * state, not what the application is requesting.
17516     *
17517     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17518     */
17519    public interface OnSystemUiVisibilityChangeListener {
17520        /**
17521         * Called when the status bar changes visibility because of a call to
17522         * {@link View#setSystemUiVisibility(int)}.
17523         *
17524         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17525         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17526         * This tells you the <strong>global</strong> state of these UI visibility
17527         * flags, not what your app is currently applying.
17528         */
17529        public void onSystemUiVisibilityChange(int visibility);
17530    }
17531
17532    /**
17533     * Interface definition for a callback to be invoked when this view is attached
17534     * or detached from its window.
17535     */
17536    public interface OnAttachStateChangeListener {
17537        /**
17538         * Called when the view is attached to a window.
17539         * @param v The view that was attached
17540         */
17541        public void onViewAttachedToWindow(View v);
17542        /**
17543         * Called when the view is detached from a window.
17544         * @param v The view that was detached
17545         */
17546        public void onViewDetachedFromWindow(View v);
17547    }
17548
17549    private final class UnsetPressedState implements Runnable {
17550        public void run() {
17551            setPressed(false);
17552        }
17553    }
17554
17555    /**
17556     * Base class for derived classes that want to save and restore their own
17557     * state in {@link android.view.View#onSaveInstanceState()}.
17558     */
17559    public static class BaseSavedState extends AbsSavedState {
17560        /**
17561         * Constructor used when reading from a parcel. Reads the state of the superclass.
17562         *
17563         * @param source
17564         */
17565        public BaseSavedState(Parcel source) {
17566            super(source);
17567        }
17568
17569        /**
17570         * Constructor called by derived classes when creating their SavedState objects
17571         *
17572         * @param superState The state of the superclass of this view
17573         */
17574        public BaseSavedState(Parcelable superState) {
17575            super(superState);
17576        }
17577
17578        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17579                new Parcelable.Creator<BaseSavedState>() {
17580            public BaseSavedState createFromParcel(Parcel in) {
17581                return new BaseSavedState(in);
17582            }
17583
17584            public BaseSavedState[] newArray(int size) {
17585                return new BaseSavedState[size];
17586            }
17587        };
17588    }
17589
17590    /**
17591     * A set of information given to a view when it is attached to its parent
17592     * window.
17593     */
17594    static class AttachInfo {
17595        interface Callbacks {
17596            void playSoundEffect(int effectId);
17597            boolean performHapticFeedback(int effectId, boolean always);
17598        }
17599
17600        /**
17601         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17602         * to a Handler. This class contains the target (View) to invalidate and
17603         * the coordinates of the dirty rectangle.
17604         *
17605         * For performance purposes, this class also implements a pool of up to
17606         * POOL_LIMIT objects that get reused. This reduces memory allocations
17607         * whenever possible.
17608         */
17609        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17610            private static final int POOL_LIMIT = 10;
17611            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17612                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17613                        public InvalidateInfo newInstance() {
17614                            return new InvalidateInfo();
17615                        }
17616
17617                        public void onAcquired(InvalidateInfo element) {
17618                        }
17619
17620                        public void onReleased(InvalidateInfo element) {
17621                            element.target = null;
17622                        }
17623                    }, POOL_LIMIT)
17624            );
17625
17626            private InvalidateInfo mNext;
17627            private boolean mIsPooled;
17628
17629            View target;
17630
17631            int left;
17632            int top;
17633            int right;
17634            int bottom;
17635
17636            public void setNextPoolable(InvalidateInfo element) {
17637                mNext = element;
17638            }
17639
17640            public InvalidateInfo getNextPoolable() {
17641                return mNext;
17642            }
17643
17644            static InvalidateInfo acquire() {
17645                return sPool.acquire();
17646            }
17647
17648            void release() {
17649                sPool.release(this);
17650            }
17651
17652            public boolean isPooled() {
17653                return mIsPooled;
17654            }
17655
17656            public void setPooled(boolean isPooled) {
17657                mIsPooled = isPooled;
17658            }
17659        }
17660
17661        final IWindowSession mSession;
17662
17663        final IWindow mWindow;
17664
17665        final IBinder mWindowToken;
17666
17667        final Display mDisplay;
17668
17669        final Callbacks mRootCallbacks;
17670
17671        HardwareCanvas mHardwareCanvas;
17672
17673        /**
17674         * The top view of the hierarchy.
17675         */
17676        View mRootView;
17677
17678        IBinder mPanelParentWindowToken;
17679        Surface mSurface;
17680
17681        boolean mHardwareAccelerated;
17682        boolean mHardwareAccelerationRequested;
17683        HardwareRenderer mHardwareRenderer;
17684
17685        boolean mScreenOn;
17686
17687        /**
17688         * Scale factor used by the compatibility mode
17689         */
17690        float mApplicationScale;
17691
17692        /**
17693         * Indicates whether the application is in compatibility mode
17694         */
17695        boolean mScalingRequired;
17696
17697        /**
17698         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17699         */
17700        boolean mTurnOffWindowResizeAnim;
17701
17702        /**
17703         * Left position of this view's window
17704         */
17705        int mWindowLeft;
17706
17707        /**
17708         * Top position of this view's window
17709         */
17710        int mWindowTop;
17711
17712        /**
17713         * Indicates whether views need to use 32-bit drawing caches
17714         */
17715        boolean mUse32BitDrawingCache;
17716
17717        /**
17718         * For windows that are full-screen but using insets to layout inside
17719         * of the screen decorations, these are the current insets for the
17720         * content of the window.
17721         */
17722        final Rect mContentInsets = new Rect();
17723
17724        /**
17725         * For windows that are full-screen but using insets to layout inside
17726         * of the screen decorations, these are the current insets for the
17727         * actual visible parts of the window.
17728         */
17729        final Rect mVisibleInsets = new Rect();
17730
17731        /**
17732         * The internal insets given by this window.  This value is
17733         * supplied by the client (through
17734         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17735         * be given to the window manager when changed to be used in laying
17736         * out windows behind it.
17737         */
17738        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17739                = new ViewTreeObserver.InternalInsetsInfo();
17740
17741        /**
17742         * All views in the window's hierarchy that serve as scroll containers,
17743         * used to determine if the window can be resized or must be panned
17744         * to adjust for a soft input area.
17745         */
17746        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17747
17748        final KeyEvent.DispatcherState mKeyDispatchState
17749                = new KeyEvent.DispatcherState();
17750
17751        /**
17752         * Indicates whether the view's window currently has the focus.
17753         */
17754        boolean mHasWindowFocus;
17755
17756        /**
17757         * The current visibility of the window.
17758         */
17759        int mWindowVisibility;
17760
17761        /**
17762         * Indicates the time at which drawing started to occur.
17763         */
17764        long mDrawingTime;
17765
17766        /**
17767         * Indicates whether or not ignoring the DIRTY_MASK flags.
17768         */
17769        boolean mIgnoreDirtyState;
17770
17771        /**
17772         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17773         * to avoid clearing that flag prematurely.
17774         */
17775        boolean mSetIgnoreDirtyState = false;
17776
17777        /**
17778         * Indicates whether the view's window is currently in touch mode.
17779         */
17780        boolean mInTouchMode;
17781
17782        /**
17783         * Indicates that ViewAncestor should trigger a global layout change
17784         * the next time it performs a traversal
17785         */
17786        boolean mRecomputeGlobalAttributes;
17787
17788        /**
17789         * Always report new attributes at next traversal.
17790         */
17791        boolean mForceReportNewAttributes;
17792
17793        /**
17794         * Set during a traveral if any views want to keep the screen on.
17795         */
17796        boolean mKeepScreenOn;
17797
17798        /**
17799         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17800         */
17801        int mSystemUiVisibility;
17802
17803        /**
17804         * Hack to force certain system UI visibility flags to be cleared.
17805         */
17806        int mDisabledSystemUiVisibility;
17807
17808        /**
17809         * Last global system UI visibility reported by the window manager.
17810         */
17811        int mGlobalSystemUiVisibility;
17812
17813        /**
17814         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17815         * attached.
17816         */
17817        boolean mHasSystemUiListeners;
17818
17819        /**
17820         * Set if the visibility of any views has changed.
17821         */
17822        boolean mViewVisibilityChanged;
17823
17824        /**
17825         * Set to true if a view has been scrolled.
17826         */
17827        boolean mViewScrollChanged;
17828
17829        /**
17830         * Global to the view hierarchy used as a temporary for dealing with
17831         * x/y points in the transparent region computations.
17832         */
17833        final int[] mTransparentLocation = new int[2];
17834
17835        /**
17836         * Global to the view hierarchy used as a temporary for dealing with
17837         * x/y points in the ViewGroup.invalidateChild implementation.
17838         */
17839        final int[] mInvalidateChildLocation = new int[2];
17840
17841
17842        /**
17843         * Global to the view hierarchy used as a temporary for dealing with
17844         * x/y location when view is transformed.
17845         */
17846        final float[] mTmpTransformLocation = new float[2];
17847
17848        /**
17849         * The view tree observer used to dispatch global events like
17850         * layout, pre-draw, touch mode change, etc.
17851         */
17852        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17853
17854        /**
17855         * A Canvas used by the view hierarchy to perform bitmap caching.
17856         */
17857        Canvas mCanvas;
17858
17859        /**
17860         * The view root impl.
17861         */
17862        final ViewRootImpl mViewRootImpl;
17863
17864        /**
17865         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17866         * handler can be used to pump events in the UI events queue.
17867         */
17868        final Handler mHandler;
17869
17870        /**
17871         * Temporary for use in computing invalidate rectangles while
17872         * calling up the hierarchy.
17873         */
17874        final Rect mTmpInvalRect = new Rect();
17875
17876        /**
17877         * Temporary for use in computing hit areas with transformed views
17878         */
17879        final RectF mTmpTransformRect = new RectF();
17880
17881        /**
17882         * Temporary for use in transforming invalidation rect
17883         */
17884        final Matrix mTmpMatrix = new Matrix();
17885
17886        /**
17887         * Temporary for use in transforming invalidation rect
17888         */
17889        final Transformation mTmpTransformation = new Transformation();
17890
17891        /**
17892         * Temporary list for use in collecting focusable descendents of a view.
17893         */
17894        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17895
17896        /**
17897         * The id of the window for accessibility purposes.
17898         */
17899        int mAccessibilityWindowId = View.NO_ID;
17900
17901        /**
17902         * Whether to ingore not exposed for accessibility Views when
17903         * reporting the view tree to accessibility services.
17904         */
17905        boolean mIncludeNotImportantViews;
17906
17907        /**
17908         * The drawable for highlighting accessibility focus.
17909         */
17910        Drawable mAccessibilityFocusDrawable;
17911
17912        /**
17913         * Show where the margins, bounds and layout bounds are for each view.
17914         */
17915        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17916
17917        /**
17918         * Point used to compute visible regions.
17919         */
17920        final Point mPoint = new Point();
17921
17922        /**
17923         * Creates a new set of attachment information with the specified
17924         * events handler and thread.
17925         *
17926         * @param handler the events handler the view must use
17927         */
17928        AttachInfo(IWindowSession session, IWindow window, Display display,
17929                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17930            mSession = session;
17931            mWindow = window;
17932            mWindowToken = window.asBinder();
17933            mDisplay = display;
17934            mViewRootImpl = viewRootImpl;
17935            mHandler = handler;
17936            mRootCallbacks = effectPlayer;
17937        }
17938    }
17939
17940    /**
17941     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17942     * is supported. This avoids keeping too many unused fields in most
17943     * instances of View.</p>
17944     */
17945    private static class ScrollabilityCache implements Runnable {
17946
17947        /**
17948         * Scrollbars are not visible
17949         */
17950        public static final int OFF = 0;
17951
17952        /**
17953         * Scrollbars are visible
17954         */
17955        public static final int ON = 1;
17956
17957        /**
17958         * Scrollbars are fading away
17959         */
17960        public static final int FADING = 2;
17961
17962        public boolean fadeScrollBars;
17963
17964        public int fadingEdgeLength;
17965        public int scrollBarDefaultDelayBeforeFade;
17966        public int scrollBarFadeDuration;
17967
17968        public int scrollBarSize;
17969        public ScrollBarDrawable scrollBar;
17970        public float[] interpolatorValues;
17971        public View host;
17972
17973        public final Paint paint;
17974        public final Matrix matrix;
17975        public Shader shader;
17976
17977        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17978
17979        private static final float[] OPAQUE = { 255 };
17980        private static final float[] TRANSPARENT = { 0.0f };
17981
17982        /**
17983         * When fading should start. This time moves into the future every time
17984         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17985         */
17986        public long fadeStartTime;
17987
17988
17989        /**
17990         * The current state of the scrollbars: ON, OFF, or FADING
17991         */
17992        public int state = OFF;
17993
17994        private int mLastColor;
17995
17996        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17997            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17998            scrollBarSize = configuration.getScaledScrollBarSize();
17999            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18000            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18001
18002            paint = new Paint();
18003            matrix = new Matrix();
18004            // use use a height of 1, and then wack the matrix each time we
18005            // actually use it.
18006            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18007            paint.setShader(shader);
18008            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18009
18010            this.host = host;
18011        }
18012
18013        public void setFadeColor(int color) {
18014            if (color != mLastColor) {
18015                mLastColor = color;
18016
18017                if (color != 0) {
18018                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18019                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18020                    paint.setShader(shader);
18021                    // Restore the default transfer mode (src_over)
18022                    paint.setXfermode(null);
18023                } else {
18024                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18025                    paint.setShader(shader);
18026                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18027                }
18028            }
18029        }
18030
18031        public void run() {
18032            long now = AnimationUtils.currentAnimationTimeMillis();
18033            if (now >= fadeStartTime) {
18034
18035                // the animation fades the scrollbars out by changing
18036                // the opacity (alpha) from fully opaque to fully
18037                // transparent
18038                int nextFrame = (int) now;
18039                int framesCount = 0;
18040
18041                Interpolator interpolator = scrollBarInterpolator;
18042
18043                // Start opaque
18044                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18045
18046                // End transparent
18047                nextFrame += scrollBarFadeDuration;
18048                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18049
18050                state = FADING;
18051
18052                // Kick off the fade animation
18053                host.invalidate(true);
18054            }
18055        }
18056    }
18057
18058    /**
18059     * Resuable callback for sending
18060     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18061     */
18062    private class SendViewScrolledAccessibilityEvent implements Runnable {
18063        public volatile boolean mIsPending;
18064
18065        public void run() {
18066            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18067            mIsPending = false;
18068        }
18069    }
18070
18071    /**
18072     * <p>
18073     * This class represents a delegate that can be registered in a {@link View}
18074     * to enhance accessibility support via composition rather via inheritance.
18075     * It is specifically targeted to widget developers that extend basic View
18076     * classes i.e. classes in package android.view, that would like their
18077     * applications to be backwards compatible.
18078     * </p>
18079     * <div class="special reference">
18080     * <h3>Developer Guides</h3>
18081     * <p>For more information about making applications accessible, read the
18082     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18083     * developer guide.</p>
18084     * </div>
18085     * <p>
18086     * A scenario in which a developer would like to use an accessibility delegate
18087     * is overriding a method introduced in a later API version then the minimal API
18088     * version supported by the application. For example, the method
18089     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18090     * in API version 4 when the accessibility APIs were first introduced. If a
18091     * developer would like his application to run on API version 4 devices (assuming
18092     * all other APIs used by the application are version 4 or lower) and take advantage
18093     * of this method, instead of overriding the method which would break the application's
18094     * backwards compatibility, he can override the corresponding method in this
18095     * delegate and register the delegate in the target View if the API version of
18096     * the system is high enough i.e. the API version is same or higher to the API
18097     * version that introduced
18098     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18099     * </p>
18100     * <p>
18101     * Here is an example implementation:
18102     * </p>
18103     * <code><pre><p>
18104     * if (Build.VERSION.SDK_INT >= 14) {
18105     *     // If the API version is equal of higher than the version in
18106     *     // which onInitializeAccessibilityNodeInfo was introduced we
18107     *     // register a delegate with a customized implementation.
18108     *     View view = findViewById(R.id.view_id);
18109     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18110     *         public void onInitializeAccessibilityNodeInfo(View host,
18111     *                 AccessibilityNodeInfo info) {
18112     *             // Let the default implementation populate the info.
18113     *             super.onInitializeAccessibilityNodeInfo(host, info);
18114     *             // Set some other information.
18115     *             info.setEnabled(host.isEnabled());
18116     *         }
18117     *     });
18118     * }
18119     * </code></pre></p>
18120     * <p>
18121     * This delegate contains methods that correspond to the accessibility methods
18122     * in View. If a delegate has been specified the implementation in View hands
18123     * off handling to the corresponding method in this delegate. The default
18124     * implementation the delegate methods behaves exactly as the corresponding
18125     * method in View for the case of no accessibility delegate been set. Hence,
18126     * to customize the behavior of a View method, clients can override only the
18127     * corresponding delegate method without altering the behavior of the rest
18128     * accessibility related methods of the host view.
18129     * </p>
18130     */
18131    public static class AccessibilityDelegate {
18132
18133        /**
18134         * Sends an accessibility event of the given type. If accessibility is not
18135         * enabled this method has no effect.
18136         * <p>
18137         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18138         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18139         * been set.
18140         * </p>
18141         *
18142         * @param host The View hosting the delegate.
18143         * @param eventType The type of the event to send.
18144         *
18145         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18146         */
18147        public void sendAccessibilityEvent(View host, int eventType) {
18148            host.sendAccessibilityEventInternal(eventType);
18149        }
18150
18151        /**
18152         * Performs the specified accessibility action on the view. For
18153         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18154         * <p>
18155         * The default implementation behaves as
18156         * {@link View#performAccessibilityAction(int, Bundle)
18157         *  View#performAccessibilityAction(int, Bundle)} for the case of
18158         *  no accessibility delegate been set.
18159         * </p>
18160         *
18161         * @param action The action to perform.
18162         * @return Whether the action was performed.
18163         *
18164         * @see View#performAccessibilityAction(int, Bundle)
18165         *      View#performAccessibilityAction(int, Bundle)
18166         */
18167        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18168            return host.performAccessibilityActionInternal(action, args);
18169        }
18170
18171        /**
18172         * Sends an accessibility event. This method behaves exactly as
18173         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18174         * empty {@link AccessibilityEvent} and does not perform a check whether
18175         * accessibility is enabled.
18176         * <p>
18177         * The default implementation behaves as
18178         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18179         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18180         * the case of no accessibility delegate been set.
18181         * </p>
18182         *
18183         * @param host The View hosting the delegate.
18184         * @param event The event to send.
18185         *
18186         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18187         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18188         */
18189        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18190            host.sendAccessibilityEventUncheckedInternal(event);
18191        }
18192
18193        /**
18194         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18195         * to its children for adding their text content to the event.
18196         * <p>
18197         * The default implementation behaves as
18198         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18199         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18200         * the case of no accessibility delegate been set.
18201         * </p>
18202         *
18203         * @param host The View hosting the delegate.
18204         * @param event The event.
18205         * @return True if the event population was completed.
18206         *
18207         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18208         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18209         */
18210        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18211            return host.dispatchPopulateAccessibilityEventInternal(event);
18212        }
18213
18214        /**
18215         * Gives a chance to the host View to populate the accessibility event with its
18216         * text content.
18217         * <p>
18218         * The default implementation behaves as
18219         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18220         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18221         * the case of no accessibility delegate been set.
18222         * </p>
18223         *
18224         * @param host The View hosting the delegate.
18225         * @param event The accessibility event which to populate.
18226         *
18227         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18228         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18229         */
18230        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18231            host.onPopulateAccessibilityEventInternal(event);
18232        }
18233
18234        /**
18235         * Initializes an {@link AccessibilityEvent} with information about the
18236         * the host View which is the event source.
18237         * <p>
18238         * The default implementation behaves as
18239         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18240         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18241         * the case of no accessibility delegate been set.
18242         * </p>
18243         *
18244         * @param host The View hosting the delegate.
18245         * @param event The event to initialize.
18246         *
18247         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18248         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18249         */
18250        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18251            host.onInitializeAccessibilityEventInternal(event);
18252        }
18253
18254        /**
18255         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18256         * <p>
18257         * The default implementation behaves as
18258         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18259         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18260         * the case of no accessibility delegate been set.
18261         * </p>
18262         *
18263         * @param host The View hosting the delegate.
18264         * @param info The instance to initialize.
18265         *
18266         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18267         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18268         */
18269        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18270            host.onInitializeAccessibilityNodeInfoInternal(info);
18271        }
18272
18273        /**
18274         * Called when a child of the host View has requested sending an
18275         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18276         * to augment the event.
18277         * <p>
18278         * The default implementation behaves as
18279         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18280         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18281         * the case of no accessibility delegate been set.
18282         * </p>
18283         *
18284         * @param host The View hosting the delegate.
18285         * @param child The child which requests sending the event.
18286         * @param event The event to be sent.
18287         * @return True if the event should be sent
18288         *
18289         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18290         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18291         */
18292        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18293                AccessibilityEvent event) {
18294            return host.onRequestSendAccessibilityEventInternal(child, event);
18295        }
18296
18297        /**
18298         * Gets the provider for managing a virtual view hierarchy rooted at this View
18299         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18300         * that explore the window content.
18301         * <p>
18302         * The default implementation behaves as
18303         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18304         * the case of no accessibility delegate been set.
18305         * </p>
18306         *
18307         * @return The provider.
18308         *
18309         * @see AccessibilityNodeProvider
18310         */
18311        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18312            return null;
18313        }
18314    }
18315
18316    private class MatchIdPredicate implements Predicate<View> {
18317        public int mId;
18318
18319        @Override
18320        public boolean apply(View view) {
18321            return (view.mID == mId);
18322        }
18323    }
18324
18325    private class MatchLabelForPredicate implements Predicate<View> {
18326        private int mLabeledId;
18327
18328        @Override
18329        public boolean apply(View view) {
18330            return (view.mLabelForId == mLabeledId);
18331        }
18332    }
18333
18334    /**
18335     * Dump all private flags in readable format, useful for documentation and
18336     * sanity checking.
18337     */
18338    private static void dumpFlags() {
18339        final HashMap<String, String> found = Maps.newHashMap();
18340        try {
18341            for (Field field : View.class.getDeclaredFields()) {
18342                final int modifiers = field.getModifiers();
18343                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
18344                    if (field.getType().equals(int.class)) {
18345                        final int value = field.getInt(null);
18346                        dumpFlag(found, field.getName(), value);
18347                    } else if (field.getType().equals(int[].class)) {
18348                        final int[] values = (int[]) field.get(null);
18349                        for (int i = 0; i < values.length; i++) {
18350                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
18351                        }
18352                    }
18353                }
18354            }
18355        } catch (IllegalAccessException e) {
18356            throw new RuntimeException(e);
18357        }
18358
18359        final ArrayList<String> keys = Lists.newArrayList();
18360        keys.addAll(found.keySet());
18361        Collections.sort(keys);
18362        for (String key : keys) {
18363            Log.d(VIEW_LOG_TAG, found.get(key));
18364        }
18365    }
18366
18367    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
18368        // Sort flags by prefix, then by bits, always keeping unique keys
18369        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
18370        final int prefix = name.indexOf('_');
18371        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
18372        final String output = bits + " " + name;
18373        found.put(key, output);
18374    }
18375}
18376