View.java revision 81547effacfea78a3c26d34b77e1e99ffc89c89a
12008747941749ad27fe80663d23036ac320e998fJason Sams/*
22008747941749ad27fe80663d23036ac320e998fJason Sams * Copyright (C) 2006 The Android Open Source Project
32008747941749ad27fe80663d23036ac320e998fJason Sams *
42008747941749ad27fe80663d23036ac320e998fJason Sams * Licensed under the Apache License, Version 2.0 (the "License");
52008747941749ad27fe80663d23036ac320e998fJason Sams * you may not use this file except in compliance with the License.
62008747941749ad27fe80663d23036ac320e998fJason Sams * You may obtain a copy of the License at
72008747941749ad27fe80663d23036ac320e998fJason Sams *
82008747941749ad27fe80663d23036ac320e998fJason Sams *      http://www.apache.org/licenses/LICENSE-2.0
92008747941749ad27fe80663d23036ac320e998fJason Sams *
102008747941749ad27fe80663d23036ac320e998fJason Sams * Unless required by applicable law or agreed to in writing, software
112008747941749ad27fe80663d23036ac320e998fJason Sams * distributed under the License is distributed on an "AS IS" BASIS,
122008747941749ad27fe80663d23036ac320e998fJason Sams * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
132008747941749ad27fe80663d23036ac320e998fJason Sams * See the License for the specific language governing permissions and
142008747941749ad27fe80663d23036ac320e998fJason Sams * limitations under the License.
152008747941749ad27fe80663d23036ac320e998fJason Sams */
162008747941749ad27fe80663d23036ac320e998fJason Sams
172008747941749ad27fe80663d23036ac320e998fJason Samspackage android.view;
182008747941749ad27fe80663d23036ac320e998fJason Sams
192008747941749ad27fe80663d23036ac320e998fJason Samsimport android.annotation.IntDef;
202008747941749ad27fe80663d23036ac320e998fJason Samsimport android.annotation.NonNull;
212008747941749ad27fe80663d23036ac320e998fJason Samsimport android.annotation.Nullable;
222008747941749ad27fe80663d23036ac320e998fJason Samsimport android.content.ClipData;
232008747941749ad27fe80663d23036ac320e998fJason Samsimport android.content.Context;
242008747941749ad27fe80663d23036ac320e998fJason Samsimport android.content.res.Configuration;
252008747941749ad27fe80663d23036ac320e998fJason Samsimport android.content.res.Resources;
262008747941749ad27fe80663d23036ac320e998fJason Samsimport android.content.res.TypedArray;
272008747941749ad27fe80663d23036ac320e998fJason Samsimport android.graphics.Bitmap;
282008747941749ad27fe80663d23036ac320e998fJason Samsimport android.graphics.Camera;
292008747941749ad27fe80663d23036ac320e998fJason Samsimport android.graphics.Canvas;
302008747941749ad27fe80663d23036ac320e998fJason Samsimport android.graphics.Insets;
312008747941749ad27fe80663d23036ac320e998fJason Samsimport android.graphics.Interpolator;
325f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.LinearGradient;
335f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.Matrix;
345f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.Paint;
352008747941749ad27fe80663d23036ac320e998fJason Samsimport android.graphics.Path;
362008747941749ad27fe80663d23036ac320e998fJason Samsimport android.graphics.PixelFormat;
375f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.Point;
385f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.PorterDuff;
395f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.PorterDuffXfermode;
405f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.Rect;
415f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.RectF;
422008747941749ad27fe80663d23036ac320e998fJason Samsimport android.graphics.Region;
435f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.Shader;
445f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.graphics.drawable.ColorDrawable;
452008747941749ad27fe80663d23036ac320e998fJason Samsimport android.graphics.drawable.Drawable;
462008747941749ad27fe80663d23036ac320e998fJason Samsimport android.hardware.display.DisplayManagerGlobal;
472008747941749ad27fe80663d23036ac320e998fJason Samsimport android.os.Bundle;
485f27d6fb0b0b9184ba9820c629fc1354a635e515Jason Samsimport android.os.Handler;
492008747941749ad27fe80663d23036ac320e998fJason Samsimport android.os.IBinder;
502008747941749ad27fe80663d23036ac320e998fJason Samsimport android.os.Parcel;
517974fc03e11f3a8dd40f794f3b33b4889483090cRahul Chaudhryimport android.os.Parcelable;
527974fc03e11f3a8dd40f794f3b33b4889483090cRahul Chaudhryimport android.os.RemoteException;
532008747941749ad27fe80663d23036ac320e998fJason Samsimport android.os.SystemClock;
542008747941749ad27fe80663d23036ac320e998fJason Samsimport android.os.SystemProperties;
55import android.text.TextUtils;
56import android.util.AttributeSet;
57import android.util.FloatProperty;
58import android.util.LayoutDirection;
59import android.util.Log;
60import android.util.LongSparseLongArray;
61import android.util.Pools.SynchronizedPool;
62import android.util.Property;
63import android.util.SparseArray;
64import android.util.SuperNotCalledException;
65import android.util.TypedValue;
66import android.view.ContextMenu.ContextMenuInfo;
67import android.view.AccessibilityIterators.TextSegmentIterator;
68import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
69import android.view.AccessibilityIterators.WordTextSegmentIterator;
70import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
71import android.view.accessibility.AccessibilityEvent;
72import android.view.accessibility.AccessibilityEventSource;
73import android.view.accessibility.AccessibilityManager;
74import android.view.accessibility.AccessibilityNodeInfo;
75import android.view.accessibility.AccessibilityNodeProvider;
76import android.view.animation.Animation;
77import android.view.animation.AnimationUtils;
78import android.view.animation.Transformation;
79import android.view.inputmethod.EditorInfo;
80import android.view.inputmethod.InputConnection;
81import android.view.inputmethod.InputMethodManager;
82import android.widget.ScrollBarDrawable;
83
84import static android.os.Build.VERSION_CODES.*;
85import static java.lang.Math.max;
86
87import com.android.internal.R;
88import com.android.internal.util.Predicate;
89import com.android.internal.view.menu.MenuBuilder;
90import com.google.android.collect.Lists;
91import com.google.android.collect.Maps;
92
93import java.lang.annotation.Retention;
94import java.lang.annotation.RetentionPolicy;
95import java.lang.ref.WeakReference;
96import java.lang.reflect.Field;
97import java.lang.reflect.InvocationTargetException;
98import java.lang.reflect.Method;
99import java.lang.reflect.Modifier;
100import java.util.ArrayList;
101import java.util.Arrays;
102import java.util.Collections;
103import java.util.HashMap;
104import java.util.Locale;
105import java.util.concurrent.CopyOnWriteArrayList;
106import java.util.concurrent.atomic.AtomicInteger;
107
108/**
109 * <p>
110 * This class represents the basic building block for user interface components. A View
111 * occupies a rectangular area on the screen and is responsible for drawing and
112 * event handling. View is the base class for <em>widgets</em>, which are
113 * used to create interactive UI components (buttons, text fields, etc.). The
114 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
115 * are invisible containers that hold other Views (or other ViewGroups) and define
116 * their layout properties.
117 * </p>
118 *
119 * <div class="special reference">
120 * <h3>Developer Guides</h3>
121 * <p>For information about using this class to develop your application's user interface,
122 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
123 * </div>
124 *
125 * <a name="Using"></a>
126 * <h3>Using Views</h3>
127 * <p>
128 * All of the views in a window are arranged in a single tree. You can add views
129 * either from code or by specifying a tree of views in one or more XML layout
130 * files. There are many specialized subclasses of views that act as controls or
131 * are capable of displaying text, images, or other content.
132 * </p>
133 * <p>
134 * Once you have created a tree of views, there are typically a few types of
135 * common operations you may wish to perform:
136 * <ul>
137 * <li><strong>Set properties:</strong> for example setting the text of a
138 * {@link android.widget.TextView}. The available properties and the methods
139 * that set them will vary among the different subclasses of views. Note that
140 * properties that are known at build time can be set in the XML layout
141 * files.</li>
142 * <li><strong>Set focus:</strong> The framework will handled moving focus in
143 * response to user input. To force focus to a specific view, call
144 * {@link #requestFocus}.</li>
145 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
146 * that will be notified when something interesting happens to the view. For
147 * example, all views will let you set a listener to be notified when the view
148 * gains or loses focus. You can register such a listener using
149 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
150 * Other view subclasses offer more specialized listeners. For example, a Button
151 * exposes a listener to notify clients when the button is clicked.</li>
152 * <li><strong>Set visibility:</strong> You can hide or show views using
153 * {@link #setVisibility(int)}.</li>
154 * </ul>
155 * </p>
156 * <p><em>
157 * Note: The Android framework is responsible for measuring, laying out and
158 * drawing views. You should not call methods that perform these actions on
159 * views yourself unless you are actually implementing a
160 * {@link android.view.ViewGroup}.
161 * </em></p>
162 *
163 * <a name="Lifecycle"></a>
164 * <h3>Implementing a Custom View</h3>
165 *
166 * <p>
167 * To implement a custom view, you will usually begin by providing overrides for
168 * some of the standard methods that the framework calls on all views. You do
169 * not need to override all of these methods. In fact, you can start by just
170 * overriding {@link #onDraw(android.graphics.Canvas)}.
171 * <table border="2" width="85%" align="center" cellpadding="5">
172 *     <thead>
173 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
174 *     </thead>
175 *
176 *     <tbody>
177 *     <tr>
178 *         <td rowspan="2">Creation</td>
179 *         <td>Constructors</td>
180 *         <td>There is a form of the constructor that are called when the view
181 *         is created from code and a form that is called when the view is
182 *         inflated from a layout file. The second form should parse and apply
183 *         any attributes defined in the layout file.
184 *         </td>
185 *     </tr>
186 *     <tr>
187 *         <td><code>{@link #onFinishInflate()}</code></td>
188 *         <td>Called after a view and all of its children has been inflated
189 *         from XML.</td>
190 *     </tr>
191 *
192 *     <tr>
193 *         <td rowspan="3">Layout</td>
194 *         <td><code>{@link #onMeasure(int, int)}</code></td>
195 *         <td>Called to determine the size requirements for this view and all
196 *         of its children.
197 *         </td>
198 *     </tr>
199 *     <tr>
200 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
201 *         <td>Called when this view should assign a size and position to all
202 *         of its children.
203 *         </td>
204 *     </tr>
205 *     <tr>
206 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
207 *         <td>Called when the size of this view has changed.
208 *         </td>
209 *     </tr>
210 *
211 *     <tr>
212 *         <td>Drawing</td>
213 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
214 *         <td>Called when the view should render its content.
215 *         </td>
216 *     </tr>
217 *
218 *     <tr>
219 *         <td rowspan="4">Event processing</td>
220 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
221 *         <td>Called when a new hardware key event occurs.
222 *         </td>
223 *     </tr>
224 *     <tr>
225 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
226 *         <td>Called when a hardware key up event occurs.
227 *         </td>
228 *     </tr>
229 *     <tr>
230 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
231 *         <td>Called when a trackball motion event occurs.
232 *         </td>
233 *     </tr>
234 *     <tr>
235 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
236 *         <td>Called when a touch screen motion event occurs.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td rowspan="2">Focus</td>
242 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
243 *         <td>Called when the view gains or loses focus.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
249 *         <td>Called when the window containing the view gains or loses focus.
250 *         </td>
251 *     </tr>
252 *
253 *     <tr>
254 *         <td rowspan="3">Attaching</td>
255 *         <td><code>{@link #onAttachedToWindow()}</code></td>
256 *         <td>Called when the view is attached to a window.
257 *         </td>
258 *     </tr>
259 *
260 *     <tr>
261 *         <td><code>{@link #onDetachedFromWindow}</code></td>
262 *         <td>Called when the view is detached from its window.
263 *         </td>
264 *     </tr>
265 *
266 *     <tr>
267 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
268 *         <td>Called when the visibility of the window containing the view
269 *         has changed.
270 *         </td>
271 *     </tr>
272 *     </tbody>
273 *
274 * </table>
275 * </p>
276 *
277 * <a name="IDs"></a>
278 * <h3>IDs</h3>
279 * Views may have an integer id associated with them. These ids are typically
280 * assigned in the layout XML files, and are used to find specific views within
281 * the view tree. A common pattern is to:
282 * <ul>
283 * <li>Define a Button in the layout file and assign it a unique ID.
284 * <pre>
285 * &lt;Button
286 *     android:id="@+id/my_button"
287 *     android:layout_width="wrap_content"
288 *     android:layout_height="wrap_content"
289 *     android:text="@string/my_button_text"/&gt;
290 * </pre></li>
291 * <li>From the onCreate method of an Activity, find the Button
292 * <pre class="prettyprint">
293 *      Button myButton = (Button) findViewById(R.id.my_button);
294 * </pre></li>
295 * </ul>
296 * <p>
297 * View IDs need not be unique throughout the tree, but it is good practice to
298 * ensure that they are at least unique within the part of the tree you are
299 * searching.
300 * </p>
301 *
302 * <a name="Position"></a>
303 * <h3>Position</h3>
304 * <p>
305 * The geometry of a view is that of a rectangle. A view has a location,
306 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
307 * two dimensions, expressed as a width and a height. The unit for location
308 * and dimensions is the pixel.
309 * </p>
310 *
311 * <p>
312 * It is possible to retrieve the location of a view by invoking the methods
313 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
314 * coordinate of the rectangle representing the view. The latter returns the
315 * top, or Y, coordinate of the rectangle representing the view. These methods
316 * both return the location of the view relative to its parent. For instance,
317 * when getLeft() returns 20, that means the view is located 20 pixels to the
318 * right of the left edge of its direct parent.
319 * </p>
320 *
321 * <p>
322 * In addition, several convenience methods are offered to avoid unnecessary
323 * computations, namely {@link #getRight()} and {@link #getBottom()}.
324 * These methods return the coordinates of the right and bottom edges of the
325 * rectangle representing the view. For instance, calling {@link #getRight()}
326 * is similar to the following computation: <code>getLeft() + getWidth()</code>
327 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
328 * </p>
329 *
330 * <a name="SizePaddingMargins"></a>
331 * <h3>Size, padding and margins</h3>
332 * <p>
333 * The size of a view is expressed with a width and a height. A view actually
334 * possess two pairs of width and height values.
335 * </p>
336 *
337 * <p>
338 * The first pair is known as <em>measured width</em> and
339 * <em>measured height</em>. These dimensions define how big a view wants to be
340 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
341 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
342 * and {@link #getMeasuredHeight()}.
343 * </p>
344 *
345 * <p>
346 * The second pair is simply known as <em>width</em> and <em>height</em>, or
347 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
348 * dimensions define the actual size of the view on screen, at drawing time and
349 * after layout. These values may, but do not have to, be different from the
350 * measured width and height. The width and height can be obtained by calling
351 * {@link #getWidth()} and {@link #getHeight()}.
352 * </p>
353 *
354 * <p>
355 * To measure its dimensions, a view takes into account its padding. The padding
356 * is expressed in pixels for the left, top, right and bottom parts of the view.
357 * Padding can be used to offset the content of the view by a specific amount of
358 * pixels. For instance, a left padding of 2 will push the view's content by
359 * 2 pixels to the right of the left edge. Padding can be set using the
360 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
361 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
362 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
363 * {@link #getPaddingEnd()}.
364 * </p>
365 *
366 * <p>
367 * Even though a view can define a padding, it does not provide any support for
368 * margins. However, view groups provide such a support. Refer to
369 * {@link android.view.ViewGroup} and
370 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
371 * </p>
372 *
373 * <a name="Layout"></a>
374 * <h3>Layout</h3>
375 * <p>
376 * Layout is a two pass process: a measure pass and a layout pass. The measuring
377 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
378 * of the view tree. Each view pushes dimension specifications down the tree
379 * during the recursion. At the end of the measure pass, every view has stored
380 * its measurements. The second pass happens in
381 * {@link #layout(int,int,int,int)} and is also top-down. During
382 * this pass each parent is responsible for positioning all of its children
383 * using the sizes computed in the measure pass.
384 * </p>
385 *
386 * <p>
387 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
388 * {@link #getMeasuredHeight()} values must be set, along with those for all of
389 * that view's descendants. A view's measured width and measured height values
390 * must respect the constraints imposed by the view's parents. This guarantees
391 * that at the end of the measure pass, all parents accept all of their
392 * children's measurements. A parent view may call measure() more than once on
393 * its children. For example, the parent may measure each child once with
394 * unspecified dimensions to find out how big they want to be, then call
395 * measure() on them again with actual numbers if the sum of all the children's
396 * unconstrained sizes is too big or too small.
397 * </p>
398 *
399 * <p>
400 * The measure pass uses two classes to communicate dimensions. The
401 * {@link MeasureSpec} class is used by views to tell their parents how they
402 * want to be measured and positioned. The base LayoutParams class just
403 * describes how big the view wants to be for both width and height. For each
404 * dimension, it can specify one of:
405 * <ul>
406 * <li> an exact number
407 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
408 * (minus padding)
409 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
410 * enclose its content (plus padding).
411 * </ul>
412 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
413 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
414 * an X and Y value.
415 * </p>
416 *
417 * <p>
418 * MeasureSpecs are used to push requirements down the tree from parent to
419 * child. A MeasureSpec can be in one of three modes:
420 * <ul>
421 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
422 * of a child view. For example, a LinearLayout may call measure() on its child
423 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
424 * tall the child view wants to be given a width of 240 pixels.
425 * <li>EXACTLY: This is used by the parent to impose an exact size on the
426 * child. The child must use this size, and guarantee that all of its
427 * descendants will fit within this size.
428 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
429 * child. The child must gurantee that it and all of its descendants will fit
430 * within this size.
431 * </ul>
432 * </p>
433 *
434 * <p>
435 * To intiate a layout, call {@link #requestLayout}. This method is typically
436 * called by a view on itself when it believes that is can no longer fit within
437 * its current bounds.
438 * </p>
439 *
440 * <a name="Drawing"></a>
441 * <h3>Drawing</h3>
442 * <p>
443 * Drawing is handled by walking the tree and rendering each view that
444 * intersects the invalid region. Because the tree is traversed in-order,
445 * this means that parents will draw before (i.e., behind) their children, with
446 * siblings drawn in the order they appear in the tree.
447 * If you set a background drawable for a View, then the View will draw it for you
448 * before calling back to its <code>onDraw()</code> method.
449 * </p>
450 *
451 * <p>
452 * Note that the framework will not draw views that are not in the invalid region.
453 * </p>
454 *
455 * <p>
456 * To force a view to draw, call {@link #invalidate()}.
457 * </p>
458 *
459 * <a name="EventHandlingThreading"></a>
460 * <h3>Event Handling and Threading</h3>
461 * <p>
462 * The basic cycle of a view is as follows:
463 * <ol>
464 * <li>An event comes in and is dispatched to the appropriate view. The view
465 * handles the event and notifies any listeners.</li>
466 * <li>If in the course of processing the event, the view's bounds may need
467 * to be changed, the view will call {@link #requestLayout()}.</li>
468 * <li>Similarly, if in the course of processing the event the view's appearance
469 * may need to be changed, the view will call {@link #invalidate()}.</li>
470 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
471 * the framework will take care of measuring, laying out, and drawing the tree
472 * as appropriate.</li>
473 * </ol>
474 * </p>
475 *
476 * <p><em>Note: The entire view tree is single threaded. You must always be on
477 * the UI thread when calling any method on any view.</em>
478 * If you are doing work on other threads and want to update the state of a view
479 * from that thread, you should use a {@link Handler}.
480 * </p>
481 *
482 * <a name="FocusHandling"></a>
483 * <h3>Focus Handling</h3>
484 * <p>
485 * The framework will handle routine focus movement in response to user input.
486 * This includes changing the focus as views are removed or hidden, or as new
487 * views become available. Views indicate their willingness to take focus
488 * through the {@link #isFocusable} method. To change whether a view can take
489 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
490 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
491 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
492 * </p>
493 * <p>
494 * Focus movement is based on an algorithm which finds the nearest neighbor in a
495 * given direction. In rare cases, the default algorithm may not match the
496 * intended behavior of the developer. In these situations, you can provide
497 * explicit overrides by using these XML attributes in the layout file:
498 * <pre>
499 * nextFocusDown
500 * nextFocusLeft
501 * nextFocusRight
502 * nextFocusUp
503 * </pre>
504 * </p>
505 *
506 *
507 * <p>
508 * To get a particular view to take focus, call {@link #requestFocus()}.
509 * </p>
510 *
511 * <a name="TouchMode"></a>
512 * <h3>Touch Mode</h3>
513 * <p>
514 * When a user is navigating a user interface via directional keys such as a D-pad, it is
515 * necessary to give focus to actionable items such as buttons so the user can see
516 * what will take input.  If the device has touch capabilities, however, and the user
517 * begins interacting with the interface by touching it, it is no longer necessary to
518 * always highlight, or give focus to, a particular view.  This motivates a mode
519 * for interaction named 'touch mode'.
520 * </p>
521 * <p>
522 * For a touch capable device, once the user touches the screen, the device
523 * will enter touch mode.  From this point onward, only views for which
524 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
525 * Other views that are touchable, like buttons, will not take focus when touched; they will
526 * only fire the on click listeners.
527 * </p>
528 * <p>
529 * Any time a user hits a directional key, such as a D-pad direction, the view device will
530 * exit touch mode, and find a view to take focus, so that the user may resume interacting
531 * with the user interface without touching the screen again.
532 * </p>
533 * <p>
534 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
535 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
536 * </p>
537 *
538 * <a name="Scrolling"></a>
539 * <h3>Scrolling</h3>
540 * <p>
541 * The framework provides basic support for views that wish to internally
542 * scroll their content. This includes keeping track of the X and Y scroll
543 * offset as well as mechanisms for drawing scrollbars. See
544 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
545 * {@link #awakenScrollBars()} for more details.
546 * </p>
547 *
548 * <a name="Tags"></a>
549 * <h3>Tags</h3>
550 * <p>
551 * Unlike IDs, tags are not used to identify views. Tags are essentially an
552 * extra piece of information that can be associated with a view. They are most
553 * often used as a convenience to store data related to views in the views
554 * themselves rather than by putting them in a separate structure.
555 * </p>
556 *
557 * <a name="Properties"></a>
558 * <h3>Properties</h3>
559 * <p>
560 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
561 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
562 * available both in the {@link Property} form as well as in similarly-named setter/getter
563 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
564 * be used to set persistent state associated with these rendering-related properties on the view.
565 * The properties and methods can also be used in conjunction with
566 * {@link android.animation.Animator Animator}-based animations, described more in the
567 * <a href="#Animation">Animation</a> section.
568 * </p>
569 *
570 * <a name="Animation"></a>
571 * <h3>Animation</h3>
572 * <p>
573 * Starting with Android 3.0, the preferred way of animating views is to use the
574 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
575 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
576 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
577 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
578 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
579 * makes animating these View properties particularly easy and efficient.
580 * </p>
581 * <p>
582 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
583 * You can attach an {@link Animation} object to a view using
584 * {@link #setAnimation(Animation)} or
585 * {@link #startAnimation(Animation)}. The animation can alter the scale,
586 * rotation, translation and alpha of a view over time. If the animation is
587 * attached to a view that has children, the animation will affect the entire
588 * subtree rooted by that node. When an animation is started, the framework will
589 * take care of redrawing the appropriate views until the animation completes.
590 * </p>
591 *
592 * <a name="Security"></a>
593 * <h3>Security</h3>
594 * <p>
595 * Sometimes it is essential that an application be able to verify that an action
596 * is being performed with the full knowledge and consent of the user, such as
597 * granting a permission request, making a purchase or clicking on an advertisement.
598 * Unfortunately, a malicious application could try to spoof the user into
599 * performing these actions, unaware, by concealing the intended purpose of the view.
600 * As a remedy, the framework offers a touch filtering mechanism that can be used to
601 * improve the security of views that provide access to sensitive functionality.
602 * </p><p>
603 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
604 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
605 * will discard touches that are received whenever the view's window is obscured by
606 * another visible window.  As a result, the view will not receive touches whenever a
607 * toast, dialog or other window appears above the view's window.
608 * </p><p>
609 * For more fine-grained control over security, consider overriding the
610 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
611 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
612 * </p>
613 *
614 * @attr ref android.R.styleable#View_alpha
615 * @attr ref android.R.styleable#View_background
616 * @attr ref android.R.styleable#View_clickable
617 * @attr ref android.R.styleable#View_contentDescription
618 * @attr ref android.R.styleable#View_drawingCacheQuality
619 * @attr ref android.R.styleable#View_duplicateParentState
620 * @attr ref android.R.styleable#View_id
621 * @attr ref android.R.styleable#View_requiresFadingEdge
622 * @attr ref android.R.styleable#View_fadeScrollbars
623 * @attr ref android.R.styleable#View_fadingEdgeLength
624 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
625 * @attr ref android.R.styleable#View_fitsSystemWindows
626 * @attr ref android.R.styleable#View_isScrollContainer
627 * @attr ref android.R.styleable#View_focusable
628 * @attr ref android.R.styleable#View_focusableInTouchMode
629 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
630 * @attr ref android.R.styleable#View_keepScreenOn
631 * @attr ref android.R.styleable#View_layerType
632 * @attr ref android.R.styleable#View_layoutDirection
633 * @attr ref android.R.styleable#View_longClickable
634 * @attr ref android.R.styleable#View_minHeight
635 * @attr ref android.R.styleable#View_minWidth
636 * @attr ref android.R.styleable#View_nextFocusDown
637 * @attr ref android.R.styleable#View_nextFocusLeft
638 * @attr ref android.R.styleable#View_nextFocusRight
639 * @attr ref android.R.styleable#View_nextFocusUp
640 * @attr ref android.R.styleable#View_onClick
641 * @attr ref android.R.styleable#View_padding
642 * @attr ref android.R.styleable#View_paddingBottom
643 * @attr ref android.R.styleable#View_paddingLeft
644 * @attr ref android.R.styleable#View_paddingRight
645 * @attr ref android.R.styleable#View_paddingTop
646 * @attr ref android.R.styleable#View_paddingStart
647 * @attr ref android.R.styleable#View_paddingEnd
648 * @attr ref android.R.styleable#View_saveEnabled
649 * @attr ref android.R.styleable#View_rotation
650 * @attr ref android.R.styleable#View_rotationX
651 * @attr ref android.R.styleable#View_rotationY
652 * @attr ref android.R.styleable#View_scaleX
653 * @attr ref android.R.styleable#View_scaleY
654 * @attr ref android.R.styleable#View_scrollX
655 * @attr ref android.R.styleable#View_scrollY
656 * @attr ref android.R.styleable#View_scrollbarSize
657 * @attr ref android.R.styleable#View_scrollbarStyle
658 * @attr ref android.R.styleable#View_scrollbars
659 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
660 * @attr ref android.R.styleable#View_scrollbarFadeDuration
661 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
662 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
663 * @attr ref android.R.styleable#View_scrollbarThumbVertical
664 * @attr ref android.R.styleable#View_scrollbarTrackVertical
665 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
666 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
667 * @attr ref android.R.styleable#View_sharedElementName
668 * @attr ref android.R.styleable#View_soundEffectsEnabled
669 * @attr ref android.R.styleable#View_tag
670 * @attr ref android.R.styleable#View_textAlignment
671 * @attr ref android.R.styleable#View_textDirection
672 * @attr ref android.R.styleable#View_transformPivotX
673 * @attr ref android.R.styleable#View_transformPivotY
674 * @attr ref android.R.styleable#View_translationX
675 * @attr ref android.R.styleable#View_translationY
676 * @attr ref android.R.styleable#View_translationZ
677 * @attr ref android.R.styleable#View_visibility
678 *
679 * @see android.view.ViewGroup
680 */
681public class View implements Drawable.Callback, KeyEvent.Callback,
682        AccessibilityEventSource {
683    private static final boolean DBG = false;
684
685    /**
686     * The logging tag used by this class with android.util.Log.
687     */
688    protected static final String VIEW_LOG_TAG = "View";
689
690    /**
691     * When set to true, apps will draw debugging information about their layouts.
692     *
693     * @hide
694     */
695    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
696
697    /**
698     * Used to mark a View that has no ID.
699     */
700    public static final int NO_ID = -1;
701
702    /**
703     * Signals that compatibility booleans have been initialized according to
704     * target SDK versions.
705     */
706    private static boolean sCompatibilityDone = false;
707
708    /**
709     * Use the old (broken) way of building MeasureSpecs.
710     */
711    private static boolean sUseBrokenMakeMeasureSpec = false;
712
713    /**
714     * Ignore any optimizations using the measure cache.
715     */
716    private static boolean sIgnoreMeasureCache = false;
717
718    /**
719     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
720     * calling setFlags.
721     */
722    private static final int NOT_FOCUSABLE = 0x00000000;
723
724    /**
725     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
726     * setFlags.
727     */
728    private static final int FOCUSABLE = 0x00000001;
729
730    /**
731     * Mask for use with setFlags indicating bits used for focus.
732     */
733    private static final int FOCUSABLE_MASK = 0x00000001;
734
735    /**
736     * This view will adjust its padding to fit sytem windows (e.g. status bar)
737     */
738    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
739
740    /** @hide */
741    @IntDef({VISIBLE, INVISIBLE, GONE})
742    @Retention(RetentionPolicy.SOURCE)
743    public @interface Visibility {}
744
745    /**
746     * This view is visible.
747     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
748     * android:visibility}.
749     */
750    public static final int VISIBLE = 0x00000000;
751
752    /**
753     * This view is invisible, but it still takes up space for layout purposes.
754     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
755     * android:visibility}.
756     */
757    public static final int INVISIBLE = 0x00000004;
758
759    /**
760     * This view is invisible, and it doesn't take any space for layout
761     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
762     * android:visibility}.
763     */
764    public static final int GONE = 0x00000008;
765
766    /**
767     * Mask for use with setFlags indicating bits used for visibility.
768     * {@hide}
769     */
770    static final int VISIBILITY_MASK = 0x0000000C;
771
772    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
773
774    /**
775     * This view is enabled. Interpretation varies by subclass.
776     * Use with ENABLED_MASK when calling setFlags.
777     * {@hide}
778     */
779    static final int ENABLED = 0x00000000;
780
781    /**
782     * This view is disabled. Interpretation varies by subclass.
783     * Use with ENABLED_MASK when calling setFlags.
784     * {@hide}
785     */
786    static final int DISABLED = 0x00000020;
787
788   /**
789    * Mask for use with setFlags indicating bits used for indicating whether
790    * this view is enabled
791    * {@hide}
792    */
793    static final int ENABLED_MASK = 0x00000020;
794
795    /**
796     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
797     * called and further optimizations will be performed. It is okay to have
798     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
799     * {@hide}
800     */
801    static final int WILL_NOT_DRAW = 0x00000080;
802
803    /**
804     * Mask for use with setFlags indicating bits used for indicating whether
805     * this view is will draw
806     * {@hide}
807     */
808    static final int DRAW_MASK = 0x00000080;
809
810    /**
811     * <p>This view doesn't show scrollbars.</p>
812     * {@hide}
813     */
814    static final int SCROLLBARS_NONE = 0x00000000;
815
816    /**
817     * <p>This view shows horizontal scrollbars.</p>
818     * {@hide}
819     */
820    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
821
822    /**
823     * <p>This view shows vertical scrollbars.</p>
824     * {@hide}
825     */
826    static final int SCROLLBARS_VERTICAL = 0x00000200;
827
828    /**
829     * <p>Mask for use with setFlags indicating bits used for indicating which
830     * scrollbars are enabled.</p>
831     * {@hide}
832     */
833    static final int SCROLLBARS_MASK = 0x00000300;
834
835    /**
836     * Indicates that the view should filter touches when its window is obscured.
837     * Refer to the class comments for more information about this security feature.
838     * {@hide}
839     */
840    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
841
842    /**
843     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
844     * that they are optional and should be skipped if the window has
845     * requested system UI flags that ignore those insets for layout.
846     */
847    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
848
849    /**
850     * <p>This view doesn't show fading edges.</p>
851     * {@hide}
852     */
853    static final int FADING_EDGE_NONE = 0x00000000;
854
855    /**
856     * <p>This view shows horizontal fading edges.</p>
857     * {@hide}
858     */
859    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
860
861    /**
862     * <p>This view shows vertical fading edges.</p>
863     * {@hide}
864     */
865    static final int FADING_EDGE_VERTICAL = 0x00002000;
866
867    /**
868     * <p>Mask for use with setFlags indicating bits used for indicating which
869     * fading edges are enabled.</p>
870     * {@hide}
871     */
872    static final int FADING_EDGE_MASK = 0x00003000;
873
874    /**
875     * <p>Indicates this view can be clicked. When clickable, a View reacts
876     * to clicks by notifying the OnClickListener.<p>
877     * {@hide}
878     */
879    static final int CLICKABLE = 0x00004000;
880
881    /**
882     * <p>Indicates this view is caching its drawing into a bitmap.</p>
883     * {@hide}
884     */
885    static final int DRAWING_CACHE_ENABLED = 0x00008000;
886
887    /**
888     * <p>Indicates that no icicle should be saved for this view.<p>
889     * {@hide}
890     */
891    static final int SAVE_DISABLED = 0x000010000;
892
893    /**
894     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
895     * property.</p>
896     * {@hide}
897     */
898    static final int SAVE_DISABLED_MASK = 0x000010000;
899
900    /**
901     * <p>Indicates that no drawing cache should ever be created for this view.<p>
902     * {@hide}
903     */
904    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
905
906    /**
907     * <p>Indicates this view can take / keep focus when int touch mode.</p>
908     * {@hide}
909     */
910    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
911
912    /** @hide */
913    @Retention(RetentionPolicy.SOURCE)
914    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
915    public @interface DrawingCacheQuality {}
916
917    /**
918     * <p>Enables low quality mode for the drawing cache.</p>
919     */
920    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
921
922    /**
923     * <p>Enables high quality mode for the drawing cache.</p>
924     */
925    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
926
927    /**
928     * <p>Enables automatic quality mode for the drawing cache.</p>
929     */
930    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
931
932    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
933            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
934    };
935
936    /**
937     * <p>Mask for use with setFlags indicating bits used for the cache
938     * quality property.</p>
939     * {@hide}
940     */
941    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
942
943    /**
944     * <p>
945     * Indicates this view can be long clicked. When long clickable, a View
946     * reacts to long clicks by notifying the OnLongClickListener or showing a
947     * context menu.
948     * </p>
949     * {@hide}
950     */
951    static final int LONG_CLICKABLE = 0x00200000;
952
953    /**
954     * <p>Indicates that this view gets its drawable states from its direct parent
955     * and ignores its original internal states.</p>
956     *
957     * @hide
958     */
959    static final int DUPLICATE_PARENT_STATE = 0x00400000;
960
961    /** @hide */
962    @IntDef({
963        SCROLLBARS_INSIDE_OVERLAY,
964        SCROLLBARS_INSIDE_INSET,
965        SCROLLBARS_OUTSIDE_OVERLAY,
966        SCROLLBARS_OUTSIDE_INSET
967    })
968    @Retention(RetentionPolicy.SOURCE)
969    public @interface ScrollBarStyle {}
970
971    /**
972     * The scrollbar style to display the scrollbars inside the content area,
973     * without increasing the padding. The scrollbars will be overlaid with
974     * translucency on the view's content.
975     */
976    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
977
978    /**
979     * The scrollbar style to display the scrollbars inside the padded area,
980     * increasing the padding of the view. The scrollbars will not overlap the
981     * content area of the view.
982     */
983    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
984
985    /**
986     * The scrollbar style to display the scrollbars at the edge of the view,
987     * without increasing the padding. The scrollbars will be overlaid with
988     * translucency.
989     */
990    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
991
992    /**
993     * The scrollbar style to display the scrollbars at the edge of the view,
994     * increasing the padding of the view. The scrollbars will only overlap the
995     * background, if any.
996     */
997    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
998
999    /**
1000     * Mask to check if the scrollbar style is overlay or inset.
1001     * {@hide}
1002     */
1003    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1004
1005    /**
1006     * Mask to check if the scrollbar style is inside or outside.
1007     * {@hide}
1008     */
1009    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1010
1011    /**
1012     * Mask for scrollbar style.
1013     * {@hide}
1014     */
1015    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1016
1017    /**
1018     * View flag indicating that the screen should remain on while the
1019     * window containing this view is visible to the user.  This effectively
1020     * takes care of automatically setting the WindowManager's
1021     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1022     */
1023    public static final int KEEP_SCREEN_ON = 0x04000000;
1024
1025    /**
1026     * View flag indicating whether this view should have sound effects enabled
1027     * for events such as clicking and touching.
1028     */
1029    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1030
1031    /**
1032     * View flag indicating whether this view should have haptic feedback
1033     * enabled for events such as long presses.
1034     */
1035    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1036
1037    /**
1038     * <p>Indicates that the view hierarchy should stop saving state when
1039     * it reaches this view.  If state saving is initiated immediately at
1040     * the view, it will be allowed.
1041     * {@hide}
1042     */
1043    static final int PARENT_SAVE_DISABLED = 0x20000000;
1044
1045    /**
1046     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1047     * {@hide}
1048     */
1049    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1050
1051    /** @hide */
1052    @IntDef(flag = true,
1053            value = {
1054                FOCUSABLES_ALL,
1055                FOCUSABLES_TOUCH_MODE
1056            })
1057    @Retention(RetentionPolicy.SOURCE)
1058    public @interface FocusableMode {}
1059
1060    /**
1061     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1062     * should add all focusable Views regardless if they are focusable in touch mode.
1063     */
1064    public static final int FOCUSABLES_ALL = 0x00000000;
1065
1066    /**
1067     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1068     * should add only Views focusable in touch mode.
1069     */
1070    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1071
1072    /** @hide */
1073    @IntDef({
1074            FOCUS_BACKWARD,
1075            FOCUS_FORWARD,
1076            FOCUS_LEFT,
1077            FOCUS_UP,
1078            FOCUS_RIGHT,
1079            FOCUS_DOWN
1080    })
1081    @Retention(RetentionPolicy.SOURCE)
1082    public @interface FocusDirection {}
1083
1084    /** @hide */
1085    @IntDef({
1086            FOCUS_LEFT,
1087            FOCUS_UP,
1088            FOCUS_RIGHT,
1089            FOCUS_DOWN
1090    })
1091    @Retention(RetentionPolicy.SOURCE)
1092    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1093
1094    /**
1095     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1096     * item.
1097     */
1098    public static final int FOCUS_BACKWARD = 0x00000001;
1099
1100    /**
1101     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1102     * item.
1103     */
1104    public static final int FOCUS_FORWARD = 0x00000002;
1105
1106    /**
1107     * Use with {@link #focusSearch(int)}. Move focus to the left.
1108     */
1109    public static final int FOCUS_LEFT = 0x00000011;
1110
1111    /**
1112     * Use with {@link #focusSearch(int)}. Move focus up.
1113     */
1114    public static final int FOCUS_UP = 0x00000021;
1115
1116    /**
1117     * Use with {@link #focusSearch(int)}. Move focus to the right.
1118     */
1119    public static final int FOCUS_RIGHT = 0x00000042;
1120
1121    /**
1122     * Use with {@link #focusSearch(int)}. Move focus down.
1123     */
1124    public static final int FOCUS_DOWN = 0x00000082;
1125
1126    /**
1127     * Bits of {@link #getMeasuredWidthAndState()} and
1128     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1129     */
1130    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1131
1132    /**
1133     * Bits of {@link #getMeasuredWidthAndState()} and
1134     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1135     */
1136    public static final int MEASURED_STATE_MASK = 0xff000000;
1137
1138    /**
1139     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1140     * for functions that combine both width and height into a single int,
1141     * such as {@link #getMeasuredState()} and the childState argument of
1142     * {@link #resolveSizeAndState(int, int, int)}.
1143     */
1144    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1145
1146    /**
1147     * Bit of {@link #getMeasuredWidthAndState()} and
1148     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1149     * is smaller that the space the view would like to have.
1150     */
1151    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1152
1153    /**
1154     * Base View state sets
1155     */
1156    // Singles
1157    /**
1158     * Indicates the view has no states set. States are used with
1159     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1160     * view depending on its state.
1161     *
1162     * @see android.graphics.drawable.Drawable
1163     * @see #getDrawableState()
1164     */
1165    protected static final int[] EMPTY_STATE_SET;
1166    /**
1167     * Indicates the view is enabled. States are used with
1168     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1169     * view depending on its state.
1170     *
1171     * @see android.graphics.drawable.Drawable
1172     * @see #getDrawableState()
1173     */
1174    protected static final int[] ENABLED_STATE_SET;
1175    /**
1176     * Indicates the view is focused. States are used with
1177     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1178     * view depending on its state.
1179     *
1180     * @see android.graphics.drawable.Drawable
1181     * @see #getDrawableState()
1182     */
1183    protected static final int[] FOCUSED_STATE_SET;
1184    /**
1185     * Indicates the view is selected. States are used with
1186     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1187     * view depending on its state.
1188     *
1189     * @see android.graphics.drawable.Drawable
1190     * @see #getDrawableState()
1191     */
1192    protected static final int[] SELECTED_STATE_SET;
1193    /**
1194     * Indicates the view is pressed. States are used with
1195     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1196     * view depending on its state.
1197     *
1198     * @see android.graphics.drawable.Drawable
1199     * @see #getDrawableState()
1200     */
1201    protected static final int[] PRESSED_STATE_SET;
1202    /**
1203     * Indicates the view's window has focus. States are used with
1204     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1205     * view depending on its state.
1206     *
1207     * @see android.graphics.drawable.Drawable
1208     * @see #getDrawableState()
1209     */
1210    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1211    // Doubles
1212    /**
1213     * Indicates the view is enabled and has the focus.
1214     *
1215     * @see #ENABLED_STATE_SET
1216     * @see #FOCUSED_STATE_SET
1217     */
1218    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1219    /**
1220     * Indicates the view is enabled and selected.
1221     *
1222     * @see #ENABLED_STATE_SET
1223     * @see #SELECTED_STATE_SET
1224     */
1225    protected static final int[] ENABLED_SELECTED_STATE_SET;
1226    /**
1227     * Indicates the view is enabled and that its window has focus.
1228     *
1229     * @see #ENABLED_STATE_SET
1230     * @see #WINDOW_FOCUSED_STATE_SET
1231     */
1232    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1233    /**
1234     * Indicates the view is focused and selected.
1235     *
1236     * @see #FOCUSED_STATE_SET
1237     * @see #SELECTED_STATE_SET
1238     */
1239    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1240    /**
1241     * Indicates the view has the focus and that its window has the focus.
1242     *
1243     * @see #FOCUSED_STATE_SET
1244     * @see #WINDOW_FOCUSED_STATE_SET
1245     */
1246    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1247    /**
1248     * Indicates the view is selected and that its window has the focus.
1249     *
1250     * @see #SELECTED_STATE_SET
1251     * @see #WINDOW_FOCUSED_STATE_SET
1252     */
1253    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1254    // Triples
1255    /**
1256     * Indicates the view is enabled, focused and selected.
1257     *
1258     * @see #ENABLED_STATE_SET
1259     * @see #FOCUSED_STATE_SET
1260     * @see #SELECTED_STATE_SET
1261     */
1262    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1263    /**
1264     * Indicates the view is enabled, focused and its window has the focus.
1265     *
1266     * @see #ENABLED_STATE_SET
1267     * @see #FOCUSED_STATE_SET
1268     * @see #WINDOW_FOCUSED_STATE_SET
1269     */
1270    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1271    /**
1272     * Indicates the view is enabled, selected and its window has the focus.
1273     *
1274     * @see #ENABLED_STATE_SET
1275     * @see #SELECTED_STATE_SET
1276     * @see #WINDOW_FOCUSED_STATE_SET
1277     */
1278    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1279    /**
1280     * Indicates the view is focused, selected and its window has the focus.
1281     *
1282     * @see #FOCUSED_STATE_SET
1283     * @see #SELECTED_STATE_SET
1284     * @see #WINDOW_FOCUSED_STATE_SET
1285     */
1286    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1287    /**
1288     * Indicates the view is enabled, focused, selected and its window
1289     * has the focus.
1290     *
1291     * @see #ENABLED_STATE_SET
1292     * @see #FOCUSED_STATE_SET
1293     * @see #SELECTED_STATE_SET
1294     * @see #WINDOW_FOCUSED_STATE_SET
1295     */
1296    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1297    /**
1298     * Indicates the view is pressed and its window has the focus.
1299     *
1300     * @see #PRESSED_STATE_SET
1301     * @see #WINDOW_FOCUSED_STATE_SET
1302     */
1303    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1304    /**
1305     * Indicates the view is pressed and selected.
1306     *
1307     * @see #PRESSED_STATE_SET
1308     * @see #SELECTED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_SELECTED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, selected and its window has the focus.
1313     *
1314     * @see #PRESSED_STATE_SET
1315     * @see #SELECTED_STATE_SET
1316     * @see #WINDOW_FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed and focused.
1321     *
1322     * @see #PRESSED_STATE_SET
1323     * @see #FOCUSED_STATE_SET
1324     */
1325    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1326    /**
1327     * Indicates the view is pressed, focused and its window has the focus.
1328     *
1329     * @see #PRESSED_STATE_SET
1330     * @see #FOCUSED_STATE_SET
1331     * @see #WINDOW_FOCUSED_STATE_SET
1332     */
1333    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1334    /**
1335     * Indicates the view is pressed, focused and selected.
1336     *
1337     * @see #PRESSED_STATE_SET
1338     * @see #SELECTED_STATE_SET
1339     * @see #FOCUSED_STATE_SET
1340     */
1341    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1342    /**
1343     * Indicates the view is pressed, focused, selected and its window has the focus.
1344     *
1345     * @see #PRESSED_STATE_SET
1346     * @see #FOCUSED_STATE_SET
1347     * @see #SELECTED_STATE_SET
1348     * @see #WINDOW_FOCUSED_STATE_SET
1349     */
1350    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1351    /**
1352     * Indicates the view is pressed and enabled.
1353     *
1354     * @see #PRESSED_STATE_SET
1355     * @see #ENABLED_STATE_SET
1356     */
1357    protected static final int[] PRESSED_ENABLED_STATE_SET;
1358    /**
1359     * Indicates the view is pressed, enabled and its window has the focus.
1360     *
1361     * @see #PRESSED_STATE_SET
1362     * @see #ENABLED_STATE_SET
1363     * @see #WINDOW_FOCUSED_STATE_SET
1364     */
1365    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1366    /**
1367     * Indicates the view is pressed, enabled and selected.
1368     *
1369     * @see #PRESSED_STATE_SET
1370     * @see #ENABLED_STATE_SET
1371     * @see #SELECTED_STATE_SET
1372     */
1373    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1374    /**
1375     * Indicates the view is pressed, enabled, selected and its window has the
1376     * focus.
1377     *
1378     * @see #PRESSED_STATE_SET
1379     * @see #ENABLED_STATE_SET
1380     * @see #SELECTED_STATE_SET
1381     * @see #WINDOW_FOCUSED_STATE_SET
1382     */
1383    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1384    /**
1385     * Indicates the view is pressed, enabled and focused.
1386     *
1387     * @see #PRESSED_STATE_SET
1388     * @see #ENABLED_STATE_SET
1389     * @see #FOCUSED_STATE_SET
1390     */
1391    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1392    /**
1393     * Indicates the view is pressed, enabled, focused and its window has the
1394     * focus.
1395     *
1396     * @see #PRESSED_STATE_SET
1397     * @see #ENABLED_STATE_SET
1398     * @see #FOCUSED_STATE_SET
1399     * @see #WINDOW_FOCUSED_STATE_SET
1400     */
1401    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1402    /**
1403     * Indicates the view is pressed, enabled, focused and selected.
1404     *
1405     * @see #PRESSED_STATE_SET
1406     * @see #ENABLED_STATE_SET
1407     * @see #SELECTED_STATE_SET
1408     * @see #FOCUSED_STATE_SET
1409     */
1410    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1411    /**
1412     * Indicates the view is pressed, enabled, focused, selected and its window
1413     * has the focus.
1414     *
1415     * @see #PRESSED_STATE_SET
1416     * @see #ENABLED_STATE_SET
1417     * @see #SELECTED_STATE_SET
1418     * @see #FOCUSED_STATE_SET
1419     * @see #WINDOW_FOCUSED_STATE_SET
1420     */
1421    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1422
1423    /**
1424     * The order here is very important to {@link #getDrawableState()}
1425     */
1426    private static final int[][] VIEW_STATE_SETS;
1427
1428    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1429    static final int VIEW_STATE_SELECTED = 1 << 1;
1430    static final int VIEW_STATE_FOCUSED = 1 << 2;
1431    static final int VIEW_STATE_ENABLED = 1 << 3;
1432    static final int VIEW_STATE_PRESSED = 1 << 4;
1433    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1434    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1435    static final int VIEW_STATE_HOVERED = 1 << 7;
1436    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1437    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1438
1439    static final int[] VIEW_STATE_IDS = new int[] {
1440        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1441        R.attr.state_selected,          VIEW_STATE_SELECTED,
1442        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1443        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1444        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1445        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1446        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1447        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1448        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1449        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1450    };
1451
1452    static {
1453        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1454            throw new IllegalStateException(
1455                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1456        }
1457        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1458        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1459            int viewState = R.styleable.ViewDrawableStates[i];
1460            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1461                if (VIEW_STATE_IDS[j] == viewState) {
1462                    orderedIds[i * 2] = viewState;
1463                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1464                }
1465            }
1466        }
1467        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1468        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1469        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1470            int numBits = Integer.bitCount(i);
1471            int[] set = new int[numBits];
1472            int pos = 0;
1473            for (int j = 0; j < orderedIds.length; j += 2) {
1474                if ((i & orderedIds[j+1]) != 0) {
1475                    set[pos++] = orderedIds[j];
1476                }
1477            }
1478            VIEW_STATE_SETS[i] = set;
1479        }
1480
1481        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1482        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1483        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1484        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1485                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1486        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1487        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1488                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1489        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1490                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1491        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1492                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1493                | VIEW_STATE_FOCUSED];
1494        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1495        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1497        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1499        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1500                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1501                | VIEW_STATE_ENABLED];
1502        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1504        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1505                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1506                | VIEW_STATE_ENABLED];
1507        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1508                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1509                | VIEW_STATE_ENABLED];
1510        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1512                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1513
1514        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1515        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1516                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1517        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1518                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1519        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1520                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1521                | VIEW_STATE_PRESSED];
1522        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1523                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1524        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1525                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1526                | VIEW_STATE_PRESSED];
1527        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1528                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1529                | VIEW_STATE_PRESSED];
1530        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1532                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1533        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1534                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1535        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1536                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1537                | VIEW_STATE_PRESSED];
1538        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1539                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1540                | VIEW_STATE_PRESSED];
1541        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1543                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1544        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1546                | VIEW_STATE_PRESSED];
1547        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1548                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1549                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1550        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1551                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1552                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1553        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1554                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1555                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1556                | VIEW_STATE_PRESSED];
1557    }
1558
1559    /**
1560     * Accessibility event types that are dispatched for text population.
1561     */
1562    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1563            AccessibilityEvent.TYPE_VIEW_CLICKED
1564            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1565            | AccessibilityEvent.TYPE_VIEW_SELECTED
1566            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1567            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1568            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1569            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1570            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1571            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1572            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1573            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1574
1575    /**
1576     * Temporary Rect currently for use in setBackground().  This will probably
1577     * be extended in the future to hold our own class with more than just
1578     * a Rect. :)
1579     */
1580    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1581
1582    /**
1583     * Map used to store views' tags.
1584     */
1585    private SparseArray<Object> mKeyedTags;
1586
1587    /**
1588     * The next available accessibility id.
1589     */
1590    private static int sNextAccessibilityViewId;
1591
1592    /**
1593     * The animation currently associated with this view.
1594     * @hide
1595     */
1596    protected Animation mCurrentAnimation = null;
1597
1598    /**
1599     * Width as measured during measure pass.
1600     * {@hide}
1601     */
1602    @ViewDebug.ExportedProperty(category = "measurement")
1603    int mMeasuredWidth;
1604
1605    /**
1606     * Height as measured during measure pass.
1607     * {@hide}
1608     */
1609    @ViewDebug.ExportedProperty(category = "measurement")
1610    int mMeasuredHeight;
1611
1612    /**
1613     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1614     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1615     * its display list. This flag, used only when hw accelerated, allows us to clear the
1616     * flag while retaining this information until it's needed (at getDisplayList() time and
1617     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1618     *
1619     * {@hide}
1620     */
1621    boolean mRecreateDisplayList = false;
1622
1623    /**
1624     * The view's identifier.
1625     * {@hide}
1626     *
1627     * @see #setId(int)
1628     * @see #getId()
1629     */
1630    @ViewDebug.ExportedProperty(resolveId = true)
1631    int mID = NO_ID;
1632
1633    /**
1634     * The stable ID of this view for accessibility purposes.
1635     */
1636    int mAccessibilityViewId = NO_ID;
1637
1638    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1639
1640    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1641
1642    /**
1643     * The view's tag.
1644     * {@hide}
1645     *
1646     * @see #setTag(Object)
1647     * @see #getTag()
1648     */
1649    protected Object mTag = null;
1650
1651    // for mPrivateFlags:
1652    /** {@hide} */
1653    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1654    /** {@hide} */
1655    static final int PFLAG_FOCUSED                     = 0x00000002;
1656    /** {@hide} */
1657    static final int PFLAG_SELECTED                    = 0x00000004;
1658    /** {@hide} */
1659    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1660    /** {@hide} */
1661    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1662    /** {@hide} */
1663    static final int PFLAG_DRAWN                       = 0x00000020;
1664    /**
1665     * When this flag is set, this view is running an animation on behalf of its
1666     * children and should therefore not cancel invalidate requests, even if they
1667     * lie outside of this view's bounds.
1668     *
1669     * {@hide}
1670     */
1671    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1672    /** {@hide} */
1673    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1674    /** {@hide} */
1675    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1676    /** {@hide} */
1677    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1678    /** {@hide} */
1679    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1680    /** {@hide} */
1681    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1682    /** {@hide} */
1683    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1684    /** {@hide} */
1685    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1686
1687    private static final int PFLAG_PRESSED             = 0x00004000;
1688
1689    /** {@hide} */
1690    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1691    /**
1692     * Flag used to indicate that this view should be drawn once more (and only once
1693     * more) after its animation has completed.
1694     * {@hide}
1695     */
1696    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1697
1698    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1699
1700    /**
1701     * Indicates that the View returned true when onSetAlpha() was called and that
1702     * the alpha must be restored.
1703     * {@hide}
1704     */
1705    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1706
1707    /**
1708     * Set by {@link #setScrollContainer(boolean)}.
1709     */
1710    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1711
1712    /**
1713     * Set by {@link #setScrollContainer(boolean)}.
1714     */
1715    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1716
1717    /**
1718     * View flag indicating whether this view was invalidated (fully or partially.)
1719     *
1720     * @hide
1721     */
1722    static final int PFLAG_DIRTY                       = 0x00200000;
1723
1724    /**
1725     * View flag indicating whether this view was invalidated by an opaque
1726     * invalidate request.
1727     *
1728     * @hide
1729     */
1730    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1731
1732    /**
1733     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1734     *
1735     * @hide
1736     */
1737    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1738
1739    /**
1740     * Indicates whether the background is opaque.
1741     *
1742     * @hide
1743     */
1744    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1745
1746    /**
1747     * Indicates whether the scrollbars are opaque.
1748     *
1749     * @hide
1750     */
1751    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1752
1753    /**
1754     * Indicates whether the view is opaque.
1755     *
1756     * @hide
1757     */
1758    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1759
1760    /**
1761     * Indicates a prepressed state;
1762     * the short time between ACTION_DOWN and recognizing
1763     * a 'real' press. Prepressed is used to recognize quick taps
1764     * even when they are shorter than ViewConfiguration.getTapTimeout().
1765     *
1766     * @hide
1767     */
1768    private static final int PFLAG_PREPRESSED          = 0x02000000;
1769
1770    /**
1771     * Indicates whether the view is temporarily detached.
1772     *
1773     * @hide
1774     */
1775    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1776
1777    /**
1778     * Indicates that we should awaken scroll bars once attached
1779     *
1780     * @hide
1781     */
1782    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1783
1784    /**
1785     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1786     * @hide
1787     */
1788    private static final int PFLAG_HOVERED             = 0x10000000;
1789
1790    /**
1791     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1792     * for transform operations
1793     *
1794     * @hide
1795     */
1796    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1797
1798    /** {@hide} */
1799    static final int PFLAG_ACTIVATED                   = 0x40000000;
1800
1801    /**
1802     * Indicates that this view was specifically invalidated, not just dirtied because some
1803     * child view was invalidated. The flag is used to determine when we need to recreate
1804     * a view's display list (as opposed to just returning a reference to its existing
1805     * display list).
1806     *
1807     * @hide
1808     */
1809    static final int PFLAG_INVALIDATED                 = 0x80000000;
1810
1811    /**
1812     * Masks for mPrivateFlags2, as generated by dumpFlags():
1813     *
1814     * |-------|-------|-------|-------|
1815     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1816     *                                1  PFLAG2_DRAG_HOVERED
1817     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1818     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1819     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1820     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1821     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1822     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1823     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1824     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1825     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1826     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1827     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1828     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1829     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1830     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1831     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1832     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1833     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1834     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1835     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1836     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1837     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1838     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1839     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1840     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1841     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1842     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1843     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1844     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1845     *    1                              PFLAG2_PADDING_RESOLVED
1846     *   1                               PFLAG2_DRAWABLE_RESOLVED
1847     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1848     * |-------|-------|-------|-------|
1849     */
1850
1851    /**
1852     * Indicates that this view has reported that it can accept the current drag's content.
1853     * Cleared when the drag operation concludes.
1854     * @hide
1855     */
1856    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1857
1858    /**
1859     * Indicates that this view is currently directly under the drag location in a
1860     * drag-and-drop operation involving content that it can accept.  Cleared when
1861     * the drag exits the view, or when the drag operation concludes.
1862     * @hide
1863     */
1864    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1865
1866    /** @hide */
1867    @IntDef({
1868        LAYOUT_DIRECTION_LTR,
1869        LAYOUT_DIRECTION_RTL,
1870        LAYOUT_DIRECTION_INHERIT,
1871        LAYOUT_DIRECTION_LOCALE
1872    })
1873    @Retention(RetentionPolicy.SOURCE)
1874    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1875    public @interface LayoutDir {}
1876
1877    /** @hide */
1878    @IntDef({
1879        LAYOUT_DIRECTION_LTR,
1880        LAYOUT_DIRECTION_RTL
1881    })
1882    @Retention(RetentionPolicy.SOURCE)
1883    public @interface ResolvedLayoutDir {}
1884
1885    /**
1886     * Horizontal layout direction of this view is from Left to Right.
1887     * Use with {@link #setLayoutDirection}.
1888     */
1889    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1890
1891    /**
1892     * Horizontal layout direction of this view is from Right to Left.
1893     * Use with {@link #setLayoutDirection}.
1894     */
1895    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1896
1897    /**
1898     * Horizontal layout direction of this view is inherited from its parent.
1899     * Use with {@link #setLayoutDirection}.
1900     */
1901    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1902
1903    /**
1904     * Horizontal layout direction of this view is from deduced from the default language
1905     * script for the locale. Use with {@link #setLayoutDirection}.
1906     */
1907    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1908
1909    /**
1910     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1911     * @hide
1912     */
1913    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1914
1915    /**
1916     * Mask for use with private flags indicating bits used for horizontal layout direction.
1917     * @hide
1918     */
1919    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1920
1921    /**
1922     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1923     * right-to-left direction.
1924     * @hide
1925     */
1926    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1927
1928    /**
1929     * Indicates whether the view horizontal layout direction has been resolved.
1930     * @hide
1931     */
1932    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1933
1934    /**
1935     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1936     * @hide
1937     */
1938    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1939            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1940
1941    /*
1942     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1943     * flag value.
1944     * @hide
1945     */
1946    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1947            LAYOUT_DIRECTION_LTR,
1948            LAYOUT_DIRECTION_RTL,
1949            LAYOUT_DIRECTION_INHERIT,
1950            LAYOUT_DIRECTION_LOCALE
1951    };
1952
1953    /**
1954     * Default horizontal layout direction.
1955     */
1956    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1957
1958    /**
1959     * Default horizontal layout direction.
1960     * @hide
1961     */
1962    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1963
1964    /**
1965     * Text direction is inherited thru {@link ViewGroup}
1966     */
1967    public static final int TEXT_DIRECTION_INHERIT = 0;
1968
1969    /**
1970     * Text direction is using "first strong algorithm". The first strong directional character
1971     * determines the paragraph direction. If there is no strong directional character, the
1972     * paragraph direction is the view's resolved layout direction.
1973     */
1974    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1975
1976    /**
1977     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1978     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1979     * If there are neither, the paragraph direction is the view's resolved layout direction.
1980     */
1981    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1982
1983    /**
1984     * Text direction is forced to LTR.
1985     */
1986    public static final int TEXT_DIRECTION_LTR = 3;
1987
1988    /**
1989     * Text direction is forced to RTL.
1990     */
1991    public static final int TEXT_DIRECTION_RTL = 4;
1992
1993    /**
1994     * Text direction is coming from the system Locale.
1995     */
1996    public static final int TEXT_DIRECTION_LOCALE = 5;
1997
1998    /**
1999     * Default text direction is inherited
2000     */
2001    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2002
2003    /**
2004     * Default resolved text direction
2005     * @hide
2006     */
2007    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2008
2009    /**
2010     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2011     * @hide
2012     */
2013    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2014
2015    /**
2016     * Mask for use with private flags indicating bits used for text direction.
2017     * @hide
2018     */
2019    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2020            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2021
2022    /**
2023     * Array of text direction flags for mapping attribute "textDirection" to correct
2024     * flag value.
2025     * @hide
2026     */
2027    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2028            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2029            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2030            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2031            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2032            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2033            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2034    };
2035
2036    /**
2037     * Indicates whether the view text direction has been resolved.
2038     * @hide
2039     */
2040    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2041            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2042
2043    /**
2044     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2045     * @hide
2046     */
2047    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2048
2049    /**
2050     * Mask for use with private flags indicating bits used for resolved text direction.
2051     * @hide
2052     */
2053    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2054            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2055
2056    /**
2057     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2058     * @hide
2059     */
2060    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2061            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2062
2063    /** @hide */
2064    @IntDef({
2065        TEXT_ALIGNMENT_INHERIT,
2066        TEXT_ALIGNMENT_GRAVITY,
2067        TEXT_ALIGNMENT_CENTER,
2068        TEXT_ALIGNMENT_TEXT_START,
2069        TEXT_ALIGNMENT_TEXT_END,
2070        TEXT_ALIGNMENT_VIEW_START,
2071        TEXT_ALIGNMENT_VIEW_END
2072    })
2073    @Retention(RetentionPolicy.SOURCE)
2074    public @interface TextAlignment {}
2075
2076    /**
2077     * Default text alignment. The text alignment of this View is inherited from its parent.
2078     * Use with {@link #setTextAlignment(int)}
2079     */
2080    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2081
2082    /**
2083     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2084     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2085     *
2086     * Use with {@link #setTextAlignment(int)}
2087     */
2088    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2089
2090    /**
2091     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2092     *
2093     * Use with {@link #setTextAlignment(int)}
2094     */
2095    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2096
2097    /**
2098     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2099     *
2100     * Use with {@link #setTextAlignment(int)}
2101     */
2102    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2103
2104    /**
2105     * Center the paragraph, e.g. ALIGN_CENTER.
2106     *
2107     * Use with {@link #setTextAlignment(int)}
2108     */
2109    public static final int TEXT_ALIGNMENT_CENTER = 4;
2110
2111    /**
2112     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2113     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2114     *
2115     * Use with {@link #setTextAlignment(int)}
2116     */
2117    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2118
2119    /**
2120     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2121     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2122     *
2123     * Use with {@link #setTextAlignment(int)}
2124     */
2125    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2126
2127    /**
2128     * Default text alignment is inherited
2129     */
2130    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2131
2132    /**
2133     * Default resolved text alignment
2134     * @hide
2135     */
2136    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2137
2138    /**
2139      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2140      * @hide
2141      */
2142    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2143
2144    /**
2145      * Mask for use with private flags indicating bits used for text alignment.
2146      * @hide
2147      */
2148    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2149
2150    /**
2151     * Array of text direction flags for mapping attribute "textAlignment" to correct
2152     * flag value.
2153     * @hide
2154     */
2155    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2156            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2157            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2158            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2159            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2160            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2161            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2162            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2163    };
2164
2165    /**
2166     * Indicates whether the view text alignment has been resolved.
2167     * @hide
2168     */
2169    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2170
2171    /**
2172     * Bit shift to get the resolved text alignment.
2173     * @hide
2174     */
2175    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2176
2177    /**
2178     * Mask for use with private flags indicating bits used for text alignment.
2179     * @hide
2180     */
2181    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2182            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2183
2184    /**
2185     * Indicates whether if the view text alignment has been resolved to gravity
2186     */
2187    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2188            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2189
2190    // Accessiblity constants for mPrivateFlags2
2191
2192    /**
2193     * Shift for the bits in {@link #mPrivateFlags2} related to the
2194     * "importantForAccessibility" attribute.
2195     */
2196    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2197
2198    /**
2199     * Automatically determine whether a view is important for accessibility.
2200     */
2201    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2202
2203    /**
2204     * The view is important for accessibility.
2205     */
2206    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2207
2208    /**
2209     * The view is not important for accessibility.
2210     */
2211    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2212
2213    /**
2214     * The view is not important for accessibility, nor are any of its
2215     * descendant views.
2216     */
2217    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2218
2219    /**
2220     * The default whether the view is important for accessibility.
2221     */
2222    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2223
2224    /**
2225     * Mask for obtainig the bits which specify how to determine
2226     * whether a view is important for accessibility.
2227     */
2228    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2229        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2230        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2231        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2232
2233    /**
2234     * Shift for the bits in {@link #mPrivateFlags2} related to the
2235     * "accessibilityLiveRegion" attribute.
2236     */
2237    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2238
2239    /**
2240     * Live region mode specifying that accessibility services should not
2241     * automatically announce changes to this view. This is the default live
2242     * region mode for most views.
2243     * <p>
2244     * Use with {@link #setAccessibilityLiveRegion(int)}.
2245     */
2246    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2247
2248    /**
2249     * Live region mode specifying that accessibility services should announce
2250     * changes to this view.
2251     * <p>
2252     * Use with {@link #setAccessibilityLiveRegion(int)}.
2253     */
2254    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2255
2256    /**
2257     * Live region mode specifying that accessibility services should interrupt
2258     * ongoing speech to immediately announce changes to this view.
2259     * <p>
2260     * Use with {@link #setAccessibilityLiveRegion(int)}.
2261     */
2262    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2263
2264    /**
2265     * The default whether the view is important for accessibility.
2266     */
2267    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2268
2269    /**
2270     * Mask for obtaining the bits which specify a view's accessibility live
2271     * region mode.
2272     */
2273    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2274            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2275            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2276
2277    /**
2278     * Flag indicating whether a view has accessibility focus.
2279     */
2280    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2281
2282    /**
2283     * Flag whether the accessibility state of the subtree rooted at this view changed.
2284     */
2285    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2286
2287    /**
2288     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2289     * is used to check whether later changes to the view's transform should invalidate the
2290     * view to force the quickReject test to run again.
2291     */
2292    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2293
2294    /**
2295     * Flag indicating that start/end padding has been resolved into left/right padding
2296     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2297     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2298     * during measurement. In some special cases this is required such as when an adapter-based
2299     * view measures prospective children without attaching them to a window.
2300     */
2301    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2302
2303    /**
2304     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2305     */
2306    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2307
2308    /**
2309     * Indicates that the view is tracking some sort of transient state
2310     * that the app should not need to be aware of, but that the framework
2311     * should take special care to preserve.
2312     */
2313    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2314
2315    /**
2316     * Group of bits indicating that RTL properties resolution is done.
2317     */
2318    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2319            PFLAG2_TEXT_DIRECTION_RESOLVED |
2320            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2321            PFLAG2_PADDING_RESOLVED |
2322            PFLAG2_DRAWABLE_RESOLVED;
2323
2324    // There are a couple of flags left in mPrivateFlags2
2325
2326    /* End of masks for mPrivateFlags2 */
2327
2328    /**
2329     * Masks for mPrivateFlags3, as generated by dumpFlags():
2330     *
2331     * |-------|-------|-------|-------|
2332     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2333     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2334     *                               1   PFLAG3_IS_LAID_OUT
2335     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2336     *                             1     PFLAG3_CALLED_SUPER
2337     * |-------|-------|-------|-------|
2338     */
2339
2340    /**
2341     * Flag indicating that view has a transform animation set on it. This is used to track whether
2342     * an animation is cleared between successive frames, in order to tell the associated
2343     * DisplayList to clear its animation matrix.
2344     */
2345    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2346
2347    /**
2348     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2349     * animation is cleared between successive frames, in order to tell the associated
2350     * DisplayList to restore its alpha value.
2351     */
2352    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2353
2354    /**
2355     * Flag indicating that the view has been through at least one layout since it
2356     * was last attached to a window.
2357     */
2358    static final int PFLAG3_IS_LAID_OUT = 0x4;
2359
2360    /**
2361     * Flag indicating that a call to measure() was skipped and should be done
2362     * instead when layout() is invoked.
2363     */
2364    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2365
2366    /**
2367     * Flag indicating that an overridden method correctly  called down to
2368     * the superclass implementation as required by the API spec.
2369     */
2370    static final int PFLAG3_CALLED_SUPER = 0x10;
2371
2372    /**
2373     * Flag indicating that an view will be clipped to its outline.
2374     */
2375    static final int PFLAG3_CLIP_TO_OUTLINE = 0x20;
2376
2377    /**
2378     * Flag indicating that we're in the process of applying window insets.
2379     */
2380    static final int PFLAG3_APPLYING_INSETS = 0x40;
2381
2382    /**
2383     * Flag indicating that we're in the process of fitting system windows using the old method.
2384     */
2385    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80;
2386
2387    /**
2388     * Flag indicating that an view will cast a shadow onto the Z=0 plane if elevated.
2389     */
2390    static final int PFLAG3_CASTS_SHADOW = 0x100;
2391
2392    /**
2393     * Flag indicating that view will be transformed by the global camera if rotated in 3d, or given
2394     * a non-0 Z translation.
2395     */
2396    static final int PFLAG3_USES_GLOBAL_CAMERA = 0x200;
2397
2398    /* End of masks for mPrivateFlags3 */
2399
2400    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2401
2402    /**
2403     * Always allow a user to over-scroll this view, provided it is a
2404     * view that can scroll.
2405     *
2406     * @see #getOverScrollMode()
2407     * @see #setOverScrollMode(int)
2408     */
2409    public static final int OVER_SCROLL_ALWAYS = 0;
2410
2411    /**
2412     * Allow a user to over-scroll this view only if the content is large
2413     * enough to meaningfully scroll, provided it is a view that can scroll.
2414     *
2415     * @see #getOverScrollMode()
2416     * @see #setOverScrollMode(int)
2417     */
2418    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2419
2420    /**
2421     * Never allow a user to over-scroll this view.
2422     *
2423     * @see #getOverScrollMode()
2424     * @see #setOverScrollMode(int)
2425     */
2426    public static final int OVER_SCROLL_NEVER = 2;
2427
2428    /**
2429     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2430     * requested the system UI (status bar) to be visible (the default).
2431     *
2432     * @see #setSystemUiVisibility(int)
2433     */
2434    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2435
2436    /**
2437     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2438     * system UI to enter an unobtrusive "low profile" mode.
2439     *
2440     * <p>This is for use in games, book readers, video players, or any other
2441     * "immersive" application where the usual system chrome is deemed too distracting.
2442     *
2443     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2444     *
2445     * @see #setSystemUiVisibility(int)
2446     */
2447    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2448
2449    /**
2450     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2451     * system navigation be temporarily hidden.
2452     *
2453     * <p>This is an even less obtrusive state than that called for by
2454     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2455     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2456     * those to disappear. This is useful (in conjunction with the
2457     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2458     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2459     * window flags) for displaying content using every last pixel on the display.
2460     *
2461     * <p>There is a limitation: because navigation controls are so important, the least user
2462     * interaction will cause them to reappear immediately.  When this happens, both
2463     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2464     * so that both elements reappear at the same time.
2465     *
2466     * @see #setSystemUiVisibility(int)
2467     */
2468    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2469
2470    /**
2471     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2472     * into the normal fullscreen mode so that its content can take over the screen
2473     * while still allowing the user to interact with the application.
2474     *
2475     * <p>This has the same visual effect as
2476     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2477     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2478     * meaning that non-critical screen decorations (such as the status bar) will be
2479     * hidden while the user is in the View's window, focusing the experience on
2480     * that content.  Unlike the window flag, if you are using ActionBar in
2481     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2482     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2483     * hide the action bar.
2484     *
2485     * <p>This approach to going fullscreen is best used over the window flag when
2486     * it is a transient state -- that is, the application does this at certain
2487     * points in its user interaction where it wants to allow the user to focus
2488     * on content, but not as a continuous state.  For situations where the application
2489     * would like to simply stay full screen the entire time (such as a game that
2490     * wants to take over the screen), the
2491     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2492     * is usually a better approach.  The state set here will be removed by the system
2493     * in various situations (such as the user moving to another application) like
2494     * the other system UI states.
2495     *
2496     * <p>When using this flag, the application should provide some easy facility
2497     * for the user to go out of it.  A common example would be in an e-book
2498     * reader, where tapping on the screen brings back whatever screen and UI
2499     * decorations that had been hidden while the user was immersed in reading
2500     * the book.
2501     *
2502     * @see #setSystemUiVisibility(int)
2503     */
2504    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2505
2506    /**
2507     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2508     * flags, we would like a stable view of the content insets given to
2509     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2510     * will always represent the worst case that the application can expect
2511     * as a continuous state.  In the stock Android UI this is the space for
2512     * the system bar, nav bar, and status bar, but not more transient elements
2513     * such as an input method.
2514     *
2515     * The stable layout your UI sees is based on the system UI modes you can
2516     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2517     * then you will get a stable layout for changes of the
2518     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2519     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2520     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2521     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2522     * with a stable layout.  (Note that you should avoid using
2523     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2524     *
2525     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2526     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2527     * then a hidden status bar will be considered a "stable" state for purposes
2528     * here.  This allows your UI to continually hide the status bar, while still
2529     * using the system UI flags to hide the action bar while still retaining
2530     * a stable layout.  Note that changing the window fullscreen flag will never
2531     * provide a stable layout for a clean transition.
2532     *
2533     * <p>If you are using ActionBar in
2534     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2535     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2536     * insets it adds to those given to the application.
2537     */
2538    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2539
2540    /**
2541     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2542     * to be layed out as if it has requested
2543     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2544     * allows it to avoid artifacts when switching in and out of that mode, at
2545     * the expense that some of its user interface may be covered by screen
2546     * decorations when they are shown.  You can perform layout of your inner
2547     * UI elements to account for the navigation system UI through the
2548     * {@link #fitSystemWindows(Rect)} method.
2549     */
2550    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2551
2552    /**
2553     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2554     * to be layed out as if it has requested
2555     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2556     * allows it to avoid artifacts when switching in and out of that mode, at
2557     * the expense that some of its user interface may be covered by screen
2558     * decorations when they are shown.  You can perform layout of your inner
2559     * UI elements to account for non-fullscreen system UI through the
2560     * {@link #fitSystemWindows(Rect)} method.
2561     */
2562    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2563
2564    /**
2565     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2566     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2567     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2568     * user interaction.
2569     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2570     * has an effect when used in combination with that flag.</p>
2571     */
2572    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2573
2574    /**
2575     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2576     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2577     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2578     * experience while also hiding the system bars.  If this flag is not set,
2579     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2580     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2581     * if the user swipes from the top of the screen.
2582     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2583     * system gestures, such as swiping from the top of the screen.  These transient system bars
2584     * will overlay app’s content, may have some degree of transparency, and will automatically
2585     * hide after a short timeout.
2586     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2587     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2588     * with one or both of those flags.</p>
2589     */
2590    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2591
2592    /**
2593     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2594     */
2595    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2596
2597    /**
2598     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2599     */
2600    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2601
2602    /**
2603     * @hide
2604     *
2605     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2606     * out of the public fields to keep the undefined bits out of the developer's way.
2607     *
2608     * Flag to make the status bar not expandable.  Unless you also
2609     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2610     */
2611    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2612
2613    /**
2614     * @hide
2615     *
2616     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2617     * out of the public fields to keep the undefined bits out of the developer's way.
2618     *
2619     * Flag to hide notification icons and scrolling ticker text.
2620     */
2621    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2622
2623    /**
2624     * @hide
2625     *
2626     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2627     * out of the public fields to keep the undefined bits out of the developer's way.
2628     *
2629     * Flag to disable incoming notification alerts.  This will not block
2630     * icons, but it will block sound, vibrating and other visual or aural notifications.
2631     */
2632    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2633
2634    /**
2635     * @hide
2636     *
2637     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2638     * out of the public fields to keep the undefined bits out of the developer's way.
2639     *
2640     * Flag to hide only the scrolling ticker.  Note that
2641     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2642     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2643     */
2644    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2645
2646    /**
2647     * @hide
2648     *
2649     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2650     * out of the public fields to keep the undefined bits out of the developer's way.
2651     *
2652     * Flag to hide the center system info area.
2653     */
2654    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2655
2656    /**
2657     * @hide
2658     *
2659     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2660     * out of the public fields to keep the undefined bits out of the developer's way.
2661     *
2662     * Flag to hide only the home button.  Don't use this
2663     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2664     */
2665    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2666
2667    /**
2668     * @hide
2669     *
2670     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2671     * out of the public fields to keep the undefined bits out of the developer's way.
2672     *
2673     * Flag to hide only the back button. Don't use this
2674     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2675     */
2676    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2677
2678    /**
2679     * @hide
2680     *
2681     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2682     * out of the public fields to keep the undefined bits out of the developer's way.
2683     *
2684     * Flag to hide only the clock.  You might use this if your activity has
2685     * its own clock making the status bar's clock redundant.
2686     */
2687    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2688
2689    /**
2690     * @hide
2691     *
2692     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2693     * out of the public fields to keep the undefined bits out of the developer's way.
2694     *
2695     * Flag to hide only the recent apps button. Don't use this
2696     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2697     */
2698    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2699
2700    /**
2701     * @hide
2702     *
2703     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2704     * out of the public fields to keep the undefined bits out of the developer's way.
2705     *
2706     * Flag to disable the global search gesture. Don't use this
2707     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2708     */
2709    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2710
2711    /**
2712     * @hide
2713     *
2714     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2715     * out of the public fields to keep the undefined bits out of the developer's way.
2716     *
2717     * Flag to specify that the status bar is displayed in transient mode.
2718     */
2719    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2720
2721    /**
2722     * @hide
2723     *
2724     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2725     * out of the public fields to keep the undefined bits out of the developer's way.
2726     *
2727     * Flag to specify that the navigation bar is displayed in transient mode.
2728     */
2729    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2730
2731    /**
2732     * @hide
2733     *
2734     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2735     * out of the public fields to keep the undefined bits out of the developer's way.
2736     *
2737     * Flag to specify that the hidden status bar would like to be shown.
2738     */
2739    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2740
2741    /**
2742     * @hide
2743     *
2744     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2745     * out of the public fields to keep the undefined bits out of the developer's way.
2746     *
2747     * Flag to specify that the hidden navigation bar would like to be shown.
2748     */
2749    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2750
2751    /**
2752     * @hide
2753     *
2754     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2755     * out of the public fields to keep the undefined bits out of the developer's way.
2756     *
2757     * Flag to specify that the status bar is displayed in translucent mode.
2758     */
2759    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2760
2761    /**
2762     * @hide
2763     *
2764     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2765     * out of the public fields to keep the undefined bits out of the developer's way.
2766     *
2767     * Flag to specify that the navigation bar is displayed in translucent mode.
2768     */
2769    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2770
2771    /**
2772     * @hide
2773     */
2774    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2775
2776    /**
2777     * These are the system UI flags that can be cleared by events outside
2778     * of an application.  Currently this is just the ability to tap on the
2779     * screen while hiding the navigation bar to have it return.
2780     * @hide
2781     */
2782    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2783            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2784            | SYSTEM_UI_FLAG_FULLSCREEN;
2785
2786    /**
2787     * Flags that can impact the layout in relation to system UI.
2788     */
2789    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2790            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2791            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2792
2793    /** @hide */
2794    @IntDef(flag = true,
2795            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2796    @Retention(RetentionPolicy.SOURCE)
2797    public @interface FindViewFlags {}
2798
2799    /**
2800     * Find views that render the specified text.
2801     *
2802     * @see #findViewsWithText(ArrayList, CharSequence, int)
2803     */
2804    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2805
2806    /**
2807     * Find find views that contain the specified content description.
2808     *
2809     * @see #findViewsWithText(ArrayList, CharSequence, int)
2810     */
2811    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2812
2813    /**
2814     * Find views that contain {@link AccessibilityNodeProvider}. Such
2815     * a View is a root of virtual view hierarchy and may contain the searched
2816     * text. If this flag is set Views with providers are automatically
2817     * added and it is a responsibility of the client to call the APIs of
2818     * the provider to determine whether the virtual tree rooted at this View
2819     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2820     * representing the virtual views with this text.
2821     *
2822     * @see #findViewsWithText(ArrayList, CharSequence, int)
2823     *
2824     * @hide
2825     */
2826    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2827
2828    /**
2829     * The undefined cursor position.
2830     *
2831     * @hide
2832     */
2833    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2834
2835    /**
2836     * Indicates that the screen has changed state and is now off.
2837     *
2838     * @see #onScreenStateChanged(int)
2839     */
2840    public static final int SCREEN_STATE_OFF = 0x0;
2841
2842    /**
2843     * Indicates that the screen has changed state and is now on.
2844     *
2845     * @see #onScreenStateChanged(int)
2846     */
2847    public static final int SCREEN_STATE_ON = 0x1;
2848
2849    /**
2850     * Controls the over-scroll mode for this view.
2851     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2852     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2853     * and {@link #OVER_SCROLL_NEVER}.
2854     */
2855    private int mOverScrollMode;
2856
2857    /**
2858     * The parent this view is attached to.
2859     * {@hide}
2860     *
2861     * @see #getParent()
2862     */
2863    protected ViewParent mParent;
2864
2865    /**
2866     * {@hide}
2867     */
2868    AttachInfo mAttachInfo;
2869
2870    /**
2871     * {@hide}
2872     */
2873    @ViewDebug.ExportedProperty(flagMapping = {
2874        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2875                name = "FORCE_LAYOUT"),
2876        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2877                name = "LAYOUT_REQUIRED"),
2878        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2879            name = "DRAWING_CACHE_INVALID", outputIf = false),
2880        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2881        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2882        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2883        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2884    })
2885    int mPrivateFlags;
2886    int mPrivateFlags2;
2887    int mPrivateFlags3;
2888
2889    /**
2890     * This view's request for the visibility of the status bar.
2891     * @hide
2892     */
2893    @ViewDebug.ExportedProperty(flagMapping = {
2894        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2895                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2896                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2897        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2898                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2899                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2900        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2901                                equals = SYSTEM_UI_FLAG_VISIBLE,
2902                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2903    })
2904    int mSystemUiVisibility;
2905
2906    /**
2907     * Reference count for transient state.
2908     * @see #setHasTransientState(boolean)
2909     */
2910    int mTransientStateCount = 0;
2911
2912    /**
2913     * Count of how many windows this view has been attached to.
2914     */
2915    int mWindowAttachCount;
2916
2917    /**
2918     * The layout parameters associated with this view and used by the parent
2919     * {@link android.view.ViewGroup} to determine how this view should be
2920     * laid out.
2921     * {@hide}
2922     */
2923    protected ViewGroup.LayoutParams mLayoutParams;
2924
2925    /**
2926     * The view flags hold various views states.
2927     * {@hide}
2928     */
2929    @ViewDebug.ExportedProperty
2930    int mViewFlags;
2931
2932    static class TransformationInfo {
2933        /**
2934         * The transform matrix for the View. This transform is calculated internally
2935         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2936         * is used by default. Do *not* use this variable directly; instead call
2937         * getMatrix(), which will automatically recalculate the matrix if necessary
2938         * to get the correct matrix based on the latest rotation and scale properties.
2939         */
2940        private final Matrix mMatrix = new Matrix();
2941
2942        /**
2943         * The transform matrix for the View. This transform is calculated internally
2944         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2945         * is used by default. Do *not* use this variable directly; instead call
2946         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2947         * to get the correct matrix based on the latest rotation and scale properties.
2948         */
2949        private Matrix mInverseMatrix;
2950
2951        /**
2952         * An internal variable that tracks whether we need to recalculate the
2953         * transform matrix, based on whether the rotation or scaleX/Y properties
2954         * have changed since the matrix was last calculated.
2955         */
2956        boolean mMatrixDirty = false;
2957
2958        /**
2959         * An internal variable that tracks whether we need to recalculate the
2960         * transform matrix, based on whether the rotation or scaleX/Y properties
2961         * have changed since the matrix was last calculated.
2962         */
2963        private boolean mInverseMatrixDirty = true;
2964
2965        /**
2966         * A variable that tracks whether we need to recalculate the
2967         * transform matrix, based on whether the rotation or scaleX/Y properties
2968         * have changed since the matrix was last calculated. This variable
2969         * is only valid after a call to updateMatrix() or to a function that
2970         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2971         */
2972        private boolean mMatrixIsIdentity = true;
2973
2974        /**
2975         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2976         */
2977        private Camera mCamera = null;
2978
2979        /**
2980         * This matrix is used when computing the matrix for 3D rotations.
2981         */
2982        private Matrix matrix3D = null;
2983
2984        /**
2985         * These prev values are used to recalculate a centered pivot point when necessary. The
2986         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2987         * set), so thes values are only used then as well.
2988         */
2989        private int mPrevWidth = -1;
2990        private int mPrevHeight = -1;
2991
2992        /**
2993         * The degrees rotation around the vertical axis through the pivot point.
2994         */
2995        @ViewDebug.ExportedProperty
2996        float mRotationY = 0f;
2997
2998        /**
2999         * The degrees rotation around the horizontal axis through the pivot point.
3000         */
3001        @ViewDebug.ExportedProperty
3002        float mRotationX = 0f;
3003
3004        /**
3005         * The degrees rotation around the pivot point.
3006         */
3007        @ViewDebug.ExportedProperty
3008        float mRotation = 0f;
3009
3010        /**
3011         * The amount of translation of the object away from its left property (post-layout).
3012         */
3013        @ViewDebug.ExportedProperty
3014        float mTranslationX = 0f;
3015
3016        /**
3017         * The amount of translation of the object away from its top property (post-layout).
3018         */
3019        @ViewDebug.ExportedProperty
3020        float mTranslationY = 0f;
3021
3022        @ViewDebug.ExportedProperty
3023        float mTranslationZ = 0f;
3024
3025        /**
3026         * The amount of scale in the x direction around the pivot point. A
3027         * value of 1 means no scaling is applied.
3028         */
3029        @ViewDebug.ExportedProperty
3030        float mScaleX = 1f;
3031
3032        /**
3033         * The amount of scale in the y direction around the pivot point. A
3034         * value of 1 means no scaling is applied.
3035         */
3036        @ViewDebug.ExportedProperty
3037        float mScaleY = 1f;
3038
3039        /**
3040         * The x location of the point around which the view is rotated and scaled.
3041         */
3042        @ViewDebug.ExportedProperty
3043        float mPivotX = 0f;
3044
3045        /**
3046         * The y location of the point around which the view is rotated and scaled.
3047         */
3048        @ViewDebug.ExportedProperty
3049        float mPivotY = 0f;
3050
3051        /**
3052         * The opacity of the View. This is a value from 0 to 1, where 0 means
3053         * completely transparent and 1 means completely opaque.
3054         */
3055        @ViewDebug.ExportedProperty
3056        float mAlpha = 1f;
3057
3058        /**
3059         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3060         * property only used by transitions, which is composited with the other alpha
3061         * values to calculate the final visual alpha value.
3062         */
3063        float mTransitionAlpha = 1f;
3064    }
3065
3066    TransformationInfo mTransformationInfo;
3067
3068    /**
3069     * Current clip bounds. to which all drawing of this view are constrained.
3070     */
3071    private Rect mClipBounds = null;
3072
3073    private boolean mLastIsOpaque;
3074
3075    /**
3076     * Convenience value to check for float values that are close enough to zero to be considered
3077     * zero.
3078     */
3079    private static final float NONZERO_EPSILON = .001f;
3080
3081    /**
3082     * The distance in pixels from the left edge of this view's parent
3083     * to the left edge of this view.
3084     * {@hide}
3085     */
3086    @ViewDebug.ExportedProperty(category = "layout")
3087    protected int mLeft;
3088    /**
3089     * The distance in pixels from the left edge of this view's parent
3090     * to the right edge of this view.
3091     * {@hide}
3092     */
3093    @ViewDebug.ExportedProperty(category = "layout")
3094    protected int mRight;
3095    /**
3096     * The distance in pixels from the top edge of this view's parent
3097     * to the top edge of this view.
3098     * {@hide}
3099     */
3100    @ViewDebug.ExportedProperty(category = "layout")
3101    protected int mTop;
3102    /**
3103     * The distance in pixels from the top edge of this view's parent
3104     * to the bottom edge of this view.
3105     * {@hide}
3106     */
3107    @ViewDebug.ExportedProperty(category = "layout")
3108    protected int mBottom;
3109
3110    /**
3111     * The offset, in pixels, by which the content of this view is scrolled
3112     * horizontally.
3113     * {@hide}
3114     */
3115    @ViewDebug.ExportedProperty(category = "scrolling")
3116    protected int mScrollX;
3117    /**
3118     * The offset, in pixels, by which the content of this view is scrolled
3119     * vertically.
3120     * {@hide}
3121     */
3122    @ViewDebug.ExportedProperty(category = "scrolling")
3123    protected int mScrollY;
3124
3125    /**
3126     * The left padding in pixels, that is the distance in pixels between the
3127     * left edge of this view and the left edge of its content.
3128     * {@hide}
3129     */
3130    @ViewDebug.ExportedProperty(category = "padding")
3131    protected int mPaddingLeft = 0;
3132    /**
3133     * The right padding in pixels, that is the distance in pixels between the
3134     * right edge of this view and the right edge of its content.
3135     * {@hide}
3136     */
3137    @ViewDebug.ExportedProperty(category = "padding")
3138    protected int mPaddingRight = 0;
3139    /**
3140     * The top padding in pixels, that is the distance in pixels between the
3141     * top edge of this view and the top edge of its content.
3142     * {@hide}
3143     */
3144    @ViewDebug.ExportedProperty(category = "padding")
3145    protected int mPaddingTop;
3146    /**
3147     * The bottom padding in pixels, that is the distance in pixels between the
3148     * bottom edge of this view and the bottom edge of its content.
3149     * {@hide}
3150     */
3151    @ViewDebug.ExportedProperty(category = "padding")
3152    protected int mPaddingBottom;
3153
3154    /**
3155     * The layout insets in pixels, that is the distance in pixels between the
3156     * visible edges of this view its bounds.
3157     */
3158    private Insets mLayoutInsets;
3159
3160    /**
3161     * Briefly describes the view and is primarily used for accessibility support.
3162     */
3163    private CharSequence mContentDescription;
3164
3165    /**
3166     * Specifies the id of a view for which this view serves as a label for
3167     * accessibility purposes.
3168     */
3169    private int mLabelForId = View.NO_ID;
3170
3171    /**
3172     * Predicate for matching labeled view id with its label for
3173     * accessibility purposes.
3174     */
3175    private MatchLabelForPredicate mMatchLabelForPredicate;
3176
3177    /**
3178     * Predicate for matching a view by its id.
3179     */
3180    private MatchIdPredicate mMatchIdPredicate;
3181
3182    /**
3183     * Cache the paddingRight set by the user to append to the scrollbar's size.
3184     *
3185     * @hide
3186     */
3187    @ViewDebug.ExportedProperty(category = "padding")
3188    protected int mUserPaddingRight;
3189
3190    /**
3191     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3192     *
3193     * @hide
3194     */
3195    @ViewDebug.ExportedProperty(category = "padding")
3196    protected int mUserPaddingBottom;
3197
3198    /**
3199     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3200     *
3201     * @hide
3202     */
3203    @ViewDebug.ExportedProperty(category = "padding")
3204    protected int mUserPaddingLeft;
3205
3206    /**
3207     * Cache the paddingStart set by the user to append to the scrollbar's size.
3208     *
3209     */
3210    @ViewDebug.ExportedProperty(category = "padding")
3211    int mUserPaddingStart;
3212
3213    /**
3214     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3215     *
3216     */
3217    @ViewDebug.ExportedProperty(category = "padding")
3218    int mUserPaddingEnd;
3219
3220    /**
3221     * Cache initial left padding.
3222     *
3223     * @hide
3224     */
3225    int mUserPaddingLeftInitial;
3226
3227    /**
3228     * Cache initial right padding.
3229     *
3230     * @hide
3231     */
3232    int mUserPaddingRightInitial;
3233
3234    /**
3235     * Default undefined padding
3236     */
3237    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3238
3239    /**
3240     * Cache if a left padding has been defined
3241     */
3242    private boolean mLeftPaddingDefined = false;
3243
3244    /**
3245     * Cache if a right padding has been defined
3246     */
3247    private boolean mRightPaddingDefined = false;
3248
3249    /**
3250     * @hide
3251     */
3252    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3253    /**
3254     * @hide
3255     */
3256    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3257
3258    private LongSparseLongArray mMeasureCache;
3259
3260    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3261    private Drawable mBackground;
3262
3263    /**
3264     * Display list used for backgrounds.
3265     * <p>
3266     * When non-null and valid, this is expected to contain an up-to-date copy
3267     * of the background drawable. It is cleared on temporary detach and reset
3268     * on cleanup.
3269     */
3270    private DisplayList mBackgroundDisplayList;
3271
3272    private int mBackgroundResource;
3273    private boolean mBackgroundSizeChanged;
3274
3275    static class ListenerInfo {
3276        /**
3277         * Listener used to dispatch focus change events.
3278         * This field should be made private, so it is hidden from the SDK.
3279         * {@hide}
3280         */
3281        protected OnFocusChangeListener mOnFocusChangeListener;
3282
3283        /**
3284         * Listeners for layout change events.
3285         */
3286        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3287
3288        /**
3289         * Listeners for attach events.
3290         */
3291        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3292
3293        /**
3294         * Listener used to dispatch click events.
3295         * This field should be made private, so it is hidden from the SDK.
3296         * {@hide}
3297         */
3298        public OnClickListener mOnClickListener;
3299
3300        /**
3301         * Listener used to dispatch long click events.
3302         * This field should be made private, so it is hidden from the SDK.
3303         * {@hide}
3304         */
3305        protected OnLongClickListener mOnLongClickListener;
3306
3307        /**
3308         * Listener used to build the context menu.
3309         * This field should be made private, so it is hidden from the SDK.
3310         * {@hide}
3311         */
3312        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3313
3314        private OnKeyListener mOnKeyListener;
3315
3316        private OnTouchListener mOnTouchListener;
3317
3318        private OnHoverListener mOnHoverListener;
3319
3320        private OnGenericMotionListener mOnGenericMotionListener;
3321
3322        private OnDragListener mOnDragListener;
3323
3324        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3325
3326        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3327    }
3328
3329    ListenerInfo mListenerInfo;
3330
3331    /**
3332     * The application environment this view lives in.
3333     * This field should be made private, so it is hidden from the SDK.
3334     * {@hide}
3335     */
3336    protected Context mContext;
3337
3338    private final Resources mResources;
3339
3340    private ScrollabilityCache mScrollCache;
3341
3342    private int[] mDrawableState = null;
3343
3344    /**
3345     * Stores the outline of the view, passed down to the DisplayList level for
3346     * defining shadow shape and clipping.
3347     */
3348    private Path mOutline;
3349
3350    /**
3351     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3352     * the user may specify which view to go to next.
3353     */
3354    private int mNextFocusLeftId = View.NO_ID;
3355
3356    /**
3357     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3358     * the user may specify which view to go to next.
3359     */
3360    private int mNextFocusRightId = View.NO_ID;
3361
3362    /**
3363     * When this view has focus and the next focus is {@link #FOCUS_UP},
3364     * the user may specify which view to go to next.
3365     */
3366    private int mNextFocusUpId = View.NO_ID;
3367
3368    /**
3369     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3370     * the user may specify which view to go to next.
3371     */
3372    private int mNextFocusDownId = View.NO_ID;
3373
3374    /**
3375     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3376     * the user may specify which view to go to next.
3377     */
3378    int mNextFocusForwardId = View.NO_ID;
3379
3380    private CheckForLongPress mPendingCheckForLongPress;
3381    private CheckForTap mPendingCheckForTap = null;
3382    private PerformClick mPerformClick;
3383    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3384
3385    private UnsetPressedState mUnsetPressedState;
3386
3387    /**
3388     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3389     * up event while a long press is invoked as soon as the long press duration is reached, so
3390     * a long press could be performed before the tap is checked, in which case the tap's action
3391     * should not be invoked.
3392     */
3393    private boolean mHasPerformedLongPress;
3394
3395    /**
3396     * The minimum height of the view. We'll try our best to have the height
3397     * of this view to at least this amount.
3398     */
3399    @ViewDebug.ExportedProperty(category = "measurement")
3400    private int mMinHeight;
3401
3402    /**
3403     * The minimum width of the view. We'll try our best to have the width
3404     * of this view to at least this amount.
3405     */
3406    @ViewDebug.ExportedProperty(category = "measurement")
3407    private int mMinWidth;
3408
3409    /**
3410     * The delegate to handle touch events that are physically in this view
3411     * but should be handled by another view.
3412     */
3413    private TouchDelegate mTouchDelegate = null;
3414
3415    /**
3416     * Solid color to use as a background when creating the drawing cache. Enables
3417     * the cache to use 16 bit bitmaps instead of 32 bit.
3418     */
3419    private int mDrawingCacheBackgroundColor = 0;
3420
3421    /**
3422     * Special tree observer used when mAttachInfo is null.
3423     */
3424    private ViewTreeObserver mFloatingTreeObserver;
3425
3426    /**
3427     * Cache the touch slop from the context that created the view.
3428     */
3429    private int mTouchSlop;
3430
3431    /**
3432     * Object that handles automatic animation of view properties.
3433     */
3434    private ViewPropertyAnimator mAnimator = null;
3435
3436    /**
3437     * Flag indicating that a drag can cross window boundaries.  When
3438     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3439     * with this flag set, all visible applications will be able to participate
3440     * in the drag operation and receive the dragged content.
3441     *
3442     * @hide
3443     */
3444    public static final int DRAG_FLAG_GLOBAL = 1;
3445
3446    /**
3447     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3448     */
3449    private float mVerticalScrollFactor;
3450
3451    /**
3452     * Position of the vertical scroll bar.
3453     */
3454    private int mVerticalScrollbarPosition;
3455
3456    /**
3457     * Position the scroll bar at the default position as determined by the system.
3458     */
3459    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3460
3461    /**
3462     * Position the scroll bar along the left edge.
3463     */
3464    public static final int SCROLLBAR_POSITION_LEFT = 1;
3465
3466    /**
3467     * Position the scroll bar along the right edge.
3468     */
3469    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3470
3471    /**
3472     * Indicates that the view does not have a layer.
3473     *
3474     * @see #getLayerType()
3475     * @see #setLayerType(int, android.graphics.Paint)
3476     * @see #LAYER_TYPE_SOFTWARE
3477     * @see #LAYER_TYPE_HARDWARE
3478     */
3479    public static final int LAYER_TYPE_NONE = 0;
3480
3481    /**
3482     * <p>Indicates that the view has a software layer. A software layer is backed
3483     * by a bitmap and causes the view to be rendered using Android's software
3484     * rendering pipeline, even if hardware acceleration is enabled.</p>
3485     *
3486     * <p>Software layers have various usages:</p>
3487     * <p>When the application is not using hardware acceleration, a software layer
3488     * is useful to apply a specific color filter and/or blending mode and/or
3489     * translucency to a view and all its children.</p>
3490     * <p>When the application is using hardware acceleration, a software layer
3491     * is useful to render drawing primitives not supported by the hardware
3492     * accelerated pipeline. It can also be used to cache a complex view tree
3493     * into a texture and reduce the complexity of drawing operations. For instance,
3494     * when animating a complex view tree with a translation, a software layer can
3495     * be used to render the view tree only once.</p>
3496     * <p>Software layers should be avoided when the affected view tree updates
3497     * often. Every update will require to re-render the software layer, which can
3498     * potentially be slow (particularly when hardware acceleration is turned on
3499     * since the layer will have to be uploaded into a hardware texture after every
3500     * update.)</p>
3501     *
3502     * @see #getLayerType()
3503     * @see #setLayerType(int, android.graphics.Paint)
3504     * @see #LAYER_TYPE_NONE
3505     * @see #LAYER_TYPE_HARDWARE
3506     */
3507    public static final int LAYER_TYPE_SOFTWARE = 1;
3508
3509    /**
3510     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3511     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3512     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3513     * rendering pipeline, but only if hardware acceleration is turned on for the
3514     * view hierarchy. When hardware acceleration is turned off, hardware layers
3515     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3516     *
3517     * <p>A hardware layer is useful to apply a specific color filter and/or
3518     * blending mode and/or translucency to a view and all its children.</p>
3519     * <p>A hardware layer can be used to cache a complex view tree into a
3520     * texture and reduce the complexity of drawing operations. For instance,
3521     * when animating a complex view tree with a translation, a hardware layer can
3522     * be used to render the view tree only once.</p>
3523     * <p>A hardware layer can also be used to increase the rendering quality when
3524     * rotation transformations are applied on a view. It can also be used to
3525     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3526     *
3527     * @see #getLayerType()
3528     * @see #setLayerType(int, android.graphics.Paint)
3529     * @see #LAYER_TYPE_NONE
3530     * @see #LAYER_TYPE_SOFTWARE
3531     */
3532    public static final int LAYER_TYPE_HARDWARE = 2;
3533
3534    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3535            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3536            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3537            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3538    })
3539    int mLayerType = LAYER_TYPE_NONE;
3540    Paint mLayerPaint;
3541    Rect mLocalDirtyRect;
3542    private HardwareLayer mHardwareLayer;
3543
3544    /**
3545     * Set to true when drawing cache is enabled and cannot be created.
3546     *
3547     * @hide
3548     */
3549    public boolean mCachingFailed;
3550    private Bitmap mDrawingCache;
3551    private Bitmap mUnscaledDrawingCache;
3552
3553    /**
3554     * Display list used for the View content.
3555     * <p>
3556     * When non-null and valid, this is expected to contain an up-to-date copy
3557     * of the View content. It is cleared on temporary detach and reset on
3558     * cleanup.
3559     */
3560    DisplayList mDisplayList;
3561
3562    /**
3563     * Set to true when the view is sending hover accessibility events because it
3564     * is the innermost hovered view.
3565     */
3566    private boolean mSendingHoverAccessibilityEvents;
3567
3568    /**
3569     * Delegate for injecting accessibility functionality.
3570     */
3571    AccessibilityDelegate mAccessibilityDelegate;
3572
3573    /**
3574     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3575     * and add/remove objects to/from the overlay directly through the Overlay methods.
3576     */
3577    ViewOverlay mOverlay;
3578
3579    /**
3580     * Consistency verifier for debugging purposes.
3581     * @hide
3582     */
3583    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3584            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3585                    new InputEventConsistencyVerifier(this, 0) : null;
3586
3587    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3588
3589    /**
3590     * Simple constructor to use when creating a view from code.
3591     *
3592     * @param context The Context the view is running in, through which it can
3593     *        access the current theme, resources, etc.
3594     */
3595    public View(Context context) {
3596        mContext = context;
3597        mResources = context != null ? context.getResources() : null;
3598        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3599        // Set some flags defaults
3600        mPrivateFlags2 =
3601                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3602                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3603                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3604                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3605                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3606                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3607        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3608        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3609        mUserPaddingStart = UNDEFINED_PADDING;
3610        mUserPaddingEnd = UNDEFINED_PADDING;
3611
3612        if (!sCompatibilityDone && context != null) {
3613            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3614
3615            // Older apps may need this compatibility hack for measurement.
3616            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3617
3618            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3619            // of whether a layout was requested on that View.
3620            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3621
3622            sCompatibilityDone = true;
3623        }
3624    }
3625
3626    /**
3627     * Constructor that is called when inflating a view from XML. This is called
3628     * when a view is being constructed from an XML file, supplying attributes
3629     * that were specified in the XML file. This version uses a default style of
3630     * 0, so the only attribute values applied are those in the Context's Theme
3631     * and the given AttributeSet.
3632     *
3633     * <p>
3634     * The method onFinishInflate() will be called after all children have been
3635     * added.
3636     *
3637     * @param context The Context the view is running in, through which it can
3638     *        access the current theme, resources, etc.
3639     * @param attrs The attributes of the XML tag that is inflating the view.
3640     * @see #View(Context, AttributeSet, int)
3641     */
3642    public View(Context context, AttributeSet attrs) {
3643        this(context, attrs, 0);
3644    }
3645
3646    /**
3647     * Perform inflation from XML and apply a class-specific base style from a
3648     * theme attribute. This constructor of View allows subclasses to use their
3649     * own base style when they are inflating. For example, a Button class's
3650     * constructor would call this version of the super class constructor and
3651     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3652     * allows the theme's button style to modify all of the base view attributes
3653     * (in particular its background) as well as the Button class's attributes.
3654     *
3655     * @param context The Context the view is running in, through which it can
3656     *        access the current theme, resources, etc.
3657     * @param attrs The attributes of the XML tag that is inflating the view.
3658     * @param defStyleAttr An attribute in the current theme that contains a
3659     *        reference to a style resource that supplies default values for
3660     *        the view. Can be 0 to not look for defaults.
3661     * @see #View(Context, AttributeSet)
3662     */
3663    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3664        this(context, attrs, defStyleAttr, 0);
3665    }
3666
3667    /**
3668     * Perform inflation from XML and apply a class-specific base style from a
3669     * theme attribute or style resource. This constructor of View allows
3670     * subclasses to use their own base style when they are inflating.
3671     * <p>
3672     * When determining the final value of a particular attribute, there are
3673     * four inputs that come into play:
3674     * <ol>
3675     * <li>Any attribute values in the given AttributeSet.
3676     * <li>The style resource specified in the AttributeSet (named "style").
3677     * <li>The default style specified by <var>defStyleAttr</var>.
3678     * <li>The default style specified by <var>defStyleRes</var>.
3679     * <li>The base values in this theme.
3680     * </ol>
3681     * <p>
3682     * Each of these inputs is considered in-order, with the first listed taking
3683     * precedence over the following ones. In other words, if in the
3684     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3685     * , then the button's text will <em>always</em> be black, regardless of
3686     * what is specified in any of the styles.
3687     *
3688     * @param context The Context the view is running in, through which it can
3689     *        access the current theme, resources, etc.
3690     * @param attrs The attributes of the XML tag that is inflating the view.
3691     * @param defStyleAttr An attribute in the current theme that contains a
3692     *        reference to a style resource that supplies default values for
3693     *        the view. Can be 0 to not look for defaults.
3694     * @param defStyleRes A resource identifier of a style resource that
3695     *        supplies default values for the view, used only if
3696     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3697     *        to not look for defaults.
3698     * @see #View(Context, AttributeSet, int)
3699     */
3700    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3701        this(context);
3702
3703        final TypedArray a = context.obtainStyledAttributes(
3704                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3705
3706        Drawable background = null;
3707
3708        int leftPadding = -1;
3709        int topPadding = -1;
3710        int rightPadding = -1;
3711        int bottomPadding = -1;
3712        int startPadding = UNDEFINED_PADDING;
3713        int endPadding = UNDEFINED_PADDING;
3714
3715        int padding = -1;
3716
3717        int viewFlagValues = 0;
3718        int viewFlagMasks = 0;
3719
3720        boolean setScrollContainer = false;
3721
3722        int x = 0;
3723        int y = 0;
3724
3725        float tx = 0;
3726        float ty = 0;
3727        float tz = 0;
3728        float rotation = 0;
3729        float rotationX = 0;
3730        float rotationY = 0;
3731        float sx = 1f;
3732        float sy = 1f;
3733        boolean transformSet = false;
3734
3735        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3736        int overScrollMode = mOverScrollMode;
3737        boolean initializeScrollbars = false;
3738
3739        boolean startPaddingDefined = false;
3740        boolean endPaddingDefined = false;
3741        boolean leftPaddingDefined = false;
3742        boolean rightPaddingDefined = false;
3743
3744        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3745
3746        final int N = a.getIndexCount();
3747        for (int i = 0; i < N; i++) {
3748            int attr = a.getIndex(i);
3749            switch (attr) {
3750                case com.android.internal.R.styleable.View_background:
3751                    background = a.getDrawable(attr);
3752                    break;
3753                case com.android.internal.R.styleable.View_padding:
3754                    padding = a.getDimensionPixelSize(attr, -1);
3755                    mUserPaddingLeftInitial = padding;
3756                    mUserPaddingRightInitial = padding;
3757                    leftPaddingDefined = true;
3758                    rightPaddingDefined = true;
3759                    break;
3760                 case com.android.internal.R.styleable.View_paddingLeft:
3761                    leftPadding = a.getDimensionPixelSize(attr, -1);
3762                    mUserPaddingLeftInitial = leftPadding;
3763                    leftPaddingDefined = true;
3764                    break;
3765                case com.android.internal.R.styleable.View_paddingTop:
3766                    topPadding = a.getDimensionPixelSize(attr, -1);
3767                    break;
3768                case com.android.internal.R.styleable.View_paddingRight:
3769                    rightPadding = a.getDimensionPixelSize(attr, -1);
3770                    mUserPaddingRightInitial = rightPadding;
3771                    rightPaddingDefined = true;
3772                    break;
3773                case com.android.internal.R.styleable.View_paddingBottom:
3774                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3775                    break;
3776                case com.android.internal.R.styleable.View_paddingStart:
3777                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3778                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3779                    break;
3780                case com.android.internal.R.styleable.View_paddingEnd:
3781                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3782                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3783                    break;
3784                case com.android.internal.R.styleable.View_scrollX:
3785                    x = a.getDimensionPixelOffset(attr, 0);
3786                    break;
3787                case com.android.internal.R.styleable.View_scrollY:
3788                    y = a.getDimensionPixelOffset(attr, 0);
3789                    break;
3790                case com.android.internal.R.styleable.View_alpha:
3791                    setAlpha(a.getFloat(attr, 1f));
3792                    break;
3793                case com.android.internal.R.styleable.View_transformPivotX:
3794                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3795                    break;
3796                case com.android.internal.R.styleable.View_transformPivotY:
3797                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3798                    break;
3799                case com.android.internal.R.styleable.View_translationX:
3800                    tx = a.getDimensionPixelOffset(attr, 0);
3801                    transformSet = true;
3802                    break;
3803                case com.android.internal.R.styleable.View_translationY:
3804                    ty = a.getDimensionPixelOffset(attr, 0);
3805                    transformSet = true;
3806                    break;
3807                case com.android.internal.R.styleable.View_translationZ:
3808                    tz = a.getDimensionPixelOffset(attr, 0);
3809                    transformSet = true;
3810                    break;
3811                case com.android.internal.R.styleable.View_rotation:
3812                    rotation = a.getFloat(attr, 0);
3813                    transformSet = true;
3814                    break;
3815                case com.android.internal.R.styleable.View_rotationX:
3816                    rotationX = a.getFloat(attr, 0);
3817                    transformSet = true;
3818                    break;
3819                case com.android.internal.R.styleable.View_rotationY:
3820                    rotationY = a.getFloat(attr, 0);
3821                    transformSet = true;
3822                    break;
3823                case com.android.internal.R.styleable.View_scaleX:
3824                    sx = a.getFloat(attr, 1f);
3825                    transformSet = true;
3826                    break;
3827                case com.android.internal.R.styleable.View_scaleY:
3828                    sy = a.getFloat(attr, 1f);
3829                    transformSet = true;
3830                    break;
3831                case com.android.internal.R.styleable.View_id:
3832                    mID = a.getResourceId(attr, NO_ID);
3833                    break;
3834                case com.android.internal.R.styleable.View_tag:
3835                    mTag = a.getText(attr);
3836                    break;
3837                case com.android.internal.R.styleable.View_fitsSystemWindows:
3838                    if (a.getBoolean(attr, false)) {
3839                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3840                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3841                    }
3842                    break;
3843                case com.android.internal.R.styleable.View_focusable:
3844                    if (a.getBoolean(attr, false)) {
3845                        viewFlagValues |= FOCUSABLE;
3846                        viewFlagMasks |= FOCUSABLE_MASK;
3847                    }
3848                    break;
3849                case com.android.internal.R.styleable.View_focusableInTouchMode:
3850                    if (a.getBoolean(attr, false)) {
3851                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3852                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3853                    }
3854                    break;
3855                case com.android.internal.R.styleable.View_clickable:
3856                    if (a.getBoolean(attr, false)) {
3857                        viewFlagValues |= CLICKABLE;
3858                        viewFlagMasks |= CLICKABLE;
3859                    }
3860                    break;
3861                case com.android.internal.R.styleable.View_longClickable:
3862                    if (a.getBoolean(attr, false)) {
3863                        viewFlagValues |= LONG_CLICKABLE;
3864                        viewFlagMasks |= LONG_CLICKABLE;
3865                    }
3866                    break;
3867                case com.android.internal.R.styleable.View_saveEnabled:
3868                    if (!a.getBoolean(attr, true)) {
3869                        viewFlagValues |= SAVE_DISABLED;
3870                        viewFlagMasks |= SAVE_DISABLED_MASK;
3871                    }
3872                    break;
3873                case com.android.internal.R.styleable.View_duplicateParentState:
3874                    if (a.getBoolean(attr, false)) {
3875                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3876                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3877                    }
3878                    break;
3879                case com.android.internal.R.styleable.View_visibility:
3880                    final int visibility = a.getInt(attr, 0);
3881                    if (visibility != 0) {
3882                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3883                        viewFlagMasks |= VISIBILITY_MASK;
3884                    }
3885                    break;
3886                case com.android.internal.R.styleable.View_layoutDirection:
3887                    // Clear any layout direction flags (included resolved bits) already set
3888                    mPrivateFlags2 &=
3889                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3890                    // Set the layout direction flags depending on the value of the attribute
3891                    final int layoutDirection = a.getInt(attr, -1);
3892                    final int value = (layoutDirection != -1) ?
3893                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3894                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3895                    break;
3896                case com.android.internal.R.styleable.View_drawingCacheQuality:
3897                    final int cacheQuality = a.getInt(attr, 0);
3898                    if (cacheQuality != 0) {
3899                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3900                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3901                    }
3902                    break;
3903                case com.android.internal.R.styleable.View_contentDescription:
3904                    setContentDescription(a.getString(attr));
3905                    break;
3906                case com.android.internal.R.styleable.View_labelFor:
3907                    setLabelFor(a.getResourceId(attr, NO_ID));
3908                    break;
3909                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3910                    if (!a.getBoolean(attr, true)) {
3911                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3912                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3913                    }
3914                    break;
3915                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3916                    if (!a.getBoolean(attr, true)) {
3917                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3918                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3919                    }
3920                    break;
3921                case R.styleable.View_scrollbars:
3922                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3923                    if (scrollbars != SCROLLBARS_NONE) {
3924                        viewFlagValues |= scrollbars;
3925                        viewFlagMasks |= SCROLLBARS_MASK;
3926                        initializeScrollbars = true;
3927                    }
3928                    break;
3929                //noinspection deprecation
3930                case R.styleable.View_fadingEdge:
3931                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3932                        // Ignore the attribute starting with ICS
3933                        break;
3934                    }
3935                    // With builds < ICS, fall through and apply fading edges
3936                case R.styleable.View_requiresFadingEdge:
3937                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3938                    if (fadingEdge != FADING_EDGE_NONE) {
3939                        viewFlagValues |= fadingEdge;
3940                        viewFlagMasks |= FADING_EDGE_MASK;
3941                        initializeFadingEdge(a);
3942                    }
3943                    break;
3944                case R.styleable.View_scrollbarStyle:
3945                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3946                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3947                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3948                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3949                    }
3950                    break;
3951                case R.styleable.View_isScrollContainer:
3952                    setScrollContainer = true;
3953                    if (a.getBoolean(attr, false)) {
3954                        setScrollContainer(true);
3955                    }
3956                    break;
3957                case com.android.internal.R.styleable.View_keepScreenOn:
3958                    if (a.getBoolean(attr, false)) {
3959                        viewFlagValues |= KEEP_SCREEN_ON;
3960                        viewFlagMasks |= KEEP_SCREEN_ON;
3961                    }
3962                    break;
3963                case R.styleable.View_filterTouchesWhenObscured:
3964                    if (a.getBoolean(attr, false)) {
3965                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3966                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3967                    }
3968                    break;
3969                case R.styleable.View_nextFocusLeft:
3970                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3971                    break;
3972                case R.styleable.View_nextFocusRight:
3973                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3974                    break;
3975                case R.styleable.View_nextFocusUp:
3976                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3977                    break;
3978                case R.styleable.View_nextFocusDown:
3979                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3980                    break;
3981                case R.styleable.View_nextFocusForward:
3982                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3983                    break;
3984                case R.styleable.View_minWidth:
3985                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3986                    break;
3987                case R.styleable.View_minHeight:
3988                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3989                    break;
3990                case R.styleable.View_onClick:
3991                    if (context.isRestricted()) {
3992                        throw new IllegalStateException("The android:onClick attribute cannot "
3993                                + "be used within a restricted context");
3994                    }
3995
3996                    final String handlerName = a.getString(attr);
3997                    if (handlerName != null) {
3998                        setOnClickListener(new OnClickListener() {
3999                            private Method mHandler;
4000
4001                            public void onClick(View v) {
4002                                if (mHandler == null) {
4003                                    try {
4004                                        mHandler = getContext().getClass().getMethod(handlerName,
4005                                                View.class);
4006                                    } catch (NoSuchMethodException e) {
4007                                        int id = getId();
4008                                        String idText = id == NO_ID ? "" : " with id '"
4009                                                + getContext().getResources().getResourceEntryName(
4010                                                    id) + "'";
4011                                        throw new IllegalStateException("Could not find a method " +
4012                                                handlerName + "(View) in the activity "
4013                                                + getContext().getClass() + " for onClick handler"
4014                                                + " on view " + View.this.getClass() + idText, e);
4015                                    }
4016                                }
4017
4018                                try {
4019                                    mHandler.invoke(getContext(), View.this);
4020                                } catch (IllegalAccessException e) {
4021                                    throw new IllegalStateException("Could not execute non "
4022                                            + "public method of the activity", e);
4023                                } catch (InvocationTargetException e) {
4024                                    throw new IllegalStateException("Could not execute "
4025                                            + "method of the activity", e);
4026                                }
4027                            }
4028                        });
4029                    }
4030                    break;
4031                case R.styleable.View_overScrollMode:
4032                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4033                    break;
4034                case R.styleable.View_verticalScrollbarPosition:
4035                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4036                    break;
4037                case R.styleable.View_layerType:
4038                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4039                    break;
4040                case R.styleable.View_castsShadow:
4041                    if (a.getBoolean(attr, false)) {
4042                        mPrivateFlags3 |= PFLAG3_CASTS_SHADOW;
4043                    }
4044                    break;
4045                case R.styleable.View_textDirection:
4046                    // Clear any text direction flag already set
4047                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4048                    // Set the text direction flags depending on the value of the attribute
4049                    final int textDirection = a.getInt(attr, -1);
4050                    if (textDirection != -1) {
4051                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4052                    }
4053                    break;
4054                case R.styleable.View_textAlignment:
4055                    // Clear any text alignment flag already set
4056                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4057                    // Set the text alignment flag depending on the value of the attribute
4058                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4059                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4060                    break;
4061                case R.styleable.View_importantForAccessibility:
4062                    setImportantForAccessibility(a.getInt(attr,
4063                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4064                    break;
4065                case R.styleable.View_accessibilityLiveRegion:
4066                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4067                    break;
4068                case R.styleable.View_sharedElementName:
4069                    setSharedElementName(a.getString(attr));
4070                    break;
4071            }
4072        }
4073
4074        setOverScrollMode(overScrollMode);
4075
4076        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4077        // the resolved layout direction). Those cached values will be used later during padding
4078        // resolution.
4079        mUserPaddingStart = startPadding;
4080        mUserPaddingEnd = endPadding;
4081
4082        if (background != null) {
4083            setBackground(background);
4084        }
4085
4086        // setBackground above will record that padding is currently provided by the background.
4087        // If we have padding specified via xml, record that here instead and use it.
4088        mLeftPaddingDefined = leftPaddingDefined;
4089        mRightPaddingDefined = rightPaddingDefined;
4090
4091        if (padding >= 0) {
4092            leftPadding = padding;
4093            topPadding = padding;
4094            rightPadding = padding;
4095            bottomPadding = padding;
4096            mUserPaddingLeftInitial = padding;
4097            mUserPaddingRightInitial = padding;
4098        }
4099
4100        if (isRtlCompatibilityMode()) {
4101            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4102            // left / right padding are used if defined (meaning here nothing to do). If they are not
4103            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4104            // start / end and resolve them as left / right (layout direction is not taken into account).
4105            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4106            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4107            // defined.
4108            if (!mLeftPaddingDefined && startPaddingDefined) {
4109                leftPadding = startPadding;
4110            }
4111            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4112            if (!mRightPaddingDefined && endPaddingDefined) {
4113                rightPadding = endPadding;
4114            }
4115            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4116        } else {
4117            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4118            // values defined. Otherwise, left /right values are used.
4119            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4120            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4121            // defined.
4122            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4123
4124            if (mLeftPaddingDefined && !hasRelativePadding) {
4125                mUserPaddingLeftInitial = leftPadding;
4126            }
4127            if (mRightPaddingDefined && !hasRelativePadding) {
4128                mUserPaddingRightInitial = rightPadding;
4129            }
4130        }
4131
4132        internalSetPadding(
4133                mUserPaddingLeftInitial,
4134                topPadding >= 0 ? topPadding : mPaddingTop,
4135                mUserPaddingRightInitial,
4136                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4137
4138        if (viewFlagMasks != 0) {
4139            setFlags(viewFlagValues, viewFlagMasks);
4140        }
4141
4142        if (initializeScrollbars) {
4143            initializeScrollbars(a);
4144        }
4145
4146        a.recycle();
4147
4148        // Needs to be called after mViewFlags is set
4149        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4150            recomputePadding();
4151        }
4152
4153        if (x != 0 || y != 0) {
4154            scrollTo(x, y);
4155        }
4156
4157        if (transformSet) {
4158            setTranslationX(tx);
4159            setTranslationY(ty);
4160            setTranslationZ(tz);
4161            setRotation(rotation);
4162            setRotationX(rotationX);
4163            setRotationY(rotationY);
4164            setScaleX(sx);
4165            setScaleY(sy);
4166        }
4167
4168        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4169            setScrollContainer(true);
4170        }
4171
4172        computeOpaqueFlags();
4173    }
4174
4175    /**
4176     * Non-public constructor for use in testing
4177     */
4178    View() {
4179        mResources = null;
4180    }
4181
4182    public String toString() {
4183        StringBuilder out = new StringBuilder(128);
4184        out.append(getClass().getName());
4185        out.append('{');
4186        out.append(Integer.toHexString(System.identityHashCode(this)));
4187        out.append(' ');
4188        switch (mViewFlags&VISIBILITY_MASK) {
4189            case VISIBLE: out.append('V'); break;
4190            case INVISIBLE: out.append('I'); break;
4191            case GONE: out.append('G'); break;
4192            default: out.append('.'); break;
4193        }
4194        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4195        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4196        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4197        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4198        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4199        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4200        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4201        out.append(' ');
4202        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4203        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4204        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4205        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4206            out.append('p');
4207        } else {
4208            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4209        }
4210        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4211        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4212        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4213        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4214        out.append(' ');
4215        out.append(mLeft);
4216        out.append(',');
4217        out.append(mTop);
4218        out.append('-');
4219        out.append(mRight);
4220        out.append(',');
4221        out.append(mBottom);
4222        final int id = getId();
4223        if (id != NO_ID) {
4224            out.append(" #");
4225            out.append(Integer.toHexString(id));
4226            final Resources r = mResources;
4227            if (id != 0 && r != null) {
4228                try {
4229                    String pkgname;
4230                    switch (id&0xff000000) {
4231                        case 0x7f000000:
4232                            pkgname="app";
4233                            break;
4234                        case 0x01000000:
4235                            pkgname="android";
4236                            break;
4237                        default:
4238                            pkgname = r.getResourcePackageName(id);
4239                            break;
4240                    }
4241                    String typename = r.getResourceTypeName(id);
4242                    String entryname = r.getResourceEntryName(id);
4243                    out.append(" ");
4244                    out.append(pkgname);
4245                    out.append(":");
4246                    out.append(typename);
4247                    out.append("/");
4248                    out.append(entryname);
4249                } catch (Resources.NotFoundException e) {
4250                }
4251            }
4252        }
4253        out.append("}");
4254        return out.toString();
4255    }
4256
4257    /**
4258     * <p>
4259     * Initializes the fading edges from a given set of styled attributes. This
4260     * method should be called by subclasses that need fading edges and when an
4261     * instance of these subclasses is created programmatically rather than
4262     * being inflated from XML. This method is automatically called when the XML
4263     * is inflated.
4264     * </p>
4265     *
4266     * @param a the styled attributes set to initialize the fading edges from
4267     */
4268    protected void initializeFadingEdge(TypedArray a) {
4269        initScrollCache();
4270
4271        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4272                R.styleable.View_fadingEdgeLength,
4273                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4274    }
4275
4276    /**
4277     * Returns the size of the vertical faded edges used to indicate that more
4278     * content in this view is visible.
4279     *
4280     * @return The size in pixels of the vertical faded edge or 0 if vertical
4281     *         faded edges are not enabled for this view.
4282     * @attr ref android.R.styleable#View_fadingEdgeLength
4283     */
4284    public int getVerticalFadingEdgeLength() {
4285        if (isVerticalFadingEdgeEnabled()) {
4286            ScrollabilityCache cache = mScrollCache;
4287            if (cache != null) {
4288                return cache.fadingEdgeLength;
4289            }
4290        }
4291        return 0;
4292    }
4293
4294    /**
4295     * Set the size of the faded edge used to indicate that more content in this
4296     * view is available.  Will not change whether the fading edge is enabled; use
4297     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4298     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4299     * for the vertical or horizontal fading edges.
4300     *
4301     * @param length The size in pixels of the faded edge used to indicate that more
4302     *        content in this view is visible.
4303     */
4304    public void setFadingEdgeLength(int length) {
4305        initScrollCache();
4306        mScrollCache.fadingEdgeLength = length;
4307    }
4308
4309    /**
4310     * Returns the size of the horizontal faded edges used to indicate that more
4311     * content in this view is visible.
4312     *
4313     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4314     *         faded edges are not enabled for this view.
4315     * @attr ref android.R.styleable#View_fadingEdgeLength
4316     */
4317    public int getHorizontalFadingEdgeLength() {
4318        if (isHorizontalFadingEdgeEnabled()) {
4319            ScrollabilityCache cache = mScrollCache;
4320            if (cache != null) {
4321                return cache.fadingEdgeLength;
4322            }
4323        }
4324        return 0;
4325    }
4326
4327    /**
4328     * Returns the width of the vertical scrollbar.
4329     *
4330     * @return The width in pixels of the vertical scrollbar or 0 if there
4331     *         is no vertical scrollbar.
4332     */
4333    public int getVerticalScrollbarWidth() {
4334        ScrollabilityCache cache = mScrollCache;
4335        if (cache != null) {
4336            ScrollBarDrawable scrollBar = cache.scrollBar;
4337            if (scrollBar != null) {
4338                int size = scrollBar.getSize(true);
4339                if (size <= 0) {
4340                    size = cache.scrollBarSize;
4341                }
4342                return size;
4343            }
4344            return 0;
4345        }
4346        return 0;
4347    }
4348
4349    /**
4350     * Returns the height of the horizontal scrollbar.
4351     *
4352     * @return The height in pixels of the horizontal scrollbar or 0 if
4353     *         there is no horizontal scrollbar.
4354     */
4355    protected int getHorizontalScrollbarHeight() {
4356        ScrollabilityCache cache = mScrollCache;
4357        if (cache != null) {
4358            ScrollBarDrawable scrollBar = cache.scrollBar;
4359            if (scrollBar != null) {
4360                int size = scrollBar.getSize(false);
4361                if (size <= 0) {
4362                    size = cache.scrollBarSize;
4363                }
4364                return size;
4365            }
4366            return 0;
4367        }
4368        return 0;
4369    }
4370
4371    /**
4372     * <p>
4373     * Initializes the scrollbars from a given set of styled attributes. This
4374     * method should be called by subclasses that need scrollbars and when an
4375     * instance of these subclasses is created programmatically rather than
4376     * being inflated from XML. This method is automatically called when the XML
4377     * is inflated.
4378     * </p>
4379     *
4380     * @param a the styled attributes set to initialize the scrollbars from
4381     */
4382    protected void initializeScrollbars(TypedArray a) {
4383        initScrollCache();
4384
4385        final ScrollabilityCache scrollabilityCache = mScrollCache;
4386
4387        if (scrollabilityCache.scrollBar == null) {
4388            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4389        }
4390
4391        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4392
4393        if (!fadeScrollbars) {
4394            scrollabilityCache.state = ScrollabilityCache.ON;
4395        }
4396        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4397
4398
4399        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4400                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4401                        .getScrollBarFadeDuration());
4402        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4403                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4404                ViewConfiguration.getScrollDefaultDelay());
4405
4406
4407        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4408                com.android.internal.R.styleable.View_scrollbarSize,
4409                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4410
4411        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4412        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4413
4414        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4415        if (thumb != null) {
4416            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4417        }
4418
4419        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4420                false);
4421        if (alwaysDraw) {
4422            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4423        }
4424
4425        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4426        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4427
4428        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4429        if (thumb != null) {
4430            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4431        }
4432
4433        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4434                false);
4435        if (alwaysDraw) {
4436            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4437        }
4438
4439        // Apply layout direction to the new Drawables if needed
4440        final int layoutDirection = getLayoutDirection();
4441        if (track != null) {
4442            track.setLayoutDirection(layoutDirection);
4443        }
4444        if (thumb != null) {
4445            thumb.setLayoutDirection(layoutDirection);
4446        }
4447
4448        // Re-apply user/background padding so that scrollbar(s) get added
4449        resolvePadding();
4450    }
4451
4452    /**
4453     * <p>
4454     * Initalizes the scrollability cache if necessary.
4455     * </p>
4456     */
4457    private void initScrollCache() {
4458        if (mScrollCache == null) {
4459            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4460        }
4461    }
4462
4463    private ScrollabilityCache getScrollCache() {
4464        initScrollCache();
4465        return mScrollCache;
4466    }
4467
4468    /**
4469     * Set the position of the vertical scroll bar. Should be one of
4470     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4471     * {@link #SCROLLBAR_POSITION_RIGHT}.
4472     *
4473     * @param position Where the vertical scroll bar should be positioned.
4474     */
4475    public void setVerticalScrollbarPosition(int position) {
4476        if (mVerticalScrollbarPosition != position) {
4477            mVerticalScrollbarPosition = position;
4478            computeOpaqueFlags();
4479            resolvePadding();
4480        }
4481    }
4482
4483    /**
4484     * @return The position where the vertical scroll bar will show, if applicable.
4485     * @see #setVerticalScrollbarPosition(int)
4486     */
4487    public int getVerticalScrollbarPosition() {
4488        return mVerticalScrollbarPosition;
4489    }
4490
4491    ListenerInfo getListenerInfo() {
4492        if (mListenerInfo != null) {
4493            return mListenerInfo;
4494        }
4495        mListenerInfo = new ListenerInfo();
4496        return mListenerInfo;
4497    }
4498
4499    /**
4500     * Register a callback to be invoked when focus of this view changed.
4501     *
4502     * @param l The callback that will run.
4503     */
4504    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4505        getListenerInfo().mOnFocusChangeListener = l;
4506    }
4507
4508    /**
4509     * Add a listener that will be called when the bounds of the view change due to
4510     * layout processing.
4511     *
4512     * @param listener The listener that will be called when layout bounds change.
4513     */
4514    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4515        ListenerInfo li = getListenerInfo();
4516        if (li.mOnLayoutChangeListeners == null) {
4517            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4518        }
4519        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4520            li.mOnLayoutChangeListeners.add(listener);
4521        }
4522    }
4523
4524    /**
4525     * Remove a listener for layout changes.
4526     *
4527     * @param listener The listener for layout bounds change.
4528     */
4529    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4530        ListenerInfo li = mListenerInfo;
4531        if (li == null || li.mOnLayoutChangeListeners == null) {
4532            return;
4533        }
4534        li.mOnLayoutChangeListeners.remove(listener);
4535    }
4536
4537    /**
4538     * Add a listener for attach state changes.
4539     *
4540     * This listener will be called whenever this view is attached or detached
4541     * from a window. Remove the listener using
4542     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4543     *
4544     * @param listener Listener to attach
4545     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4546     */
4547    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4548        ListenerInfo li = getListenerInfo();
4549        if (li.mOnAttachStateChangeListeners == null) {
4550            li.mOnAttachStateChangeListeners
4551                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4552        }
4553        li.mOnAttachStateChangeListeners.add(listener);
4554    }
4555
4556    /**
4557     * Remove a listener for attach state changes. The listener will receive no further
4558     * notification of window attach/detach events.
4559     *
4560     * @param listener Listener to remove
4561     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4562     */
4563    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4564        ListenerInfo li = mListenerInfo;
4565        if (li == null || li.mOnAttachStateChangeListeners == null) {
4566            return;
4567        }
4568        li.mOnAttachStateChangeListeners.remove(listener);
4569    }
4570
4571    /**
4572     * Returns the focus-change callback registered for this view.
4573     *
4574     * @return The callback, or null if one is not registered.
4575     */
4576    public OnFocusChangeListener getOnFocusChangeListener() {
4577        ListenerInfo li = mListenerInfo;
4578        return li != null ? li.mOnFocusChangeListener : null;
4579    }
4580
4581    /**
4582     * Register a callback to be invoked when this view is clicked. If this view is not
4583     * clickable, it becomes clickable.
4584     *
4585     * @param l The callback that will run
4586     *
4587     * @see #setClickable(boolean)
4588     */
4589    public void setOnClickListener(OnClickListener l) {
4590        if (!isClickable()) {
4591            setClickable(true);
4592        }
4593        getListenerInfo().mOnClickListener = l;
4594    }
4595
4596    /**
4597     * Return whether this view has an attached OnClickListener.  Returns
4598     * true if there is a listener, false if there is none.
4599     */
4600    public boolean hasOnClickListeners() {
4601        ListenerInfo li = mListenerInfo;
4602        return (li != null && li.mOnClickListener != null);
4603    }
4604
4605    /**
4606     * Register a callback to be invoked when this view is clicked and held. If this view is not
4607     * long clickable, it becomes long clickable.
4608     *
4609     * @param l The callback that will run
4610     *
4611     * @see #setLongClickable(boolean)
4612     */
4613    public void setOnLongClickListener(OnLongClickListener l) {
4614        if (!isLongClickable()) {
4615            setLongClickable(true);
4616        }
4617        getListenerInfo().mOnLongClickListener = l;
4618    }
4619
4620    /**
4621     * Register a callback to be invoked when the context menu for this view is
4622     * being built. If this view is not long clickable, it becomes long clickable.
4623     *
4624     * @param l The callback that will run
4625     *
4626     */
4627    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4628        if (!isLongClickable()) {
4629            setLongClickable(true);
4630        }
4631        getListenerInfo().mOnCreateContextMenuListener = l;
4632    }
4633
4634    /**
4635     * Call this view's OnClickListener, if it is defined.  Performs all normal
4636     * actions associated with clicking: reporting accessibility event, playing
4637     * a sound, etc.
4638     *
4639     * @return True there was an assigned OnClickListener that was called, false
4640     *         otherwise is returned.
4641     */
4642    public boolean performClick() {
4643        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4644
4645        ListenerInfo li = mListenerInfo;
4646        if (li != null && li.mOnClickListener != null) {
4647            playSoundEffect(SoundEffectConstants.CLICK);
4648            li.mOnClickListener.onClick(this);
4649            return true;
4650        }
4651
4652        return false;
4653    }
4654
4655    /**
4656     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4657     * this only calls the listener, and does not do any associated clicking
4658     * actions like reporting an accessibility event.
4659     *
4660     * @return True there was an assigned OnClickListener that was called, false
4661     *         otherwise is returned.
4662     */
4663    public boolean callOnClick() {
4664        ListenerInfo li = mListenerInfo;
4665        if (li != null && li.mOnClickListener != null) {
4666            li.mOnClickListener.onClick(this);
4667            return true;
4668        }
4669        return false;
4670    }
4671
4672    /**
4673     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4674     * OnLongClickListener did not consume the event.
4675     *
4676     * @return True if one of the above receivers consumed the event, false otherwise.
4677     */
4678    public boolean performLongClick() {
4679        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4680
4681        boolean handled = false;
4682        ListenerInfo li = mListenerInfo;
4683        if (li != null && li.mOnLongClickListener != null) {
4684            handled = li.mOnLongClickListener.onLongClick(View.this);
4685        }
4686        if (!handled) {
4687            handled = showContextMenu();
4688        }
4689        if (handled) {
4690            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4691        }
4692        return handled;
4693    }
4694
4695    /**
4696     * Performs button-related actions during a touch down event.
4697     *
4698     * @param event The event.
4699     * @return True if the down was consumed.
4700     *
4701     * @hide
4702     */
4703    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4704        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4705            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4706                return true;
4707            }
4708        }
4709        return false;
4710    }
4711
4712    /**
4713     * Bring up the context menu for this view.
4714     *
4715     * @return Whether a context menu was displayed.
4716     */
4717    public boolean showContextMenu() {
4718        return getParent().showContextMenuForChild(this);
4719    }
4720
4721    /**
4722     * Bring up the context menu for this view, referring to the item under the specified point.
4723     *
4724     * @param x The referenced x coordinate.
4725     * @param y The referenced y coordinate.
4726     * @param metaState The keyboard modifiers that were pressed.
4727     * @return Whether a context menu was displayed.
4728     *
4729     * @hide
4730     */
4731    public boolean showContextMenu(float x, float y, int metaState) {
4732        return showContextMenu();
4733    }
4734
4735    /**
4736     * Start an action mode.
4737     *
4738     * @param callback Callback that will control the lifecycle of the action mode
4739     * @return The new action mode if it is started, null otherwise
4740     *
4741     * @see ActionMode
4742     */
4743    public ActionMode startActionMode(ActionMode.Callback callback) {
4744        ViewParent parent = getParent();
4745        if (parent == null) return null;
4746        return parent.startActionModeForChild(this, callback);
4747    }
4748
4749    /**
4750     * Register a callback to be invoked when a hardware key is pressed in this view.
4751     * Key presses in software input methods will generally not trigger the methods of
4752     * this listener.
4753     * @param l the key listener to attach to this view
4754     */
4755    public void setOnKeyListener(OnKeyListener l) {
4756        getListenerInfo().mOnKeyListener = l;
4757    }
4758
4759    /**
4760     * Register a callback to be invoked when a touch event is sent to this view.
4761     * @param l the touch listener to attach to this view
4762     */
4763    public void setOnTouchListener(OnTouchListener l) {
4764        getListenerInfo().mOnTouchListener = l;
4765    }
4766
4767    /**
4768     * Register a callback to be invoked when a generic motion event is sent to this view.
4769     * @param l the generic motion listener to attach to this view
4770     */
4771    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4772        getListenerInfo().mOnGenericMotionListener = l;
4773    }
4774
4775    /**
4776     * Register a callback to be invoked when a hover event is sent to this view.
4777     * @param l the hover listener to attach to this view
4778     */
4779    public void setOnHoverListener(OnHoverListener l) {
4780        getListenerInfo().mOnHoverListener = l;
4781    }
4782
4783    /**
4784     * Register a drag event listener callback object for this View. The parameter is
4785     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4786     * View, the system calls the
4787     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4788     * @param l An implementation of {@link android.view.View.OnDragListener}.
4789     */
4790    public void setOnDragListener(OnDragListener l) {
4791        getListenerInfo().mOnDragListener = l;
4792    }
4793
4794    /**
4795     * Give this view focus. This will cause
4796     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4797     *
4798     * Note: this does not check whether this {@link View} should get focus, it just
4799     * gives it focus no matter what.  It should only be called internally by framework
4800     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4801     *
4802     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4803     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4804     *        focus moved when requestFocus() is called. It may not always
4805     *        apply, in which case use the default View.FOCUS_DOWN.
4806     * @param previouslyFocusedRect The rectangle of the view that had focus
4807     *        prior in this View's coordinate system.
4808     */
4809    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4810        if (DBG) {
4811            System.out.println(this + " requestFocus()");
4812        }
4813
4814        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4815            mPrivateFlags |= PFLAG_FOCUSED;
4816
4817            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4818
4819            if (mParent != null) {
4820                mParent.requestChildFocus(this, this);
4821            }
4822
4823            if (mAttachInfo != null) {
4824                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4825            }
4826
4827            manageFocusHotspot(true, oldFocus);
4828            onFocusChanged(true, direction, previouslyFocusedRect);
4829            refreshDrawableState();
4830        }
4831    }
4832
4833    /**
4834     * Forwards focus information to the background drawable, if necessary. When
4835     * the view is gaining focus, <code>v</code> is the previous focus holder.
4836     * When the view is losing focus, <code>v</code> is the next focus holder.
4837     *
4838     * @param focused whether this view is focused
4839     * @param v previous or the next focus holder, or null if none
4840     */
4841    private void manageFocusHotspot(boolean focused, View v) {
4842        if (mBackground != null && mBackground.supportsHotspots()) {
4843            final Rect r = new Rect();
4844            if (v != null) {
4845                v.getBoundsOnScreen(r);
4846                final int[] location = new int[2];
4847                getLocationOnScreen(location);
4848                r.offset(-location[0], -location[1]);
4849            } else {
4850                r.set(mLeft, mTop, mRight, mBottom);
4851            }
4852
4853            final float x = r.exactCenterX();
4854            final float y = r.exactCenterY();
4855            mBackground.setHotspot(Drawable.HOTSPOT_FOCUS, x, y);
4856
4857            if (!focused) {
4858                mBackground.removeHotspot(Drawable.HOTSPOT_FOCUS);
4859            }
4860        }
4861    }
4862
4863    /**
4864     * Request that a rectangle of this view be visible on the screen,
4865     * scrolling if necessary just enough.
4866     *
4867     * <p>A View should call this if it maintains some notion of which part
4868     * of its content is interesting.  For example, a text editing view
4869     * should call this when its cursor moves.
4870     *
4871     * @param rectangle The rectangle.
4872     * @return Whether any parent scrolled.
4873     */
4874    public boolean requestRectangleOnScreen(Rect rectangle) {
4875        return requestRectangleOnScreen(rectangle, false);
4876    }
4877
4878    /**
4879     * Request that a rectangle of this view be visible on the screen,
4880     * scrolling if necessary just enough.
4881     *
4882     * <p>A View should call this if it maintains some notion of which part
4883     * of its content is interesting.  For example, a text editing view
4884     * should call this when its cursor moves.
4885     *
4886     * <p>When <code>immediate</code> is set to true, scrolling will not be
4887     * animated.
4888     *
4889     * @param rectangle The rectangle.
4890     * @param immediate True to forbid animated scrolling, false otherwise
4891     * @return Whether any parent scrolled.
4892     */
4893    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4894        if (mParent == null) {
4895            return false;
4896        }
4897
4898        View child = this;
4899
4900        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4901        position.set(rectangle);
4902
4903        ViewParent parent = mParent;
4904        boolean scrolled = false;
4905        while (parent != null) {
4906            rectangle.set((int) position.left, (int) position.top,
4907                    (int) position.right, (int) position.bottom);
4908
4909            scrolled |= parent.requestChildRectangleOnScreen(child,
4910                    rectangle, immediate);
4911
4912            if (!child.hasIdentityMatrix()) {
4913                child.getMatrix().mapRect(position);
4914            }
4915
4916            position.offset(child.mLeft, child.mTop);
4917
4918            if (!(parent instanceof View)) {
4919                break;
4920            }
4921
4922            View parentView = (View) parent;
4923
4924            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4925
4926            child = parentView;
4927            parent = child.getParent();
4928        }
4929
4930        return scrolled;
4931    }
4932
4933    /**
4934     * Called when this view wants to give up focus. If focus is cleared
4935     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4936     * <p>
4937     * <strong>Note:</strong> When a View clears focus the framework is trying
4938     * to give focus to the first focusable View from the top. Hence, if this
4939     * View is the first from the top that can take focus, then all callbacks
4940     * related to clearing focus will be invoked after wich the framework will
4941     * give focus to this view.
4942     * </p>
4943     */
4944    public void clearFocus() {
4945        if (DBG) {
4946            System.out.println(this + " clearFocus()");
4947        }
4948
4949        clearFocusInternal(null, true, true);
4950    }
4951
4952    /**
4953     * Clears focus from the view, optionally propagating the change up through
4954     * the parent hierarchy and requesting that the root view place new focus.
4955     *
4956     * @param propagate whether to propagate the change up through the parent
4957     *            hierarchy
4958     * @param refocus when propagate is true, specifies whether to request the
4959     *            root view place new focus
4960     */
4961    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4962        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4963            mPrivateFlags &= ~PFLAG_FOCUSED;
4964
4965            if (hasFocus()) {
4966                manageFocusHotspot(false, focused);
4967            }
4968
4969            if (propagate && mParent != null) {
4970                mParent.clearChildFocus(this);
4971            }
4972
4973            onFocusChanged(false, 0, null);
4974
4975            refreshDrawableState();
4976
4977            if (propagate && (!refocus || !rootViewRequestFocus())) {
4978                notifyGlobalFocusCleared(this);
4979            }
4980        }
4981    }
4982
4983    void notifyGlobalFocusCleared(View oldFocus) {
4984        if (oldFocus != null && mAttachInfo != null) {
4985            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4986        }
4987    }
4988
4989    boolean rootViewRequestFocus() {
4990        final View root = getRootView();
4991        return root != null && root.requestFocus();
4992    }
4993
4994    /**
4995     * Called internally by the view system when a new view is getting focus.
4996     * This is what clears the old focus.
4997     * <p>
4998     * <b>NOTE:</b> The parent view's focused child must be updated manually
4999     * after calling this method. Otherwise, the view hierarchy may be left in
5000     * an inconstent state.
5001     */
5002    void unFocus(View focused) {
5003        if (DBG) {
5004            System.out.println(this + " unFocus()");
5005        }
5006
5007        clearFocusInternal(focused, false, false);
5008    }
5009
5010    /**
5011     * Returns true if this view has focus iteself, or is the ancestor of the
5012     * view that has focus.
5013     *
5014     * @return True if this view has or contains focus, false otherwise.
5015     */
5016    @ViewDebug.ExportedProperty(category = "focus")
5017    public boolean hasFocus() {
5018        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5019    }
5020
5021    /**
5022     * Returns true if this view is focusable or if it contains a reachable View
5023     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5024     * is a View whose parents do not block descendants focus.
5025     *
5026     * Only {@link #VISIBLE} views are considered focusable.
5027     *
5028     * @return True if the view is focusable or if the view contains a focusable
5029     *         View, false otherwise.
5030     *
5031     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5032     */
5033    public boolean hasFocusable() {
5034        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5035    }
5036
5037    /**
5038     * Called by the view system when the focus state of this view changes.
5039     * When the focus change event is caused by directional navigation, direction
5040     * and previouslyFocusedRect provide insight into where the focus is coming from.
5041     * When overriding, be sure to call up through to the super class so that
5042     * the standard focus handling will occur.
5043     *
5044     * @param gainFocus True if the View has focus; false otherwise.
5045     * @param direction The direction focus has moved when requestFocus()
5046     *                  is called to give this view focus. Values are
5047     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5048     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5049     *                  It may not always apply, in which case use the default.
5050     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5051     *        system, of the previously focused view.  If applicable, this will be
5052     *        passed in as finer grained information about where the focus is coming
5053     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5054     */
5055    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5056            @Nullable Rect previouslyFocusedRect) {
5057        if (gainFocus) {
5058            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5059        } else {
5060            notifyViewAccessibilityStateChangedIfNeeded(
5061                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5062        }
5063
5064        InputMethodManager imm = InputMethodManager.peekInstance();
5065        if (!gainFocus) {
5066            if (isPressed()) {
5067                setPressed(false);
5068            }
5069            if (imm != null && mAttachInfo != null
5070                    && mAttachInfo.mHasWindowFocus) {
5071                imm.focusOut(this);
5072            }
5073            onFocusLost();
5074        } else if (imm != null && mAttachInfo != null
5075                && mAttachInfo.mHasWindowFocus) {
5076            imm.focusIn(this);
5077        }
5078
5079        invalidate(true);
5080        ListenerInfo li = mListenerInfo;
5081        if (li != null && li.mOnFocusChangeListener != null) {
5082            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5083        }
5084
5085        if (mAttachInfo != null) {
5086            mAttachInfo.mKeyDispatchState.reset(this);
5087        }
5088    }
5089
5090    /**
5091     * Sends an accessibility event of the given type. If accessibility is
5092     * not enabled this method has no effect. The default implementation calls
5093     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5094     * to populate information about the event source (this View), then calls
5095     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5096     * populate the text content of the event source including its descendants,
5097     * and last calls
5098     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5099     * on its parent to resuest sending of the event to interested parties.
5100     * <p>
5101     * If an {@link AccessibilityDelegate} has been specified via calling
5102     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5103     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5104     * responsible for handling this call.
5105     * </p>
5106     *
5107     * @param eventType The type of the event to send, as defined by several types from
5108     * {@link android.view.accessibility.AccessibilityEvent}, such as
5109     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5110     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5111     *
5112     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5113     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5114     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5115     * @see AccessibilityDelegate
5116     */
5117    public void sendAccessibilityEvent(int eventType) {
5118        // Excluded views do not send accessibility events.
5119        if (!includeForAccessibility()) {
5120            return;
5121        }
5122        if (mAccessibilityDelegate != null) {
5123            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5124        } else {
5125            sendAccessibilityEventInternal(eventType);
5126        }
5127    }
5128
5129    /**
5130     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5131     * {@link AccessibilityEvent} to make an announcement which is related to some
5132     * sort of a context change for which none of the events representing UI transitions
5133     * is a good fit. For example, announcing a new page in a book. If accessibility
5134     * is not enabled this method does nothing.
5135     *
5136     * @param text The announcement text.
5137     */
5138    public void announceForAccessibility(CharSequence text) {
5139        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null
5140                && isImportantForAccessibility()) {
5141            AccessibilityEvent event = AccessibilityEvent.obtain(
5142                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5143            onInitializeAccessibilityEvent(event);
5144            event.getText().add(text);
5145            event.setContentDescription(null);
5146            mParent.requestSendAccessibilityEvent(this, event);
5147        }
5148    }
5149
5150    /**
5151     * @see #sendAccessibilityEvent(int)
5152     *
5153     * Note: Called from the default {@link AccessibilityDelegate}.
5154     */
5155    void sendAccessibilityEventInternal(int eventType) {
5156        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5157            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5158        }
5159    }
5160
5161    /**
5162     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5163     * takes as an argument an empty {@link AccessibilityEvent} and does not
5164     * perform a check whether accessibility is enabled.
5165     * <p>
5166     * If an {@link AccessibilityDelegate} has been specified via calling
5167     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5168     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5169     * is responsible for handling this call.
5170     * </p>
5171     *
5172     * @param event The event to send.
5173     *
5174     * @see #sendAccessibilityEvent(int)
5175     */
5176    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5177        if (mAccessibilityDelegate != null) {
5178            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5179        } else {
5180            sendAccessibilityEventUncheckedInternal(event);
5181        }
5182    }
5183
5184    /**
5185     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5186     *
5187     * Note: Called from the default {@link AccessibilityDelegate}.
5188     */
5189    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5190        if (!isShown() || !isImportantForAccessibility()) {
5191            return;
5192        }
5193        onInitializeAccessibilityEvent(event);
5194        // Only a subset of accessibility events populates text content.
5195        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5196            dispatchPopulateAccessibilityEvent(event);
5197        }
5198        // In the beginning we called #isShown(), so we know that getParent() is not null.
5199        getParent().requestSendAccessibilityEvent(this, event);
5200    }
5201
5202    /**
5203     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5204     * to its children for adding their text content to the event. Note that the
5205     * event text is populated in a separate dispatch path since we add to the
5206     * event not only the text of the source but also the text of all its descendants.
5207     * A typical implementation will call
5208     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5209     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5210     * on each child. Override this method if custom population of the event text
5211     * content is required.
5212     * <p>
5213     * If an {@link AccessibilityDelegate} has been specified via calling
5214     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5215     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5216     * is responsible for handling this call.
5217     * </p>
5218     * <p>
5219     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5220     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5221     * </p>
5222     *
5223     * @param event The event.
5224     *
5225     * @return True if the event population was completed.
5226     */
5227    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5228        if (mAccessibilityDelegate != null) {
5229            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5230        } else {
5231            return dispatchPopulateAccessibilityEventInternal(event);
5232        }
5233    }
5234
5235    /**
5236     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5237     *
5238     * Note: Called from the default {@link AccessibilityDelegate}.
5239     */
5240    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5241        onPopulateAccessibilityEvent(event);
5242        return false;
5243    }
5244
5245    /**
5246     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5247     * giving a chance to this View to populate the accessibility event with its
5248     * text content. While this method is free to modify event
5249     * attributes other than text content, doing so should normally be performed in
5250     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5251     * <p>
5252     * Example: Adding formatted date string to an accessibility event in addition
5253     *          to the text added by the super implementation:
5254     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5255     *     super.onPopulateAccessibilityEvent(event);
5256     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5257     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5258     *         mCurrentDate.getTimeInMillis(), flags);
5259     *     event.getText().add(selectedDateUtterance);
5260     * }</pre>
5261     * <p>
5262     * If an {@link AccessibilityDelegate} has been specified via calling
5263     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5264     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5265     * is responsible for handling this call.
5266     * </p>
5267     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5268     * information to the event, in case the default implementation has basic information to add.
5269     * </p>
5270     *
5271     * @param event The accessibility event which to populate.
5272     *
5273     * @see #sendAccessibilityEvent(int)
5274     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5275     */
5276    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5277        if (mAccessibilityDelegate != null) {
5278            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5279        } else {
5280            onPopulateAccessibilityEventInternal(event);
5281        }
5282    }
5283
5284    /**
5285     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5286     *
5287     * Note: Called from the default {@link AccessibilityDelegate}.
5288     */
5289    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5290    }
5291
5292    /**
5293     * Initializes an {@link AccessibilityEvent} with information about
5294     * this View which is the event source. In other words, the source of
5295     * an accessibility event is the view whose state change triggered firing
5296     * the event.
5297     * <p>
5298     * Example: Setting the password property of an event in addition
5299     *          to properties set by the super implementation:
5300     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5301     *     super.onInitializeAccessibilityEvent(event);
5302     *     event.setPassword(true);
5303     * }</pre>
5304     * <p>
5305     * If an {@link AccessibilityDelegate} has been specified via calling
5306     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5307     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5308     * is responsible for handling this call.
5309     * </p>
5310     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5311     * information to the event, in case the default implementation has basic information to add.
5312     * </p>
5313     * @param event The event to initialize.
5314     *
5315     * @see #sendAccessibilityEvent(int)
5316     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5317     */
5318    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5319        if (mAccessibilityDelegate != null) {
5320            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5321        } else {
5322            onInitializeAccessibilityEventInternal(event);
5323        }
5324    }
5325
5326    /**
5327     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5328     *
5329     * Note: Called from the default {@link AccessibilityDelegate}.
5330     */
5331    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5332        event.setSource(this);
5333        event.setClassName(View.class.getName());
5334        event.setPackageName(getContext().getPackageName());
5335        event.setEnabled(isEnabled());
5336        event.setContentDescription(mContentDescription);
5337
5338        switch (event.getEventType()) {
5339            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5340                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5341                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5342                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5343                event.setItemCount(focusablesTempList.size());
5344                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5345                if (mAttachInfo != null) {
5346                    focusablesTempList.clear();
5347                }
5348            } break;
5349            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5350                CharSequence text = getIterableTextForAccessibility();
5351                if (text != null && text.length() > 0) {
5352                    event.setFromIndex(getAccessibilitySelectionStart());
5353                    event.setToIndex(getAccessibilitySelectionEnd());
5354                    event.setItemCount(text.length());
5355                }
5356            } break;
5357        }
5358    }
5359
5360    /**
5361     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5362     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5363     * This method is responsible for obtaining an accessibility node info from a
5364     * pool of reusable instances and calling
5365     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5366     * initialize the former.
5367     * <p>
5368     * Note: The client is responsible for recycling the obtained instance by calling
5369     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5370     * </p>
5371     *
5372     * @return A populated {@link AccessibilityNodeInfo}.
5373     *
5374     * @see AccessibilityNodeInfo
5375     */
5376    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5377        if (mAccessibilityDelegate != null) {
5378            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5379        } else {
5380            return createAccessibilityNodeInfoInternal();
5381        }
5382    }
5383
5384    /**
5385     * @see #createAccessibilityNodeInfo()
5386     */
5387    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5388        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5389        if (provider != null) {
5390            return provider.createAccessibilityNodeInfo(View.NO_ID);
5391        } else {
5392            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5393            onInitializeAccessibilityNodeInfo(info);
5394            return info;
5395        }
5396    }
5397
5398    /**
5399     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5400     * The base implementation sets:
5401     * <ul>
5402     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5403     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5404     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5405     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5406     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5407     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5408     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5409     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5410     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5411     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5412     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5413     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5414     * </ul>
5415     * <p>
5416     * Subclasses should override this method, call the super implementation,
5417     * and set additional attributes.
5418     * </p>
5419     * <p>
5420     * If an {@link AccessibilityDelegate} has been specified via calling
5421     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5422     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5423     * is responsible for handling this call.
5424     * </p>
5425     *
5426     * @param info The instance to initialize.
5427     */
5428    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5429        if (mAccessibilityDelegate != null) {
5430            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5431        } else {
5432            onInitializeAccessibilityNodeInfoInternal(info);
5433        }
5434    }
5435
5436    /**
5437     * Gets the location of this view in screen coordintates.
5438     *
5439     * @param outRect The output location
5440     */
5441    void getBoundsOnScreen(Rect outRect) {
5442        if (mAttachInfo == null) {
5443            return;
5444        }
5445
5446        RectF position = mAttachInfo.mTmpTransformRect;
5447        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5448
5449        if (!hasIdentityMatrix()) {
5450            getMatrix().mapRect(position);
5451        }
5452
5453        position.offset(mLeft, mTop);
5454
5455        ViewParent parent = mParent;
5456        while (parent instanceof View) {
5457            View parentView = (View) parent;
5458
5459            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5460
5461            if (!parentView.hasIdentityMatrix()) {
5462                parentView.getMatrix().mapRect(position);
5463            }
5464
5465            position.offset(parentView.mLeft, parentView.mTop);
5466
5467            parent = parentView.mParent;
5468        }
5469
5470        if (parent instanceof ViewRootImpl) {
5471            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5472            position.offset(0, -viewRootImpl.mCurScrollY);
5473        }
5474
5475        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5476
5477        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5478                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5479    }
5480
5481    /**
5482     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5483     *
5484     * Note: Called from the default {@link AccessibilityDelegate}.
5485     */
5486    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5487        Rect bounds = mAttachInfo.mTmpInvalRect;
5488
5489        getDrawingRect(bounds);
5490        info.setBoundsInParent(bounds);
5491
5492        getBoundsOnScreen(bounds);
5493        info.setBoundsInScreen(bounds);
5494
5495        ViewParent parent = getParentForAccessibility();
5496        if (parent instanceof View) {
5497            info.setParent((View) parent);
5498        }
5499
5500        if (mID != View.NO_ID) {
5501            View rootView = getRootView();
5502            if (rootView == null) {
5503                rootView = this;
5504            }
5505            View label = rootView.findLabelForView(this, mID);
5506            if (label != null) {
5507                info.setLabeledBy(label);
5508            }
5509
5510            if ((mAttachInfo.mAccessibilityFetchFlags
5511                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5512                    && Resources.resourceHasPackage(mID)) {
5513                try {
5514                    String viewId = getResources().getResourceName(mID);
5515                    info.setViewIdResourceName(viewId);
5516                } catch (Resources.NotFoundException nfe) {
5517                    /* ignore */
5518                }
5519            }
5520        }
5521
5522        if (mLabelForId != View.NO_ID) {
5523            View rootView = getRootView();
5524            if (rootView == null) {
5525                rootView = this;
5526            }
5527            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5528            if (labeled != null) {
5529                info.setLabelFor(labeled);
5530            }
5531        }
5532
5533        info.setVisibleToUser(isVisibleToUser());
5534
5535        info.setPackageName(mContext.getPackageName());
5536        info.setClassName(View.class.getName());
5537        info.setContentDescription(getContentDescription());
5538
5539        info.setEnabled(isEnabled());
5540        info.setClickable(isClickable());
5541        info.setFocusable(isFocusable());
5542        info.setFocused(isFocused());
5543        info.setAccessibilityFocused(isAccessibilityFocused());
5544        info.setSelected(isSelected());
5545        info.setLongClickable(isLongClickable());
5546        info.setLiveRegion(getAccessibilityLiveRegion());
5547
5548        // TODO: These make sense only if we are in an AdapterView but all
5549        // views can be selected. Maybe from accessibility perspective
5550        // we should report as selectable view in an AdapterView.
5551        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5552        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5553
5554        if (isFocusable()) {
5555            if (isFocused()) {
5556                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5557            } else {
5558                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5559            }
5560        }
5561
5562        if (!isAccessibilityFocused()) {
5563            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5564        } else {
5565            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5566        }
5567
5568        if (isClickable() && isEnabled()) {
5569            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5570        }
5571
5572        if (isLongClickable() && isEnabled()) {
5573            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5574        }
5575
5576        CharSequence text = getIterableTextForAccessibility();
5577        if (text != null && text.length() > 0) {
5578            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5579
5580            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5581            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5582            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5583            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5584                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5585                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5586        }
5587    }
5588
5589    private View findLabelForView(View view, int labeledId) {
5590        if (mMatchLabelForPredicate == null) {
5591            mMatchLabelForPredicate = new MatchLabelForPredicate();
5592        }
5593        mMatchLabelForPredicate.mLabeledId = labeledId;
5594        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5595    }
5596
5597    /**
5598     * Computes whether this view is visible to the user. Such a view is
5599     * attached, visible, all its predecessors are visible, it is not clipped
5600     * entirely by its predecessors, and has an alpha greater than zero.
5601     *
5602     * @return Whether the view is visible on the screen.
5603     *
5604     * @hide
5605     */
5606    protected boolean isVisibleToUser() {
5607        return isVisibleToUser(null);
5608    }
5609
5610    /**
5611     * Computes whether the given portion of this view is visible to the user.
5612     * Such a view is attached, visible, all its predecessors are visible,
5613     * has an alpha greater than zero, and the specified portion is not
5614     * clipped entirely by its predecessors.
5615     *
5616     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5617     *                    <code>null</code>, and the entire view will be tested in this case.
5618     *                    When <code>true</code> is returned by the function, the actual visible
5619     *                    region will be stored in this parameter; that is, if boundInView is fully
5620     *                    contained within the view, no modification will be made, otherwise regions
5621     *                    outside of the visible area of the view will be clipped.
5622     *
5623     * @return Whether the specified portion of the view is visible on the screen.
5624     *
5625     * @hide
5626     */
5627    protected boolean isVisibleToUser(Rect boundInView) {
5628        if (mAttachInfo != null) {
5629            // Attached to invisible window means this view is not visible.
5630            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5631                return false;
5632            }
5633            // An invisible predecessor or one with alpha zero means
5634            // that this view is not visible to the user.
5635            Object current = this;
5636            while (current instanceof View) {
5637                View view = (View) current;
5638                // We have attach info so this view is attached and there is no
5639                // need to check whether we reach to ViewRootImpl on the way up.
5640                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5641                        view.getVisibility() != VISIBLE) {
5642                    return false;
5643                }
5644                current = view.mParent;
5645            }
5646            // Check if the view is entirely covered by its predecessors.
5647            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5648            Point offset = mAttachInfo.mPoint;
5649            if (!getGlobalVisibleRect(visibleRect, offset)) {
5650                return false;
5651            }
5652            // Check if the visible portion intersects the rectangle of interest.
5653            if (boundInView != null) {
5654                visibleRect.offset(-offset.x, -offset.y);
5655                return boundInView.intersect(visibleRect);
5656            }
5657            return true;
5658        }
5659        return false;
5660    }
5661
5662    /**
5663     * Returns the delegate for implementing accessibility support via
5664     * composition. For more details see {@link AccessibilityDelegate}.
5665     *
5666     * @return The delegate, or null if none set.
5667     *
5668     * @hide
5669     */
5670    public AccessibilityDelegate getAccessibilityDelegate() {
5671        return mAccessibilityDelegate;
5672    }
5673
5674    /**
5675     * Sets a delegate for implementing accessibility support via composition as
5676     * opposed to inheritance. The delegate's primary use is for implementing
5677     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5678     *
5679     * @param delegate The delegate instance.
5680     *
5681     * @see AccessibilityDelegate
5682     */
5683    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5684        mAccessibilityDelegate = delegate;
5685    }
5686
5687    /**
5688     * Gets the provider for managing a virtual view hierarchy rooted at this View
5689     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5690     * that explore the window content.
5691     * <p>
5692     * If this method returns an instance, this instance is responsible for managing
5693     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5694     * View including the one representing the View itself. Similarly the returned
5695     * instance is responsible for performing accessibility actions on any virtual
5696     * view or the root view itself.
5697     * </p>
5698     * <p>
5699     * If an {@link AccessibilityDelegate} has been specified via calling
5700     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5701     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5702     * is responsible for handling this call.
5703     * </p>
5704     *
5705     * @return The provider.
5706     *
5707     * @see AccessibilityNodeProvider
5708     */
5709    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5710        if (mAccessibilityDelegate != null) {
5711            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5712        } else {
5713            return null;
5714        }
5715    }
5716
5717    /**
5718     * Gets the unique identifier of this view on the screen for accessibility purposes.
5719     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5720     *
5721     * @return The view accessibility id.
5722     *
5723     * @hide
5724     */
5725    public int getAccessibilityViewId() {
5726        if (mAccessibilityViewId == NO_ID) {
5727            mAccessibilityViewId = sNextAccessibilityViewId++;
5728        }
5729        return mAccessibilityViewId;
5730    }
5731
5732    /**
5733     * Gets the unique identifier of the window in which this View reseides.
5734     *
5735     * @return The window accessibility id.
5736     *
5737     * @hide
5738     */
5739    public int getAccessibilityWindowId() {
5740        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5741    }
5742
5743    /**
5744     * Gets the {@link View} description. It briefly describes the view and is
5745     * primarily used for accessibility support. Set this property to enable
5746     * better accessibility support for your application. This is especially
5747     * true for views that do not have textual representation (For example,
5748     * ImageButton).
5749     *
5750     * @return The content description.
5751     *
5752     * @attr ref android.R.styleable#View_contentDescription
5753     */
5754    @ViewDebug.ExportedProperty(category = "accessibility")
5755    public CharSequence getContentDescription() {
5756        return mContentDescription;
5757    }
5758
5759    /**
5760     * Sets the {@link View} description. It briefly describes the view and is
5761     * primarily used for accessibility support. Set this property to enable
5762     * better accessibility support for your application. This is especially
5763     * true for views that do not have textual representation (For example,
5764     * ImageButton).
5765     *
5766     * @param contentDescription The content description.
5767     *
5768     * @attr ref android.R.styleable#View_contentDescription
5769     */
5770    @RemotableViewMethod
5771    public void setContentDescription(CharSequence contentDescription) {
5772        if (mContentDescription == null) {
5773            if (contentDescription == null) {
5774                return;
5775            }
5776        } else if (mContentDescription.equals(contentDescription)) {
5777            return;
5778        }
5779        mContentDescription = contentDescription;
5780        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5781        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5782            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5783            notifySubtreeAccessibilityStateChangedIfNeeded();
5784        } else {
5785            notifyViewAccessibilityStateChangedIfNeeded(
5786                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5787        }
5788    }
5789
5790    /**
5791     * Gets the id of a view for which this view serves as a label for
5792     * accessibility purposes.
5793     *
5794     * @return The labeled view id.
5795     */
5796    @ViewDebug.ExportedProperty(category = "accessibility")
5797    public int getLabelFor() {
5798        return mLabelForId;
5799    }
5800
5801    /**
5802     * Sets the id of a view for which this view serves as a label for
5803     * accessibility purposes.
5804     *
5805     * @param id The labeled view id.
5806     */
5807    @RemotableViewMethod
5808    public void setLabelFor(int id) {
5809        mLabelForId = id;
5810        if (mLabelForId != View.NO_ID
5811                && mID == View.NO_ID) {
5812            mID = generateViewId();
5813        }
5814    }
5815
5816    /**
5817     * Invoked whenever this view loses focus, either by losing window focus or by losing
5818     * focus within its window. This method can be used to clear any state tied to the
5819     * focus. For instance, if a button is held pressed with the trackball and the window
5820     * loses focus, this method can be used to cancel the press.
5821     *
5822     * Subclasses of View overriding this method should always call super.onFocusLost().
5823     *
5824     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5825     * @see #onWindowFocusChanged(boolean)
5826     *
5827     * @hide pending API council approval
5828     */
5829    protected void onFocusLost() {
5830        resetPressedState();
5831    }
5832
5833    private void resetPressedState() {
5834        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5835            return;
5836        }
5837
5838        if (isPressed()) {
5839            setPressed(false);
5840
5841            if (!mHasPerformedLongPress) {
5842                removeLongPressCallback();
5843            }
5844        }
5845    }
5846
5847    /**
5848     * Returns true if this view has focus
5849     *
5850     * @return True if this view has focus, false otherwise.
5851     */
5852    @ViewDebug.ExportedProperty(category = "focus")
5853    public boolean isFocused() {
5854        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5855    }
5856
5857    /**
5858     * Find the view in the hierarchy rooted at this view that currently has
5859     * focus.
5860     *
5861     * @return The view that currently has focus, or null if no focused view can
5862     *         be found.
5863     */
5864    public View findFocus() {
5865        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5866    }
5867
5868    /**
5869     * Indicates whether this view is one of the set of scrollable containers in
5870     * its window.
5871     *
5872     * @return whether this view is one of the set of scrollable containers in
5873     * its window
5874     *
5875     * @attr ref android.R.styleable#View_isScrollContainer
5876     */
5877    public boolean isScrollContainer() {
5878        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5879    }
5880
5881    /**
5882     * Change whether this view is one of the set of scrollable containers in
5883     * its window.  This will be used to determine whether the window can
5884     * resize or must pan when a soft input area is open -- scrollable
5885     * containers allow the window to use resize mode since the container
5886     * will appropriately shrink.
5887     *
5888     * @attr ref android.R.styleable#View_isScrollContainer
5889     */
5890    public void setScrollContainer(boolean isScrollContainer) {
5891        if (isScrollContainer) {
5892            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5893                mAttachInfo.mScrollContainers.add(this);
5894                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5895            }
5896            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5897        } else {
5898            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5899                mAttachInfo.mScrollContainers.remove(this);
5900            }
5901            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5902        }
5903    }
5904
5905    /**
5906     * Returns the quality of the drawing cache.
5907     *
5908     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5909     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5910     *
5911     * @see #setDrawingCacheQuality(int)
5912     * @see #setDrawingCacheEnabled(boolean)
5913     * @see #isDrawingCacheEnabled()
5914     *
5915     * @attr ref android.R.styleable#View_drawingCacheQuality
5916     */
5917    @DrawingCacheQuality
5918    public int getDrawingCacheQuality() {
5919        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5920    }
5921
5922    /**
5923     * Set the drawing cache quality of this view. This value is used only when the
5924     * drawing cache is enabled
5925     *
5926     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5927     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5928     *
5929     * @see #getDrawingCacheQuality()
5930     * @see #setDrawingCacheEnabled(boolean)
5931     * @see #isDrawingCacheEnabled()
5932     *
5933     * @attr ref android.R.styleable#View_drawingCacheQuality
5934     */
5935    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5936        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5937    }
5938
5939    /**
5940     * Returns whether the screen should remain on, corresponding to the current
5941     * value of {@link #KEEP_SCREEN_ON}.
5942     *
5943     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5944     *
5945     * @see #setKeepScreenOn(boolean)
5946     *
5947     * @attr ref android.R.styleable#View_keepScreenOn
5948     */
5949    public boolean getKeepScreenOn() {
5950        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5951    }
5952
5953    /**
5954     * Controls whether the screen should remain on, modifying the
5955     * value of {@link #KEEP_SCREEN_ON}.
5956     *
5957     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5958     *
5959     * @see #getKeepScreenOn()
5960     *
5961     * @attr ref android.R.styleable#View_keepScreenOn
5962     */
5963    public void setKeepScreenOn(boolean keepScreenOn) {
5964        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5965    }
5966
5967    /**
5968     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5969     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5970     *
5971     * @attr ref android.R.styleable#View_nextFocusLeft
5972     */
5973    public int getNextFocusLeftId() {
5974        return mNextFocusLeftId;
5975    }
5976
5977    /**
5978     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5979     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5980     * decide automatically.
5981     *
5982     * @attr ref android.R.styleable#View_nextFocusLeft
5983     */
5984    public void setNextFocusLeftId(int nextFocusLeftId) {
5985        mNextFocusLeftId = nextFocusLeftId;
5986    }
5987
5988    /**
5989     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5990     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5991     *
5992     * @attr ref android.R.styleable#View_nextFocusRight
5993     */
5994    public int getNextFocusRightId() {
5995        return mNextFocusRightId;
5996    }
5997
5998    /**
5999     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6000     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6001     * decide automatically.
6002     *
6003     * @attr ref android.R.styleable#View_nextFocusRight
6004     */
6005    public void setNextFocusRightId(int nextFocusRightId) {
6006        mNextFocusRightId = nextFocusRightId;
6007    }
6008
6009    /**
6010     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6011     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6012     *
6013     * @attr ref android.R.styleable#View_nextFocusUp
6014     */
6015    public int getNextFocusUpId() {
6016        return mNextFocusUpId;
6017    }
6018
6019    /**
6020     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6021     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6022     * decide automatically.
6023     *
6024     * @attr ref android.R.styleable#View_nextFocusUp
6025     */
6026    public void setNextFocusUpId(int nextFocusUpId) {
6027        mNextFocusUpId = nextFocusUpId;
6028    }
6029
6030    /**
6031     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6032     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6033     *
6034     * @attr ref android.R.styleable#View_nextFocusDown
6035     */
6036    public int getNextFocusDownId() {
6037        return mNextFocusDownId;
6038    }
6039
6040    /**
6041     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6042     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6043     * decide automatically.
6044     *
6045     * @attr ref android.R.styleable#View_nextFocusDown
6046     */
6047    public void setNextFocusDownId(int nextFocusDownId) {
6048        mNextFocusDownId = nextFocusDownId;
6049    }
6050
6051    /**
6052     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6053     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6054     *
6055     * @attr ref android.R.styleable#View_nextFocusForward
6056     */
6057    public int getNextFocusForwardId() {
6058        return mNextFocusForwardId;
6059    }
6060
6061    /**
6062     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6063     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6064     * decide automatically.
6065     *
6066     * @attr ref android.R.styleable#View_nextFocusForward
6067     */
6068    public void setNextFocusForwardId(int nextFocusForwardId) {
6069        mNextFocusForwardId = nextFocusForwardId;
6070    }
6071
6072    /**
6073     * Returns the visibility of this view and all of its ancestors
6074     *
6075     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6076     */
6077    public boolean isShown() {
6078        View current = this;
6079        //noinspection ConstantConditions
6080        do {
6081            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6082                return false;
6083            }
6084            ViewParent parent = current.mParent;
6085            if (parent == null) {
6086                return false; // We are not attached to the view root
6087            }
6088            if (!(parent instanceof View)) {
6089                return true;
6090            }
6091            current = (View) parent;
6092        } while (current != null);
6093
6094        return false;
6095    }
6096
6097    /**
6098     * Called by the view hierarchy when the content insets for a window have
6099     * changed, to allow it to adjust its content to fit within those windows.
6100     * The content insets tell you the space that the status bar, input method,
6101     * and other system windows infringe on the application's window.
6102     *
6103     * <p>You do not normally need to deal with this function, since the default
6104     * window decoration given to applications takes care of applying it to the
6105     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6106     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6107     * and your content can be placed under those system elements.  You can then
6108     * use this method within your view hierarchy if you have parts of your UI
6109     * which you would like to ensure are not being covered.
6110     *
6111     * <p>The default implementation of this method simply applies the content
6112     * insets to the view's padding, consuming that content (modifying the
6113     * insets to be 0), and returning true.  This behavior is off by default, but can
6114     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6115     *
6116     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6117     * insets object is propagated down the hierarchy, so any changes made to it will
6118     * be seen by all following views (including potentially ones above in
6119     * the hierarchy since this is a depth-first traversal).  The first view
6120     * that returns true will abort the entire traversal.
6121     *
6122     * <p>The default implementation works well for a situation where it is
6123     * used with a container that covers the entire window, allowing it to
6124     * apply the appropriate insets to its content on all edges.  If you need
6125     * a more complicated layout (such as two different views fitting system
6126     * windows, one on the top of the window, and one on the bottom),
6127     * you can override the method and handle the insets however you would like.
6128     * Note that the insets provided by the framework are always relative to the
6129     * far edges of the window, not accounting for the location of the called view
6130     * within that window.  (In fact when this method is called you do not yet know
6131     * where the layout will place the view, as it is done before layout happens.)
6132     *
6133     * <p>Note: unlike many View methods, there is no dispatch phase to this
6134     * call.  If you are overriding it in a ViewGroup and want to allow the
6135     * call to continue to your children, you must be sure to call the super
6136     * implementation.
6137     *
6138     * <p>Here is a sample layout that makes use of fitting system windows
6139     * to have controls for a video view placed inside of the window decorations
6140     * that it hides and shows.  This can be used with code like the second
6141     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6142     *
6143     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6144     *
6145     * @param insets Current content insets of the window.  Prior to
6146     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6147     * the insets or else you and Android will be unhappy.
6148     *
6149     * @return {@code true} if this view applied the insets and it should not
6150     * continue propagating further down the hierarchy, {@code false} otherwise.
6151     * @see #getFitsSystemWindows()
6152     * @see #setFitsSystemWindows(boolean)
6153     * @see #setSystemUiVisibility(int)
6154     *
6155     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6156     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6157     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6158     * to implement handling their own insets.
6159     */
6160    protected boolean fitSystemWindows(Rect insets) {
6161        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6162            // If we're not in the process of dispatching the newer apply insets call,
6163            // that means we're not in the compatibility path. Dispatch into the newer
6164            // apply insets path and take things from there.
6165            try {
6166                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6167                return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets();
6168            } finally {
6169                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6170            }
6171        } else {
6172            // We're being called from the newer apply insets path.
6173            // Perform the standard fallback behavior.
6174            return fitSystemWindowsInt(insets);
6175        }
6176    }
6177
6178    private boolean fitSystemWindowsInt(Rect insets) {
6179        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6180            mUserPaddingStart = UNDEFINED_PADDING;
6181            mUserPaddingEnd = UNDEFINED_PADDING;
6182            Rect localInsets = sThreadLocal.get();
6183            if (localInsets == null) {
6184                localInsets = new Rect();
6185                sThreadLocal.set(localInsets);
6186            }
6187            boolean res = computeFitSystemWindows(insets, localInsets);
6188            mUserPaddingLeftInitial = localInsets.left;
6189            mUserPaddingRightInitial = localInsets.right;
6190            internalSetPadding(localInsets.left, localInsets.top,
6191                    localInsets.right, localInsets.bottom);
6192            return res;
6193        }
6194        return false;
6195    }
6196
6197    /**
6198     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6199     *
6200     * <p>This method should be overridden by views that wish to apply a policy different from or
6201     * in addition to the default behavior. Clients that wish to force a view subtree
6202     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6203     *
6204     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6205     * it will be called during dispatch instead of this method. The listener may optionally
6206     * call this method from its own implementation if it wishes to apply the view's default
6207     * insets policy in addition to its own.</p>
6208     *
6209     * <p>Implementations of this method should either return the insets parameter unchanged
6210     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6211     * that this view applied itself. This allows new inset types added in future platform
6212     * versions to pass through existing implementations unchanged without being erroneously
6213     * consumed.</p>
6214     *
6215     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6216     * property is set then the view will consume the system window insets and apply them
6217     * as padding for the view.</p>
6218     *
6219     * @param insets Insets to apply
6220     * @return The supplied insets with any applied insets consumed
6221     */
6222    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6223        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6224            // We weren't called from within a direct call to fitSystemWindows,
6225            // call into it as a fallback in case we're in a class that overrides it
6226            // and has logic to perform.
6227            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6228                return insets.cloneWithSystemWindowInsetsConsumed();
6229            }
6230        } else {
6231            // We were called from within a direct call to fitSystemWindows.
6232            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6233                return insets.cloneWithSystemWindowInsetsConsumed();
6234            }
6235        }
6236        return insets;
6237    }
6238
6239    /**
6240     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6241     * window insets to this view. The listener's
6242     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6243     * method will be called instead of the view's
6244     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6245     *
6246     * @param listener Listener to set
6247     *
6248     * @see #onApplyWindowInsets(WindowInsets)
6249     */
6250    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6251        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6252    }
6253
6254    /**
6255     * Request to apply the given window insets to this view or another view in its subtree.
6256     *
6257     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6258     * obscured by window decorations or overlays. This can include the status and navigation bars,
6259     * action bars, input methods and more. New inset categories may be added in the future.
6260     * The method returns the insets provided minus any that were applied by this view or its
6261     * children.</p>
6262     *
6263     * <p>Clients wishing to provide custom behavior should override the
6264     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6265     * {@link OnApplyWindowInsetsListener} via the
6266     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6267     * method.</p>
6268     *
6269     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6270     * </p>
6271     *
6272     * @param insets Insets to apply
6273     * @return The provided insets minus the insets that were consumed
6274     */
6275    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6276        try {
6277            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6278            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6279                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6280            } else {
6281                return onApplyWindowInsets(insets);
6282            }
6283        } finally {
6284            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6285        }
6286    }
6287
6288    /**
6289     * @hide Compute the insets that should be consumed by this view and the ones
6290     * that should propagate to those under it.
6291     */
6292    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6293        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6294                || mAttachInfo == null
6295                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6296                        && !mAttachInfo.mOverscanRequested)) {
6297            outLocalInsets.set(inoutInsets);
6298            inoutInsets.set(0, 0, 0, 0);
6299            return true;
6300        } else {
6301            // The application wants to take care of fitting system window for
6302            // the content...  however we still need to take care of any overscan here.
6303            final Rect overscan = mAttachInfo.mOverscanInsets;
6304            outLocalInsets.set(overscan);
6305            inoutInsets.left -= overscan.left;
6306            inoutInsets.top -= overscan.top;
6307            inoutInsets.right -= overscan.right;
6308            inoutInsets.bottom -= overscan.bottom;
6309            return false;
6310        }
6311    }
6312
6313    /**
6314     * Sets whether or not this view should account for system screen decorations
6315     * such as the status bar and inset its content; that is, controlling whether
6316     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6317     * executed.  See that method for more details.
6318     *
6319     * <p>Note that if you are providing your own implementation of
6320     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6321     * flag to true -- your implementation will be overriding the default
6322     * implementation that checks this flag.
6323     *
6324     * @param fitSystemWindows If true, then the default implementation of
6325     * {@link #fitSystemWindows(Rect)} will be executed.
6326     *
6327     * @attr ref android.R.styleable#View_fitsSystemWindows
6328     * @see #getFitsSystemWindows()
6329     * @see #fitSystemWindows(Rect)
6330     * @see #setSystemUiVisibility(int)
6331     */
6332    public void setFitsSystemWindows(boolean fitSystemWindows) {
6333        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6334    }
6335
6336    /**
6337     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6338     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6339     * will be executed.
6340     *
6341     * @return {@code true} if the default implementation of
6342     * {@link #fitSystemWindows(Rect)} will be executed.
6343     *
6344     * @attr ref android.R.styleable#View_fitsSystemWindows
6345     * @see #setFitsSystemWindows(boolean)
6346     * @see #fitSystemWindows(Rect)
6347     * @see #setSystemUiVisibility(int)
6348     */
6349    public boolean getFitsSystemWindows() {
6350        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6351    }
6352
6353    /** @hide */
6354    public boolean fitsSystemWindows() {
6355        return getFitsSystemWindows();
6356    }
6357
6358    /**
6359     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6360     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6361     */
6362    public void requestFitSystemWindows() {
6363        if (mParent != null) {
6364            mParent.requestFitSystemWindows();
6365        }
6366    }
6367
6368    /**
6369     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6370     */
6371    public void requestApplyInsets() {
6372        requestFitSystemWindows();
6373    }
6374
6375    /**
6376     * For use by PhoneWindow to make its own system window fitting optional.
6377     * @hide
6378     */
6379    public void makeOptionalFitsSystemWindows() {
6380        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6381    }
6382
6383    /**
6384     * Returns the visibility status for this view.
6385     *
6386     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6387     * @attr ref android.R.styleable#View_visibility
6388     */
6389    @ViewDebug.ExportedProperty(mapping = {
6390        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6391        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6392        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6393    })
6394    @Visibility
6395    public int getVisibility() {
6396        return mViewFlags & VISIBILITY_MASK;
6397    }
6398
6399    /**
6400     * Set the enabled state of this view.
6401     *
6402     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6403     * @attr ref android.R.styleable#View_visibility
6404     */
6405    @RemotableViewMethod
6406    public void setVisibility(@Visibility int visibility) {
6407        setFlags(visibility, VISIBILITY_MASK);
6408        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6409    }
6410
6411    /**
6412     * Returns the enabled status for this view. The interpretation of the
6413     * enabled state varies by subclass.
6414     *
6415     * @return True if this view is enabled, false otherwise.
6416     */
6417    @ViewDebug.ExportedProperty
6418    public boolean isEnabled() {
6419        return (mViewFlags & ENABLED_MASK) == ENABLED;
6420    }
6421
6422    /**
6423     * Set the enabled state of this view. The interpretation of the enabled
6424     * state varies by subclass.
6425     *
6426     * @param enabled True if this view is enabled, false otherwise.
6427     */
6428    @RemotableViewMethod
6429    public void setEnabled(boolean enabled) {
6430        if (enabled == isEnabled()) return;
6431
6432        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6433
6434        /*
6435         * The View most likely has to change its appearance, so refresh
6436         * the drawable state.
6437         */
6438        refreshDrawableState();
6439
6440        // Invalidate too, since the default behavior for views is to be
6441        // be drawn at 50% alpha rather than to change the drawable.
6442        invalidate(true);
6443
6444        if (!enabled) {
6445            cancelPendingInputEvents();
6446        }
6447    }
6448
6449    /**
6450     * Set whether this view can receive the focus.
6451     *
6452     * Setting this to false will also ensure that this view is not focusable
6453     * in touch mode.
6454     *
6455     * @param focusable If true, this view can receive the focus.
6456     *
6457     * @see #setFocusableInTouchMode(boolean)
6458     * @attr ref android.R.styleable#View_focusable
6459     */
6460    public void setFocusable(boolean focusable) {
6461        if (!focusable) {
6462            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6463        }
6464        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6465    }
6466
6467    /**
6468     * Set whether this view can receive focus while in touch mode.
6469     *
6470     * Setting this to true will also ensure that this view is focusable.
6471     *
6472     * @param focusableInTouchMode If true, this view can receive the focus while
6473     *   in touch mode.
6474     *
6475     * @see #setFocusable(boolean)
6476     * @attr ref android.R.styleable#View_focusableInTouchMode
6477     */
6478    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6479        // Focusable in touch mode should always be set before the focusable flag
6480        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6481        // which, in touch mode, will not successfully request focus on this view
6482        // because the focusable in touch mode flag is not set
6483        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6484        if (focusableInTouchMode) {
6485            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6486        }
6487    }
6488
6489    /**
6490     * Set whether this view should have sound effects enabled for events such as
6491     * clicking and touching.
6492     *
6493     * <p>You may wish to disable sound effects for a view if you already play sounds,
6494     * for instance, a dial key that plays dtmf tones.
6495     *
6496     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6497     * @see #isSoundEffectsEnabled()
6498     * @see #playSoundEffect(int)
6499     * @attr ref android.R.styleable#View_soundEffectsEnabled
6500     */
6501    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6502        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6503    }
6504
6505    /**
6506     * @return whether this view should have sound effects enabled for events such as
6507     *     clicking and touching.
6508     *
6509     * @see #setSoundEffectsEnabled(boolean)
6510     * @see #playSoundEffect(int)
6511     * @attr ref android.R.styleable#View_soundEffectsEnabled
6512     */
6513    @ViewDebug.ExportedProperty
6514    public boolean isSoundEffectsEnabled() {
6515        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6516    }
6517
6518    /**
6519     * Set whether this view should have haptic feedback for events such as
6520     * long presses.
6521     *
6522     * <p>You may wish to disable haptic feedback if your view already controls
6523     * its own haptic feedback.
6524     *
6525     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6526     * @see #isHapticFeedbackEnabled()
6527     * @see #performHapticFeedback(int)
6528     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6529     */
6530    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6531        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6532    }
6533
6534    /**
6535     * @return whether this view should have haptic feedback enabled for events
6536     * long presses.
6537     *
6538     * @see #setHapticFeedbackEnabled(boolean)
6539     * @see #performHapticFeedback(int)
6540     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6541     */
6542    @ViewDebug.ExportedProperty
6543    public boolean isHapticFeedbackEnabled() {
6544        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6545    }
6546
6547    /**
6548     * Returns the layout direction for this view.
6549     *
6550     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6551     *   {@link #LAYOUT_DIRECTION_RTL},
6552     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6553     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6554     *
6555     * @attr ref android.R.styleable#View_layoutDirection
6556     *
6557     * @hide
6558     */
6559    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6560        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6561        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6562        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6563        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6564    })
6565    @LayoutDir
6566    public int getRawLayoutDirection() {
6567        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6568    }
6569
6570    /**
6571     * Set the layout direction for this view. This will propagate a reset of layout direction
6572     * resolution to the view's children and resolve layout direction for this view.
6573     *
6574     * @param layoutDirection the layout direction to set. Should be one of:
6575     *
6576     * {@link #LAYOUT_DIRECTION_LTR},
6577     * {@link #LAYOUT_DIRECTION_RTL},
6578     * {@link #LAYOUT_DIRECTION_INHERIT},
6579     * {@link #LAYOUT_DIRECTION_LOCALE}.
6580     *
6581     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6582     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6583     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6584     *
6585     * @attr ref android.R.styleable#View_layoutDirection
6586     */
6587    @RemotableViewMethod
6588    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6589        if (getRawLayoutDirection() != layoutDirection) {
6590            // Reset the current layout direction and the resolved one
6591            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6592            resetRtlProperties();
6593            // Set the new layout direction (filtered)
6594            mPrivateFlags2 |=
6595                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6596            // We need to resolve all RTL properties as they all depend on layout direction
6597            resolveRtlPropertiesIfNeeded();
6598            requestLayout();
6599            invalidate(true);
6600        }
6601    }
6602
6603    /**
6604     * Returns the resolved layout direction for this view.
6605     *
6606     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6607     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6608     *
6609     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6610     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6611     *
6612     * @attr ref android.R.styleable#View_layoutDirection
6613     */
6614    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6615        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6616        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6617    })
6618    @ResolvedLayoutDir
6619    public int getLayoutDirection() {
6620        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6621        if (targetSdkVersion < JELLY_BEAN_MR1) {
6622            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6623            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6624        }
6625        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6626                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6627    }
6628
6629    /**
6630     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6631     * layout attribute and/or the inherited value from the parent
6632     *
6633     * @return true if the layout is right-to-left.
6634     *
6635     * @hide
6636     */
6637    @ViewDebug.ExportedProperty(category = "layout")
6638    public boolean isLayoutRtl() {
6639        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6640    }
6641
6642    /**
6643     * Indicates whether the view is currently tracking transient state that the
6644     * app should not need to concern itself with saving and restoring, but that
6645     * the framework should take special note to preserve when possible.
6646     *
6647     * <p>A view with transient state cannot be trivially rebound from an external
6648     * data source, such as an adapter binding item views in a list. This may be
6649     * because the view is performing an animation, tracking user selection
6650     * of content, or similar.</p>
6651     *
6652     * @return true if the view has transient state
6653     */
6654    @ViewDebug.ExportedProperty(category = "layout")
6655    public boolean hasTransientState() {
6656        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6657    }
6658
6659    /**
6660     * Set whether this view is currently tracking transient state that the
6661     * framework should attempt to preserve when possible. This flag is reference counted,
6662     * so every call to setHasTransientState(true) should be paired with a later call
6663     * to setHasTransientState(false).
6664     *
6665     * <p>A view with transient state cannot be trivially rebound from an external
6666     * data source, such as an adapter binding item views in a list. This may be
6667     * because the view is performing an animation, tracking user selection
6668     * of content, or similar.</p>
6669     *
6670     * @param hasTransientState true if this view has transient state
6671     */
6672    public void setHasTransientState(boolean hasTransientState) {
6673        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6674                mTransientStateCount - 1;
6675        if (mTransientStateCount < 0) {
6676            mTransientStateCount = 0;
6677            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6678                    "unmatched pair of setHasTransientState calls");
6679        } else if ((hasTransientState && mTransientStateCount == 1) ||
6680                (!hasTransientState && mTransientStateCount == 0)) {
6681            // update flag if we've just incremented up from 0 or decremented down to 0
6682            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6683                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6684            if (mParent != null) {
6685                try {
6686                    mParent.childHasTransientStateChanged(this, hasTransientState);
6687                } catch (AbstractMethodError e) {
6688                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6689                            " does not fully implement ViewParent", e);
6690                }
6691            }
6692        }
6693    }
6694
6695    /**
6696     * Returns true if this view is currently attached to a window.
6697     */
6698    public boolean isAttachedToWindow() {
6699        return mAttachInfo != null;
6700    }
6701
6702    /**
6703     * Returns true if this view has been through at least one layout since it
6704     * was last attached to or detached from a window.
6705     */
6706    public boolean isLaidOut() {
6707        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6708    }
6709
6710    /**
6711     * If this view doesn't do any drawing on its own, set this flag to
6712     * allow further optimizations. By default, this flag is not set on
6713     * View, but could be set on some View subclasses such as ViewGroup.
6714     *
6715     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6716     * you should clear this flag.
6717     *
6718     * @param willNotDraw whether or not this View draw on its own
6719     */
6720    public void setWillNotDraw(boolean willNotDraw) {
6721        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6722    }
6723
6724    /**
6725     * Returns whether or not this View draws on its own.
6726     *
6727     * @return true if this view has nothing to draw, false otherwise
6728     */
6729    @ViewDebug.ExportedProperty(category = "drawing")
6730    public boolean willNotDraw() {
6731        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6732    }
6733
6734    /**
6735     * When a View's drawing cache is enabled, drawing is redirected to an
6736     * offscreen bitmap. Some views, like an ImageView, must be able to
6737     * bypass this mechanism if they already draw a single bitmap, to avoid
6738     * unnecessary usage of the memory.
6739     *
6740     * @param willNotCacheDrawing true if this view does not cache its
6741     *        drawing, false otherwise
6742     */
6743    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6744        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6745    }
6746
6747    /**
6748     * Returns whether or not this View can cache its drawing or not.
6749     *
6750     * @return true if this view does not cache its drawing, false otherwise
6751     */
6752    @ViewDebug.ExportedProperty(category = "drawing")
6753    public boolean willNotCacheDrawing() {
6754        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6755    }
6756
6757    /**
6758     * Indicates whether this view reacts to click events or not.
6759     *
6760     * @return true if the view is clickable, false otherwise
6761     *
6762     * @see #setClickable(boolean)
6763     * @attr ref android.R.styleable#View_clickable
6764     */
6765    @ViewDebug.ExportedProperty
6766    public boolean isClickable() {
6767        return (mViewFlags & CLICKABLE) == CLICKABLE;
6768    }
6769
6770    /**
6771     * Enables or disables click events for this view. When a view
6772     * is clickable it will change its state to "pressed" on every click.
6773     * Subclasses should set the view clickable to visually react to
6774     * user's clicks.
6775     *
6776     * @param clickable true to make the view clickable, false otherwise
6777     *
6778     * @see #isClickable()
6779     * @attr ref android.R.styleable#View_clickable
6780     */
6781    public void setClickable(boolean clickable) {
6782        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6783    }
6784
6785    /**
6786     * Indicates whether this view reacts to long click events or not.
6787     *
6788     * @return true if the view is long clickable, false otherwise
6789     *
6790     * @see #setLongClickable(boolean)
6791     * @attr ref android.R.styleable#View_longClickable
6792     */
6793    public boolean isLongClickable() {
6794        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6795    }
6796
6797    /**
6798     * Enables or disables long click events for this view. When a view is long
6799     * clickable it reacts to the user holding down the button for a longer
6800     * duration than a tap. This event can either launch the listener or a
6801     * context menu.
6802     *
6803     * @param longClickable true to make the view long clickable, false otherwise
6804     * @see #isLongClickable()
6805     * @attr ref android.R.styleable#View_longClickable
6806     */
6807    public void setLongClickable(boolean longClickable) {
6808        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6809    }
6810
6811    /**
6812     * Sets the pressed state for this view.
6813     *
6814     * @see #isClickable()
6815     * @see #setClickable(boolean)
6816     *
6817     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6818     *        the View's internal state from a previously set "pressed" state.
6819     */
6820    public void setPressed(boolean pressed) {
6821        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6822
6823        if (pressed) {
6824            mPrivateFlags |= PFLAG_PRESSED;
6825        } else {
6826            mPrivateFlags &= ~PFLAG_PRESSED;
6827        }
6828
6829        if (needsRefresh) {
6830            refreshDrawableState();
6831        }
6832        dispatchSetPressed(pressed);
6833    }
6834
6835    /**
6836     * Dispatch setPressed to all of this View's children.
6837     *
6838     * @see #setPressed(boolean)
6839     *
6840     * @param pressed The new pressed state
6841     */
6842    protected void dispatchSetPressed(boolean pressed) {
6843    }
6844
6845    /**
6846     * Indicates whether the view is currently in pressed state. Unless
6847     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6848     * the pressed state.
6849     *
6850     * @see #setPressed(boolean)
6851     * @see #isClickable()
6852     * @see #setClickable(boolean)
6853     *
6854     * @return true if the view is currently pressed, false otherwise
6855     */
6856    public boolean isPressed() {
6857        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6858    }
6859
6860    /**
6861     * Indicates whether this view will save its state (that is,
6862     * whether its {@link #onSaveInstanceState} method will be called).
6863     *
6864     * @return Returns true if the view state saving is enabled, else false.
6865     *
6866     * @see #setSaveEnabled(boolean)
6867     * @attr ref android.R.styleable#View_saveEnabled
6868     */
6869    public boolean isSaveEnabled() {
6870        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6871    }
6872
6873    /**
6874     * Controls whether the saving of this view's state is
6875     * enabled (that is, whether its {@link #onSaveInstanceState} method
6876     * will be called).  Note that even if freezing is enabled, the
6877     * view still must have an id assigned to it (via {@link #setId(int)})
6878     * for its state to be saved.  This flag can only disable the
6879     * saving of this view; any child views may still have their state saved.
6880     *
6881     * @param enabled Set to false to <em>disable</em> state saving, or true
6882     * (the default) to allow it.
6883     *
6884     * @see #isSaveEnabled()
6885     * @see #setId(int)
6886     * @see #onSaveInstanceState()
6887     * @attr ref android.R.styleable#View_saveEnabled
6888     */
6889    public void setSaveEnabled(boolean enabled) {
6890        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6891    }
6892
6893    /**
6894     * Gets whether the framework should discard touches when the view's
6895     * window is obscured by another visible window.
6896     * Refer to the {@link View} security documentation for more details.
6897     *
6898     * @return True if touch filtering is enabled.
6899     *
6900     * @see #setFilterTouchesWhenObscured(boolean)
6901     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6902     */
6903    @ViewDebug.ExportedProperty
6904    public boolean getFilterTouchesWhenObscured() {
6905        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6906    }
6907
6908    /**
6909     * Sets whether the framework should discard touches when the view's
6910     * window is obscured by another visible window.
6911     * Refer to the {@link View} security documentation for more details.
6912     *
6913     * @param enabled True if touch filtering should be enabled.
6914     *
6915     * @see #getFilterTouchesWhenObscured
6916     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6917     */
6918    public void setFilterTouchesWhenObscured(boolean enabled) {
6919        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6920                FILTER_TOUCHES_WHEN_OBSCURED);
6921    }
6922
6923    /**
6924     * Indicates whether the entire hierarchy under this view will save its
6925     * state when a state saving traversal occurs from its parent.  The default
6926     * is true; if false, these views will not be saved unless
6927     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6928     *
6929     * @return Returns true if the view state saving from parent is enabled, else false.
6930     *
6931     * @see #setSaveFromParentEnabled(boolean)
6932     */
6933    public boolean isSaveFromParentEnabled() {
6934        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6935    }
6936
6937    /**
6938     * Controls whether the entire hierarchy under this view will save its
6939     * state when a state saving traversal occurs from its parent.  The default
6940     * is true; if false, these views will not be saved unless
6941     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6942     *
6943     * @param enabled Set to false to <em>disable</em> state saving, or true
6944     * (the default) to allow it.
6945     *
6946     * @see #isSaveFromParentEnabled()
6947     * @see #setId(int)
6948     * @see #onSaveInstanceState()
6949     */
6950    public void setSaveFromParentEnabled(boolean enabled) {
6951        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6952    }
6953
6954
6955    /**
6956     * Returns whether this View is able to take focus.
6957     *
6958     * @return True if this view can take focus, or false otherwise.
6959     * @attr ref android.R.styleable#View_focusable
6960     */
6961    @ViewDebug.ExportedProperty(category = "focus")
6962    public final boolean isFocusable() {
6963        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6964    }
6965
6966    /**
6967     * When a view is focusable, it may not want to take focus when in touch mode.
6968     * For example, a button would like focus when the user is navigating via a D-pad
6969     * so that the user can click on it, but once the user starts touching the screen,
6970     * the button shouldn't take focus
6971     * @return Whether the view is focusable in touch mode.
6972     * @attr ref android.R.styleable#View_focusableInTouchMode
6973     */
6974    @ViewDebug.ExportedProperty
6975    public final boolean isFocusableInTouchMode() {
6976        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6977    }
6978
6979    /**
6980     * Find the nearest view in the specified direction that can take focus.
6981     * This does not actually give focus to that view.
6982     *
6983     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6984     *
6985     * @return The nearest focusable in the specified direction, or null if none
6986     *         can be found.
6987     */
6988    public View focusSearch(@FocusRealDirection int direction) {
6989        if (mParent != null) {
6990            return mParent.focusSearch(this, direction);
6991        } else {
6992            return null;
6993        }
6994    }
6995
6996    /**
6997     * This method is the last chance for the focused view and its ancestors to
6998     * respond to an arrow key. This is called when the focused view did not
6999     * consume the key internally, nor could the view system find a new view in
7000     * the requested direction to give focus to.
7001     *
7002     * @param focused The currently focused view.
7003     * @param direction The direction focus wants to move. One of FOCUS_UP,
7004     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7005     * @return True if the this view consumed this unhandled move.
7006     */
7007    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7008        return false;
7009    }
7010
7011    /**
7012     * If a user manually specified the next view id for a particular direction,
7013     * use the root to look up the view.
7014     * @param root The root view of the hierarchy containing this view.
7015     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7016     * or FOCUS_BACKWARD.
7017     * @return The user specified next view, or null if there is none.
7018     */
7019    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7020        switch (direction) {
7021            case FOCUS_LEFT:
7022                if (mNextFocusLeftId == View.NO_ID) return null;
7023                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7024            case FOCUS_RIGHT:
7025                if (mNextFocusRightId == View.NO_ID) return null;
7026                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7027            case FOCUS_UP:
7028                if (mNextFocusUpId == View.NO_ID) return null;
7029                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7030            case FOCUS_DOWN:
7031                if (mNextFocusDownId == View.NO_ID) return null;
7032                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7033            case FOCUS_FORWARD:
7034                if (mNextFocusForwardId == View.NO_ID) return null;
7035                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7036            case FOCUS_BACKWARD: {
7037                if (mID == View.NO_ID) return null;
7038                final int id = mID;
7039                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7040                    @Override
7041                    public boolean apply(View t) {
7042                        return t.mNextFocusForwardId == id;
7043                    }
7044                });
7045            }
7046        }
7047        return null;
7048    }
7049
7050    private View findViewInsideOutShouldExist(View root, int id) {
7051        if (mMatchIdPredicate == null) {
7052            mMatchIdPredicate = new MatchIdPredicate();
7053        }
7054        mMatchIdPredicate.mId = id;
7055        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7056        if (result == null) {
7057            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7058        }
7059        return result;
7060    }
7061
7062    /**
7063     * Find and return all focusable views that are descendants of this view,
7064     * possibly including this view if it is focusable itself.
7065     *
7066     * @param direction The direction of the focus
7067     * @return A list of focusable views
7068     */
7069    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7070        ArrayList<View> result = new ArrayList<View>(24);
7071        addFocusables(result, direction);
7072        return result;
7073    }
7074
7075    /**
7076     * Add any focusable views that are descendants of this view (possibly
7077     * including this view if it is focusable itself) to views.  If we are in touch mode,
7078     * only add views that are also focusable in touch mode.
7079     *
7080     * @param views Focusable views found so far
7081     * @param direction The direction of the focus
7082     */
7083    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7084        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7085    }
7086
7087    /**
7088     * Adds any focusable views that are descendants of this view (possibly
7089     * including this view if it is focusable itself) to views. This method
7090     * adds all focusable views regardless if we are in touch mode or
7091     * only views focusable in touch mode if we are in touch mode or
7092     * only views that can take accessibility focus if accessibility is enabeld
7093     * depending on the focusable mode paramater.
7094     *
7095     * @param views Focusable views found so far or null if all we are interested is
7096     *        the number of focusables.
7097     * @param direction The direction of the focus.
7098     * @param focusableMode The type of focusables to be added.
7099     *
7100     * @see #FOCUSABLES_ALL
7101     * @see #FOCUSABLES_TOUCH_MODE
7102     */
7103    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7104            @FocusableMode int focusableMode) {
7105        if (views == null) {
7106            return;
7107        }
7108        if (!isFocusable()) {
7109            return;
7110        }
7111        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7112                && isInTouchMode() && !isFocusableInTouchMode()) {
7113            return;
7114        }
7115        views.add(this);
7116    }
7117
7118    /**
7119     * Finds the Views that contain given text. The containment is case insensitive.
7120     * The search is performed by either the text that the View renders or the content
7121     * description that describes the view for accessibility purposes and the view does
7122     * not render or both. Clients can specify how the search is to be performed via
7123     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7124     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7125     *
7126     * @param outViews The output list of matching Views.
7127     * @param searched The text to match against.
7128     *
7129     * @see #FIND_VIEWS_WITH_TEXT
7130     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7131     * @see #setContentDescription(CharSequence)
7132     */
7133    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7134            @FindViewFlags int flags) {
7135        if (getAccessibilityNodeProvider() != null) {
7136            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7137                outViews.add(this);
7138            }
7139        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7140                && (searched != null && searched.length() > 0)
7141                && (mContentDescription != null && mContentDescription.length() > 0)) {
7142            String searchedLowerCase = searched.toString().toLowerCase();
7143            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7144            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7145                outViews.add(this);
7146            }
7147        }
7148    }
7149
7150    /**
7151     * Find and return all touchable views that are descendants of this view,
7152     * possibly including this view if it is touchable itself.
7153     *
7154     * @return A list of touchable views
7155     */
7156    public ArrayList<View> getTouchables() {
7157        ArrayList<View> result = new ArrayList<View>();
7158        addTouchables(result);
7159        return result;
7160    }
7161
7162    /**
7163     * Add any touchable views that are descendants of this view (possibly
7164     * including this view if it is touchable itself) to views.
7165     *
7166     * @param views Touchable views found so far
7167     */
7168    public void addTouchables(ArrayList<View> views) {
7169        final int viewFlags = mViewFlags;
7170
7171        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7172                && (viewFlags & ENABLED_MASK) == ENABLED) {
7173            views.add(this);
7174        }
7175    }
7176
7177    /**
7178     * Returns whether this View is accessibility focused.
7179     *
7180     * @return True if this View is accessibility focused.
7181     */
7182    public boolean isAccessibilityFocused() {
7183        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7184    }
7185
7186    /**
7187     * Call this to try to give accessibility focus to this view.
7188     *
7189     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7190     * returns false or the view is no visible or the view already has accessibility
7191     * focus.
7192     *
7193     * See also {@link #focusSearch(int)}, which is what you call to say that you
7194     * have focus, and you want your parent to look for the next one.
7195     *
7196     * @return Whether this view actually took accessibility focus.
7197     *
7198     * @hide
7199     */
7200    public boolean requestAccessibilityFocus() {
7201        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7202        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7203            return false;
7204        }
7205        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7206            return false;
7207        }
7208        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7209            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7210            ViewRootImpl viewRootImpl = getViewRootImpl();
7211            if (viewRootImpl != null) {
7212                viewRootImpl.setAccessibilityFocus(this, null);
7213            }
7214            invalidate();
7215            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7216            return true;
7217        }
7218        return false;
7219    }
7220
7221    /**
7222     * Call this to try to clear accessibility focus of this view.
7223     *
7224     * See also {@link #focusSearch(int)}, which is what you call to say that you
7225     * have focus, and you want your parent to look for the next one.
7226     *
7227     * @hide
7228     */
7229    public void clearAccessibilityFocus() {
7230        clearAccessibilityFocusNoCallbacks();
7231        // Clear the global reference of accessibility focus if this
7232        // view or any of its descendants had accessibility focus.
7233        ViewRootImpl viewRootImpl = getViewRootImpl();
7234        if (viewRootImpl != null) {
7235            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7236            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7237                viewRootImpl.setAccessibilityFocus(null, null);
7238            }
7239        }
7240    }
7241
7242    private void sendAccessibilityHoverEvent(int eventType) {
7243        // Since we are not delivering to a client accessibility events from not
7244        // important views (unless the clinet request that) we need to fire the
7245        // event from the deepest view exposed to the client. As a consequence if
7246        // the user crosses a not exposed view the client will see enter and exit
7247        // of the exposed predecessor followed by and enter and exit of that same
7248        // predecessor when entering and exiting the not exposed descendant. This
7249        // is fine since the client has a clear idea which view is hovered at the
7250        // price of a couple more events being sent. This is a simple and
7251        // working solution.
7252        View source = this;
7253        while (true) {
7254            if (source.includeForAccessibility()) {
7255                source.sendAccessibilityEvent(eventType);
7256                return;
7257            }
7258            ViewParent parent = source.getParent();
7259            if (parent instanceof View) {
7260                source = (View) parent;
7261            } else {
7262                return;
7263            }
7264        }
7265    }
7266
7267    /**
7268     * Clears accessibility focus without calling any callback methods
7269     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7270     * is used for clearing accessibility focus when giving this focus to
7271     * another view.
7272     */
7273    void clearAccessibilityFocusNoCallbacks() {
7274        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7275            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7276            invalidate();
7277            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7278        }
7279    }
7280
7281    /**
7282     * Call this to try to give focus to a specific view or to one of its
7283     * descendants.
7284     *
7285     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7286     * false), or if it is focusable and it is not focusable in touch mode
7287     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7288     *
7289     * See also {@link #focusSearch(int)}, which is what you call to say that you
7290     * have focus, and you want your parent to look for the next one.
7291     *
7292     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7293     * {@link #FOCUS_DOWN} and <code>null</code>.
7294     *
7295     * @return Whether this view or one of its descendants actually took focus.
7296     */
7297    public final boolean requestFocus() {
7298        return requestFocus(View.FOCUS_DOWN);
7299    }
7300
7301    /**
7302     * Call this to try to give focus to a specific view or to one of its
7303     * descendants and give it a hint about what direction focus is heading.
7304     *
7305     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7306     * false), or if it is focusable and it is not focusable in touch mode
7307     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7308     *
7309     * See also {@link #focusSearch(int)}, which is what you call to say that you
7310     * have focus, and you want your parent to look for the next one.
7311     *
7312     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7313     * <code>null</code> set for the previously focused rectangle.
7314     *
7315     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7316     * @return Whether this view or one of its descendants actually took focus.
7317     */
7318    public final boolean requestFocus(int direction) {
7319        return requestFocus(direction, null);
7320    }
7321
7322    /**
7323     * Call this to try to give focus to a specific view or to one of its descendants
7324     * and give it hints about the direction and a specific rectangle that the focus
7325     * is coming from.  The rectangle can help give larger views a finer grained hint
7326     * about where focus is coming from, and therefore, where to show selection, or
7327     * forward focus change internally.
7328     *
7329     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7330     * false), or if it is focusable and it is not focusable in touch mode
7331     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7332     *
7333     * A View will not take focus if it is not visible.
7334     *
7335     * A View will not take focus if one of its parents has
7336     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7337     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7338     *
7339     * See also {@link #focusSearch(int)}, which is what you call to say that you
7340     * have focus, and you want your parent to look for the next one.
7341     *
7342     * You may wish to override this method if your custom {@link View} has an internal
7343     * {@link View} that it wishes to forward the request to.
7344     *
7345     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7346     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7347     *        to give a finer grained hint about where focus is coming from.  May be null
7348     *        if there is no hint.
7349     * @return Whether this view or one of its descendants actually took focus.
7350     */
7351    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7352        return requestFocusNoSearch(direction, previouslyFocusedRect);
7353    }
7354
7355    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7356        // need to be focusable
7357        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7358                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7359            return false;
7360        }
7361
7362        // need to be focusable in touch mode if in touch mode
7363        if (isInTouchMode() &&
7364            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7365               return false;
7366        }
7367
7368        // need to not have any parents blocking us
7369        if (hasAncestorThatBlocksDescendantFocus()) {
7370            return false;
7371        }
7372
7373        handleFocusGainInternal(direction, previouslyFocusedRect);
7374        return true;
7375    }
7376
7377    /**
7378     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7379     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7380     * touch mode to request focus when they are touched.
7381     *
7382     * @return Whether this view or one of its descendants actually took focus.
7383     *
7384     * @see #isInTouchMode()
7385     *
7386     */
7387    public final boolean requestFocusFromTouch() {
7388        // Leave touch mode if we need to
7389        if (isInTouchMode()) {
7390            ViewRootImpl viewRoot = getViewRootImpl();
7391            if (viewRoot != null) {
7392                viewRoot.ensureTouchMode(false);
7393            }
7394        }
7395        return requestFocus(View.FOCUS_DOWN);
7396    }
7397
7398    /**
7399     * @return Whether any ancestor of this view blocks descendant focus.
7400     */
7401    private boolean hasAncestorThatBlocksDescendantFocus() {
7402        ViewParent ancestor = mParent;
7403        while (ancestor instanceof ViewGroup) {
7404            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7405            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7406                return true;
7407            } else {
7408                ancestor = vgAncestor.getParent();
7409            }
7410        }
7411        return false;
7412    }
7413
7414    /**
7415     * Gets the mode for determining whether this View is important for accessibility
7416     * which is if it fires accessibility events and if it is reported to
7417     * accessibility services that query the screen.
7418     *
7419     * @return The mode for determining whether a View is important for accessibility.
7420     *
7421     * @attr ref android.R.styleable#View_importantForAccessibility
7422     *
7423     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7424     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7425     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7426     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7427     */
7428    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7429            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7430            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7431            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7432            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7433                    to = "noHideDescendants")
7434        })
7435    public int getImportantForAccessibility() {
7436        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7437                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7438    }
7439
7440    /**
7441     * Sets the live region mode for this view. This indicates to accessibility
7442     * services whether they should automatically notify the user about changes
7443     * to the view's content description or text, or to the content descriptions
7444     * or text of the view's children (where applicable).
7445     * <p>
7446     * For example, in a login screen with a TextView that displays an "incorrect
7447     * password" notification, that view should be marked as a live region with
7448     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7449     * <p>
7450     * To disable change notifications for this view, use
7451     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7452     * mode for most views.
7453     * <p>
7454     * To indicate that the user should be notified of changes, use
7455     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7456     * <p>
7457     * If the view's changes should interrupt ongoing speech and notify the user
7458     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7459     *
7460     * @param mode The live region mode for this view, one of:
7461     *        <ul>
7462     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7463     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7464     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7465     *        </ul>
7466     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7467     */
7468    public void setAccessibilityLiveRegion(int mode) {
7469        if (mode != getAccessibilityLiveRegion()) {
7470            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7471            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7472                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7473            notifyViewAccessibilityStateChangedIfNeeded(
7474                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7475        }
7476    }
7477
7478    /**
7479     * Gets the live region mode for this View.
7480     *
7481     * @return The live region mode for the view.
7482     *
7483     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7484     *
7485     * @see #setAccessibilityLiveRegion(int)
7486     */
7487    public int getAccessibilityLiveRegion() {
7488        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7489                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7490    }
7491
7492    /**
7493     * Sets how to determine whether this view is important for accessibility
7494     * which is if it fires accessibility events and if it is reported to
7495     * accessibility services that query the screen.
7496     *
7497     * @param mode How to determine whether this view is important for accessibility.
7498     *
7499     * @attr ref android.R.styleable#View_importantForAccessibility
7500     *
7501     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7502     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7503     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7504     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7505     */
7506    public void setImportantForAccessibility(int mode) {
7507        final int oldMode = getImportantForAccessibility();
7508        if (mode != oldMode) {
7509            // If we're moving between AUTO and another state, we might not need
7510            // to send a subtree changed notification. We'll store the computed
7511            // importance, since we'll need to check it later to make sure.
7512            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7513                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7514            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7515            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7516            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7517                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7518            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7519                notifySubtreeAccessibilityStateChangedIfNeeded();
7520            } else {
7521                notifyViewAccessibilityStateChangedIfNeeded(
7522                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7523            }
7524        }
7525    }
7526
7527    /**
7528     * Computes whether this view should be exposed for accessibility. In
7529     * general, views that are interactive or provide information are exposed
7530     * while views that serve only as containers are hidden.
7531     * <p>
7532     * If an ancestor of this view has importance
7533     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7534     * returns <code>false</code>.
7535     * <p>
7536     * Otherwise, the value is computed according to the view's
7537     * {@link #getImportantForAccessibility()} value:
7538     * <ol>
7539     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7540     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7541     * </code>
7542     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7543     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7544     * view satisfies any of the following:
7545     * <ul>
7546     * <li>Is actionable, e.g. {@link #isClickable()},
7547     * {@link #isLongClickable()}, or {@link #isFocusable()}
7548     * <li>Has an {@link AccessibilityDelegate}
7549     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7550     * {@link OnKeyListener}, etc.
7551     * <li>Is an accessibility live region, e.g.
7552     * {@link #getAccessibilityLiveRegion()} is not
7553     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7554     * </ul>
7555     * </ol>
7556     *
7557     * @return Whether the view is exposed for accessibility.
7558     * @see #setImportantForAccessibility(int)
7559     * @see #getImportantForAccessibility()
7560     */
7561    public boolean isImportantForAccessibility() {
7562        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7563                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7564        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7565                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7566            return false;
7567        }
7568
7569        // Check parent mode to ensure we're not hidden.
7570        ViewParent parent = mParent;
7571        while (parent instanceof View) {
7572            if (((View) parent).getImportantForAccessibility()
7573                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7574                return false;
7575            }
7576            parent = parent.getParent();
7577        }
7578
7579        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7580                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7581                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7582    }
7583
7584    /**
7585     * Gets the parent for accessibility purposes. Note that the parent for
7586     * accessibility is not necessary the immediate parent. It is the first
7587     * predecessor that is important for accessibility.
7588     *
7589     * @return The parent for accessibility purposes.
7590     */
7591    public ViewParent getParentForAccessibility() {
7592        if (mParent instanceof View) {
7593            View parentView = (View) mParent;
7594            if (parentView.includeForAccessibility()) {
7595                return mParent;
7596            } else {
7597                return mParent.getParentForAccessibility();
7598            }
7599        }
7600        return null;
7601    }
7602
7603    /**
7604     * Adds the children of a given View for accessibility. Since some Views are
7605     * not important for accessibility the children for accessibility are not
7606     * necessarily direct children of the view, rather they are the first level of
7607     * descendants important for accessibility.
7608     *
7609     * @param children The list of children for accessibility.
7610     */
7611    public void addChildrenForAccessibility(ArrayList<View> children) {
7612
7613    }
7614
7615    /**
7616     * Whether to regard this view for accessibility. A view is regarded for
7617     * accessibility if it is important for accessibility or the querying
7618     * accessibility service has explicitly requested that view not
7619     * important for accessibility are regarded.
7620     *
7621     * @return Whether to regard the view for accessibility.
7622     *
7623     * @hide
7624     */
7625    public boolean includeForAccessibility() {
7626        if (mAttachInfo != null) {
7627            return (mAttachInfo.mAccessibilityFetchFlags
7628                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7629                    || isImportantForAccessibility();
7630        }
7631        return false;
7632    }
7633
7634    /**
7635     * Returns whether the View is considered actionable from
7636     * accessibility perspective. Such view are important for
7637     * accessibility.
7638     *
7639     * @return True if the view is actionable for accessibility.
7640     *
7641     * @hide
7642     */
7643    public boolean isActionableForAccessibility() {
7644        return (isClickable() || isLongClickable() || isFocusable());
7645    }
7646
7647    /**
7648     * Returns whether the View has registered callbacks which makes it
7649     * important for accessibility.
7650     *
7651     * @return True if the view is actionable for accessibility.
7652     */
7653    private boolean hasListenersForAccessibility() {
7654        ListenerInfo info = getListenerInfo();
7655        return mTouchDelegate != null || info.mOnKeyListener != null
7656                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7657                || info.mOnHoverListener != null || info.mOnDragListener != null;
7658    }
7659
7660    /**
7661     * Notifies that the accessibility state of this view changed. The change
7662     * is local to this view and does not represent structural changes such
7663     * as children and parent. For example, the view became focusable. The
7664     * notification is at at most once every
7665     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7666     * to avoid unnecessary load to the system. Also once a view has a pending
7667     * notification this method is a NOP until the notification has been sent.
7668     *
7669     * @hide
7670     */
7671    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7672        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7673            return;
7674        }
7675        if (mSendViewStateChangedAccessibilityEvent == null) {
7676            mSendViewStateChangedAccessibilityEvent =
7677                    new SendViewStateChangedAccessibilityEvent();
7678        }
7679        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7680    }
7681
7682    /**
7683     * Notifies that the accessibility state of this view changed. The change
7684     * is *not* local to this view and does represent structural changes such
7685     * as children and parent. For example, the view size changed. The
7686     * notification is at at most once every
7687     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7688     * to avoid unnecessary load to the system. Also once a view has a pending
7689     * notifucation this method is a NOP until the notification has been sent.
7690     *
7691     * @hide
7692     */
7693    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7694        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7695            return;
7696        }
7697        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7698            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7699            if (mParent != null) {
7700                try {
7701                    mParent.notifySubtreeAccessibilityStateChanged(
7702                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7703                } catch (AbstractMethodError e) {
7704                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7705                            " does not fully implement ViewParent", e);
7706                }
7707            }
7708        }
7709    }
7710
7711    /**
7712     * Reset the flag indicating the accessibility state of the subtree rooted
7713     * at this view changed.
7714     */
7715    void resetSubtreeAccessibilityStateChanged() {
7716        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7717    }
7718
7719    /**
7720     * Performs the specified accessibility action on the view. For
7721     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7722     * <p>
7723     * If an {@link AccessibilityDelegate} has been specified via calling
7724     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7725     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7726     * is responsible for handling this call.
7727     * </p>
7728     *
7729     * @param action The action to perform.
7730     * @param arguments Optional action arguments.
7731     * @return Whether the action was performed.
7732     */
7733    public boolean performAccessibilityAction(int action, Bundle arguments) {
7734      if (mAccessibilityDelegate != null) {
7735          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7736      } else {
7737          return performAccessibilityActionInternal(action, arguments);
7738      }
7739    }
7740
7741   /**
7742    * @see #performAccessibilityAction(int, Bundle)
7743    *
7744    * Note: Called from the default {@link AccessibilityDelegate}.
7745    */
7746    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7747        switch (action) {
7748            case AccessibilityNodeInfo.ACTION_CLICK: {
7749                if (isClickable()) {
7750                    performClick();
7751                    return true;
7752                }
7753            } break;
7754            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7755                if (isLongClickable()) {
7756                    performLongClick();
7757                    return true;
7758                }
7759            } break;
7760            case AccessibilityNodeInfo.ACTION_FOCUS: {
7761                if (!hasFocus()) {
7762                    // Get out of touch mode since accessibility
7763                    // wants to move focus around.
7764                    getViewRootImpl().ensureTouchMode(false);
7765                    return requestFocus();
7766                }
7767            } break;
7768            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7769                if (hasFocus()) {
7770                    clearFocus();
7771                    return !isFocused();
7772                }
7773            } break;
7774            case AccessibilityNodeInfo.ACTION_SELECT: {
7775                if (!isSelected()) {
7776                    setSelected(true);
7777                    return isSelected();
7778                }
7779            } break;
7780            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7781                if (isSelected()) {
7782                    setSelected(false);
7783                    return !isSelected();
7784                }
7785            } break;
7786            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7787                if (!isAccessibilityFocused()) {
7788                    return requestAccessibilityFocus();
7789                }
7790            } break;
7791            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7792                if (isAccessibilityFocused()) {
7793                    clearAccessibilityFocus();
7794                    return true;
7795                }
7796            } break;
7797            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7798                if (arguments != null) {
7799                    final int granularity = arguments.getInt(
7800                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7801                    final boolean extendSelection = arguments.getBoolean(
7802                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7803                    return traverseAtGranularity(granularity, true, extendSelection);
7804                }
7805            } break;
7806            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7807                if (arguments != null) {
7808                    final int granularity = arguments.getInt(
7809                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7810                    final boolean extendSelection = arguments.getBoolean(
7811                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7812                    return traverseAtGranularity(granularity, false, extendSelection);
7813                }
7814            } break;
7815            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7816                CharSequence text = getIterableTextForAccessibility();
7817                if (text == null) {
7818                    return false;
7819                }
7820                final int start = (arguments != null) ? arguments.getInt(
7821                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7822                final int end = (arguments != null) ? arguments.getInt(
7823                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7824                // Only cursor position can be specified (selection length == 0)
7825                if ((getAccessibilitySelectionStart() != start
7826                        || getAccessibilitySelectionEnd() != end)
7827                        && (start == end)) {
7828                    setAccessibilitySelection(start, end);
7829                    notifyViewAccessibilityStateChangedIfNeeded(
7830                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7831                    return true;
7832                }
7833            } break;
7834        }
7835        return false;
7836    }
7837
7838    private boolean traverseAtGranularity(int granularity, boolean forward,
7839            boolean extendSelection) {
7840        CharSequence text = getIterableTextForAccessibility();
7841        if (text == null || text.length() == 0) {
7842            return false;
7843        }
7844        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7845        if (iterator == null) {
7846            return false;
7847        }
7848        int current = getAccessibilitySelectionEnd();
7849        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7850            current = forward ? 0 : text.length();
7851        }
7852        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7853        if (range == null) {
7854            return false;
7855        }
7856        final int segmentStart = range[0];
7857        final int segmentEnd = range[1];
7858        int selectionStart;
7859        int selectionEnd;
7860        if (extendSelection && isAccessibilitySelectionExtendable()) {
7861            selectionStart = getAccessibilitySelectionStart();
7862            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7863                selectionStart = forward ? segmentStart : segmentEnd;
7864            }
7865            selectionEnd = forward ? segmentEnd : segmentStart;
7866        } else {
7867            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7868        }
7869        setAccessibilitySelection(selectionStart, selectionEnd);
7870        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7871                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7872        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7873        return true;
7874    }
7875
7876    /**
7877     * Gets the text reported for accessibility purposes.
7878     *
7879     * @return The accessibility text.
7880     *
7881     * @hide
7882     */
7883    public CharSequence getIterableTextForAccessibility() {
7884        return getContentDescription();
7885    }
7886
7887    /**
7888     * Gets whether accessibility selection can be extended.
7889     *
7890     * @return If selection is extensible.
7891     *
7892     * @hide
7893     */
7894    public boolean isAccessibilitySelectionExtendable() {
7895        return false;
7896    }
7897
7898    /**
7899     * @hide
7900     */
7901    public int getAccessibilitySelectionStart() {
7902        return mAccessibilityCursorPosition;
7903    }
7904
7905    /**
7906     * @hide
7907     */
7908    public int getAccessibilitySelectionEnd() {
7909        return getAccessibilitySelectionStart();
7910    }
7911
7912    /**
7913     * @hide
7914     */
7915    public void setAccessibilitySelection(int start, int end) {
7916        if (start ==  end && end == mAccessibilityCursorPosition) {
7917            return;
7918        }
7919        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7920            mAccessibilityCursorPosition = start;
7921        } else {
7922            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7923        }
7924        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7925    }
7926
7927    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7928            int fromIndex, int toIndex) {
7929        if (mParent == null) {
7930            return;
7931        }
7932        AccessibilityEvent event = AccessibilityEvent.obtain(
7933                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7934        onInitializeAccessibilityEvent(event);
7935        onPopulateAccessibilityEvent(event);
7936        event.setFromIndex(fromIndex);
7937        event.setToIndex(toIndex);
7938        event.setAction(action);
7939        event.setMovementGranularity(granularity);
7940        mParent.requestSendAccessibilityEvent(this, event);
7941    }
7942
7943    /**
7944     * @hide
7945     */
7946    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7947        switch (granularity) {
7948            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7949                CharSequence text = getIterableTextForAccessibility();
7950                if (text != null && text.length() > 0) {
7951                    CharacterTextSegmentIterator iterator =
7952                        CharacterTextSegmentIterator.getInstance(
7953                                mContext.getResources().getConfiguration().locale);
7954                    iterator.initialize(text.toString());
7955                    return iterator;
7956                }
7957            } break;
7958            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7959                CharSequence text = getIterableTextForAccessibility();
7960                if (text != null && text.length() > 0) {
7961                    WordTextSegmentIterator iterator =
7962                        WordTextSegmentIterator.getInstance(
7963                                mContext.getResources().getConfiguration().locale);
7964                    iterator.initialize(text.toString());
7965                    return iterator;
7966                }
7967            } break;
7968            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7969                CharSequence text = getIterableTextForAccessibility();
7970                if (text != null && text.length() > 0) {
7971                    ParagraphTextSegmentIterator iterator =
7972                        ParagraphTextSegmentIterator.getInstance();
7973                    iterator.initialize(text.toString());
7974                    return iterator;
7975                }
7976            } break;
7977        }
7978        return null;
7979    }
7980
7981    /**
7982     * @hide
7983     */
7984    public void dispatchStartTemporaryDetach() {
7985        clearDisplayList();
7986
7987        onStartTemporaryDetach();
7988    }
7989
7990    /**
7991     * This is called when a container is going to temporarily detach a child, with
7992     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7993     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7994     * {@link #onDetachedFromWindow()} when the container is done.
7995     */
7996    public void onStartTemporaryDetach() {
7997        removeUnsetPressCallback();
7998        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7999    }
8000
8001    /**
8002     * @hide
8003     */
8004    public void dispatchFinishTemporaryDetach() {
8005        onFinishTemporaryDetach();
8006    }
8007
8008    /**
8009     * Called after {@link #onStartTemporaryDetach} when the container is done
8010     * changing the view.
8011     */
8012    public void onFinishTemporaryDetach() {
8013    }
8014
8015    /**
8016     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8017     * for this view's window.  Returns null if the view is not currently attached
8018     * to the window.  Normally you will not need to use this directly, but
8019     * just use the standard high-level event callbacks like
8020     * {@link #onKeyDown(int, KeyEvent)}.
8021     */
8022    public KeyEvent.DispatcherState getKeyDispatcherState() {
8023        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8024    }
8025
8026    /**
8027     * Dispatch a key event before it is processed by any input method
8028     * associated with the view hierarchy.  This can be used to intercept
8029     * key events in special situations before the IME consumes them; a
8030     * typical example would be handling the BACK key to update the application's
8031     * UI instead of allowing the IME to see it and close itself.
8032     *
8033     * @param event The key event to be dispatched.
8034     * @return True if the event was handled, false otherwise.
8035     */
8036    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8037        return onKeyPreIme(event.getKeyCode(), event);
8038    }
8039
8040    /**
8041     * Dispatch a key event to the next view on the focus path. This path runs
8042     * from the top of the view tree down to the currently focused view. If this
8043     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8044     * the next node down the focus path. This method also fires any key
8045     * listeners.
8046     *
8047     * @param event The key event to be dispatched.
8048     * @return True if the event was handled, false otherwise.
8049     */
8050    public boolean dispatchKeyEvent(KeyEvent event) {
8051        if (mInputEventConsistencyVerifier != null) {
8052            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8053        }
8054
8055        // Give any attached key listener a first crack at the event.
8056        //noinspection SimplifiableIfStatement
8057        ListenerInfo li = mListenerInfo;
8058        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8059                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8060            return true;
8061        }
8062
8063        if (event.dispatch(this, mAttachInfo != null
8064                ? mAttachInfo.mKeyDispatchState : null, this)) {
8065            return true;
8066        }
8067
8068        if (mInputEventConsistencyVerifier != null) {
8069            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8070        }
8071        return false;
8072    }
8073
8074    /**
8075     * Dispatches a key shortcut event.
8076     *
8077     * @param event The key event to be dispatched.
8078     * @return True if the event was handled by the view, false otherwise.
8079     */
8080    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8081        return onKeyShortcut(event.getKeyCode(), event);
8082    }
8083
8084    /**
8085     * Pass the touch screen motion event down to the target view, or this
8086     * view if it is the target.
8087     *
8088     * @param event The motion event to be dispatched.
8089     * @return True if the event was handled by the view, false otherwise.
8090     */
8091    public boolean dispatchTouchEvent(MotionEvent event) {
8092        if (mInputEventConsistencyVerifier != null) {
8093            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8094        }
8095
8096        if (onFilterTouchEventForSecurity(event)) {
8097            //noinspection SimplifiableIfStatement
8098            ListenerInfo li = mListenerInfo;
8099            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8100                    && li.mOnTouchListener.onTouch(this, event)) {
8101                return true;
8102            }
8103
8104            if (onTouchEvent(event)) {
8105                return true;
8106            }
8107        }
8108
8109        if (mInputEventConsistencyVerifier != null) {
8110            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8111        }
8112        return false;
8113    }
8114
8115    /**
8116     * Filter the touch event to apply security policies.
8117     *
8118     * @param event The motion event to be filtered.
8119     * @return True if the event should be dispatched, false if the event should be dropped.
8120     *
8121     * @see #getFilterTouchesWhenObscured
8122     */
8123    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8124        //noinspection RedundantIfStatement
8125        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8126                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8127            // Window is obscured, drop this touch.
8128            return false;
8129        }
8130        return true;
8131    }
8132
8133    /**
8134     * Pass a trackball motion event down to the focused view.
8135     *
8136     * @param event The motion event to be dispatched.
8137     * @return True if the event was handled by the view, false otherwise.
8138     */
8139    public boolean dispatchTrackballEvent(MotionEvent event) {
8140        if (mInputEventConsistencyVerifier != null) {
8141            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8142        }
8143
8144        return onTrackballEvent(event);
8145    }
8146
8147    /**
8148     * Dispatch a generic motion event.
8149     * <p>
8150     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8151     * are delivered to the view under the pointer.  All other generic motion events are
8152     * delivered to the focused view.  Hover events are handled specially and are delivered
8153     * to {@link #onHoverEvent(MotionEvent)}.
8154     * </p>
8155     *
8156     * @param event The motion event to be dispatched.
8157     * @return True if the event was handled by the view, false otherwise.
8158     */
8159    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8160        if (mInputEventConsistencyVerifier != null) {
8161            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8162        }
8163
8164        final int source = event.getSource();
8165        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8166            final int action = event.getAction();
8167            if (action == MotionEvent.ACTION_HOVER_ENTER
8168                    || action == MotionEvent.ACTION_HOVER_MOVE
8169                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8170                if (dispatchHoverEvent(event)) {
8171                    return true;
8172                }
8173            } else if (dispatchGenericPointerEvent(event)) {
8174                return true;
8175            }
8176        } else if (dispatchGenericFocusedEvent(event)) {
8177            return true;
8178        }
8179
8180        if (dispatchGenericMotionEventInternal(event)) {
8181            return true;
8182        }
8183
8184        if (mInputEventConsistencyVerifier != null) {
8185            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8186        }
8187        return false;
8188    }
8189
8190    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8191        //noinspection SimplifiableIfStatement
8192        ListenerInfo li = mListenerInfo;
8193        if (li != null && li.mOnGenericMotionListener != null
8194                && (mViewFlags & ENABLED_MASK) == ENABLED
8195                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8196            return true;
8197        }
8198
8199        if (onGenericMotionEvent(event)) {
8200            return true;
8201        }
8202
8203        if (mInputEventConsistencyVerifier != null) {
8204            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8205        }
8206        return false;
8207    }
8208
8209    /**
8210     * Dispatch a hover event.
8211     * <p>
8212     * Do not call this method directly.
8213     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8214     * </p>
8215     *
8216     * @param event The motion event to be dispatched.
8217     * @return True if the event was handled by the view, false otherwise.
8218     */
8219    protected boolean dispatchHoverEvent(MotionEvent event) {
8220        ListenerInfo li = mListenerInfo;
8221        //noinspection SimplifiableIfStatement
8222        if (li != null && li.mOnHoverListener != null
8223                && (mViewFlags & ENABLED_MASK) == ENABLED
8224                && li.mOnHoverListener.onHover(this, event)) {
8225            return true;
8226        }
8227
8228        return onHoverEvent(event);
8229    }
8230
8231    /**
8232     * Returns true if the view has a child to which it has recently sent
8233     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8234     * it does not have a hovered child, then it must be the innermost hovered view.
8235     * @hide
8236     */
8237    protected boolean hasHoveredChild() {
8238        return false;
8239    }
8240
8241    /**
8242     * Dispatch a generic motion event to the view under the first pointer.
8243     * <p>
8244     * Do not call this method directly.
8245     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8246     * </p>
8247     *
8248     * @param event The motion event to be dispatched.
8249     * @return True if the event was handled by the view, false otherwise.
8250     */
8251    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8252        return false;
8253    }
8254
8255    /**
8256     * Dispatch a generic motion event to the currently focused view.
8257     * <p>
8258     * Do not call this method directly.
8259     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8260     * </p>
8261     *
8262     * @param event The motion event to be dispatched.
8263     * @return True if the event was handled by the view, false otherwise.
8264     */
8265    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8266        return false;
8267    }
8268
8269    /**
8270     * Dispatch a pointer event.
8271     * <p>
8272     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8273     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8274     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8275     * and should not be expected to handle other pointing device features.
8276     * </p>
8277     *
8278     * @param event The motion event to be dispatched.
8279     * @return True if the event was handled by the view, false otherwise.
8280     * @hide
8281     */
8282    public final boolean dispatchPointerEvent(MotionEvent event) {
8283        if (event.isTouchEvent()) {
8284            return dispatchTouchEvent(event);
8285        } else {
8286            return dispatchGenericMotionEvent(event);
8287        }
8288    }
8289
8290    /**
8291     * Called when the window containing this view gains or loses window focus.
8292     * ViewGroups should override to route to their children.
8293     *
8294     * @param hasFocus True if the window containing this view now has focus,
8295     *        false otherwise.
8296     */
8297    public void dispatchWindowFocusChanged(boolean hasFocus) {
8298        onWindowFocusChanged(hasFocus);
8299    }
8300
8301    /**
8302     * Called when the window containing this view gains or loses focus.  Note
8303     * that this is separate from view focus: to receive key events, both
8304     * your view and its window must have focus.  If a window is displayed
8305     * on top of yours that takes input focus, then your own window will lose
8306     * focus but the view focus will remain unchanged.
8307     *
8308     * @param hasWindowFocus True if the window containing this view now has
8309     *        focus, false otherwise.
8310     */
8311    public void onWindowFocusChanged(boolean hasWindowFocus) {
8312        InputMethodManager imm = InputMethodManager.peekInstance();
8313        if (!hasWindowFocus) {
8314            if (isPressed()) {
8315                setPressed(false);
8316            }
8317            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8318                imm.focusOut(this);
8319            }
8320            removeLongPressCallback();
8321            removeTapCallback();
8322            onFocusLost();
8323        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8324            imm.focusIn(this);
8325        }
8326        refreshDrawableState();
8327    }
8328
8329    /**
8330     * Returns true if this view is in a window that currently has window focus.
8331     * Note that this is not the same as the view itself having focus.
8332     *
8333     * @return True if this view is in a window that currently has window focus.
8334     */
8335    public boolean hasWindowFocus() {
8336        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8337    }
8338
8339    /**
8340     * Dispatch a view visibility change down the view hierarchy.
8341     * ViewGroups should override to route to their children.
8342     * @param changedView The view whose visibility changed. Could be 'this' or
8343     * an ancestor view.
8344     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8345     * {@link #INVISIBLE} or {@link #GONE}.
8346     */
8347    protected void dispatchVisibilityChanged(@NonNull View changedView,
8348            @Visibility int visibility) {
8349        onVisibilityChanged(changedView, visibility);
8350    }
8351
8352    /**
8353     * Called when the visibility of the view or an ancestor of the view is changed.
8354     * @param changedView The view whose visibility changed. Could be 'this' or
8355     * an ancestor view.
8356     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8357     * {@link #INVISIBLE} or {@link #GONE}.
8358     */
8359    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8360        if (visibility == VISIBLE) {
8361            if (mAttachInfo != null) {
8362                initialAwakenScrollBars();
8363            } else {
8364                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8365            }
8366        }
8367    }
8368
8369    /**
8370     * Dispatch a hint about whether this view is displayed. For instance, when
8371     * a View moves out of the screen, it might receives a display hint indicating
8372     * the view is not displayed. Applications should not <em>rely</em> on this hint
8373     * as there is no guarantee that they will receive one.
8374     *
8375     * @param hint A hint about whether or not this view is displayed:
8376     * {@link #VISIBLE} or {@link #INVISIBLE}.
8377     */
8378    public void dispatchDisplayHint(@Visibility int hint) {
8379        onDisplayHint(hint);
8380    }
8381
8382    /**
8383     * Gives this view a hint about whether is displayed or not. For instance, when
8384     * a View moves out of the screen, it might receives a display hint indicating
8385     * the view is not displayed. Applications should not <em>rely</em> on this hint
8386     * as there is no guarantee that they will receive one.
8387     *
8388     * @param hint A hint about whether or not this view is displayed:
8389     * {@link #VISIBLE} or {@link #INVISIBLE}.
8390     */
8391    protected void onDisplayHint(@Visibility int hint) {
8392    }
8393
8394    /**
8395     * Dispatch a window visibility change down the view hierarchy.
8396     * ViewGroups should override to route to their children.
8397     *
8398     * @param visibility The new visibility of the window.
8399     *
8400     * @see #onWindowVisibilityChanged(int)
8401     */
8402    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8403        onWindowVisibilityChanged(visibility);
8404    }
8405
8406    /**
8407     * Called when the window containing has change its visibility
8408     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8409     * that this tells you whether or not your window is being made visible
8410     * to the window manager; this does <em>not</em> tell you whether or not
8411     * your window is obscured by other windows on the screen, even if it
8412     * is itself visible.
8413     *
8414     * @param visibility The new visibility of the window.
8415     */
8416    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8417        if (visibility == VISIBLE) {
8418            initialAwakenScrollBars();
8419        }
8420    }
8421
8422    /**
8423     * Returns the current visibility of the window this view is attached to
8424     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8425     *
8426     * @return Returns the current visibility of the view's window.
8427     */
8428    @Visibility
8429    public int getWindowVisibility() {
8430        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8431    }
8432
8433    /**
8434     * Retrieve the overall visible display size in which the window this view is
8435     * attached to has been positioned in.  This takes into account screen
8436     * decorations above the window, for both cases where the window itself
8437     * is being position inside of them or the window is being placed under
8438     * then and covered insets are used for the window to position its content
8439     * inside.  In effect, this tells you the available area where content can
8440     * be placed and remain visible to users.
8441     *
8442     * <p>This function requires an IPC back to the window manager to retrieve
8443     * the requested information, so should not be used in performance critical
8444     * code like drawing.
8445     *
8446     * @param outRect Filled in with the visible display frame.  If the view
8447     * is not attached to a window, this is simply the raw display size.
8448     */
8449    public void getWindowVisibleDisplayFrame(Rect outRect) {
8450        if (mAttachInfo != null) {
8451            try {
8452                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8453            } catch (RemoteException e) {
8454                return;
8455            }
8456            // XXX This is really broken, and probably all needs to be done
8457            // in the window manager, and we need to know more about whether
8458            // we want the area behind or in front of the IME.
8459            final Rect insets = mAttachInfo.mVisibleInsets;
8460            outRect.left += insets.left;
8461            outRect.top += insets.top;
8462            outRect.right -= insets.right;
8463            outRect.bottom -= insets.bottom;
8464            return;
8465        }
8466        // The view is not attached to a display so we don't have a context.
8467        // Make a best guess about the display size.
8468        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8469        d.getRectSize(outRect);
8470    }
8471
8472    /**
8473     * Dispatch a notification about a resource configuration change down
8474     * the view hierarchy.
8475     * ViewGroups should override to route to their children.
8476     *
8477     * @param newConfig The new resource configuration.
8478     *
8479     * @see #onConfigurationChanged(android.content.res.Configuration)
8480     */
8481    public void dispatchConfigurationChanged(Configuration newConfig) {
8482        onConfigurationChanged(newConfig);
8483    }
8484
8485    /**
8486     * Called when the current configuration of the resources being used
8487     * by the application have changed.  You can use this to decide when
8488     * to reload resources that can changed based on orientation and other
8489     * configuration characterstics.  You only need to use this if you are
8490     * not relying on the normal {@link android.app.Activity} mechanism of
8491     * recreating the activity instance upon a configuration change.
8492     *
8493     * @param newConfig The new resource configuration.
8494     */
8495    protected void onConfigurationChanged(Configuration newConfig) {
8496    }
8497
8498    /**
8499     * Private function to aggregate all per-view attributes in to the view
8500     * root.
8501     */
8502    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8503        performCollectViewAttributes(attachInfo, visibility);
8504    }
8505
8506    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8507        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8508            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8509                attachInfo.mKeepScreenOn = true;
8510            }
8511            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8512            ListenerInfo li = mListenerInfo;
8513            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8514                attachInfo.mHasSystemUiListeners = true;
8515            }
8516        }
8517    }
8518
8519    void needGlobalAttributesUpdate(boolean force) {
8520        final AttachInfo ai = mAttachInfo;
8521        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8522            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8523                    || ai.mHasSystemUiListeners) {
8524                ai.mRecomputeGlobalAttributes = true;
8525            }
8526        }
8527    }
8528
8529    /**
8530     * Returns whether the device is currently in touch mode.  Touch mode is entered
8531     * once the user begins interacting with the device by touch, and affects various
8532     * things like whether focus is always visible to the user.
8533     *
8534     * @return Whether the device is in touch mode.
8535     */
8536    @ViewDebug.ExportedProperty
8537    public boolean isInTouchMode() {
8538        if (mAttachInfo != null) {
8539            return mAttachInfo.mInTouchMode;
8540        } else {
8541            return ViewRootImpl.isInTouchMode();
8542        }
8543    }
8544
8545    /**
8546     * Returns the context the view is running in, through which it can
8547     * access the current theme, resources, etc.
8548     *
8549     * @return The view's Context.
8550     */
8551    @ViewDebug.CapturedViewProperty
8552    public final Context getContext() {
8553        return mContext;
8554    }
8555
8556    /**
8557     * Handle a key event before it is processed by any input method
8558     * associated with the view hierarchy.  This can be used to intercept
8559     * key events in special situations before the IME consumes them; a
8560     * typical example would be handling the BACK key to update the application's
8561     * UI instead of allowing the IME to see it and close itself.
8562     *
8563     * @param keyCode The value in event.getKeyCode().
8564     * @param event Description of the key event.
8565     * @return If you handled the event, return true. If you want to allow the
8566     *         event to be handled by the next receiver, return false.
8567     */
8568    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8569        return false;
8570    }
8571
8572    /**
8573     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8574     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8575     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8576     * is released, if the view is enabled and clickable.
8577     *
8578     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8579     * although some may elect to do so in some situations. Do not rely on this to
8580     * catch software key presses.
8581     *
8582     * @param keyCode A key code that represents the button pressed, from
8583     *                {@link android.view.KeyEvent}.
8584     * @param event   The KeyEvent object that defines the button action.
8585     */
8586    public boolean onKeyDown(int keyCode, KeyEvent event) {
8587        boolean result = false;
8588
8589        if (KeyEvent.isConfirmKey(keyCode)) {
8590            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8591                return true;
8592            }
8593            // Long clickable items don't necessarily have to be clickable
8594            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8595                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8596                    (event.getRepeatCount() == 0)) {
8597                setPressed(true);
8598                checkForLongClick(0);
8599                return true;
8600            }
8601        }
8602        return result;
8603    }
8604
8605    /**
8606     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8607     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8608     * the event).
8609     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8610     * although some may elect to do so in some situations. Do not rely on this to
8611     * catch software key presses.
8612     */
8613    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8614        return false;
8615    }
8616
8617    /**
8618     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8619     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8620     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8621     * {@link KeyEvent#KEYCODE_ENTER} is released.
8622     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8623     * although some may elect to do so in some situations. Do not rely on this to
8624     * catch software key presses.
8625     *
8626     * @param keyCode A key code that represents the button pressed, from
8627     *                {@link android.view.KeyEvent}.
8628     * @param event   The KeyEvent object that defines the button action.
8629     */
8630    public boolean onKeyUp(int keyCode, KeyEvent event) {
8631        if (KeyEvent.isConfirmKey(keyCode)) {
8632            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8633                return true;
8634            }
8635            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8636                setPressed(false);
8637
8638                if (!mHasPerformedLongPress) {
8639                    // This is a tap, so remove the longpress check
8640                    removeLongPressCallback();
8641                    return performClick();
8642                }
8643            }
8644        }
8645        return false;
8646    }
8647
8648    /**
8649     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8650     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8651     * the event).
8652     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8653     * although some may elect to do so in some situations. Do not rely on this to
8654     * catch software key presses.
8655     *
8656     * @param keyCode     A key code that represents the button pressed, from
8657     *                    {@link android.view.KeyEvent}.
8658     * @param repeatCount The number of times the action was made.
8659     * @param event       The KeyEvent object that defines the button action.
8660     */
8661    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8662        return false;
8663    }
8664
8665    /**
8666     * Called on the focused view when a key shortcut event is not handled.
8667     * Override this method to implement local key shortcuts for the View.
8668     * Key shortcuts can also be implemented by setting the
8669     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8670     *
8671     * @param keyCode The value in event.getKeyCode().
8672     * @param event Description of the key event.
8673     * @return If you handled the event, return true. If you want to allow the
8674     *         event to be handled by the next receiver, return false.
8675     */
8676    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8677        return false;
8678    }
8679
8680    /**
8681     * Check whether the called view is a text editor, in which case it
8682     * would make sense to automatically display a soft input window for
8683     * it.  Subclasses should override this if they implement
8684     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8685     * a call on that method would return a non-null InputConnection, and
8686     * they are really a first-class editor that the user would normally
8687     * start typing on when the go into a window containing your view.
8688     *
8689     * <p>The default implementation always returns false.  This does
8690     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8691     * will not be called or the user can not otherwise perform edits on your
8692     * view; it is just a hint to the system that this is not the primary
8693     * purpose of this view.
8694     *
8695     * @return Returns true if this view is a text editor, else false.
8696     */
8697    public boolean onCheckIsTextEditor() {
8698        return false;
8699    }
8700
8701    /**
8702     * Create a new InputConnection for an InputMethod to interact
8703     * with the view.  The default implementation returns null, since it doesn't
8704     * support input methods.  You can override this to implement such support.
8705     * This is only needed for views that take focus and text input.
8706     *
8707     * <p>When implementing this, you probably also want to implement
8708     * {@link #onCheckIsTextEditor()} to indicate you will return a
8709     * non-null InputConnection.
8710     *
8711     * @param outAttrs Fill in with attribute information about the connection.
8712     */
8713    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8714        return null;
8715    }
8716
8717    /**
8718     * Called by the {@link android.view.inputmethod.InputMethodManager}
8719     * when a view who is not the current
8720     * input connection target is trying to make a call on the manager.  The
8721     * default implementation returns false; you can override this to return
8722     * true for certain views if you are performing InputConnection proxying
8723     * to them.
8724     * @param view The View that is making the InputMethodManager call.
8725     * @return Return true to allow the call, false to reject.
8726     */
8727    public boolean checkInputConnectionProxy(View view) {
8728        return false;
8729    }
8730
8731    /**
8732     * Show the context menu for this view. It is not safe to hold on to the
8733     * menu after returning from this method.
8734     *
8735     * You should normally not overload this method. Overload
8736     * {@link #onCreateContextMenu(ContextMenu)} or define an
8737     * {@link OnCreateContextMenuListener} to add items to the context menu.
8738     *
8739     * @param menu The context menu to populate
8740     */
8741    public void createContextMenu(ContextMenu menu) {
8742        ContextMenuInfo menuInfo = getContextMenuInfo();
8743
8744        // Sets the current menu info so all items added to menu will have
8745        // my extra info set.
8746        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8747
8748        onCreateContextMenu(menu);
8749        ListenerInfo li = mListenerInfo;
8750        if (li != null && li.mOnCreateContextMenuListener != null) {
8751            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8752        }
8753
8754        // Clear the extra information so subsequent items that aren't mine don't
8755        // have my extra info.
8756        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8757
8758        if (mParent != null) {
8759            mParent.createContextMenu(menu);
8760        }
8761    }
8762
8763    /**
8764     * Views should implement this if they have extra information to associate
8765     * with the context menu. The return result is supplied as a parameter to
8766     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8767     * callback.
8768     *
8769     * @return Extra information about the item for which the context menu
8770     *         should be shown. This information will vary across different
8771     *         subclasses of View.
8772     */
8773    protected ContextMenuInfo getContextMenuInfo() {
8774        return null;
8775    }
8776
8777    /**
8778     * Views should implement this if the view itself is going to add items to
8779     * the context menu.
8780     *
8781     * @param menu the context menu to populate
8782     */
8783    protected void onCreateContextMenu(ContextMenu menu) {
8784    }
8785
8786    /**
8787     * Implement this method to handle trackball motion events.  The
8788     * <em>relative</em> movement of the trackball since the last event
8789     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8790     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8791     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8792     * they will often be fractional values, representing the more fine-grained
8793     * movement information available from a trackball).
8794     *
8795     * @param event The motion event.
8796     * @return True if the event was handled, false otherwise.
8797     */
8798    public boolean onTrackballEvent(MotionEvent event) {
8799        return false;
8800    }
8801
8802    /**
8803     * Implement this method to handle generic motion events.
8804     * <p>
8805     * Generic motion events describe joystick movements, mouse hovers, track pad
8806     * touches, scroll wheel movements and other input events.  The
8807     * {@link MotionEvent#getSource() source} of the motion event specifies
8808     * the class of input that was received.  Implementations of this method
8809     * must examine the bits in the source before processing the event.
8810     * The following code example shows how this is done.
8811     * </p><p>
8812     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8813     * are delivered to the view under the pointer.  All other generic motion events are
8814     * delivered to the focused view.
8815     * </p>
8816     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8817     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8818     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8819     *             // process the joystick movement...
8820     *             return true;
8821     *         }
8822     *     }
8823     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8824     *         switch (event.getAction()) {
8825     *             case MotionEvent.ACTION_HOVER_MOVE:
8826     *                 // process the mouse hover movement...
8827     *                 return true;
8828     *             case MotionEvent.ACTION_SCROLL:
8829     *                 // process the scroll wheel movement...
8830     *                 return true;
8831     *         }
8832     *     }
8833     *     return super.onGenericMotionEvent(event);
8834     * }</pre>
8835     *
8836     * @param event The generic motion event being processed.
8837     * @return True if the event was handled, false otherwise.
8838     */
8839    public boolean onGenericMotionEvent(MotionEvent event) {
8840        return false;
8841    }
8842
8843    /**
8844     * Implement this method to handle hover events.
8845     * <p>
8846     * This method is called whenever a pointer is hovering into, over, or out of the
8847     * bounds of a view and the view is not currently being touched.
8848     * Hover events are represented as pointer events with action
8849     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8850     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8851     * </p>
8852     * <ul>
8853     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8854     * when the pointer enters the bounds of the view.</li>
8855     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8856     * when the pointer has already entered the bounds of the view and has moved.</li>
8857     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8858     * when the pointer has exited the bounds of the view or when the pointer is
8859     * about to go down due to a button click, tap, or similar user action that
8860     * causes the view to be touched.</li>
8861     * </ul>
8862     * <p>
8863     * The view should implement this method to return true to indicate that it is
8864     * handling the hover event, such as by changing its drawable state.
8865     * </p><p>
8866     * The default implementation calls {@link #setHovered} to update the hovered state
8867     * of the view when a hover enter or hover exit event is received, if the view
8868     * is enabled and is clickable.  The default implementation also sends hover
8869     * accessibility events.
8870     * </p>
8871     *
8872     * @param event The motion event that describes the hover.
8873     * @return True if the view handled the hover event.
8874     *
8875     * @see #isHovered
8876     * @see #setHovered
8877     * @see #onHoverChanged
8878     */
8879    public boolean onHoverEvent(MotionEvent event) {
8880        // The root view may receive hover (or touch) events that are outside the bounds of
8881        // the window.  This code ensures that we only send accessibility events for
8882        // hovers that are actually within the bounds of the root view.
8883        final int action = event.getActionMasked();
8884        if (!mSendingHoverAccessibilityEvents) {
8885            if ((action == MotionEvent.ACTION_HOVER_ENTER
8886                    || action == MotionEvent.ACTION_HOVER_MOVE)
8887                    && !hasHoveredChild()
8888                    && pointInView(event.getX(), event.getY())) {
8889                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8890                mSendingHoverAccessibilityEvents = true;
8891            }
8892        } else {
8893            if (action == MotionEvent.ACTION_HOVER_EXIT
8894                    || (action == MotionEvent.ACTION_MOVE
8895                            && !pointInView(event.getX(), event.getY()))) {
8896                mSendingHoverAccessibilityEvents = false;
8897                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8898                // If the window does not have input focus we take away accessibility
8899                // focus as soon as the user stop hovering over the view.
8900                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8901                    getViewRootImpl().setAccessibilityFocus(null, null);
8902                }
8903            }
8904        }
8905
8906        if (isHoverable()) {
8907            switch (action) {
8908                case MotionEvent.ACTION_HOVER_ENTER:
8909                    setHovered(true);
8910                    break;
8911                case MotionEvent.ACTION_HOVER_EXIT:
8912                    setHovered(false);
8913                    break;
8914            }
8915
8916            // Dispatch the event to onGenericMotionEvent before returning true.
8917            // This is to provide compatibility with existing applications that
8918            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8919            // break because of the new default handling for hoverable views
8920            // in onHoverEvent.
8921            // Note that onGenericMotionEvent will be called by default when
8922            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8923            dispatchGenericMotionEventInternal(event);
8924            // The event was already handled by calling setHovered(), so always
8925            // return true.
8926            return true;
8927        }
8928
8929        return false;
8930    }
8931
8932    /**
8933     * Returns true if the view should handle {@link #onHoverEvent}
8934     * by calling {@link #setHovered} to change its hovered state.
8935     *
8936     * @return True if the view is hoverable.
8937     */
8938    private boolean isHoverable() {
8939        final int viewFlags = mViewFlags;
8940        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8941            return false;
8942        }
8943
8944        return (viewFlags & CLICKABLE) == CLICKABLE
8945                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8946    }
8947
8948    /**
8949     * Returns true if the view is currently hovered.
8950     *
8951     * @return True if the view is currently hovered.
8952     *
8953     * @see #setHovered
8954     * @see #onHoverChanged
8955     */
8956    @ViewDebug.ExportedProperty
8957    public boolean isHovered() {
8958        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8959    }
8960
8961    /**
8962     * Sets whether the view is currently hovered.
8963     * <p>
8964     * Calling this method also changes the drawable state of the view.  This
8965     * enables the view to react to hover by using different drawable resources
8966     * to change its appearance.
8967     * </p><p>
8968     * The {@link #onHoverChanged} method is called when the hovered state changes.
8969     * </p>
8970     *
8971     * @param hovered True if the view is hovered.
8972     *
8973     * @see #isHovered
8974     * @see #onHoverChanged
8975     */
8976    public void setHovered(boolean hovered) {
8977        if (hovered) {
8978            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8979                mPrivateFlags |= PFLAG_HOVERED;
8980                refreshDrawableState();
8981                onHoverChanged(true);
8982            }
8983        } else {
8984            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8985                mPrivateFlags &= ~PFLAG_HOVERED;
8986                refreshDrawableState();
8987                onHoverChanged(false);
8988            }
8989        }
8990    }
8991
8992    /**
8993     * Implement this method to handle hover state changes.
8994     * <p>
8995     * This method is called whenever the hover state changes as a result of a
8996     * call to {@link #setHovered}.
8997     * </p>
8998     *
8999     * @param hovered The current hover state, as returned by {@link #isHovered}.
9000     *
9001     * @see #isHovered
9002     * @see #setHovered
9003     */
9004    public void onHoverChanged(boolean hovered) {
9005    }
9006
9007    /**
9008     * Implement this method to handle touch screen motion events.
9009     * <p>
9010     * If this method is used to detect click actions, it is recommended that
9011     * the actions be performed by implementing and calling
9012     * {@link #performClick()}. This will ensure consistent system behavior,
9013     * including:
9014     * <ul>
9015     * <li>obeying click sound preferences
9016     * <li>dispatching OnClickListener calls
9017     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9018     * accessibility features are enabled
9019     * </ul>
9020     *
9021     * @param event The motion event.
9022     * @return True if the event was handled, false otherwise.
9023     */
9024    public boolean onTouchEvent(MotionEvent event) {
9025        final int viewFlags = mViewFlags;
9026
9027        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9028            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9029                setPressed(false);
9030            }
9031            // A disabled view that is clickable still consumes the touch
9032            // events, it just doesn't respond to them.
9033            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9034                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9035        }
9036
9037        if (mTouchDelegate != null) {
9038            if (mTouchDelegate.onTouchEvent(event)) {
9039                return true;
9040            }
9041        }
9042
9043        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9044                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9045            switch (event.getAction()) {
9046                case MotionEvent.ACTION_UP:
9047                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9048                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9049                        // take focus if we don't have it already and we should in
9050                        // touch mode.
9051                        boolean focusTaken = false;
9052                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9053                            focusTaken = requestFocus();
9054                        }
9055
9056                        if (prepressed) {
9057                            // The button is being released before we actually
9058                            // showed it as pressed.  Make it show the pressed
9059                            // state now (before scheduling the click) to ensure
9060                            // the user sees it.
9061                            setPressed(true);
9062                       }
9063
9064                        if (!mHasPerformedLongPress) {
9065                            // This is a tap, so remove the longpress check
9066                            removeLongPressCallback();
9067
9068                            // Only perform take click actions if we were in the pressed state
9069                            if (!focusTaken) {
9070                                // Use a Runnable and post this rather than calling
9071                                // performClick directly. This lets other visual state
9072                                // of the view update before click actions start.
9073                                if (mPerformClick == null) {
9074                                    mPerformClick = new PerformClick();
9075                                }
9076                                if (!post(mPerformClick)) {
9077                                    performClick();
9078                                }
9079                            }
9080                        }
9081
9082                        if (mUnsetPressedState == null) {
9083                            mUnsetPressedState = new UnsetPressedState();
9084                        }
9085
9086                        if (prepressed) {
9087                            postDelayed(mUnsetPressedState,
9088                                    ViewConfiguration.getPressedStateDuration());
9089                        } else if (!post(mUnsetPressedState)) {
9090                            // If the post failed, unpress right now
9091                            mUnsetPressedState.run();
9092                        }
9093                        removeTapCallback();
9094                    }
9095                    break;
9096
9097                case MotionEvent.ACTION_DOWN:
9098                    mHasPerformedLongPress = false;
9099
9100                    if (performButtonActionOnTouchDown(event)) {
9101                        break;
9102                    }
9103
9104                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9105                    boolean isInScrollingContainer = isInScrollingContainer();
9106
9107                    // For views inside a scrolling container, delay the pressed feedback for
9108                    // a short period in case this is a scroll.
9109                    if (isInScrollingContainer) {
9110                        mPrivateFlags |= PFLAG_PREPRESSED;
9111                        if (mPendingCheckForTap == null) {
9112                            mPendingCheckForTap = new CheckForTap();
9113                        }
9114                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9115                    } else {
9116                        // Not inside a scrolling container, so show the feedback right away
9117                        setPressed(true);
9118                        checkForLongClick(0);
9119                    }
9120                    break;
9121
9122                case MotionEvent.ACTION_CANCEL:
9123                    setPressed(false);
9124                    removeTapCallback();
9125                    removeLongPressCallback();
9126                    break;
9127
9128                case MotionEvent.ACTION_MOVE:
9129                    final int x = (int) event.getX();
9130                    final int y = (int) event.getY();
9131
9132                    // Be lenient about moving outside of buttons
9133                    if (!pointInView(x, y, mTouchSlop)) {
9134                        // Outside button
9135                        removeTapCallback();
9136                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9137                            // Remove any future long press/tap checks
9138                            removeLongPressCallback();
9139
9140                            setPressed(false);
9141                        }
9142                    }
9143                    break;
9144            }
9145
9146            if (mBackground != null && mBackground.supportsHotspots()) {
9147                manageTouchHotspot(event);
9148            }
9149
9150            return true;
9151        }
9152
9153        return false;
9154    }
9155
9156    private void manageTouchHotspot(MotionEvent event) {
9157        switch (event.getAction()) {
9158            case MotionEvent.ACTION_DOWN:
9159            case MotionEvent.ACTION_POINTER_DOWN: {
9160                final int index = event.getActionIndex();
9161                setPointerHotspot(event, index);
9162            } break;
9163            case MotionEvent.ACTION_MOVE: {
9164                final int count = event.getPointerCount();
9165                for (int index = 0; index < count; index++) {
9166                    setPointerHotspot(event, index);
9167                }
9168            } break;
9169            case MotionEvent.ACTION_POINTER_UP: {
9170                final int actionIndex = event.getActionIndex();
9171                final int pointerId = event.getPointerId(actionIndex);
9172                mBackground.removeHotspot(pointerId);
9173            } break;
9174            case MotionEvent.ACTION_UP:
9175            case MotionEvent.ACTION_CANCEL:
9176                mBackground.clearHotspots();
9177                break;
9178        }
9179    }
9180
9181    private void setPointerHotspot(MotionEvent event, int index) {
9182        final int id = event.getPointerId(index);
9183        final float x = event.getX(index);
9184        final float y = event.getY(index);
9185        mBackground.setHotspot(id, x, y);
9186    }
9187
9188    /**
9189     * @hide
9190     */
9191    public boolean isInScrollingContainer() {
9192        ViewParent p = getParent();
9193        while (p != null && p instanceof ViewGroup) {
9194            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9195                return true;
9196            }
9197            p = p.getParent();
9198        }
9199        return false;
9200    }
9201
9202    /**
9203     * Remove the longpress detection timer.
9204     */
9205    private void removeLongPressCallback() {
9206        if (mPendingCheckForLongPress != null) {
9207          removeCallbacks(mPendingCheckForLongPress);
9208        }
9209    }
9210
9211    /**
9212     * Remove the pending click action
9213     */
9214    private void removePerformClickCallback() {
9215        if (mPerformClick != null) {
9216            removeCallbacks(mPerformClick);
9217        }
9218    }
9219
9220    /**
9221     * Remove the prepress detection timer.
9222     */
9223    private void removeUnsetPressCallback() {
9224        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9225            setPressed(false);
9226            removeCallbacks(mUnsetPressedState);
9227        }
9228    }
9229
9230    /**
9231     * Remove the tap detection timer.
9232     */
9233    private void removeTapCallback() {
9234        if (mPendingCheckForTap != null) {
9235            mPrivateFlags &= ~PFLAG_PREPRESSED;
9236            removeCallbacks(mPendingCheckForTap);
9237        }
9238    }
9239
9240    /**
9241     * Cancels a pending long press.  Your subclass can use this if you
9242     * want the context menu to come up if the user presses and holds
9243     * at the same place, but you don't want it to come up if they press
9244     * and then move around enough to cause scrolling.
9245     */
9246    public void cancelLongPress() {
9247        removeLongPressCallback();
9248
9249        /*
9250         * The prepressed state handled by the tap callback is a display
9251         * construct, but the tap callback will post a long press callback
9252         * less its own timeout. Remove it here.
9253         */
9254        removeTapCallback();
9255    }
9256
9257    /**
9258     * Remove the pending callback for sending a
9259     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9260     */
9261    private void removeSendViewScrolledAccessibilityEventCallback() {
9262        if (mSendViewScrolledAccessibilityEvent != null) {
9263            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9264            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9265        }
9266    }
9267
9268    /**
9269     * Sets the TouchDelegate for this View.
9270     */
9271    public void setTouchDelegate(TouchDelegate delegate) {
9272        mTouchDelegate = delegate;
9273    }
9274
9275    /**
9276     * Gets the TouchDelegate for this View.
9277     */
9278    public TouchDelegate getTouchDelegate() {
9279        return mTouchDelegate;
9280    }
9281
9282    /**
9283     * Set flags controlling behavior of this view.
9284     *
9285     * @param flags Constant indicating the value which should be set
9286     * @param mask Constant indicating the bit range that should be changed
9287     */
9288    void setFlags(int flags, int mask) {
9289        final boolean accessibilityEnabled =
9290                AccessibilityManager.getInstance(mContext).isEnabled();
9291        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9292
9293        int old = mViewFlags;
9294        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9295
9296        int changed = mViewFlags ^ old;
9297        if (changed == 0) {
9298            return;
9299        }
9300        int privateFlags = mPrivateFlags;
9301
9302        /* Check if the FOCUSABLE bit has changed */
9303        if (((changed & FOCUSABLE_MASK) != 0) &&
9304                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9305            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9306                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9307                /* Give up focus if we are no longer focusable */
9308                clearFocus();
9309            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9310                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9311                /*
9312                 * Tell the view system that we are now available to take focus
9313                 * if no one else already has it.
9314                 */
9315                if (mParent != null) mParent.focusableViewAvailable(this);
9316            }
9317        }
9318
9319        final int newVisibility = flags & VISIBILITY_MASK;
9320        if (newVisibility == VISIBLE) {
9321            if ((changed & VISIBILITY_MASK) != 0) {
9322                /*
9323                 * If this view is becoming visible, invalidate it in case it changed while
9324                 * it was not visible. Marking it drawn ensures that the invalidation will
9325                 * go through.
9326                 */
9327                mPrivateFlags |= PFLAG_DRAWN;
9328                invalidate(true);
9329
9330                needGlobalAttributesUpdate(true);
9331
9332                // a view becoming visible is worth notifying the parent
9333                // about in case nothing has focus.  even if this specific view
9334                // isn't focusable, it may contain something that is, so let
9335                // the root view try to give this focus if nothing else does.
9336                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9337                    mParent.focusableViewAvailable(this);
9338                }
9339            }
9340        }
9341
9342        /* Check if the GONE bit has changed */
9343        if ((changed & GONE) != 0) {
9344            needGlobalAttributesUpdate(false);
9345            requestLayout();
9346
9347            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9348                if (hasFocus()) clearFocus();
9349                clearAccessibilityFocus();
9350                destroyDrawingCache();
9351                if (mParent instanceof View) {
9352                    // GONE views noop invalidation, so invalidate the parent
9353                    ((View) mParent).invalidate(true);
9354                }
9355                // Mark the view drawn to ensure that it gets invalidated properly the next
9356                // time it is visible and gets invalidated
9357                mPrivateFlags |= PFLAG_DRAWN;
9358            }
9359            if (mAttachInfo != null) {
9360                mAttachInfo.mViewVisibilityChanged = true;
9361            }
9362        }
9363
9364        /* Check if the VISIBLE bit has changed */
9365        if ((changed & INVISIBLE) != 0) {
9366            needGlobalAttributesUpdate(false);
9367            /*
9368             * If this view is becoming invisible, set the DRAWN flag so that
9369             * the next invalidate() will not be skipped.
9370             */
9371            mPrivateFlags |= PFLAG_DRAWN;
9372
9373            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9374                // root view becoming invisible shouldn't clear focus and accessibility focus
9375                if (getRootView() != this) {
9376                    if (hasFocus()) clearFocus();
9377                    clearAccessibilityFocus();
9378                }
9379            }
9380            if (mAttachInfo != null) {
9381                mAttachInfo.mViewVisibilityChanged = true;
9382            }
9383        }
9384
9385        if ((changed & VISIBILITY_MASK) != 0) {
9386            // If the view is invisible, cleanup its display list to free up resources
9387            if (newVisibility != VISIBLE) {
9388                cleanupDraw();
9389            }
9390
9391            if (mParent instanceof ViewGroup) {
9392                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9393                        (changed & VISIBILITY_MASK), newVisibility);
9394                ((View) mParent).invalidate(true);
9395            } else if (mParent != null) {
9396                mParent.invalidateChild(this, null);
9397            }
9398            dispatchVisibilityChanged(this, newVisibility);
9399        }
9400
9401        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9402            destroyDrawingCache();
9403        }
9404
9405        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9406            destroyDrawingCache();
9407            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9408            invalidateParentCaches();
9409        }
9410
9411        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9412            destroyDrawingCache();
9413            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9414        }
9415
9416        if ((changed & DRAW_MASK) != 0) {
9417            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9418                if (mBackground != null) {
9419                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9420                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9421                } else {
9422                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9423                }
9424            } else {
9425                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9426            }
9427            requestLayout();
9428            invalidate(true);
9429        }
9430
9431        if ((changed & KEEP_SCREEN_ON) != 0) {
9432            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9433                mParent.recomputeViewAttributes(this);
9434            }
9435        }
9436
9437        if (accessibilityEnabled) {
9438            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9439                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9440                if (oldIncludeForAccessibility != includeForAccessibility()) {
9441                    notifySubtreeAccessibilityStateChangedIfNeeded();
9442                } else {
9443                    notifyViewAccessibilityStateChangedIfNeeded(
9444                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9445                }
9446            } else if ((changed & ENABLED_MASK) != 0) {
9447                notifyViewAccessibilityStateChangedIfNeeded(
9448                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9449            }
9450        }
9451    }
9452
9453    /**
9454     * Change the view's z order in the tree, so it's on top of other sibling
9455     * views. This ordering change may affect layout, if the parent container
9456     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9457     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9458     * method should be followed by calls to {@link #requestLayout()} and
9459     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9460     * with the new child ordering.
9461     *
9462     * @see ViewGroup#bringChildToFront(View)
9463     */
9464    public void bringToFront() {
9465        if (mParent != null) {
9466            mParent.bringChildToFront(this);
9467        }
9468    }
9469
9470    /**
9471     * This is called in response to an internal scroll in this view (i.e., the
9472     * view scrolled its own contents). This is typically as a result of
9473     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9474     * called.
9475     *
9476     * @param l Current horizontal scroll origin.
9477     * @param t Current vertical scroll origin.
9478     * @param oldl Previous horizontal scroll origin.
9479     * @param oldt Previous vertical scroll origin.
9480     */
9481    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9482        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9483            postSendViewScrolledAccessibilityEventCallback();
9484        }
9485
9486        mBackgroundSizeChanged = true;
9487
9488        final AttachInfo ai = mAttachInfo;
9489        if (ai != null) {
9490            ai.mViewScrollChanged = true;
9491        }
9492    }
9493
9494    /**
9495     * Interface definition for a callback to be invoked when the layout bounds of a view
9496     * changes due to layout processing.
9497     */
9498    public interface OnLayoutChangeListener {
9499        /**
9500         * Called when the layout bounds of a view changes due to layout processing.
9501         *
9502         * @param v The view whose bounds have changed.
9503         * @param left The new value of the view's left property.
9504         * @param top The new value of the view's top property.
9505         * @param right The new value of the view's right property.
9506         * @param bottom The new value of the view's bottom property.
9507         * @param oldLeft The previous value of the view's left property.
9508         * @param oldTop The previous value of the view's top property.
9509         * @param oldRight The previous value of the view's right property.
9510         * @param oldBottom The previous value of the view's bottom property.
9511         */
9512        void onLayoutChange(View v, int left, int top, int right, int bottom,
9513            int oldLeft, int oldTop, int oldRight, int oldBottom);
9514    }
9515
9516    /**
9517     * This is called during layout when the size of this view has changed. If
9518     * you were just added to the view hierarchy, you're called with the old
9519     * values of 0.
9520     *
9521     * @param w Current width of this view.
9522     * @param h Current height of this view.
9523     * @param oldw Old width of this view.
9524     * @param oldh Old height of this view.
9525     */
9526    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9527    }
9528
9529    /**
9530     * Called by draw to draw the child views. This may be overridden
9531     * by derived classes to gain control just before its children are drawn
9532     * (but after its own view has been drawn).
9533     * @param canvas the canvas on which to draw the view
9534     */
9535    protected void dispatchDraw(Canvas canvas) {
9536
9537    }
9538
9539    /**
9540     * Gets the parent of this view. Note that the parent is a
9541     * ViewParent and not necessarily a View.
9542     *
9543     * @return Parent of this view.
9544     */
9545    public final ViewParent getParent() {
9546        return mParent;
9547    }
9548
9549    /**
9550     * Set the horizontal scrolled position of your view. This will cause a call to
9551     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9552     * invalidated.
9553     * @param value the x position to scroll to
9554     */
9555    public void setScrollX(int value) {
9556        scrollTo(value, mScrollY);
9557    }
9558
9559    /**
9560     * Set the vertical scrolled position of your view. This will cause a call to
9561     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9562     * invalidated.
9563     * @param value the y position to scroll to
9564     */
9565    public void setScrollY(int value) {
9566        scrollTo(mScrollX, value);
9567    }
9568
9569    /**
9570     * Return the scrolled left position of this view. This is the left edge of
9571     * the displayed part of your view. You do not need to draw any pixels
9572     * farther left, since those are outside of the frame of your view on
9573     * screen.
9574     *
9575     * @return The left edge of the displayed part of your view, in pixels.
9576     */
9577    public final int getScrollX() {
9578        return mScrollX;
9579    }
9580
9581    /**
9582     * Return the scrolled top position of this view. This is the top edge of
9583     * the displayed part of your view. You do not need to draw any pixels above
9584     * it, since those are outside of the frame of your view on screen.
9585     *
9586     * @return The top edge of the displayed part of your view, in pixels.
9587     */
9588    public final int getScrollY() {
9589        return mScrollY;
9590    }
9591
9592    /**
9593     * Return the width of the your view.
9594     *
9595     * @return The width of your view, in pixels.
9596     */
9597    @ViewDebug.ExportedProperty(category = "layout")
9598    public final int getWidth() {
9599        return mRight - mLeft;
9600    }
9601
9602    /**
9603     * Return the height of your view.
9604     *
9605     * @return The height of your view, in pixels.
9606     */
9607    @ViewDebug.ExportedProperty(category = "layout")
9608    public final int getHeight() {
9609        return mBottom - mTop;
9610    }
9611
9612    /**
9613     * Return the visible drawing bounds of your view. Fills in the output
9614     * rectangle with the values from getScrollX(), getScrollY(),
9615     * getWidth(), and getHeight(). These bounds do not account for any
9616     * transformation properties currently set on the view, such as
9617     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9618     *
9619     * @param outRect The (scrolled) drawing bounds of the view.
9620     */
9621    public void getDrawingRect(Rect outRect) {
9622        outRect.left = mScrollX;
9623        outRect.top = mScrollY;
9624        outRect.right = mScrollX + (mRight - mLeft);
9625        outRect.bottom = mScrollY + (mBottom - mTop);
9626    }
9627
9628    /**
9629     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9630     * raw width component (that is the result is masked by
9631     * {@link #MEASURED_SIZE_MASK}).
9632     *
9633     * @return The raw measured width of this view.
9634     */
9635    public final int getMeasuredWidth() {
9636        return mMeasuredWidth & MEASURED_SIZE_MASK;
9637    }
9638
9639    /**
9640     * Return the full width measurement information for this view as computed
9641     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9642     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9643     * This should be used during measurement and layout calculations only. Use
9644     * {@link #getWidth()} to see how wide a view is after layout.
9645     *
9646     * @return The measured width of this view as a bit mask.
9647     */
9648    public final int getMeasuredWidthAndState() {
9649        return mMeasuredWidth;
9650    }
9651
9652    /**
9653     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9654     * raw width component (that is the result is masked by
9655     * {@link #MEASURED_SIZE_MASK}).
9656     *
9657     * @return The raw measured height of this view.
9658     */
9659    public final int getMeasuredHeight() {
9660        return mMeasuredHeight & MEASURED_SIZE_MASK;
9661    }
9662
9663    /**
9664     * Return the full height measurement information for this view as computed
9665     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9666     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9667     * This should be used during measurement and layout calculations only. Use
9668     * {@link #getHeight()} to see how wide a view is after layout.
9669     *
9670     * @return The measured width of this view as a bit mask.
9671     */
9672    public final int getMeasuredHeightAndState() {
9673        return mMeasuredHeight;
9674    }
9675
9676    /**
9677     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9678     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9679     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9680     * and the height component is at the shifted bits
9681     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9682     */
9683    public final int getMeasuredState() {
9684        return (mMeasuredWidth&MEASURED_STATE_MASK)
9685                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9686                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9687    }
9688
9689    /**
9690     * The transform matrix of this view, which is calculated based on the current
9691     * roation, scale, and pivot properties.
9692     *
9693     * @see #getRotation()
9694     * @see #getScaleX()
9695     * @see #getScaleY()
9696     * @see #getPivotX()
9697     * @see #getPivotY()
9698     * @return The current transform matrix for the view
9699     */
9700    public Matrix getMatrix() {
9701        if (mTransformationInfo != null) {
9702            updateMatrix();
9703            return mTransformationInfo.mMatrix;
9704        }
9705        return Matrix.IDENTITY_MATRIX;
9706    }
9707
9708    /**
9709     * Utility function to determine if the value is far enough away from zero to be
9710     * considered non-zero.
9711     * @param value A floating point value to check for zero-ness
9712     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9713     */
9714    private static boolean nonzero(float value) {
9715        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9716    }
9717
9718    /**
9719     * Returns true if the transform matrix is the identity matrix.
9720     * Recomputes the matrix if necessary.
9721     *
9722     * @return True if the transform matrix is the identity matrix, false otherwise.
9723     */
9724    final boolean hasIdentityMatrix() {
9725        if (mTransformationInfo != null) {
9726            updateMatrix();
9727            return mTransformationInfo.mMatrixIsIdentity;
9728        }
9729        return true;
9730    }
9731
9732    void ensureTransformationInfo() {
9733        if (mTransformationInfo == null) {
9734            mTransformationInfo = new TransformationInfo();
9735        }
9736    }
9737
9738    /**
9739     * Recomputes the transform matrix if necessary.
9740     */
9741    private void updateMatrix() {
9742        final TransformationInfo info = mTransformationInfo;
9743        if (info == null) {
9744            return;
9745        }
9746        if (info.mMatrixDirty) {
9747            // transform-related properties have changed since the last time someone
9748            // asked for the matrix; recalculate it with the current values
9749
9750            // Figure out if we need to update the pivot point
9751            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9752                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9753                    info.mPrevWidth = mRight - mLeft;
9754                    info.mPrevHeight = mBottom - mTop;
9755                    info.mPivotX = info.mPrevWidth / 2f;
9756                    info.mPivotY = info.mPrevHeight / 2f;
9757                }
9758            }
9759            info.mMatrix.reset();
9760            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9761                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9762                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9763                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9764            } else {
9765                if (info.mCamera == null) {
9766                    info.mCamera = new Camera();
9767                    info.matrix3D = new Matrix();
9768                }
9769                info.mCamera.save();
9770                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9771                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9772                info.mCamera.getMatrix(info.matrix3D);
9773                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9774                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9775                        info.mPivotY + info.mTranslationY);
9776                info.mMatrix.postConcat(info.matrix3D);
9777                info.mCamera.restore();
9778            }
9779            info.mMatrixDirty = false;
9780            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9781            info.mInverseMatrixDirty = true;
9782        }
9783    }
9784
9785   /**
9786     * Utility method to retrieve the inverse of the current mMatrix property.
9787     * We cache the matrix to avoid recalculating it when transform properties
9788     * have not changed.
9789     *
9790     * @return The inverse of the current matrix of this view.
9791     */
9792    final Matrix getInverseMatrix() {
9793        final TransformationInfo info = mTransformationInfo;
9794        if (info != null) {
9795            updateMatrix();
9796            if (info.mInverseMatrixDirty) {
9797                if (info.mInverseMatrix == null) {
9798                    info.mInverseMatrix = new Matrix();
9799                }
9800                info.mMatrix.invert(info.mInverseMatrix);
9801                info.mInverseMatrixDirty = false;
9802            }
9803            return info.mInverseMatrix;
9804        }
9805        return Matrix.IDENTITY_MATRIX;
9806    }
9807
9808    /**
9809     * Gets the distance along the Z axis from the camera to this view.
9810     *
9811     * @see #setCameraDistance(float)
9812     *
9813     * @return The distance along the Z axis.
9814     */
9815    public float getCameraDistance() {
9816        ensureTransformationInfo();
9817        final float dpi = mResources.getDisplayMetrics().densityDpi;
9818        final TransformationInfo info = mTransformationInfo;
9819        if (info.mCamera == null) {
9820            info.mCamera = new Camera();
9821            info.matrix3D = new Matrix();
9822        }
9823        return -(info.mCamera.getLocationZ() * dpi);
9824    }
9825
9826    /**
9827     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9828     * views are drawn) from the camera to this view. The camera's distance
9829     * affects 3D transformations, for instance rotations around the X and Y
9830     * axis. If the rotationX or rotationY properties are changed and this view is
9831     * large (more than half the size of the screen), it is recommended to always
9832     * use a camera distance that's greater than the height (X axis rotation) or
9833     * the width (Y axis rotation) of this view.</p>
9834     *
9835     * <p>The distance of the camera from the view plane can have an affect on the
9836     * perspective distortion of the view when it is rotated around the x or y axis.
9837     * For example, a large distance will result in a large viewing angle, and there
9838     * will not be much perspective distortion of the view as it rotates. A short
9839     * distance may cause much more perspective distortion upon rotation, and can
9840     * also result in some drawing artifacts if the rotated view ends up partially
9841     * behind the camera (which is why the recommendation is to use a distance at
9842     * least as far as the size of the view, if the view is to be rotated.)</p>
9843     *
9844     * <p>The distance is expressed in "depth pixels." The default distance depends
9845     * on the screen density. For instance, on a medium density display, the
9846     * default distance is 1280. On a high density display, the default distance
9847     * is 1920.</p>
9848     *
9849     * <p>If you want to specify a distance that leads to visually consistent
9850     * results across various densities, use the following formula:</p>
9851     * <pre>
9852     * float scale = context.getResources().getDisplayMetrics().density;
9853     * view.setCameraDistance(distance * scale);
9854     * </pre>
9855     *
9856     * <p>The density scale factor of a high density display is 1.5,
9857     * and 1920 = 1280 * 1.5.</p>
9858     *
9859     * @param distance The distance in "depth pixels", if negative the opposite
9860     *        value is used
9861     *
9862     * @see #setRotationX(float)
9863     * @see #setRotationY(float)
9864     */
9865    public void setCameraDistance(float distance) {
9866        invalidateViewProperty(true, false);
9867
9868        ensureTransformationInfo();
9869        final float dpi = mResources.getDisplayMetrics().densityDpi;
9870        final TransformationInfo info = mTransformationInfo;
9871        if (info.mCamera == null) {
9872            info.mCamera = new Camera();
9873            info.matrix3D = new Matrix();
9874        }
9875
9876        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9877        info.mMatrixDirty = true;
9878
9879        invalidateViewProperty(false, false);
9880        if (mDisplayList != null) {
9881            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9882        }
9883        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9884            // View was rejected last time it was drawn by its parent; this may have changed
9885            invalidateParentIfNeeded();
9886        }
9887    }
9888
9889    /**
9890     * The degrees that the view is rotated around the pivot point.
9891     *
9892     * @see #setRotation(float)
9893     * @see #getPivotX()
9894     * @see #getPivotY()
9895     *
9896     * @return The degrees of rotation.
9897     */
9898    @ViewDebug.ExportedProperty(category = "drawing")
9899    public float getRotation() {
9900        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9901    }
9902
9903    /**
9904     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9905     * result in clockwise rotation.
9906     *
9907     * @param rotation The degrees of rotation.
9908     *
9909     * @see #getRotation()
9910     * @see #getPivotX()
9911     * @see #getPivotY()
9912     * @see #setRotationX(float)
9913     * @see #setRotationY(float)
9914     *
9915     * @attr ref android.R.styleable#View_rotation
9916     */
9917    public void setRotation(float rotation) {
9918        ensureTransformationInfo();
9919        final TransformationInfo info = mTransformationInfo;
9920        if (info.mRotation != rotation) {
9921            // Double-invalidation is necessary to capture view's old and new areas
9922            invalidateViewProperty(true, false);
9923            info.mRotation = rotation;
9924            info.mMatrixDirty = true;
9925            invalidateViewProperty(false, true);
9926            if (mDisplayList != null) {
9927                mDisplayList.setRotation(rotation);
9928            }
9929            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9930                // View was rejected last time it was drawn by its parent; this may have changed
9931                invalidateParentIfNeeded();
9932            }
9933        }
9934    }
9935
9936    /**
9937     * The degrees that the view is rotated around the vertical axis through the pivot point.
9938     *
9939     * @see #getPivotX()
9940     * @see #getPivotY()
9941     * @see #setRotationY(float)
9942     *
9943     * @return The degrees of Y rotation.
9944     */
9945    @ViewDebug.ExportedProperty(category = "drawing")
9946    public float getRotationY() {
9947        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9948    }
9949
9950    /**
9951     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9952     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9953     * down the y axis.
9954     *
9955     * When rotating large views, it is recommended to adjust the camera distance
9956     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9957     *
9958     * @param rotationY The degrees of Y rotation.
9959     *
9960     * @see #getRotationY()
9961     * @see #getPivotX()
9962     * @see #getPivotY()
9963     * @see #setRotation(float)
9964     * @see #setRotationX(float)
9965     * @see #setCameraDistance(float)
9966     *
9967     * @attr ref android.R.styleable#View_rotationY
9968     */
9969    public void setRotationY(float rotationY) {
9970        ensureTransformationInfo();
9971        final TransformationInfo info = mTransformationInfo;
9972        if (info.mRotationY != rotationY) {
9973            invalidateViewProperty(true, false);
9974            info.mRotationY = rotationY;
9975            info.mMatrixDirty = true;
9976            invalidateViewProperty(false, true);
9977            if (mDisplayList != null) {
9978                mDisplayList.setRotationY(rotationY);
9979            }
9980            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9981                // View was rejected last time it was drawn by its parent; this may have changed
9982                invalidateParentIfNeeded();
9983            }
9984        }
9985    }
9986
9987    /**
9988     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9989     *
9990     * @see #getPivotX()
9991     * @see #getPivotY()
9992     * @see #setRotationX(float)
9993     *
9994     * @return The degrees of X rotation.
9995     */
9996    @ViewDebug.ExportedProperty(category = "drawing")
9997    public float getRotationX() {
9998        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9999    }
10000
10001    /**
10002     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10003     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10004     * x axis.
10005     *
10006     * When rotating large views, it is recommended to adjust the camera distance
10007     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10008     *
10009     * @param rotationX The degrees of X rotation.
10010     *
10011     * @see #getRotationX()
10012     * @see #getPivotX()
10013     * @see #getPivotY()
10014     * @see #setRotation(float)
10015     * @see #setRotationY(float)
10016     * @see #setCameraDistance(float)
10017     *
10018     * @attr ref android.R.styleable#View_rotationX
10019     */
10020    public void setRotationX(float rotationX) {
10021        ensureTransformationInfo();
10022        final TransformationInfo info = mTransformationInfo;
10023        if (info.mRotationX != rotationX) {
10024            invalidateViewProperty(true, false);
10025            info.mRotationX = rotationX;
10026            info.mMatrixDirty = true;
10027            invalidateViewProperty(false, true);
10028            if (mDisplayList != null) {
10029                mDisplayList.setRotationX(rotationX);
10030            }
10031            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10032                // View was rejected last time it was drawn by its parent; this may have changed
10033                invalidateParentIfNeeded();
10034            }
10035        }
10036    }
10037
10038    /**
10039     * The amount that the view is scaled in x around the pivot point, as a proportion of
10040     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10041     *
10042     * <p>By default, this is 1.0f.
10043     *
10044     * @see #getPivotX()
10045     * @see #getPivotY()
10046     * @return The scaling factor.
10047     */
10048    @ViewDebug.ExportedProperty(category = "drawing")
10049    public float getScaleX() {
10050        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
10051    }
10052
10053    /**
10054     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10055     * the view's unscaled width. A value of 1 means that no scaling is applied.
10056     *
10057     * @param scaleX The scaling factor.
10058     * @see #getPivotX()
10059     * @see #getPivotY()
10060     *
10061     * @attr ref android.R.styleable#View_scaleX
10062     */
10063    public void setScaleX(float scaleX) {
10064        ensureTransformationInfo();
10065        final TransformationInfo info = mTransformationInfo;
10066        if (info.mScaleX != scaleX) {
10067            invalidateViewProperty(true, false);
10068            info.mScaleX = scaleX;
10069            info.mMatrixDirty = true;
10070            invalidateViewProperty(false, true);
10071            if (mDisplayList != null) {
10072                mDisplayList.setScaleX(scaleX);
10073            }
10074            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10075                // View was rejected last time it was drawn by its parent; this may have changed
10076                invalidateParentIfNeeded();
10077            }
10078        }
10079    }
10080
10081    /**
10082     * The amount that the view is scaled in y around the pivot point, as a proportion of
10083     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10084     *
10085     * <p>By default, this is 1.0f.
10086     *
10087     * @see #getPivotX()
10088     * @see #getPivotY()
10089     * @return The scaling factor.
10090     */
10091    @ViewDebug.ExportedProperty(category = "drawing")
10092    public float getScaleY() {
10093        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
10094    }
10095
10096    /**
10097     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10098     * the view's unscaled width. A value of 1 means that no scaling is applied.
10099     *
10100     * @param scaleY The scaling factor.
10101     * @see #getPivotX()
10102     * @see #getPivotY()
10103     *
10104     * @attr ref android.R.styleable#View_scaleY
10105     */
10106    public void setScaleY(float scaleY) {
10107        ensureTransformationInfo();
10108        final TransformationInfo info = mTransformationInfo;
10109        if (info.mScaleY != scaleY) {
10110            invalidateViewProperty(true, false);
10111            info.mScaleY = scaleY;
10112            info.mMatrixDirty = true;
10113            invalidateViewProperty(false, true);
10114            if (mDisplayList != null) {
10115                mDisplayList.setScaleY(scaleY);
10116            }
10117            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10118                // View was rejected last time it was drawn by its parent; this may have changed
10119                invalidateParentIfNeeded();
10120            }
10121        }
10122    }
10123
10124    /**
10125     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10126     * and {@link #setScaleX(float) scaled}.
10127     *
10128     * @see #getRotation()
10129     * @see #getScaleX()
10130     * @see #getScaleY()
10131     * @see #getPivotY()
10132     * @return The x location of the pivot point.
10133     *
10134     * @attr ref android.R.styleable#View_transformPivotX
10135     */
10136    @ViewDebug.ExportedProperty(category = "drawing")
10137    public float getPivotX() {
10138        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
10139    }
10140
10141    /**
10142     * Sets the x location of the point around which the view is
10143     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10144     * By default, the pivot point is centered on the object.
10145     * Setting this property disables this behavior and causes the view to use only the
10146     * explicitly set pivotX and pivotY values.
10147     *
10148     * @param pivotX The x location of the pivot point.
10149     * @see #getRotation()
10150     * @see #getScaleX()
10151     * @see #getScaleY()
10152     * @see #getPivotY()
10153     *
10154     * @attr ref android.R.styleable#View_transformPivotX
10155     */
10156    public void setPivotX(float pivotX) {
10157        ensureTransformationInfo();
10158        final TransformationInfo info = mTransformationInfo;
10159        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10160                PFLAG_PIVOT_EXPLICITLY_SET;
10161        if (info.mPivotX != pivotX || !pivotSet) {
10162            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10163            invalidateViewProperty(true, false);
10164            info.mPivotX = pivotX;
10165            info.mMatrixDirty = true;
10166            invalidateViewProperty(false, true);
10167            if (mDisplayList != null) {
10168                mDisplayList.setPivotX(pivotX);
10169            }
10170            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10171                // View was rejected last time it was drawn by its parent; this may have changed
10172                invalidateParentIfNeeded();
10173            }
10174        }
10175    }
10176
10177    /**
10178     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10179     * and {@link #setScaleY(float) scaled}.
10180     *
10181     * @see #getRotation()
10182     * @see #getScaleX()
10183     * @see #getScaleY()
10184     * @see #getPivotY()
10185     * @return The y location of the pivot point.
10186     *
10187     * @attr ref android.R.styleable#View_transformPivotY
10188     */
10189    @ViewDebug.ExportedProperty(category = "drawing")
10190    public float getPivotY() {
10191        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
10192    }
10193
10194    /**
10195     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10196     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10197     * Setting this property disables this behavior and causes the view to use only the
10198     * explicitly set pivotX and pivotY values.
10199     *
10200     * @param pivotY The y location of the pivot point.
10201     * @see #getRotation()
10202     * @see #getScaleX()
10203     * @see #getScaleY()
10204     * @see #getPivotY()
10205     *
10206     * @attr ref android.R.styleable#View_transformPivotY
10207     */
10208    public void setPivotY(float pivotY) {
10209        ensureTransformationInfo();
10210        final TransformationInfo info = mTransformationInfo;
10211        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10212                PFLAG_PIVOT_EXPLICITLY_SET;
10213        if (info.mPivotY != pivotY || !pivotSet) {
10214            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10215            invalidateViewProperty(true, false);
10216            info.mPivotY = pivotY;
10217            info.mMatrixDirty = true;
10218            invalidateViewProperty(false, true);
10219            if (mDisplayList != null) {
10220                mDisplayList.setPivotY(pivotY);
10221            }
10222            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10223                // View was rejected last time it was drawn by its parent; this may have changed
10224                invalidateParentIfNeeded();
10225            }
10226        }
10227    }
10228
10229    /**
10230     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10231     * completely transparent and 1 means the view is completely opaque.
10232     *
10233     * <p>By default this is 1.0f.
10234     * @return The opacity of the view.
10235     */
10236    @ViewDebug.ExportedProperty(category = "drawing")
10237    public float getAlpha() {
10238        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10239    }
10240
10241    /**
10242     * Returns whether this View has content which overlaps.
10243     *
10244     * <p>This function, intended to be overridden by specific View types, is an optimization when
10245     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10246     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10247     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10248     * directly. An example of overlapping rendering is a TextView with a background image, such as
10249     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10250     * ImageView with only the foreground image. The default implementation returns true; subclasses
10251     * should override if they have cases which can be optimized.</p>
10252     *
10253     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10254     * necessitates that a View return true if it uses the methods internally without passing the
10255     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10256     *
10257     * @return true if the content in this view might overlap, false otherwise.
10258     */
10259    public boolean hasOverlappingRendering() {
10260        return true;
10261    }
10262
10263    /**
10264     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10265     * completely transparent and 1 means the view is completely opaque.</p>
10266     *
10267     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10268     * performance implications, especially for large views. It is best to use the alpha property
10269     * sparingly and transiently, as in the case of fading animations.</p>
10270     *
10271     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10272     * strongly recommended for performance reasons to either override
10273     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10274     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10275     *
10276     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10277     * responsible for applying the opacity itself.</p>
10278     *
10279     * <p>Note that if the view is backed by a
10280     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10281     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10282     * 1.0 will supercede the alpha of the layer paint.</p>
10283     *
10284     * @param alpha The opacity of the view.
10285     *
10286     * @see #hasOverlappingRendering()
10287     * @see #setLayerType(int, android.graphics.Paint)
10288     *
10289     * @attr ref android.R.styleable#View_alpha
10290     */
10291    public void setAlpha(float alpha) {
10292        ensureTransformationInfo();
10293        if (mTransformationInfo.mAlpha != alpha) {
10294            mTransformationInfo.mAlpha = alpha;
10295            if (onSetAlpha((int) (alpha * 255))) {
10296                mPrivateFlags |= PFLAG_ALPHA_SET;
10297                // subclass is handling alpha - don't optimize rendering cache invalidation
10298                invalidateParentCaches();
10299                invalidate(true);
10300            } else {
10301                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10302                invalidateViewProperty(true, false);
10303                if (mDisplayList != null) {
10304                    mDisplayList.setAlpha(getFinalAlpha());
10305                }
10306            }
10307        }
10308    }
10309
10310    /**
10311     * Faster version of setAlpha() which performs the same steps except there are
10312     * no calls to invalidate(). The caller of this function should perform proper invalidation
10313     * on the parent and this object. The return value indicates whether the subclass handles
10314     * alpha (the return value for onSetAlpha()).
10315     *
10316     * @param alpha The new value for the alpha property
10317     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10318     *         the new value for the alpha property is different from the old value
10319     */
10320    boolean setAlphaNoInvalidation(float alpha) {
10321        ensureTransformationInfo();
10322        if (mTransformationInfo.mAlpha != alpha) {
10323            mTransformationInfo.mAlpha = alpha;
10324            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10325            if (subclassHandlesAlpha) {
10326                mPrivateFlags |= PFLAG_ALPHA_SET;
10327                return true;
10328            } else {
10329                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10330                if (mDisplayList != null) {
10331                    mDisplayList.setAlpha(getFinalAlpha());
10332                }
10333            }
10334        }
10335        return false;
10336    }
10337
10338    /**
10339     * This property is hidden and intended only for use by the Fade transition, which
10340     * animates it to produce a visual translucency that does not side-effect (or get
10341     * affected by) the real alpha property. This value is composited with the other
10342     * alpha value (and the AlphaAnimation value, when that is present) to produce
10343     * a final visual translucency result, which is what is passed into the DisplayList.
10344     *
10345     * @hide
10346     */
10347    public void setTransitionAlpha(float alpha) {
10348        ensureTransformationInfo();
10349        if (mTransformationInfo.mTransitionAlpha != alpha) {
10350            mTransformationInfo.mTransitionAlpha = alpha;
10351            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10352            invalidateViewProperty(true, false);
10353            if (mDisplayList != null) {
10354                mDisplayList.setAlpha(getFinalAlpha());
10355            }
10356        }
10357    }
10358
10359    /**
10360     * Calculates the visual alpha of this view, which is a combination of the actual
10361     * alpha value and the transitionAlpha value (if set).
10362     */
10363    private float getFinalAlpha() {
10364        if (mTransformationInfo != null) {
10365            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10366        }
10367        return 1;
10368    }
10369
10370    /**
10371     * This property is hidden and intended only for use by the Fade transition, which
10372     * animates it to produce a visual translucency that does not side-effect (or get
10373     * affected by) the real alpha property. This value is composited with the other
10374     * alpha value (and the AlphaAnimation value, when that is present) to produce
10375     * a final visual translucency result, which is what is passed into the DisplayList.
10376     *
10377     * @hide
10378     */
10379    public float getTransitionAlpha() {
10380        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10381    }
10382
10383    /**
10384     * Top position of this view relative to its parent.
10385     *
10386     * @return The top of this view, in pixels.
10387     */
10388    @ViewDebug.CapturedViewProperty
10389    public final int getTop() {
10390        return mTop;
10391    }
10392
10393    /**
10394     * Sets the top position of this view relative to its parent. This method is meant to be called
10395     * by the layout system and should not generally be called otherwise, because the property
10396     * may be changed at any time by the layout.
10397     *
10398     * @param top The top of this view, in pixels.
10399     */
10400    public final void setTop(int top) {
10401        if (top != mTop) {
10402            updateMatrix();
10403            final boolean matrixIsIdentity = mTransformationInfo == null
10404                    || mTransformationInfo.mMatrixIsIdentity;
10405            if (matrixIsIdentity) {
10406                if (mAttachInfo != null) {
10407                    int minTop;
10408                    int yLoc;
10409                    if (top < mTop) {
10410                        minTop = top;
10411                        yLoc = top - mTop;
10412                    } else {
10413                        minTop = mTop;
10414                        yLoc = 0;
10415                    }
10416                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10417                }
10418            } else {
10419                // Double-invalidation is necessary to capture view's old and new areas
10420                invalidate(true);
10421            }
10422
10423            int width = mRight - mLeft;
10424            int oldHeight = mBottom - mTop;
10425
10426            mTop = top;
10427            if (mDisplayList != null) {
10428                mDisplayList.setTop(mTop);
10429            }
10430
10431            sizeChange(width, mBottom - mTop, width, oldHeight);
10432
10433            if (!matrixIsIdentity) {
10434                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10435                    // A change in dimension means an auto-centered pivot point changes, too
10436                    mTransformationInfo.mMatrixDirty = true;
10437                }
10438                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10439                invalidate(true);
10440            }
10441            mBackgroundSizeChanged = true;
10442            invalidateParentIfNeeded();
10443            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10444                // View was rejected last time it was drawn by its parent; this may have changed
10445                invalidateParentIfNeeded();
10446            }
10447        }
10448    }
10449
10450    /**
10451     * Bottom position of this view relative to its parent.
10452     *
10453     * @return The bottom of this view, in pixels.
10454     */
10455    @ViewDebug.CapturedViewProperty
10456    public final int getBottom() {
10457        return mBottom;
10458    }
10459
10460    /**
10461     * True if this view has changed since the last time being drawn.
10462     *
10463     * @return The dirty state of this view.
10464     */
10465    public boolean isDirty() {
10466        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10467    }
10468
10469    /**
10470     * Sets the bottom position of this view relative to its parent. This method is meant to be
10471     * called by the layout system and should not generally be called otherwise, because the
10472     * property may be changed at any time by the layout.
10473     *
10474     * @param bottom The bottom of this view, in pixels.
10475     */
10476    public final void setBottom(int bottom) {
10477        if (bottom != mBottom) {
10478            updateMatrix();
10479            final boolean matrixIsIdentity = mTransformationInfo == null
10480                    || mTransformationInfo.mMatrixIsIdentity;
10481            if (matrixIsIdentity) {
10482                if (mAttachInfo != null) {
10483                    int maxBottom;
10484                    if (bottom < mBottom) {
10485                        maxBottom = mBottom;
10486                    } else {
10487                        maxBottom = bottom;
10488                    }
10489                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10490                }
10491            } else {
10492                // Double-invalidation is necessary to capture view's old and new areas
10493                invalidate(true);
10494            }
10495
10496            int width = mRight - mLeft;
10497            int oldHeight = mBottom - mTop;
10498
10499            mBottom = bottom;
10500            if (mDisplayList != null) {
10501                mDisplayList.setBottom(mBottom);
10502            }
10503
10504            sizeChange(width, mBottom - mTop, width, oldHeight);
10505
10506            if (!matrixIsIdentity) {
10507                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10508                    // A change in dimension means an auto-centered pivot point changes, too
10509                    mTransformationInfo.mMatrixDirty = true;
10510                }
10511                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10512                invalidate(true);
10513            }
10514            mBackgroundSizeChanged = true;
10515            invalidateParentIfNeeded();
10516            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10517                // View was rejected last time it was drawn by its parent; this may have changed
10518                invalidateParentIfNeeded();
10519            }
10520        }
10521    }
10522
10523    /**
10524     * Left position of this view relative to its parent.
10525     *
10526     * @return The left edge of this view, in pixels.
10527     */
10528    @ViewDebug.CapturedViewProperty
10529    public final int getLeft() {
10530        return mLeft;
10531    }
10532
10533    /**
10534     * Sets the left position of this view relative to its parent. This method is meant to be called
10535     * by the layout system and should not generally be called otherwise, because the property
10536     * may be changed at any time by the layout.
10537     *
10538     * @param left The bottom of this view, in pixels.
10539     */
10540    public final void setLeft(int left) {
10541        if (left != mLeft) {
10542            updateMatrix();
10543            final boolean matrixIsIdentity = mTransformationInfo == null
10544                    || mTransformationInfo.mMatrixIsIdentity;
10545            if (matrixIsIdentity) {
10546                if (mAttachInfo != null) {
10547                    int minLeft;
10548                    int xLoc;
10549                    if (left < mLeft) {
10550                        minLeft = left;
10551                        xLoc = left - mLeft;
10552                    } else {
10553                        minLeft = mLeft;
10554                        xLoc = 0;
10555                    }
10556                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10557                }
10558            } else {
10559                // Double-invalidation is necessary to capture view's old and new areas
10560                invalidate(true);
10561            }
10562
10563            int oldWidth = mRight - mLeft;
10564            int height = mBottom - mTop;
10565
10566            mLeft = left;
10567            if (mDisplayList != null) {
10568                mDisplayList.setLeft(left);
10569            }
10570
10571            sizeChange(mRight - mLeft, height, oldWidth, height);
10572
10573            if (!matrixIsIdentity) {
10574                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10575                    // A change in dimension means an auto-centered pivot point changes, too
10576                    mTransformationInfo.mMatrixDirty = true;
10577                }
10578                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10579                invalidate(true);
10580            }
10581            mBackgroundSizeChanged = true;
10582            invalidateParentIfNeeded();
10583            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10584                // View was rejected last time it was drawn by its parent; this may have changed
10585                invalidateParentIfNeeded();
10586            }
10587        }
10588    }
10589
10590    /**
10591     * Right position of this view relative to its parent.
10592     *
10593     * @return The right edge of this view, in pixels.
10594     */
10595    @ViewDebug.CapturedViewProperty
10596    public final int getRight() {
10597        return mRight;
10598    }
10599
10600    /**
10601     * Sets the right position of this view relative to its parent. This method is meant to be called
10602     * by the layout system and should not generally be called otherwise, because the property
10603     * may be changed at any time by the layout.
10604     *
10605     * @param right The bottom of this view, in pixels.
10606     */
10607    public final void setRight(int right) {
10608        if (right != mRight) {
10609            updateMatrix();
10610            final boolean matrixIsIdentity = mTransformationInfo == null
10611                    || mTransformationInfo.mMatrixIsIdentity;
10612            if (matrixIsIdentity) {
10613                if (mAttachInfo != null) {
10614                    int maxRight;
10615                    if (right < mRight) {
10616                        maxRight = mRight;
10617                    } else {
10618                        maxRight = right;
10619                    }
10620                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10621                }
10622            } else {
10623                // Double-invalidation is necessary to capture view's old and new areas
10624                invalidate(true);
10625            }
10626
10627            int oldWidth = mRight - mLeft;
10628            int height = mBottom - mTop;
10629
10630            mRight = right;
10631            if (mDisplayList != null) {
10632                mDisplayList.setRight(mRight);
10633            }
10634
10635            sizeChange(mRight - mLeft, height, oldWidth, height);
10636
10637            if (!matrixIsIdentity) {
10638                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10639                    // A change in dimension means an auto-centered pivot point changes, too
10640                    mTransformationInfo.mMatrixDirty = true;
10641                }
10642                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10643                invalidate(true);
10644            }
10645            mBackgroundSizeChanged = true;
10646            invalidateParentIfNeeded();
10647            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10648                // View was rejected last time it was drawn by its parent; this may have changed
10649                invalidateParentIfNeeded();
10650            }
10651        }
10652    }
10653
10654    /**
10655     * The visual x position of this view, in pixels. This is equivalent to the
10656     * {@link #setTranslationX(float) translationX} property plus the current
10657     * {@link #getLeft() left} property.
10658     *
10659     * @return The visual x position of this view, in pixels.
10660     */
10661    @ViewDebug.ExportedProperty(category = "drawing")
10662    public float getX() {
10663        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10664    }
10665
10666    /**
10667     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10668     * {@link #setTranslationX(float) translationX} property to be the difference between
10669     * the x value passed in and the current {@link #getLeft() left} property.
10670     *
10671     * @param x The visual x position of this view, in pixels.
10672     */
10673    public void setX(float x) {
10674        setTranslationX(x - mLeft);
10675    }
10676
10677    /**
10678     * The visual y position of this view, in pixels. This is equivalent to the
10679     * {@link #setTranslationY(float) translationY} property plus the current
10680     * {@link #getTop() top} property.
10681     *
10682     * @return The visual y position of this view, in pixels.
10683     */
10684    @ViewDebug.ExportedProperty(category = "drawing")
10685    public float getY() {
10686        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10687    }
10688
10689    /**
10690     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10691     * {@link #setTranslationY(float) translationY} property to be the difference between
10692     * the y value passed in and the current {@link #getTop() top} property.
10693     *
10694     * @param y The visual y position of this view, in pixels.
10695     */
10696    public void setY(float y) {
10697        setTranslationY(y - mTop);
10698    }
10699
10700
10701    /**
10702     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10703     * This position is post-layout, in addition to wherever the object's
10704     * layout placed it.
10705     *
10706     * @return The horizontal position of this view relative to its left position, in pixels.
10707     */
10708    @ViewDebug.ExportedProperty(category = "drawing")
10709    public float getTranslationX() {
10710        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10711    }
10712
10713    /**
10714     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10715     * This effectively positions the object post-layout, in addition to wherever the object's
10716     * layout placed it.
10717     *
10718     * @param translationX The horizontal position of this view relative to its left position,
10719     * in pixels.
10720     *
10721     * @attr ref android.R.styleable#View_translationX
10722     */
10723    public void setTranslationX(float translationX) {
10724        ensureTransformationInfo();
10725        final TransformationInfo info = mTransformationInfo;
10726        if (info.mTranslationX != translationX) {
10727            // Double-invalidation is necessary to capture view's old and new areas
10728            invalidateViewProperty(true, false);
10729            info.mTranslationX = translationX;
10730            info.mMatrixDirty = true;
10731            invalidateViewProperty(false, true);
10732            if (mDisplayList != null) {
10733                mDisplayList.setTranslationX(translationX);
10734            }
10735            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10736                // View was rejected last time it was drawn by its parent; this may have changed
10737                invalidateParentIfNeeded();
10738            }
10739        }
10740    }
10741
10742    /**
10743     * The vertical location of this view relative to its {@link #getTop() top} position.
10744     * This position is post-layout, in addition to wherever the object's
10745     * layout placed it.
10746     *
10747     * @return The vertical position of this view relative to its top position,
10748     * in pixels.
10749     */
10750    @ViewDebug.ExportedProperty(category = "drawing")
10751    public float getTranslationY() {
10752        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10753    }
10754
10755    /**
10756     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10757     * This effectively positions the object post-layout, in addition to wherever the object's
10758     * layout placed it.
10759     *
10760     * @param translationY The vertical position of this view relative to its top position,
10761     * in pixels.
10762     *
10763     * @attr ref android.R.styleable#View_translationY
10764     */
10765    public void setTranslationY(float translationY) {
10766        ensureTransformationInfo();
10767        final TransformationInfo info = mTransformationInfo;
10768        if (info.mTranslationY != translationY) {
10769            invalidateViewProperty(true, false);
10770            info.mTranslationY = translationY;
10771            info.mMatrixDirty = true;
10772            invalidateViewProperty(false, true);
10773            if (mDisplayList != null) {
10774                mDisplayList.setTranslationY(translationY);
10775            }
10776            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10777                // View was rejected last time it was drawn by its parent; this may have changed
10778                invalidateParentIfNeeded();
10779            }
10780        }
10781    }
10782
10783    /**
10784     * The depth location of this view relative to its parent.
10785     *
10786     * @return The depth of this view relative to its parent.
10787     */
10788    @ViewDebug.ExportedProperty(category = "drawing")
10789    public float getTranslationZ() {
10790        return mTransformationInfo != null ? mTransformationInfo.mTranslationZ : 0;
10791    }
10792
10793    /**
10794     * Sets the depth location of this view relative to its parent.
10795     *
10796     * @attr ref android.R.styleable#View_translationZ
10797     */
10798    public void setTranslationZ(float translationZ) {
10799        ensureTransformationInfo();
10800        final TransformationInfo info = mTransformationInfo;
10801        if (info.mTranslationZ != translationZ) {
10802            invalidateViewProperty(true, false);
10803            info.mTranslationZ = translationZ;
10804            info.mMatrixDirty = true;
10805            invalidateViewProperty(false, true);
10806            if (mDisplayList != null) {
10807                mDisplayList.setTranslationZ(translationZ);
10808            }
10809            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10810                // View was rejected last time it was drawn by its parent; this may have changed
10811                invalidateParentIfNeeded();
10812            }
10813        }
10814    }
10815
10816    /**
10817     * Copies the Outline of the View into the Path parameter.
10818     * <p>
10819     * If the outline is not set, the parameter Path is set to empty.
10820     *
10821     * @param outline Path into which View's outline will be copied. Must be non-null.
10822     *
10823     * @see #setOutline(Path)
10824     * @see #getClipToOutline()
10825     * @see #setClipToOutline(boolean)
10826     */
10827    public final void getOutline(@NonNull Path outline) {
10828        if (outline == null) {
10829            throw new IllegalArgumentException("Path must be non-null");
10830        }
10831        if (mOutline == null) {
10832            outline.reset();
10833        } else {
10834            outline.set(mOutline);
10835        }
10836    }
10837
10838    /**
10839     * Sets the outline of the view, which defines the shape of the shadow it
10840     * casts, and can used for clipping.
10841     * <p>
10842     * If the outline is not set, or {@link Path#isEmpty()}, shadows will be
10843     * cast from the bounds of the View, and clipToOutline will be ignored.
10844     *
10845     * @param outline The new outline of the view. Must be non-null.
10846     *
10847     * @see #getOutline(Path)
10848     * @see #getClipToOutline()
10849     * @see #setClipToOutline(boolean)
10850     */
10851    public void setOutline(@NonNull Path outline) {
10852        if (outline == null) {
10853            throw new IllegalArgumentException("Path must be non-null");
10854        }
10855        // always copy the path since caller may reuse
10856        if (mOutline == null) {
10857            mOutline = new Path(outline);
10858        } else {
10859            mOutline.set(outline);
10860        }
10861
10862        if (mDisplayList != null) {
10863            mDisplayList.setOutline(outline);
10864        }
10865    }
10866
10867    /**
10868     * Returns whether the outline of the View will be used for clipping.
10869     *
10870     * @see #getOutline(Path)
10871     * @see #setOutline(Path)
10872     */
10873    public final boolean getClipToOutline() {
10874        return ((mPrivateFlags3 & PFLAG3_CLIP_TO_OUTLINE) != 0);
10875    }
10876
10877    /**
10878     * Sets whether the outline of the View will be used for clipping.
10879     * <p>
10880     * The current implementation of outline clipping uses Canvas#clipPath(),
10881     * and thus does not support anti-aliasing, and is expensive in terms of
10882     * graphics performance. Therefore, it is strongly recommended that this
10883     * property only be set temporarily, as in an animation. For the same
10884     * reasons, there is no parallel XML attribute for this property.
10885     * <p>
10886     * If the outline of the view is not set or is empty, no clipping will be
10887     * performed.
10888     *
10889     * @see #getOutline(Path)
10890     * @see #setOutline(Path)
10891     */
10892    public void setClipToOutline(boolean clipToOutline) {
10893        // TODO : Add a fast invalidation here.
10894        if (getClipToOutline() != clipToOutline) {
10895            if (clipToOutline) {
10896                mPrivateFlags3 |= PFLAG3_CLIP_TO_OUTLINE;
10897            } else {
10898                mPrivateFlags3 &= ~PFLAG3_CLIP_TO_OUTLINE;
10899            }
10900            if (mDisplayList != null) {
10901                mDisplayList.setClipToOutline(clipToOutline);
10902            }
10903        }
10904    }
10905
10906    /**
10907     * Returns whether the View will cast shadows when its
10908     * {@link #setTranslationZ(float) z translation} is greater than 0, or it is
10909     * rotated in 3D.
10910     *
10911     * @see #setTranslationZ(float)
10912     * @see #setRotationX(float)
10913     * @see #setRotationY(float)
10914     * @see #setCastsShadow(boolean)
10915     * @attr ref android.R.styleable#View_castsShadow
10916     */
10917    public final boolean getCastsShadow() {
10918        return ((mPrivateFlags3 & PFLAG3_CASTS_SHADOW) != 0);
10919    }
10920
10921    /**
10922     * Set to true to enable this View to cast shadows.
10923     * <p>
10924     * If enabled, and the View has a z translation greater than 0, or is
10925     * rotated in 3D, the shadow will be cast onto the current
10926     * {@link ViewGroup#setIsolatedZVolume(boolean) isolated Z volume},
10927     * at the z = 0 plane.
10928     * <p>
10929     * The shape of the shadow being cast is defined by the
10930     * {@link #setOutline(Path) outline} of the view, or the rectangular bounds
10931     * of the view if the outline is not set or is empty.
10932     *
10933     * @see #setTranslationZ(float)
10934     * @see #getCastsShadow()
10935     * @attr ref android.R.styleable#View_castsShadow
10936     */
10937    public void setCastsShadow(boolean castsShadow) {
10938        // TODO : Add a fast invalidation here.
10939        if (getCastsShadow() != castsShadow) {
10940            if (castsShadow) {
10941                mPrivateFlags3 |= PFLAG3_CASTS_SHADOW;
10942            } else {
10943                mPrivateFlags3 &= ~PFLAG3_CASTS_SHADOW;
10944            }
10945            if (mDisplayList != null) {
10946                mDisplayList.setCastsShadow(castsShadow);
10947            }
10948        }
10949    }
10950
10951    /**
10952     * Returns whether the View will be transformed by the global camera.
10953     *
10954     * @see #setUsesGlobalCamera(boolean)
10955     *
10956     * @hide
10957     */
10958    public final boolean getUsesGlobalCamera() {
10959        return ((mPrivateFlags3 & PFLAG3_USES_GLOBAL_CAMERA) != 0);
10960    }
10961
10962    /**
10963     * Sets whether the View should be transformed by the global camera.
10964     * <p>
10965     * If the view has a Z translation or 3D rotation, perspective from the
10966     * global camera will be applied. This enables an app to transform multiple
10967     * views in 3D with coherent perspective projection among them all.
10968     * <p>
10969     * Setting this to true will cause {@link #setCameraDistance() camera distance}
10970     * to be ignored, as the global camera's position will dictate perspective
10971     * transform.
10972     * <p>
10973     * This should not be used in conjunction with {@link android.graphics.Camera}.
10974     *
10975     * @see #getUsesGlobalCamera()
10976     * @see #setTranslationZ(float)
10977     * @see #setRotationX(float)
10978     * @see #setRotationY(float)
10979     *
10980     * @hide
10981     */
10982    public void setUsesGlobalCamera(boolean usesGlobalCamera) {
10983        // TODO : Add a fast invalidation here.
10984        if (getUsesGlobalCamera() != usesGlobalCamera) {
10985            if (usesGlobalCamera) {
10986                mPrivateFlags3 |= PFLAG3_USES_GLOBAL_CAMERA;
10987            } else {
10988                mPrivateFlags3 &= ~PFLAG3_USES_GLOBAL_CAMERA;
10989            }
10990            if (mDisplayList != null) {
10991                mDisplayList.setUsesGlobalCamera(usesGlobalCamera);
10992            }
10993        }
10994    }
10995
10996    /**
10997     * Hit rectangle in parent's coordinates
10998     *
10999     * @param outRect The hit rectangle of the view.
11000     */
11001    public void getHitRect(Rect outRect) {
11002        updateMatrix();
11003        final TransformationInfo info = mTransformationInfo;
11004        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
11005            outRect.set(mLeft, mTop, mRight, mBottom);
11006        } else {
11007            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11008            tmpRect.set(0, 0, getWidth(), getHeight());
11009            info.mMatrix.mapRect(tmpRect);
11010            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11011                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11012        }
11013    }
11014
11015    /**
11016     * Determines whether the given point, in local coordinates is inside the view.
11017     */
11018    /*package*/ final boolean pointInView(float localX, float localY) {
11019        return localX >= 0 && localX < (mRight - mLeft)
11020                && localY >= 0 && localY < (mBottom - mTop);
11021    }
11022
11023    /**
11024     * Utility method to determine whether the given point, in local coordinates,
11025     * is inside the view, where the area of the view is expanded by the slop factor.
11026     * This method is called while processing touch-move events to determine if the event
11027     * is still within the view.
11028     *
11029     * @hide
11030     */
11031    public boolean pointInView(float localX, float localY, float slop) {
11032        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11033                localY < ((mBottom - mTop) + slop);
11034    }
11035
11036    /**
11037     * When a view has focus and the user navigates away from it, the next view is searched for
11038     * starting from the rectangle filled in by this method.
11039     *
11040     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11041     * of the view.  However, if your view maintains some idea of internal selection,
11042     * such as a cursor, or a selected row or column, you should override this method and
11043     * fill in a more specific rectangle.
11044     *
11045     * @param r The rectangle to fill in, in this view's coordinates.
11046     */
11047    public void getFocusedRect(Rect r) {
11048        getDrawingRect(r);
11049    }
11050
11051    /**
11052     * If some part of this view is not clipped by any of its parents, then
11053     * return that area in r in global (root) coordinates. To convert r to local
11054     * coordinates (without taking possible View rotations into account), offset
11055     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11056     * If the view is completely clipped or translated out, return false.
11057     *
11058     * @param r If true is returned, r holds the global coordinates of the
11059     *        visible portion of this view.
11060     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11061     *        between this view and its root. globalOffet may be null.
11062     * @return true if r is non-empty (i.e. part of the view is visible at the
11063     *         root level.
11064     */
11065    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11066        int width = mRight - mLeft;
11067        int height = mBottom - mTop;
11068        if (width > 0 && height > 0) {
11069            r.set(0, 0, width, height);
11070            if (globalOffset != null) {
11071                globalOffset.set(-mScrollX, -mScrollY);
11072            }
11073            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11074        }
11075        return false;
11076    }
11077
11078    public final boolean getGlobalVisibleRect(Rect r) {
11079        return getGlobalVisibleRect(r, null);
11080    }
11081
11082    public final boolean getLocalVisibleRect(Rect r) {
11083        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11084        if (getGlobalVisibleRect(r, offset)) {
11085            r.offset(-offset.x, -offset.y); // make r local
11086            return true;
11087        }
11088        return false;
11089    }
11090
11091    /**
11092     * Offset this view's vertical location by the specified number of pixels.
11093     *
11094     * @param offset the number of pixels to offset the view by
11095     */
11096    public void offsetTopAndBottom(int offset) {
11097        if (offset != 0) {
11098            updateMatrix();
11099            final boolean matrixIsIdentity = mTransformationInfo == null
11100                    || mTransformationInfo.mMatrixIsIdentity;
11101            if (matrixIsIdentity) {
11102                if (mDisplayList != null) {
11103                    invalidateViewProperty(false, false);
11104                } else {
11105                    final ViewParent p = mParent;
11106                    if (p != null && mAttachInfo != null) {
11107                        final Rect r = mAttachInfo.mTmpInvalRect;
11108                        int minTop;
11109                        int maxBottom;
11110                        int yLoc;
11111                        if (offset < 0) {
11112                            minTop = mTop + offset;
11113                            maxBottom = mBottom;
11114                            yLoc = offset;
11115                        } else {
11116                            minTop = mTop;
11117                            maxBottom = mBottom + offset;
11118                            yLoc = 0;
11119                        }
11120                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11121                        p.invalidateChild(this, r);
11122                    }
11123                }
11124            } else {
11125                invalidateViewProperty(false, false);
11126            }
11127
11128            mTop += offset;
11129            mBottom += offset;
11130            if (mDisplayList != null) {
11131                mDisplayList.offsetTopAndBottom(offset);
11132                invalidateViewProperty(false, false);
11133            } else {
11134                if (!matrixIsIdentity) {
11135                    invalidateViewProperty(false, true);
11136                }
11137                invalidateParentIfNeeded();
11138            }
11139        }
11140    }
11141
11142    /**
11143     * Offset this view's horizontal location by the specified amount of pixels.
11144     *
11145     * @param offset the number of pixels to offset the view by
11146     */
11147    public void offsetLeftAndRight(int offset) {
11148        if (offset != 0) {
11149            updateMatrix();
11150            final boolean matrixIsIdentity = mTransformationInfo == null
11151                    || mTransformationInfo.mMatrixIsIdentity;
11152            if (matrixIsIdentity) {
11153                if (mDisplayList != null) {
11154                    invalidateViewProperty(false, false);
11155                } else {
11156                    final ViewParent p = mParent;
11157                    if (p != null && mAttachInfo != null) {
11158                        final Rect r = mAttachInfo.mTmpInvalRect;
11159                        int minLeft;
11160                        int maxRight;
11161                        if (offset < 0) {
11162                            minLeft = mLeft + offset;
11163                            maxRight = mRight;
11164                        } else {
11165                            minLeft = mLeft;
11166                            maxRight = mRight + offset;
11167                        }
11168                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11169                        p.invalidateChild(this, r);
11170                    }
11171                }
11172            } else {
11173                invalidateViewProperty(false, false);
11174            }
11175
11176            mLeft += offset;
11177            mRight += offset;
11178            if (mDisplayList != null) {
11179                mDisplayList.offsetLeftAndRight(offset);
11180                invalidateViewProperty(false, false);
11181            } else {
11182                if (!matrixIsIdentity) {
11183                    invalidateViewProperty(false, true);
11184                }
11185                invalidateParentIfNeeded();
11186            }
11187        }
11188    }
11189
11190    /**
11191     * Get the LayoutParams associated with this view. All views should have
11192     * layout parameters. These supply parameters to the <i>parent</i> of this
11193     * view specifying how it should be arranged. There are many subclasses of
11194     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11195     * of ViewGroup that are responsible for arranging their children.
11196     *
11197     * This method may return null if this View is not attached to a parent
11198     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11199     * was not invoked successfully. When a View is attached to a parent
11200     * ViewGroup, this method must not return null.
11201     *
11202     * @return The LayoutParams associated with this view, or null if no
11203     *         parameters have been set yet
11204     */
11205    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11206    public ViewGroup.LayoutParams getLayoutParams() {
11207        return mLayoutParams;
11208    }
11209
11210    /**
11211     * Set the layout parameters associated with this view. These supply
11212     * parameters to the <i>parent</i> of this view specifying how it should be
11213     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11214     * correspond to the different subclasses of ViewGroup that are responsible
11215     * for arranging their children.
11216     *
11217     * @param params The layout parameters for this view, cannot be null
11218     */
11219    public void setLayoutParams(ViewGroup.LayoutParams params) {
11220        if (params == null) {
11221            throw new NullPointerException("Layout parameters cannot be null");
11222        }
11223        mLayoutParams = params;
11224        resolveLayoutParams();
11225        if (mParent instanceof ViewGroup) {
11226            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11227        }
11228        requestLayout();
11229    }
11230
11231    /**
11232     * Resolve the layout parameters depending on the resolved layout direction
11233     *
11234     * @hide
11235     */
11236    public void resolveLayoutParams() {
11237        if (mLayoutParams != null) {
11238            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11239        }
11240    }
11241
11242    /**
11243     * Set the scrolled position of your view. This will cause a call to
11244     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11245     * invalidated.
11246     * @param x the x position to scroll to
11247     * @param y the y position to scroll to
11248     */
11249    public void scrollTo(int x, int y) {
11250        if (mScrollX != x || mScrollY != y) {
11251            int oldX = mScrollX;
11252            int oldY = mScrollY;
11253            mScrollX = x;
11254            mScrollY = y;
11255            invalidateParentCaches();
11256            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11257            if (!awakenScrollBars()) {
11258                postInvalidateOnAnimation();
11259            }
11260        }
11261    }
11262
11263    /**
11264     * Move the scrolled position of your view. This will cause a call to
11265     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11266     * invalidated.
11267     * @param x the amount of pixels to scroll by horizontally
11268     * @param y the amount of pixels to scroll by vertically
11269     */
11270    public void scrollBy(int x, int y) {
11271        scrollTo(mScrollX + x, mScrollY + y);
11272    }
11273
11274    /**
11275     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11276     * animation to fade the scrollbars out after a default delay. If a subclass
11277     * provides animated scrolling, the start delay should equal the duration
11278     * of the scrolling animation.</p>
11279     *
11280     * <p>The animation starts only if at least one of the scrollbars is
11281     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11282     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11283     * this method returns true, and false otherwise. If the animation is
11284     * started, this method calls {@link #invalidate()}; in that case the
11285     * caller should not call {@link #invalidate()}.</p>
11286     *
11287     * <p>This method should be invoked every time a subclass directly updates
11288     * the scroll parameters.</p>
11289     *
11290     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11291     * and {@link #scrollTo(int, int)}.</p>
11292     *
11293     * @return true if the animation is played, false otherwise
11294     *
11295     * @see #awakenScrollBars(int)
11296     * @see #scrollBy(int, int)
11297     * @see #scrollTo(int, int)
11298     * @see #isHorizontalScrollBarEnabled()
11299     * @see #isVerticalScrollBarEnabled()
11300     * @see #setHorizontalScrollBarEnabled(boolean)
11301     * @see #setVerticalScrollBarEnabled(boolean)
11302     */
11303    protected boolean awakenScrollBars() {
11304        return mScrollCache != null &&
11305                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11306    }
11307
11308    /**
11309     * Trigger the scrollbars to draw.
11310     * This method differs from awakenScrollBars() only in its default duration.
11311     * initialAwakenScrollBars() will show the scroll bars for longer than
11312     * usual to give the user more of a chance to notice them.
11313     *
11314     * @return true if the animation is played, false otherwise.
11315     */
11316    private boolean initialAwakenScrollBars() {
11317        return mScrollCache != null &&
11318                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11319    }
11320
11321    /**
11322     * <p>
11323     * Trigger the scrollbars to draw. When invoked this method starts an
11324     * animation to fade the scrollbars out after a fixed delay. If a subclass
11325     * provides animated scrolling, the start delay should equal the duration of
11326     * the scrolling animation.
11327     * </p>
11328     *
11329     * <p>
11330     * The animation starts only if at least one of the scrollbars is enabled,
11331     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11332     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11333     * this method returns true, and false otherwise. If the animation is
11334     * started, this method calls {@link #invalidate()}; in that case the caller
11335     * should not call {@link #invalidate()}.
11336     * </p>
11337     *
11338     * <p>
11339     * This method should be invoked everytime a subclass directly updates the
11340     * scroll parameters.
11341     * </p>
11342     *
11343     * @param startDelay the delay, in milliseconds, after which the animation
11344     *        should start; when the delay is 0, the animation starts
11345     *        immediately
11346     * @return true if the animation is played, false otherwise
11347     *
11348     * @see #scrollBy(int, int)
11349     * @see #scrollTo(int, int)
11350     * @see #isHorizontalScrollBarEnabled()
11351     * @see #isVerticalScrollBarEnabled()
11352     * @see #setHorizontalScrollBarEnabled(boolean)
11353     * @see #setVerticalScrollBarEnabled(boolean)
11354     */
11355    protected boolean awakenScrollBars(int startDelay) {
11356        return awakenScrollBars(startDelay, true);
11357    }
11358
11359    /**
11360     * <p>
11361     * Trigger the scrollbars to draw. When invoked this method starts an
11362     * animation to fade the scrollbars out after a fixed delay. If a subclass
11363     * provides animated scrolling, the start delay should equal the duration of
11364     * the scrolling animation.
11365     * </p>
11366     *
11367     * <p>
11368     * The animation starts only if at least one of the scrollbars is enabled,
11369     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11370     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11371     * this method returns true, and false otherwise. If the animation is
11372     * started, this method calls {@link #invalidate()} if the invalidate parameter
11373     * is set to true; in that case the caller
11374     * should not call {@link #invalidate()}.
11375     * </p>
11376     *
11377     * <p>
11378     * This method should be invoked everytime a subclass directly updates the
11379     * scroll parameters.
11380     * </p>
11381     *
11382     * @param startDelay the delay, in milliseconds, after which the animation
11383     *        should start; when the delay is 0, the animation starts
11384     *        immediately
11385     *
11386     * @param invalidate Wheter this method should call invalidate
11387     *
11388     * @return true if the animation is played, false otherwise
11389     *
11390     * @see #scrollBy(int, int)
11391     * @see #scrollTo(int, int)
11392     * @see #isHorizontalScrollBarEnabled()
11393     * @see #isVerticalScrollBarEnabled()
11394     * @see #setHorizontalScrollBarEnabled(boolean)
11395     * @see #setVerticalScrollBarEnabled(boolean)
11396     */
11397    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11398        final ScrollabilityCache scrollCache = mScrollCache;
11399
11400        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11401            return false;
11402        }
11403
11404        if (scrollCache.scrollBar == null) {
11405            scrollCache.scrollBar = new ScrollBarDrawable();
11406        }
11407
11408        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11409
11410            if (invalidate) {
11411                // Invalidate to show the scrollbars
11412                postInvalidateOnAnimation();
11413            }
11414
11415            if (scrollCache.state == ScrollabilityCache.OFF) {
11416                // FIXME: this is copied from WindowManagerService.
11417                // We should get this value from the system when it
11418                // is possible to do so.
11419                final int KEY_REPEAT_FIRST_DELAY = 750;
11420                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11421            }
11422
11423            // Tell mScrollCache when we should start fading. This may
11424            // extend the fade start time if one was already scheduled
11425            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11426            scrollCache.fadeStartTime = fadeStartTime;
11427            scrollCache.state = ScrollabilityCache.ON;
11428
11429            // Schedule our fader to run, unscheduling any old ones first
11430            if (mAttachInfo != null) {
11431                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11432                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11433            }
11434
11435            return true;
11436        }
11437
11438        return false;
11439    }
11440
11441    /**
11442     * Do not invalidate views which are not visible and which are not running an animation. They
11443     * will not get drawn and they should not set dirty flags as if they will be drawn
11444     */
11445    private boolean skipInvalidate() {
11446        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11447                (!(mParent instanceof ViewGroup) ||
11448                        !((ViewGroup) mParent).isViewTransitioning(this));
11449    }
11450    /**
11451     * Mark the area defined by dirty as needing to be drawn. If the view is
11452     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
11453     * in the future. This must be called from a UI thread. To call from a non-UI
11454     * thread, call {@link #postInvalidate()}.
11455     *
11456     * WARNING: This method is destructive to dirty.
11457     * @param dirty the rectangle representing the bounds of the dirty region
11458     */
11459    public void invalidate(Rect dirty) {
11460        if (skipInvalidate()) {
11461            return;
11462        }
11463        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
11464                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
11465                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
11466            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11467            mPrivateFlags |= PFLAG_INVALIDATED;
11468            mPrivateFlags |= PFLAG_DIRTY;
11469            final ViewParent p = mParent;
11470            final AttachInfo ai = mAttachInfo;
11471            if (p != null && ai != null) {
11472                final int scrollX = mScrollX;
11473                final int scrollY = mScrollY;
11474                final Rect r = ai.mTmpInvalRect;
11475                r.set(dirty.left - scrollX, dirty.top - scrollY,
11476                        dirty.right - scrollX, dirty.bottom - scrollY);
11477                mParent.invalidateChild(this, r);
11478            }
11479        }
11480    }
11481
11482    /**
11483     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
11484     * The coordinates of the dirty rect are relative to the view.
11485     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
11486     * will be called at some point in the future. This must be called from
11487     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
11488     * @param l the left position of the dirty region
11489     * @param t the top position of the dirty region
11490     * @param r the right position of the dirty region
11491     * @param b the bottom position of the dirty region
11492     */
11493    public void invalidate(int l, int t, int r, int b) {
11494        if (skipInvalidate()) {
11495            return;
11496        }
11497        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
11498                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
11499                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
11500            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11501            mPrivateFlags |= PFLAG_INVALIDATED;
11502            mPrivateFlags |= PFLAG_DIRTY;
11503            final ViewParent p = mParent;
11504            final AttachInfo ai = mAttachInfo;
11505            if (p != null && ai != null && l < r && t < b) {
11506                final int scrollX = mScrollX;
11507                final int scrollY = mScrollY;
11508                final Rect tmpr = ai.mTmpInvalRect;
11509                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
11510                p.invalidateChild(this, tmpr);
11511            }
11512        }
11513    }
11514
11515    /**
11516     * Invalidate the whole view. If the view is visible,
11517     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11518     * the future. This must be called from a UI thread. To call from a non-UI thread,
11519     * call {@link #postInvalidate()}.
11520     */
11521    public void invalidate() {
11522        invalidate(true);
11523    }
11524
11525    /**
11526     * This is where the invalidate() work actually happens. A full invalidate()
11527     * causes the drawing cache to be invalidated, but this function can be called with
11528     * invalidateCache set to false to skip that invalidation step for cases that do not
11529     * need it (for example, a component that remains at the same dimensions with the same
11530     * content).
11531     *
11532     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
11533     * well. This is usually true for a full invalidate, but may be set to false if the
11534     * View's contents or dimensions have not changed.
11535     */
11536    void invalidate(boolean invalidateCache) {
11537        if (skipInvalidate()) {
11538            return;
11539        }
11540        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
11541                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
11542                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
11543            mLastIsOpaque = isOpaque();
11544            mPrivateFlags &= ~PFLAG_DRAWN;
11545            mPrivateFlags |= PFLAG_DIRTY;
11546            if (invalidateCache) {
11547                mPrivateFlags |= PFLAG_INVALIDATED;
11548                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11549            }
11550            final AttachInfo ai = mAttachInfo;
11551            final ViewParent p = mParent;
11552
11553            if (p != null && ai != null) {
11554                final Rect r = ai.mTmpInvalRect;
11555                r.set(0, 0, mRight - mLeft, mBottom - mTop);
11556                // Don't call invalidate -- we don't want to internally scroll
11557                // our own bounds
11558                p.invalidateChild(this, r);
11559            }
11560        }
11561    }
11562
11563    /**
11564     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11565     * set any flags or handle all of the cases handled by the default invalidation methods.
11566     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11567     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11568     * walk up the hierarchy, transforming the dirty rect as necessary.
11569     *
11570     * The method also handles normal invalidation logic if display list properties are not
11571     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11572     * backup approach, to handle these cases used in the various property-setting methods.
11573     *
11574     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11575     * are not being used in this view
11576     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11577     * list properties are not being used in this view
11578     */
11579    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11580        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
11581            if (invalidateParent) {
11582                invalidateParentCaches();
11583            }
11584            if (forceRedraw) {
11585                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11586            }
11587            invalidate(false);
11588        } else {
11589            final AttachInfo ai = mAttachInfo;
11590            final ViewParent p = mParent;
11591            if (p != null && ai != null) {
11592                final Rect r = ai.mTmpInvalRect;
11593                r.set(0, 0, mRight - mLeft, mBottom - mTop);
11594                if (mParent instanceof ViewGroup) {
11595                    ((ViewGroup) mParent).invalidateChildFast(this, r);
11596                } else {
11597                    mParent.invalidateChild(this, r);
11598                }
11599            }
11600        }
11601    }
11602
11603    /**
11604     * Utility method to transform a given Rect by the current matrix of this view.
11605     */
11606    void transformRect(final Rect rect) {
11607        if (!getMatrix().isIdentity()) {
11608            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11609            boundingRect.set(rect);
11610            getMatrix().mapRect(boundingRect);
11611            rect.set((int) Math.floor(boundingRect.left),
11612                    (int) Math.floor(boundingRect.top),
11613                    (int) Math.ceil(boundingRect.right),
11614                    (int) Math.ceil(boundingRect.bottom));
11615        }
11616    }
11617
11618    /**
11619     * Used to indicate that the parent of this view should clear its caches. This functionality
11620     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11621     * which is necessary when various parent-managed properties of the view change, such as
11622     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11623     * clears the parent caches and does not causes an invalidate event.
11624     *
11625     * @hide
11626     */
11627    protected void invalidateParentCaches() {
11628        if (mParent instanceof View) {
11629            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11630        }
11631    }
11632
11633    /**
11634     * Used to indicate that the parent of this view should be invalidated. This functionality
11635     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11636     * which is necessary when various parent-managed properties of the view change, such as
11637     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11638     * an invalidation event to the parent.
11639     *
11640     * @hide
11641     */
11642    protected void invalidateParentIfNeeded() {
11643        if (isHardwareAccelerated() && mParent instanceof View) {
11644            ((View) mParent).invalidate(true);
11645        }
11646    }
11647
11648    /**
11649     * Indicates whether this View is opaque. An opaque View guarantees that it will
11650     * draw all the pixels overlapping its bounds using a fully opaque color.
11651     *
11652     * Subclasses of View should override this method whenever possible to indicate
11653     * whether an instance is opaque. Opaque Views are treated in a special way by
11654     * the View hierarchy, possibly allowing it to perform optimizations during
11655     * invalidate/draw passes.
11656     *
11657     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11658     */
11659    @ViewDebug.ExportedProperty(category = "drawing")
11660    public boolean isOpaque() {
11661        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11662                getFinalAlpha() >= 1.0f;
11663    }
11664
11665    /**
11666     * @hide
11667     */
11668    protected void computeOpaqueFlags() {
11669        // Opaque if:
11670        //   - Has a background
11671        //   - Background is opaque
11672        //   - Doesn't have scrollbars or scrollbars overlay
11673
11674        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11675            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11676        } else {
11677            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11678        }
11679
11680        final int flags = mViewFlags;
11681        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11682                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11683                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11684            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11685        } else {
11686            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11687        }
11688    }
11689
11690    /**
11691     * @hide
11692     */
11693    protected boolean hasOpaqueScrollbars() {
11694        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11695    }
11696
11697    /**
11698     * @return A handler associated with the thread running the View. This
11699     * handler can be used to pump events in the UI events queue.
11700     */
11701    public Handler getHandler() {
11702        final AttachInfo attachInfo = mAttachInfo;
11703        if (attachInfo != null) {
11704            return attachInfo.mHandler;
11705        }
11706        return null;
11707    }
11708
11709    /**
11710     * Gets the view root associated with the View.
11711     * @return The view root, or null if none.
11712     * @hide
11713     */
11714    public ViewRootImpl getViewRootImpl() {
11715        if (mAttachInfo != null) {
11716            return mAttachInfo.mViewRootImpl;
11717        }
11718        return null;
11719    }
11720
11721    /**
11722     * @hide
11723     */
11724    public HardwareRenderer getHardwareRenderer() {
11725        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11726    }
11727
11728    /**
11729     * <p>Causes the Runnable to be added to the message queue.
11730     * The runnable will be run on the user interface thread.</p>
11731     *
11732     * @param action The Runnable that will be executed.
11733     *
11734     * @return Returns true if the Runnable was successfully placed in to the
11735     *         message queue.  Returns false on failure, usually because the
11736     *         looper processing the message queue is exiting.
11737     *
11738     * @see #postDelayed
11739     * @see #removeCallbacks
11740     */
11741    public boolean post(Runnable action) {
11742        final AttachInfo attachInfo = mAttachInfo;
11743        if (attachInfo != null) {
11744            return attachInfo.mHandler.post(action);
11745        }
11746        // Assume that post will succeed later
11747        ViewRootImpl.getRunQueue().post(action);
11748        return true;
11749    }
11750
11751    /**
11752     * <p>Causes the Runnable to be added to the message queue, to be run
11753     * after the specified amount of time elapses.
11754     * The runnable will be run on the user interface thread.</p>
11755     *
11756     * @param action The Runnable that will be executed.
11757     * @param delayMillis The delay (in milliseconds) until the Runnable
11758     *        will be executed.
11759     *
11760     * @return true if the Runnable was successfully placed in to the
11761     *         message queue.  Returns false on failure, usually because the
11762     *         looper processing the message queue is exiting.  Note that a
11763     *         result of true does not mean the Runnable will be processed --
11764     *         if the looper is quit before the delivery time of the message
11765     *         occurs then the message will be dropped.
11766     *
11767     * @see #post
11768     * @see #removeCallbacks
11769     */
11770    public boolean postDelayed(Runnable action, long delayMillis) {
11771        final AttachInfo attachInfo = mAttachInfo;
11772        if (attachInfo != null) {
11773            return attachInfo.mHandler.postDelayed(action, delayMillis);
11774        }
11775        // Assume that post will succeed later
11776        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11777        return true;
11778    }
11779
11780    /**
11781     * <p>Causes the Runnable to execute on the next animation time step.
11782     * The runnable will be run on the user interface thread.</p>
11783     *
11784     * @param action The Runnable that will be executed.
11785     *
11786     * @see #postOnAnimationDelayed
11787     * @see #removeCallbacks
11788     */
11789    public void postOnAnimation(Runnable action) {
11790        final AttachInfo attachInfo = mAttachInfo;
11791        if (attachInfo != null) {
11792            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11793                    Choreographer.CALLBACK_ANIMATION, action, null);
11794        } else {
11795            // Assume that post will succeed later
11796            ViewRootImpl.getRunQueue().post(action);
11797        }
11798    }
11799
11800    /**
11801     * <p>Causes the Runnable to execute on the next animation time step,
11802     * after the specified amount of time elapses.
11803     * The runnable will be run on the user interface thread.</p>
11804     *
11805     * @param action The Runnable that will be executed.
11806     * @param delayMillis The delay (in milliseconds) until the Runnable
11807     *        will be executed.
11808     *
11809     * @see #postOnAnimation
11810     * @see #removeCallbacks
11811     */
11812    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11813        final AttachInfo attachInfo = mAttachInfo;
11814        if (attachInfo != null) {
11815            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11816                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11817        } else {
11818            // Assume that post will succeed later
11819            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11820        }
11821    }
11822
11823    /**
11824     * <p>Removes the specified Runnable from the message queue.</p>
11825     *
11826     * @param action The Runnable to remove from the message handling queue
11827     *
11828     * @return true if this view could ask the Handler to remove the Runnable,
11829     *         false otherwise. When the returned value is true, the Runnable
11830     *         may or may not have been actually removed from the message queue
11831     *         (for instance, if the Runnable was not in the queue already.)
11832     *
11833     * @see #post
11834     * @see #postDelayed
11835     * @see #postOnAnimation
11836     * @see #postOnAnimationDelayed
11837     */
11838    public boolean removeCallbacks(Runnable action) {
11839        if (action != null) {
11840            final AttachInfo attachInfo = mAttachInfo;
11841            if (attachInfo != null) {
11842                attachInfo.mHandler.removeCallbacks(action);
11843                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11844                        Choreographer.CALLBACK_ANIMATION, action, null);
11845            }
11846            // Assume that post will succeed later
11847            ViewRootImpl.getRunQueue().removeCallbacks(action);
11848        }
11849        return true;
11850    }
11851
11852    /**
11853     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11854     * Use this to invalidate the View from a non-UI thread.</p>
11855     *
11856     * <p>This method can be invoked from outside of the UI thread
11857     * only when this View is attached to a window.</p>
11858     *
11859     * @see #invalidate()
11860     * @see #postInvalidateDelayed(long)
11861     */
11862    public void postInvalidate() {
11863        postInvalidateDelayed(0);
11864    }
11865
11866    /**
11867     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11868     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11869     *
11870     * <p>This method can be invoked from outside of the UI thread
11871     * only when this View is attached to a window.</p>
11872     *
11873     * @param left The left coordinate of the rectangle to invalidate.
11874     * @param top The top coordinate of the rectangle to invalidate.
11875     * @param right The right coordinate of the rectangle to invalidate.
11876     * @param bottom The bottom coordinate of the rectangle to invalidate.
11877     *
11878     * @see #invalidate(int, int, int, int)
11879     * @see #invalidate(Rect)
11880     * @see #postInvalidateDelayed(long, int, int, int, int)
11881     */
11882    public void postInvalidate(int left, int top, int right, int bottom) {
11883        postInvalidateDelayed(0, left, top, right, bottom);
11884    }
11885
11886    /**
11887     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11888     * loop. Waits for the specified amount of time.</p>
11889     *
11890     * <p>This method can be invoked from outside of the UI thread
11891     * only when this View is attached to a window.</p>
11892     *
11893     * @param delayMilliseconds the duration in milliseconds to delay the
11894     *         invalidation by
11895     *
11896     * @see #invalidate()
11897     * @see #postInvalidate()
11898     */
11899    public void postInvalidateDelayed(long delayMilliseconds) {
11900        // We try only with the AttachInfo because there's no point in invalidating
11901        // if we are not attached to our window
11902        final AttachInfo attachInfo = mAttachInfo;
11903        if (attachInfo != null) {
11904            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11905        }
11906    }
11907
11908    /**
11909     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11910     * through the event loop. Waits for the specified amount of time.</p>
11911     *
11912     * <p>This method can be invoked from outside of the UI thread
11913     * only when this View is attached to a window.</p>
11914     *
11915     * @param delayMilliseconds the duration in milliseconds to delay the
11916     *         invalidation by
11917     * @param left The left coordinate of the rectangle to invalidate.
11918     * @param top The top coordinate of the rectangle to invalidate.
11919     * @param right The right coordinate of the rectangle to invalidate.
11920     * @param bottom The bottom coordinate of the rectangle to invalidate.
11921     *
11922     * @see #invalidate(int, int, int, int)
11923     * @see #invalidate(Rect)
11924     * @see #postInvalidate(int, int, int, int)
11925     */
11926    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11927            int right, int bottom) {
11928
11929        // We try only with the AttachInfo because there's no point in invalidating
11930        // if we are not attached to our window
11931        final AttachInfo attachInfo = mAttachInfo;
11932        if (attachInfo != null) {
11933            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11934            info.target = this;
11935            info.left = left;
11936            info.top = top;
11937            info.right = right;
11938            info.bottom = bottom;
11939
11940            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11941        }
11942    }
11943
11944    /**
11945     * <p>Cause an invalidate to happen on the next animation time step, typically the
11946     * next display frame.</p>
11947     *
11948     * <p>This method can be invoked from outside of the UI thread
11949     * only when this View is attached to a window.</p>
11950     *
11951     * @see #invalidate()
11952     */
11953    public void postInvalidateOnAnimation() {
11954        // We try only with the AttachInfo because there's no point in invalidating
11955        // if we are not attached to our window
11956        final AttachInfo attachInfo = mAttachInfo;
11957        if (attachInfo != null) {
11958            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11959        }
11960    }
11961
11962    /**
11963     * <p>Cause an invalidate of the specified area to happen on the next animation
11964     * time step, typically the next display frame.</p>
11965     *
11966     * <p>This method can be invoked from outside of the UI thread
11967     * only when this View is attached to a window.</p>
11968     *
11969     * @param left The left coordinate of the rectangle to invalidate.
11970     * @param top The top coordinate of the rectangle to invalidate.
11971     * @param right The right coordinate of the rectangle to invalidate.
11972     * @param bottom The bottom coordinate of the rectangle to invalidate.
11973     *
11974     * @see #invalidate(int, int, int, int)
11975     * @see #invalidate(Rect)
11976     */
11977    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11978        // We try only with the AttachInfo because there's no point in invalidating
11979        // if we are not attached to our window
11980        final AttachInfo attachInfo = mAttachInfo;
11981        if (attachInfo != null) {
11982            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11983            info.target = this;
11984            info.left = left;
11985            info.top = top;
11986            info.right = right;
11987            info.bottom = bottom;
11988
11989            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11990        }
11991    }
11992
11993    /**
11994     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11995     * This event is sent at most once every
11996     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11997     */
11998    private void postSendViewScrolledAccessibilityEventCallback() {
11999        if (mSendViewScrolledAccessibilityEvent == null) {
12000            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12001        }
12002        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12003            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12004            postDelayed(mSendViewScrolledAccessibilityEvent,
12005                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12006        }
12007    }
12008
12009    /**
12010     * Called by a parent to request that a child update its values for mScrollX
12011     * and mScrollY if necessary. This will typically be done if the child is
12012     * animating a scroll using a {@link android.widget.Scroller Scroller}
12013     * object.
12014     */
12015    public void computeScroll() {
12016    }
12017
12018    /**
12019     * <p>Indicate whether the horizontal edges are faded when the view is
12020     * scrolled horizontally.</p>
12021     *
12022     * @return true if the horizontal edges should are faded on scroll, false
12023     *         otherwise
12024     *
12025     * @see #setHorizontalFadingEdgeEnabled(boolean)
12026     *
12027     * @attr ref android.R.styleable#View_requiresFadingEdge
12028     */
12029    public boolean isHorizontalFadingEdgeEnabled() {
12030        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12031    }
12032
12033    /**
12034     * <p>Define whether the horizontal edges should be faded when this view
12035     * is scrolled horizontally.</p>
12036     *
12037     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12038     *                                    be faded when the view is scrolled
12039     *                                    horizontally
12040     *
12041     * @see #isHorizontalFadingEdgeEnabled()
12042     *
12043     * @attr ref android.R.styleable#View_requiresFadingEdge
12044     */
12045    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12046        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12047            if (horizontalFadingEdgeEnabled) {
12048                initScrollCache();
12049            }
12050
12051            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12052        }
12053    }
12054
12055    /**
12056     * <p>Indicate whether the vertical edges are faded when the view is
12057     * scrolled horizontally.</p>
12058     *
12059     * @return true if the vertical edges should are faded on scroll, false
12060     *         otherwise
12061     *
12062     * @see #setVerticalFadingEdgeEnabled(boolean)
12063     *
12064     * @attr ref android.R.styleable#View_requiresFadingEdge
12065     */
12066    public boolean isVerticalFadingEdgeEnabled() {
12067        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12068    }
12069
12070    /**
12071     * <p>Define whether the vertical edges should be faded when this view
12072     * is scrolled vertically.</p>
12073     *
12074     * @param verticalFadingEdgeEnabled true if the vertical edges should
12075     *                                  be faded when the view is scrolled
12076     *                                  vertically
12077     *
12078     * @see #isVerticalFadingEdgeEnabled()
12079     *
12080     * @attr ref android.R.styleable#View_requiresFadingEdge
12081     */
12082    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12083        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12084            if (verticalFadingEdgeEnabled) {
12085                initScrollCache();
12086            }
12087
12088            mViewFlags ^= FADING_EDGE_VERTICAL;
12089        }
12090    }
12091
12092    /**
12093     * Returns the strength, or intensity, of the top faded edge. The strength is
12094     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12095     * returns 0.0 or 1.0 but no value in between.
12096     *
12097     * Subclasses should override this method to provide a smoother fade transition
12098     * when scrolling occurs.
12099     *
12100     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12101     */
12102    protected float getTopFadingEdgeStrength() {
12103        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12104    }
12105
12106    /**
12107     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12108     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12109     * returns 0.0 or 1.0 but no value in between.
12110     *
12111     * Subclasses should override this method to provide a smoother fade transition
12112     * when scrolling occurs.
12113     *
12114     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12115     */
12116    protected float getBottomFadingEdgeStrength() {
12117        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12118                computeVerticalScrollRange() ? 1.0f : 0.0f;
12119    }
12120
12121    /**
12122     * Returns the strength, or intensity, of the left faded edge. The strength is
12123     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12124     * returns 0.0 or 1.0 but no value in between.
12125     *
12126     * Subclasses should override this method to provide a smoother fade transition
12127     * when scrolling occurs.
12128     *
12129     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12130     */
12131    protected float getLeftFadingEdgeStrength() {
12132        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12133    }
12134
12135    /**
12136     * Returns the strength, or intensity, of the right faded edge. The strength is
12137     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12138     * returns 0.0 or 1.0 but no value in between.
12139     *
12140     * Subclasses should override this method to provide a smoother fade transition
12141     * when scrolling occurs.
12142     *
12143     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12144     */
12145    protected float getRightFadingEdgeStrength() {
12146        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12147                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12148    }
12149
12150    /**
12151     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12152     * scrollbar is not drawn by default.</p>
12153     *
12154     * @return true if the horizontal scrollbar should be painted, false
12155     *         otherwise
12156     *
12157     * @see #setHorizontalScrollBarEnabled(boolean)
12158     */
12159    public boolean isHorizontalScrollBarEnabled() {
12160        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12161    }
12162
12163    /**
12164     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12165     * scrollbar is not drawn by default.</p>
12166     *
12167     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12168     *                                   be painted
12169     *
12170     * @see #isHorizontalScrollBarEnabled()
12171     */
12172    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12173        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12174            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12175            computeOpaqueFlags();
12176            resolvePadding();
12177        }
12178    }
12179
12180    /**
12181     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12182     * scrollbar is not drawn by default.</p>
12183     *
12184     * @return true if the vertical scrollbar should be painted, false
12185     *         otherwise
12186     *
12187     * @see #setVerticalScrollBarEnabled(boolean)
12188     */
12189    public boolean isVerticalScrollBarEnabled() {
12190        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12191    }
12192
12193    /**
12194     * <p>Define whether the vertical scrollbar should be drawn or not. The
12195     * scrollbar is not drawn by default.</p>
12196     *
12197     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12198     *                                 be painted
12199     *
12200     * @see #isVerticalScrollBarEnabled()
12201     */
12202    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12203        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12204            mViewFlags ^= SCROLLBARS_VERTICAL;
12205            computeOpaqueFlags();
12206            resolvePadding();
12207        }
12208    }
12209
12210    /**
12211     * @hide
12212     */
12213    protected void recomputePadding() {
12214        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12215    }
12216
12217    /**
12218     * Define whether scrollbars will fade when the view is not scrolling.
12219     *
12220     * @param fadeScrollbars wheter to enable fading
12221     *
12222     * @attr ref android.R.styleable#View_fadeScrollbars
12223     */
12224    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12225        initScrollCache();
12226        final ScrollabilityCache scrollabilityCache = mScrollCache;
12227        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12228        if (fadeScrollbars) {
12229            scrollabilityCache.state = ScrollabilityCache.OFF;
12230        } else {
12231            scrollabilityCache.state = ScrollabilityCache.ON;
12232        }
12233    }
12234
12235    /**
12236     *
12237     * Returns true if scrollbars will fade when this view is not scrolling
12238     *
12239     * @return true if scrollbar fading is enabled
12240     *
12241     * @attr ref android.R.styleable#View_fadeScrollbars
12242     */
12243    public boolean isScrollbarFadingEnabled() {
12244        return mScrollCache != null && mScrollCache.fadeScrollBars;
12245    }
12246
12247    /**
12248     *
12249     * Returns the delay before scrollbars fade.
12250     *
12251     * @return the delay before scrollbars fade
12252     *
12253     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12254     */
12255    public int getScrollBarDefaultDelayBeforeFade() {
12256        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12257                mScrollCache.scrollBarDefaultDelayBeforeFade;
12258    }
12259
12260    /**
12261     * Define the delay before scrollbars fade.
12262     *
12263     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12264     *
12265     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12266     */
12267    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12268        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12269    }
12270
12271    /**
12272     *
12273     * Returns the scrollbar fade duration.
12274     *
12275     * @return the scrollbar fade duration
12276     *
12277     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12278     */
12279    public int getScrollBarFadeDuration() {
12280        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12281                mScrollCache.scrollBarFadeDuration;
12282    }
12283
12284    /**
12285     * Define the scrollbar fade duration.
12286     *
12287     * @param scrollBarFadeDuration - the scrollbar fade duration
12288     *
12289     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12290     */
12291    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12292        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12293    }
12294
12295    /**
12296     *
12297     * Returns the scrollbar size.
12298     *
12299     * @return the scrollbar size
12300     *
12301     * @attr ref android.R.styleable#View_scrollbarSize
12302     */
12303    public int getScrollBarSize() {
12304        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12305                mScrollCache.scrollBarSize;
12306    }
12307
12308    /**
12309     * Define the scrollbar size.
12310     *
12311     * @param scrollBarSize - the scrollbar size
12312     *
12313     * @attr ref android.R.styleable#View_scrollbarSize
12314     */
12315    public void setScrollBarSize(int scrollBarSize) {
12316        getScrollCache().scrollBarSize = scrollBarSize;
12317    }
12318
12319    /**
12320     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12321     * inset. When inset, they add to the padding of the view. And the scrollbars
12322     * can be drawn inside the padding area or on the edge of the view. For example,
12323     * if a view has a background drawable and you want to draw the scrollbars
12324     * inside the padding specified by the drawable, you can use
12325     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12326     * appear at the edge of the view, ignoring the padding, then you can use
12327     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12328     * @param style the style of the scrollbars. Should be one of
12329     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12330     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12331     * @see #SCROLLBARS_INSIDE_OVERLAY
12332     * @see #SCROLLBARS_INSIDE_INSET
12333     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12334     * @see #SCROLLBARS_OUTSIDE_INSET
12335     *
12336     * @attr ref android.R.styleable#View_scrollbarStyle
12337     */
12338    public void setScrollBarStyle(@ScrollBarStyle int style) {
12339        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12340            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12341            computeOpaqueFlags();
12342            resolvePadding();
12343        }
12344    }
12345
12346    /**
12347     * <p>Returns the current scrollbar style.</p>
12348     * @return the current scrollbar style
12349     * @see #SCROLLBARS_INSIDE_OVERLAY
12350     * @see #SCROLLBARS_INSIDE_INSET
12351     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12352     * @see #SCROLLBARS_OUTSIDE_INSET
12353     *
12354     * @attr ref android.R.styleable#View_scrollbarStyle
12355     */
12356    @ViewDebug.ExportedProperty(mapping = {
12357            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12358            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12359            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12360            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12361    })
12362    @ScrollBarStyle
12363    public int getScrollBarStyle() {
12364        return mViewFlags & SCROLLBARS_STYLE_MASK;
12365    }
12366
12367    /**
12368     * <p>Compute the horizontal range that the horizontal scrollbar
12369     * represents.</p>
12370     *
12371     * <p>The range is expressed in arbitrary units that must be the same as the
12372     * units used by {@link #computeHorizontalScrollExtent()} and
12373     * {@link #computeHorizontalScrollOffset()}.</p>
12374     *
12375     * <p>The default range is the drawing width of this view.</p>
12376     *
12377     * @return the total horizontal range represented by the horizontal
12378     *         scrollbar
12379     *
12380     * @see #computeHorizontalScrollExtent()
12381     * @see #computeHorizontalScrollOffset()
12382     * @see android.widget.ScrollBarDrawable
12383     */
12384    protected int computeHorizontalScrollRange() {
12385        return getWidth();
12386    }
12387
12388    /**
12389     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12390     * within the horizontal range. This value is used to compute the position
12391     * of the thumb within the scrollbar's track.</p>
12392     *
12393     * <p>The range is expressed in arbitrary units that must be the same as the
12394     * units used by {@link #computeHorizontalScrollRange()} and
12395     * {@link #computeHorizontalScrollExtent()}.</p>
12396     *
12397     * <p>The default offset is the scroll offset of this view.</p>
12398     *
12399     * @return the horizontal offset of the scrollbar's thumb
12400     *
12401     * @see #computeHorizontalScrollRange()
12402     * @see #computeHorizontalScrollExtent()
12403     * @see android.widget.ScrollBarDrawable
12404     */
12405    protected int computeHorizontalScrollOffset() {
12406        return mScrollX;
12407    }
12408
12409    /**
12410     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12411     * within the horizontal range. This value is used to compute the length
12412     * of the thumb within the scrollbar's track.</p>
12413     *
12414     * <p>The range is expressed in arbitrary units that must be the same as the
12415     * units used by {@link #computeHorizontalScrollRange()} and
12416     * {@link #computeHorizontalScrollOffset()}.</p>
12417     *
12418     * <p>The default extent is the drawing width of this view.</p>
12419     *
12420     * @return the horizontal extent of the scrollbar's thumb
12421     *
12422     * @see #computeHorizontalScrollRange()
12423     * @see #computeHorizontalScrollOffset()
12424     * @see android.widget.ScrollBarDrawable
12425     */
12426    protected int computeHorizontalScrollExtent() {
12427        return getWidth();
12428    }
12429
12430    /**
12431     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12432     *
12433     * <p>The range is expressed in arbitrary units that must be the same as the
12434     * units used by {@link #computeVerticalScrollExtent()} and
12435     * {@link #computeVerticalScrollOffset()}.</p>
12436     *
12437     * @return the total vertical range represented by the vertical scrollbar
12438     *
12439     * <p>The default range is the drawing height of this view.</p>
12440     *
12441     * @see #computeVerticalScrollExtent()
12442     * @see #computeVerticalScrollOffset()
12443     * @see android.widget.ScrollBarDrawable
12444     */
12445    protected int computeVerticalScrollRange() {
12446        return getHeight();
12447    }
12448
12449    /**
12450     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12451     * within the horizontal range. This value is used to compute the position
12452     * of the thumb within the scrollbar's track.</p>
12453     *
12454     * <p>The range is expressed in arbitrary units that must be the same as the
12455     * units used by {@link #computeVerticalScrollRange()} and
12456     * {@link #computeVerticalScrollExtent()}.</p>
12457     *
12458     * <p>The default offset is the scroll offset of this view.</p>
12459     *
12460     * @return the vertical offset of the scrollbar's thumb
12461     *
12462     * @see #computeVerticalScrollRange()
12463     * @see #computeVerticalScrollExtent()
12464     * @see android.widget.ScrollBarDrawable
12465     */
12466    protected int computeVerticalScrollOffset() {
12467        return mScrollY;
12468    }
12469
12470    /**
12471     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
12472     * within the vertical range. This value is used to compute the length
12473     * of the thumb within the scrollbar's track.</p>
12474     *
12475     * <p>The range is expressed in arbitrary units that must be the same as the
12476     * units used by {@link #computeVerticalScrollRange()} and
12477     * {@link #computeVerticalScrollOffset()}.</p>
12478     *
12479     * <p>The default extent is the drawing height of this view.</p>
12480     *
12481     * @return the vertical extent of the scrollbar's thumb
12482     *
12483     * @see #computeVerticalScrollRange()
12484     * @see #computeVerticalScrollOffset()
12485     * @see android.widget.ScrollBarDrawable
12486     */
12487    protected int computeVerticalScrollExtent() {
12488        return getHeight();
12489    }
12490
12491    /**
12492     * Check if this view can be scrolled horizontally in a certain direction.
12493     *
12494     * @param direction Negative to check scrolling left, positive to check scrolling right.
12495     * @return true if this view can be scrolled in the specified direction, false otherwise.
12496     */
12497    public boolean canScrollHorizontally(int direction) {
12498        final int offset = computeHorizontalScrollOffset();
12499        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12500        if (range == 0) return false;
12501        if (direction < 0) {
12502            return offset > 0;
12503        } else {
12504            return offset < range - 1;
12505        }
12506    }
12507
12508    /**
12509     * Check if this view can be scrolled vertically in a certain direction.
12510     *
12511     * @param direction Negative to check scrolling up, positive to check scrolling down.
12512     * @return true if this view can be scrolled in the specified direction, false otherwise.
12513     */
12514    public boolean canScrollVertically(int direction) {
12515        final int offset = computeVerticalScrollOffset();
12516        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12517        if (range == 0) return false;
12518        if (direction < 0) {
12519            return offset > 0;
12520        } else {
12521            return offset < range - 1;
12522        }
12523    }
12524
12525    /**
12526     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12527     * scrollbars are painted only if they have been awakened first.</p>
12528     *
12529     * @param canvas the canvas on which to draw the scrollbars
12530     *
12531     * @see #awakenScrollBars(int)
12532     */
12533    protected final void onDrawScrollBars(Canvas canvas) {
12534        // scrollbars are drawn only when the animation is running
12535        final ScrollabilityCache cache = mScrollCache;
12536        if (cache != null) {
12537
12538            int state = cache.state;
12539
12540            if (state == ScrollabilityCache.OFF) {
12541                return;
12542            }
12543
12544            boolean invalidate = false;
12545
12546            if (state == ScrollabilityCache.FADING) {
12547                // We're fading -- get our fade interpolation
12548                if (cache.interpolatorValues == null) {
12549                    cache.interpolatorValues = new float[1];
12550                }
12551
12552                float[] values = cache.interpolatorValues;
12553
12554                // Stops the animation if we're done
12555                if (cache.scrollBarInterpolator.timeToValues(values) ==
12556                        Interpolator.Result.FREEZE_END) {
12557                    cache.state = ScrollabilityCache.OFF;
12558                } else {
12559                    cache.scrollBar.setAlpha(Math.round(values[0]));
12560                }
12561
12562                // This will make the scroll bars inval themselves after
12563                // drawing. We only want this when we're fading so that
12564                // we prevent excessive redraws
12565                invalidate = true;
12566            } else {
12567                // We're just on -- but we may have been fading before so
12568                // reset alpha
12569                cache.scrollBar.setAlpha(255);
12570            }
12571
12572
12573            final int viewFlags = mViewFlags;
12574
12575            final boolean drawHorizontalScrollBar =
12576                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12577            final boolean drawVerticalScrollBar =
12578                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12579                && !isVerticalScrollBarHidden();
12580
12581            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12582                final int width = mRight - mLeft;
12583                final int height = mBottom - mTop;
12584
12585                final ScrollBarDrawable scrollBar = cache.scrollBar;
12586
12587                final int scrollX = mScrollX;
12588                final int scrollY = mScrollY;
12589                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12590
12591                int left;
12592                int top;
12593                int right;
12594                int bottom;
12595
12596                if (drawHorizontalScrollBar) {
12597                    int size = scrollBar.getSize(false);
12598                    if (size <= 0) {
12599                        size = cache.scrollBarSize;
12600                    }
12601
12602                    scrollBar.setParameters(computeHorizontalScrollRange(),
12603                                            computeHorizontalScrollOffset(),
12604                                            computeHorizontalScrollExtent(), false);
12605                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12606                            getVerticalScrollbarWidth() : 0;
12607                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12608                    left = scrollX + (mPaddingLeft & inside);
12609                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12610                    bottom = top + size;
12611                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12612                    if (invalidate) {
12613                        invalidate(left, top, right, bottom);
12614                    }
12615                }
12616
12617                if (drawVerticalScrollBar) {
12618                    int size = scrollBar.getSize(true);
12619                    if (size <= 0) {
12620                        size = cache.scrollBarSize;
12621                    }
12622
12623                    scrollBar.setParameters(computeVerticalScrollRange(),
12624                                            computeVerticalScrollOffset(),
12625                                            computeVerticalScrollExtent(), true);
12626                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12627                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12628                        verticalScrollbarPosition = isLayoutRtl() ?
12629                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12630                    }
12631                    switch (verticalScrollbarPosition) {
12632                        default:
12633                        case SCROLLBAR_POSITION_RIGHT:
12634                            left = scrollX + width - size - (mUserPaddingRight & inside);
12635                            break;
12636                        case SCROLLBAR_POSITION_LEFT:
12637                            left = scrollX + (mUserPaddingLeft & inside);
12638                            break;
12639                    }
12640                    top = scrollY + (mPaddingTop & inside);
12641                    right = left + size;
12642                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12643                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12644                    if (invalidate) {
12645                        invalidate(left, top, right, bottom);
12646                    }
12647                }
12648            }
12649        }
12650    }
12651
12652    /**
12653     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12654     * FastScroller is visible.
12655     * @return whether to temporarily hide the vertical scrollbar
12656     * @hide
12657     */
12658    protected boolean isVerticalScrollBarHidden() {
12659        return false;
12660    }
12661
12662    /**
12663     * <p>Draw the horizontal scrollbar if
12664     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12665     *
12666     * @param canvas the canvas on which to draw the scrollbar
12667     * @param scrollBar the scrollbar's drawable
12668     *
12669     * @see #isHorizontalScrollBarEnabled()
12670     * @see #computeHorizontalScrollRange()
12671     * @see #computeHorizontalScrollExtent()
12672     * @see #computeHorizontalScrollOffset()
12673     * @see android.widget.ScrollBarDrawable
12674     * @hide
12675     */
12676    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12677            int l, int t, int r, int b) {
12678        scrollBar.setBounds(l, t, r, b);
12679        scrollBar.draw(canvas);
12680    }
12681
12682    /**
12683     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12684     * returns true.</p>
12685     *
12686     * @param canvas the canvas on which to draw the scrollbar
12687     * @param scrollBar the scrollbar's drawable
12688     *
12689     * @see #isVerticalScrollBarEnabled()
12690     * @see #computeVerticalScrollRange()
12691     * @see #computeVerticalScrollExtent()
12692     * @see #computeVerticalScrollOffset()
12693     * @see android.widget.ScrollBarDrawable
12694     * @hide
12695     */
12696    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12697            int l, int t, int r, int b) {
12698        scrollBar.setBounds(l, t, r, b);
12699        scrollBar.draw(canvas);
12700    }
12701
12702    /**
12703     * Implement this to do your drawing.
12704     *
12705     * @param canvas the canvas on which the background will be drawn
12706     */
12707    protected void onDraw(Canvas canvas) {
12708    }
12709
12710    /*
12711     * Caller is responsible for calling requestLayout if necessary.
12712     * (This allows addViewInLayout to not request a new layout.)
12713     */
12714    void assignParent(ViewParent parent) {
12715        if (mParent == null) {
12716            mParent = parent;
12717        } else if (parent == null) {
12718            mParent = null;
12719        } else {
12720            throw new RuntimeException("view " + this + " being added, but"
12721                    + " it already has a parent");
12722        }
12723    }
12724
12725    /**
12726     * This is called when the view is attached to a window.  At this point it
12727     * has a Surface and will start drawing.  Note that this function is
12728     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12729     * however it may be called any time before the first onDraw -- including
12730     * before or after {@link #onMeasure(int, int)}.
12731     *
12732     * @see #onDetachedFromWindow()
12733     */
12734    protected void onAttachedToWindow() {
12735        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12736            mParent.requestTransparentRegion(this);
12737        }
12738
12739        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12740            initialAwakenScrollBars();
12741            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12742        }
12743
12744        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12745
12746        jumpDrawablesToCurrentState();
12747
12748        resetSubtreeAccessibilityStateChanged();
12749
12750        if (isFocused()) {
12751            InputMethodManager imm = InputMethodManager.peekInstance();
12752            imm.focusIn(this);
12753        }
12754
12755        if (mDisplayList != null) {
12756            mDisplayList.clearDirty();
12757        }
12758
12759        if (mBackgroundDisplayList != null) {
12760            mBackgroundDisplayList.clearDirty();
12761        }
12762    }
12763
12764    /**
12765     * Resolve all RTL related properties.
12766     *
12767     * @return true if resolution of RTL properties has been done
12768     *
12769     * @hide
12770     */
12771    public boolean resolveRtlPropertiesIfNeeded() {
12772        if (!needRtlPropertiesResolution()) return false;
12773
12774        // Order is important here: LayoutDirection MUST be resolved first
12775        if (!isLayoutDirectionResolved()) {
12776            resolveLayoutDirection();
12777            resolveLayoutParams();
12778        }
12779        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12780        if (!isTextDirectionResolved()) {
12781            resolveTextDirection();
12782        }
12783        if (!isTextAlignmentResolved()) {
12784            resolveTextAlignment();
12785        }
12786        // Should resolve Drawables before Padding because we need the layout direction of the
12787        // Drawable to correctly resolve Padding.
12788        if (!isDrawablesResolved()) {
12789            resolveDrawables();
12790        }
12791        if (!isPaddingResolved()) {
12792            resolvePadding();
12793        }
12794        onRtlPropertiesChanged(getLayoutDirection());
12795        return true;
12796    }
12797
12798    /**
12799     * Reset resolution of all RTL related properties.
12800     *
12801     * @hide
12802     */
12803    public void resetRtlProperties() {
12804        resetResolvedLayoutDirection();
12805        resetResolvedTextDirection();
12806        resetResolvedTextAlignment();
12807        resetResolvedPadding();
12808        resetResolvedDrawables();
12809    }
12810
12811    /**
12812     * @see #onScreenStateChanged(int)
12813     */
12814    void dispatchScreenStateChanged(int screenState) {
12815        onScreenStateChanged(screenState);
12816    }
12817
12818    /**
12819     * This method is called whenever the state of the screen this view is
12820     * attached to changes. A state change will usually occurs when the screen
12821     * turns on or off (whether it happens automatically or the user does it
12822     * manually.)
12823     *
12824     * @param screenState The new state of the screen. Can be either
12825     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12826     */
12827    public void onScreenStateChanged(int screenState) {
12828    }
12829
12830    /**
12831     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12832     */
12833    private boolean hasRtlSupport() {
12834        return mContext.getApplicationInfo().hasRtlSupport();
12835    }
12836
12837    /**
12838     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12839     * RTL not supported)
12840     */
12841    private boolean isRtlCompatibilityMode() {
12842        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12843        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12844    }
12845
12846    /**
12847     * @return true if RTL properties need resolution.
12848     *
12849     */
12850    private boolean needRtlPropertiesResolution() {
12851        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12852    }
12853
12854    /**
12855     * Called when any RTL property (layout direction or text direction or text alignment) has
12856     * been changed.
12857     *
12858     * Subclasses need to override this method to take care of cached information that depends on the
12859     * resolved layout direction, or to inform child views that inherit their layout direction.
12860     *
12861     * The default implementation does nothing.
12862     *
12863     * @param layoutDirection the direction of the layout
12864     *
12865     * @see #LAYOUT_DIRECTION_LTR
12866     * @see #LAYOUT_DIRECTION_RTL
12867     */
12868    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12869    }
12870
12871    /**
12872     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12873     * that the parent directionality can and will be resolved before its children.
12874     *
12875     * @return true if resolution has been done, false otherwise.
12876     *
12877     * @hide
12878     */
12879    public boolean resolveLayoutDirection() {
12880        // Clear any previous layout direction resolution
12881        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12882
12883        if (hasRtlSupport()) {
12884            // Set resolved depending on layout direction
12885            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12886                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12887                case LAYOUT_DIRECTION_INHERIT:
12888                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12889                    // later to get the correct resolved value
12890                    if (!canResolveLayoutDirection()) return false;
12891
12892                    // Parent has not yet resolved, LTR is still the default
12893                    try {
12894                        if (!mParent.isLayoutDirectionResolved()) return false;
12895
12896                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12897                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12898                        }
12899                    } catch (AbstractMethodError e) {
12900                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12901                                " does not fully implement ViewParent", e);
12902                    }
12903                    break;
12904                case LAYOUT_DIRECTION_RTL:
12905                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12906                    break;
12907                case LAYOUT_DIRECTION_LOCALE:
12908                    if((LAYOUT_DIRECTION_RTL ==
12909                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12910                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12911                    }
12912                    break;
12913                default:
12914                    // Nothing to do, LTR by default
12915            }
12916        }
12917
12918        // Set to resolved
12919        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12920        return true;
12921    }
12922
12923    /**
12924     * Check if layout direction resolution can be done.
12925     *
12926     * @return true if layout direction resolution can be done otherwise return false.
12927     */
12928    public boolean canResolveLayoutDirection() {
12929        switch (getRawLayoutDirection()) {
12930            case LAYOUT_DIRECTION_INHERIT:
12931                if (mParent != null) {
12932                    try {
12933                        return mParent.canResolveLayoutDirection();
12934                    } catch (AbstractMethodError e) {
12935                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12936                                " does not fully implement ViewParent", e);
12937                    }
12938                }
12939                return false;
12940
12941            default:
12942                return true;
12943        }
12944    }
12945
12946    /**
12947     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12948     * {@link #onMeasure(int, int)}.
12949     *
12950     * @hide
12951     */
12952    public void resetResolvedLayoutDirection() {
12953        // Reset the current resolved bits
12954        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12955    }
12956
12957    /**
12958     * @return true if the layout direction is inherited.
12959     *
12960     * @hide
12961     */
12962    public boolean isLayoutDirectionInherited() {
12963        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12964    }
12965
12966    /**
12967     * @return true if layout direction has been resolved.
12968     */
12969    public boolean isLayoutDirectionResolved() {
12970        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12971    }
12972
12973    /**
12974     * Return if padding has been resolved
12975     *
12976     * @hide
12977     */
12978    boolean isPaddingResolved() {
12979        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12980    }
12981
12982    /**
12983     * Resolves padding depending on layout direction, if applicable, and
12984     * recomputes internal padding values to adjust for scroll bars.
12985     *
12986     * @hide
12987     */
12988    public void resolvePadding() {
12989        final int resolvedLayoutDirection = getLayoutDirection();
12990
12991        if (!isRtlCompatibilityMode()) {
12992            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12993            // If start / end padding are defined, they will be resolved (hence overriding) to
12994            // left / right or right / left depending on the resolved layout direction.
12995            // If start / end padding are not defined, use the left / right ones.
12996            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12997                Rect padding = sThreadLocal.get();
12998                if (padding == null) {
12999                    padding = new Rect();
13000                    sThreadLocal.set(padding);
13001                }
13002                mBackground.getPadding(padding);
13003                if (!mLeftPaddingDefined) {
13004                    mUserPaddingLeftInitial = padding.left;
13005                }
13006                if (!mRightPaddingDefined) {
13007                    mUserPaddingRightInitial = padding.right;
13008                }
13009            }
13010            switch (resolvedLayoutDirection) {
13011                case LAYOUT_DIRECTION_RTL:
13012                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13013                        mUserPaddingRight = mUserPaddingStart;
13014                    } else {
13015                        mUserPaddingRight = mUserPaddingRightInitial;
13016                    }
13017                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13018                        mUserPaddingLeft = mUserPaddingEnd;
13019                    } else {
13020                        mUserPaddingLeft = mUserPaddingLeftInitial;
13021                    }
13022                    break;
13023                case LAYOUT_DIRECTION_LTR:
13024                default:
13025                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13026                        mUserPaddingLeft = mUserPaddingStart;
13027                    } else {
13028                        mUserPaddingLeft = mUserPaddingLeftInitial;
13029                    }
13030                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13031                        mUserPaddingRight = mUserPaddingEnd;
13032                    } else {
13033                        mUserPaddingRight = mUserPaddingRightInitial;
13034                    }
13035            }
13036
13037            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13038        }
13039
13040        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13041        onRtlPropertiesChanged(resolvedLayoutDirection);
13042
13043        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13044    }
13045
13046    /**
13047     * Reset the resolved layout direction.
13048     *
13049     * @hide
13050     */
13051    public void resetResolvedPadding() {
13052        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13053    }
13054
13055    /**
13056     * This is called when the view is detached from a window.  At this point it
13057     * no longer has a surface for drawing.
13058     *
13059     * @see #onAttachedToWindow()
13060     */
13061    protected void onDetachedFromWindow() {
13062        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13063        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13064
13065        removeUnsetPressCallback();
13066        removeLongPressCallback();
13067        removePerformClickCallback();
13068        removeSendViewScrolledAccessibilityEventCallback();
13069
13070        destroyDrawingCache();
13071        destroyLayer(false);
13072
13073        cleanupDraw();
13074
13075        mCurrentAnimation = null;
13076    }
13077
13078    private void cleanupDraw() {
13079        if (mAttachInfo != null) {
13080            // Ensure the display lists are reset when the view root dies.
13081            if (mDisplayList != null) {
13082                mDisplayList.markDirty();
13083                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
13084            }
13085            if (mBackgroundDisplayList != null) {
13086                mBackgroundDisplayList.markDirty();
13087                mAttachInfo.mViewRootImpl.enqueueDisplayList(mBackgroundDisplayList);
13088            }
13089            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13090        } else {
13091            // Should never happen.
13092            resetDisplayList();
13093        }
13094    }
13095
13096    /**
13097     * This method ensures the hardware renderer is in a valid state
13098     * before executing the specified action.
13099     *
13100     * This method will attempt to set a valid state even if the window
13101     * the renderer is attached to was destroyed.
13102     *
13103     * This method is not guaranteed to work. If the hardware renderer
13104     * does not exist or cannot be put in a valid state, this method
13105     * will not executed the specified action.
13106     *
13107     * The specified action is executed synchronously.
13108     *
13109     * @param action The action to execute after the renderer is in a valid state
13110     *
13111     * @return True if the specified Runnable was executed, false otherwise
13112     *
13113     * @hide
13114     */
13115    public boolean executeHardwareAction(Runnable action) {
13116        //noinspection SimplifiableIfStatement
13117        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
13118            return mAttachInfo.mHardwareRenderer.safelyRun(action);
13119        }
13120        return false;
13121    }
13122
13123    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13124    }
13125
13126    /**
13127     * @return The number of times this view has been attached to a window
13128     */
13129    protected int getWindowAttachCount() {
13130        return mWindowAttachCount;
13131    }
13132
13133    /**
13134     * Retrieve a unique token identifying the window this view is attached to.
13135     * @return Return the window's token for use in
13136     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13137     */
13138    public IBinder getWindowToken() {
13139        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13140    }
13141
13142    /**
13143     * Retrieve the {@link WindowId} for the window this view is
13144     * currently attached to.
13145     */
13146    public WindowId getWindowId() {
13147        if (mAttachInfo == null) {
13148            return null;
13149        }
13150        if (mAttachInfo.mWindowId == null) {
13151            try {
13152                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13153                        mAttachInfo.mWindowToken);
13154                mAttachInfo.mWindowId = new WindowId(
13155                        mAttachInfo.mIWindowId);
13156            } catch (RemoteException e) {
13157            }
13158        }
13159        return mAttachInfo.mWindowId;
13160    }
13161
13162    /**
13163     * Retrieve a unique token identifying the top-level "real" window of
13164     * the window that this view is attached to.  That is, this is like
13165     * {@link #getWindowToken}, except if the window this view in is a panel
13166     * window (attached to another containing window), then the token of
13167     * the containing window is returned instead.
13168     *
13169     * @return Returns the associated window token, either
13170     * {@link #getWindowToken()} or the containing window's token.
13171     */
13172    public IBinder getApplicationWindowToken() {
13173        AttachInfo ai = mAttachInfo;
13174        if (ai != null) {
13175            IBinder appWindowToken = ai.mPanelParentWindowToken;
13176            if (appWindowToken == null) {
13177                appWindowToken = ai.mWindowToken;
13178            }
13179            return appWindowToken;
13180        }
13181        return null;
13182    }
13183
13184    /**
13185     * Gets the logical display to which the view's window has been attached.
13186     *
13187     * @return The logical display, or null if the view is not currently attached to a window.
13188     */
13189    public Display getDisplay() {
13190        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13191    }
13192
13193    /**
13194     * Retrieve private session object this view hierarchy is using to
13195     * communicate with the window manager.
13196     * @return the session object to communicate with the window manager
13197     */
13198    /*package*/ IWindowSession getWindowSession() {
13199        return mAttachInfo != null ? mAttachInfo.mSession : null;
13200    }
13201
13202    /**
13203     * @param info the {@link android.view.View.AttachInfo} to associated with
13204     *        this view
13205     */
13206    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13207        //System.out.println("Attached! " + this);
13208        mAttachInfo = info;
13209        if (mOverlay != null) {
13210            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13211        }
13212        mWindowAttachCount++;
13213        // We will need to evaluate the drawable state at least once.
13214        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13215        if (mFloatingTreeObserver != null) {
13216            info.mTreeObserver.merge(mFloatingTreeObserver);
13217            mFloatingTreeObserver = null;
13218        }
13219        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13220            mAttachInfo.mScrollContainers.add(this);
13221            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13222        }
13223        performCollectViewAttributes(mAttachInfo, visibility);
13224        onAttachedToWindow();
13225
13226        ListenerInfo li = mListenerInfo;
13227        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13228                li != null ? li.mOnAttachStateChangeListeners : null;
13229        if (listeners != null && listeners.size() > 0) {
13230            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13231            // perform the dispatching. The iterator is a safe guard against listeners that
13232            // could mutate the list by calling the various add/remove methods. This prevents
13233            // the array from being modified while we iterate it.
13234            for (OnAttachStateChangeListener listener : listeners) {
13235                listener.onViewAttachedToWindow(this);
13236            }
13237        }
13238
13239        int vis = info.mWindowVisibility;
13240        if (vis != GONE) {
13241            onWindowVisibilityChanged(vis);
13242        }
13243        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13244            // If nobody has evaluated the drawable state yet, then do it now.
13245            refreshDrawableState();
13246        }
13247        needGlobalAttributesUpdate(false);
13248    }
13249
13250    void dispatchDetachedFromWindow() {
13251        AttachInfo info = mAttachInfo;
13252        if (info != null) {
13253            int vis = info.mWindowVisibility;
13254            if (vis != GONE) {
13255                onWindowVisibilityChanged(GONE);
13256            }
13257        }
13258
13259        onDetachedFromWindow();
13260
13261        ListenerInfo li = mListenerInfo;
13262        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13263                li != null ? li.mOnAttachStateChangeListeners : null;
13264        if (listeners != null && listeners.size() > 0) {
13265            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13266            // perform the dispatching. The iterator is a safe guard against listeners that
13267            // could mutate the list by calling the various add/remove methods. This prevents
13268            // the array from being modified while we iterate it.
13269            for (OnAttachStateChangeListener listener : listeners) {
13270                listener.onViewDetachedFromWindow(this);
13271            }
13272        }
13273
13274        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13275            mAttachInfo.mScrollContainers.remove(this);
13276            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13277        }
13278
13279        mAttachInfo = null;
13280        if (mOverlay != null) {
13281            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13282        }
13283    }
13284
13285    /**
13286     * Cancel any deferred high-level input events that were previously posted to the event queue.
13287     *
13288     * <p>Many views post high-level events such as click handlers to the event queue
13289     * to run deferred in order to preserve a desired user experience - clearing visible
13290     * pressed states before executing, etc. This method will abort any events of this nature
13291     * that are currently in flight.</p>
13292     *
13293     * <p>Custom views that generate their own high-level deferred input events should override
13294     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13295     *
13296     * <p>This will also cancel pending input events for any child views.</p>
13297     *
13298     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13299     * This will not impact newer events posted after this call that may occur as a result of
13300     * lower-level input events still waiting in the queue. If you are trying to prevent
13301     * double-submitted  events for the duration of some sort of asynchronous transaction
13302     * you should also take other steps to protect against unexpected double inputs e.g. calling
13303     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13304     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13305     */
13306    public final void cancelPendingInputEvents() {
13307        dispatchCancelPendingInputEvents();
13308    }
13309
13310    /**
13311     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13312     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13313     */
13314    void dispatchCancelPendingInputEvents() {
13315        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13316        onCancelPendingInputEvents();
13317        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13318            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13319                    " did not call through to super.onCancelPendingInputEvents()");
13320        }
13321    }
13322
13323    /**
13324     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13325     * a parent view.
13326     *
13327     * <p>This method is responsible for removing any pending high-level input events that were
13328     * posted to the event queue to run later. Custom view classes that post their own deferred
13329     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13330     * {@link android.os.Handler} should override this method, call
13331     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13332     * </p>
13333     */
13334    public void onCancelPendingInputEvents() {
13335        removePerformClickCallback();
13336        cancelLongPress();
13337        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13338    }
13339
13340    /**
13341     * Store this view hierarchy's frozen state into the given container.
13342     *
13343     * @param container The SparseArray in which to save the view's state.
13344     *
13345     * @see #restoreHierarchyState(android.util.SparseArray)
13346     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13347     * @see #onSaveInstanceState()
13348     */
13349    public void saveHierarchyState(SparseArray<Parcelable> container) {
13350        dispatchSaveInstanceState(container);
13351    }
13352
13353    /**
13354     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13355     * this view and its children. May be overridden to modify how freezing happens to a
13356     * view's children; for example, some views may want to not store state for their children.
13357     *
13358     * @param container The SparseArray in which to save the view's state.
13359     *
13360     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13361     * @see #saveHierarchyState(android.util.SparseArray)
13362     * @see #onSaveInstanceState()
13363     */
13364    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13365        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13366            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13367            Parcelable state = onSaveInstanceState();
13368            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13369                throw new IllegalStateException(
13370                        "Derived class did not call super.onSaveInstanceState()");
13371            }
13372            if (state != null) {
13373                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13374                // + ": " + state);
13375                container.put(mID, state);
13376            }
13377        }
13378    }
13379
13380    /**
13381     * Hook allowing a view to generate a representation of its internal state
13382     * that can later be used to create a new instance with that same state.
13383     * This state should only contain information that is not persistent or can
13384     * not be reconstructed later. For example, you will never store your
13385     * current position on screen because that will be computed again when a
13386     * new instance of the view is placed in its view hierarchy.
13387     * <p>
13388     * Some examples of things you may store here: the current cursor position
13389     * in a text view (but usually not the text itself since that is stored in a
13390     * content provider or other persistent storage), the currently selected
13391     * item in a list view.
13392     *
13393     * @return Returns a Parcelable object containing the view's current dynamic
13394     *         state, or null if there is nothing interesting to save. The
13395     *         default implementation returns null.
13396     * @see #onRestoreInstanceState(android.os.Parcelable)
13397     * @see #saveHierarchyState(android.util.SparseArray)
13398     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13399     * @see #setSaveEnabled(boolean)
13400     */
13401    protected Parcelable onSaveInstanceState() {
13402        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13403        return BaseSavedState.EMPTY_STATE;
13404    }
13405
13406    /**
13407     * Restore this view hierarchy's frozen state from the given container.
13408     *
13409     * @param container The SparseArray which holds previously frozen states.
13410     *
13411     * @see #saveHierarchyState(android.util.SparseArray)
13412     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13413     * @see #onRestoreInstanceState(android.os.Parcelable)
13414     */
13415    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13416        dispatchRestoreInstanceState(container);
13417    }
13418
13419    /**
13420     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13421     * state for this view and its children. May be overridden to modify how restoring
13422     * happens to a view's children; for example, some views may want to not store state
13423     * for their children.
13424     *
13425     * @param container The SparseArray which holds previously saved state.
13426     *
13427     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13428     * @see #restoreHierarchyState(android.util.SparseArray)
13429     * @see #onRestoreInstanceState(android.os.Parcelable)
13430     */
13431    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13432        if (mID != NO_ID) {
13433            Parcelable state = container.get(mID);
13434            if (state != null) {
13435                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13436                // + ": " + state);
13437                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13438                onRestoreInstanceState(state);
13439                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13440                    throw new IllegalStateException(
13441                            "Derived class did not call super.onRestoreInstanceState()");
13442                }
13443            }
13444        }
13445    }
13446
13447    /**
13448     * Hook allowing a view to re-apply a representation of its internal state that had previously
13449     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13450     * null state.
13451     *
13452     * @param state The frozen state that had previously been returned by
13453     *        {@link #onSaveInstanceState}.
13454     *
13455     * @see #onSaveInstanceState()
13456     * @see #restoreHierarchyState(android.util.SparseArray)
13457     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13458     */
13459    protected void onRestoreInstanceState(Parcelable state) {
13460        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13461        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13462            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13463                    + "received " + state.getClass().toString() + " instead. This usually happens "
13464                    + "when two views of different type have the same id in the same hierarchy. "
13465                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13466                    + "other views do not use the same id.");
13467        }
13468    }
13469
13470    /**
13471     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13472     *
13473     * @return the drawing start time in milliseconds
13474     */
13475    public long getDrawingTime() {
13476        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13477    }
13478
13479    /**
13480     * <p>Enables or disables the duplication of the parent's state into this view. When
13481     * duplication is enabled, this view gets its drawable state from its parent rather
13482     * than from its own internal properties.</p>
13483     *
13484     * <p>Note: in the current implementation, setting this property to true after the
13485     * view was added to a ViewGroup might have no effect at all. This property should
13486     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13487     *
13488     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13489     * property is enabled, an exception will be thrown.</p>
13490     *
13491     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13492     * parent, these states should not be affected by this method.</p>
13493     *
13494     * @param enabled True to enable duplication of the parent's drawable state, false
13495     *                to disable it.
13496     *
13497     * @see #getDrawableState()
13498     * @see #isDuplicateParentStateEnabled()
13499     */
13500    public void setDuplicateParentStateEnabled(boolean enabled) {
13501        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13502    }
13503
13504    /**
13505     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13506     *
13507     * @return True if this view's drawable state is duplicated from the parent,
13508     *         false otherwise
13509     *
13510     * @see #getDrawableState()
13511     * @see #setDuplicateParentStateEnabled(boolean)
13512     */
13513    public boolean isDuplicateParentStateEnabled() {
13514        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13515    }
13516
13517    /**
13518     * <p>Specifies the type of layer backing this view. The layer can be
13519     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13520     * {@link #LAYER_TYPE_HARDWARE}.</p>
13521     *
13522     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13523     * instance that controls how the layer is composed on screen. The following
13524     * properties of the paint are taken into account when composing the layer:</p>
13525     * <ul>
13526     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13527     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13528     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13529     * </ul>
13530     *
13531     * <p>If this view has an alpha value set to < 1.0 by calling
13532     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13533     * by this view's alpha value.</p>
13534     *
13535     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13536     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13537     * for more information on when and how to use layers.</p>
13538     *
13539     * @param layerType The type of layer to use with this view, must be one of
13540     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13541     *        {@link #LAYER_TYPE_HARDWARE}
13542     * @param paint The paint used to compose the layer. This argument is optional
13543     *        and can be null. It is ignored when the layer type is
13544     *        {@link #LAYER_TYPE_NONE}
13545     *
13546     * @see #getLayerType()
13547     * @see #LAYER_TYPE_NONE
13548     * @see #LAYER_TYPE_SOFTWARE
13549     * @see #LAYER_TYPE_HARDWARE
13550     * @see #setAlpha(float)
13551     *
13552     * @attr ref android.R.styleable#View_layerType
13553     */
13554    public void setLayerType(int layerType, Paint paint) {
13555        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13556            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13557                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13558        }
13559
13560        if (layerType == mLayerType) {
13561            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
13562                mLayerPaint = paint == null ? new Paint() : paint;
13563                invalidateParentCaches();
13564                invalidate(true);
13565            }
13566            return;
13567        }
13568
13569        // Destroy any previous software drawing cache if needed
13570        switch (mLayerType) {
13571            case LAYER_TYPE_HARDWARE:
13572                destroyLayer(false);
13573                // fall through - non-accelerated views may use software layer mechanism instead
13574            case LAYER_TYPE_SOFTWARE:
13575                destroyDrawingCache();
13576                break;
13577            default:
13578                break;
13579        }
13580
13581        mLayerType = layerType;
13582        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
13583        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13584        mLocalDirtyRect = layerDisabled ? null : new Rect();
13585
13586        invalidateParentCaches();
13587        invalidate(true);
13588    }
13589
13590    /**
13591     * Updates the {@link Paint} object used with the current layer (used only if the current
13592     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13593     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13594     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13595     * ensure that the view gets redrawn immediately.
13596     *
13597     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13598     * instance that controls how the layer is composed on screen. The following
13599     * properties of the paint are taken into account when composing the layer:</p>
13600     * <ul>
13601     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13602     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13603     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13604     * </ul>
13605     *
13606     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13607     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13608     *
13609     * @param paint The paint used to compose the layer. This argument is optional
13610     *        and can be null. It is ignored when the layer type is
13611     *        {@link #LAYER_TYPE_NONE}
13612     *
13613     * @see #setLayerType(int, android.graphics.Paint)
13614     */
13615    public void setLayerPaint(Paint paint) {
13616        int layerType = getLayerType();
13617        if (layerType != LAYER_TYPE_NONE) {
13618            mLayerPaint = paint == null ? new Paint() : paint;
13619            if (layerType == LAYER_TYPE_HARDWARE) {
13620                HardwareLayer layer = getHardwareLayer();
13621                if (layer != null) {
13622                    layer.setLayerPaint(paint);
13623                }
13624                invalidateViewProperty(false, false);
13625            } else {
13626                invalidate();
13627            }
13628        }
13629    }
13630
13631    /**
13632     * Indicates whether this view has a static layer. A view with layer type
13633     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13634     * dynamic.
13635     */
13636    boolean hasStaticLayer() {
13637        return true;
13638    }
13639
13640    /**
13641     * Indicates what type of layer is currently associated with this view. By default
13642     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13643     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13644     * for more information on the different types of layers.
13645     *
13646     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13647     *         {@link #LAYER_TYPE_HARDWARE}
13648     *
13649     * @see #setLayerType(int, android.graphics.Paint)
13650     * @see #buildLayer()
13651     * @see #LAYER_TYPE_NONE
13652     * @see #LAYER_TYPE_SOFTWARE
13653     * @see #LAYER_TYPE_HARDWARE
13654     */
13655    public int getLayerType() {
13656        return mLayerType;
13657    }
13658
13659    /**
13660     * Forces this view's layer to be created and this view to be rendered
13661     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13662     * invoking this method will have no effect.
13663     *
13664     * This method can for instance be used to render a view into its layer before
13665     * starting an animation. If this view is complex, rendering into the layer
13666     * before starting the animation will avoid skipping frames.
13667     *
13668     * @throws IllegalStateException If this view is not attached to a window
13669     *
13670     * @see #setLayerType(int, android.graphics.Paint)
13671     */
13672    public void buildLayer() {
13673        if (mLayerType == LAYER_TYPE_NONE) return;
13674
13675        final AttachInfo attachInfo = mAttachInfo;
13676        if (attachInfo == null) {
13677            throw new IllegalStateException("This view must be attached to a window first");
13678        }
13679
13680        switch (mLayerType) {
13681            case LAYER_TYPE_HARDWARE:
13682                getHardwareLayer();
13683                // TODO: We need a better way to handle this case
13684                // If views have registered pre-draw listeners they need
13685                // to be notified before we build the layer. Those listeners
13686                // may however rely on other events to happen first so we
13687                // cannot just invoke them here until they don't cancel the
13688                // current frame
13689                if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
13690                    attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
13691                }
13692                break;
13693            case LAYER_TYPE_SOFTWARE:
13694                buildDrawingCache(true);
13695                break;
13696        }
13697    }
13698
13699    /**
13700     * <p>Returns a hardware layer that can be used to draw this view again
13701     * without executing its draw method.</p>
13702     *
13703     * @return A HardwareLayer ready to render, or null if an error occurred.
13704     */
13705    HardwareLayer getHardwareLayer() {
13706        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
13707                !mAttachInfo.mHardwareRenderer.isEnabled()) {
13708            return null;
13709        }
13710
13711        final int width = mRight - mLeft;
13712        final int height = mBottom - mTop;
13713
13714        if (width == 0 || height == 0) {
13715            return null;
13716        }
13717
13718        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13719            if (mHardwareLayer == null) {
13720                mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer(
13721                        width, height);
13722                mLocalDirtyRect.set(0, 0, width, height);
13723            } else if (mHardwareLayer.isValid()) {
13724                // This should not be necessary but applications that change
13725                // the parameters of their background drawable without calling
13726                // this.setBackground(Drawable) can leave the view in a bad state
13727                // (for instance isOpaque() returns true, but the background is
13728                // not opaque.)
13729                computeOpaqueFlags();
13730
13731                if (mHardwareLayer.prepare(width, height, isOpaque())) {
13732                    mLocalDirtyRect.set(0, 0, width, height);
13733                }
13734            }
13735
13736            // The layer is not valid if the underlying GPU resources cannot be allocated
13737            mHardwareLayer.flushChanges();
13738            if (!mHardwareLayer.isValid()) {
13739                return null;
13740            }
13741
13742            mHardwareLayer.setLayerPaint(mLayerPaint);
13743            DisplayList displayList = mHardwareLayer.startRecording();
13744            if (getDisplayList(displayList, true) != displayList) {
13745                throw new IllegalStateException("getDisplayList() didn't return"
13746                        + " the input displaylist for a hardware layer!");
13747            }
13748            mHardwareLayer.endRecording(mLocalDirtyRect);
13749            mLocalDirtyRect.setEmpty();
13750        }
13751
13752        return mHardwareLayer;
13753    }
13754
13755    /**
13756     * Destroys this View's hardware layer if possible.
13757     *
13758     * @return True if the layer was destroyed, false otherwise.
13759     *
13760     * @see #setLayerType(int, android.graphics.Paint)
13761     * @see #LAYER_TYPE_HARDWARE
13762     */
13763    boolean destroyLayer(boolean valid) {
13764        if (mHardwareLayer != null) {
13765            mHardwareLayer.destroy();
13766            mHardwareLayer = null;
13767
13768            invalidate(true);
13769            invalidateParentCaches();
13770            return true;
13771        }
13772        return false;
13773    }
13774
13775    /**
13776     * Destroys all hardware rendering resources. This method is invoked
13777     * when the system needs to reclaim resources. Upon execution of this
13778     * method, you should free any OpenGL resources created by the view.
13779     *
13780     * Note: you <strong>must</strong> call
13781     * <code>super.destroyHardwareResources()</code> when overriding
13782     * this method.
13783     *
13784     * @hide
13785     */
13786    protected void destroyHardwareResources() {
13787        resetDisplayList();
13788        destroyLayer(true);
13789    }
13790
13791    /**
13792     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13793     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13794     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13795     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13796     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13797     * null.</p>
13798     *
13799     * <p>Enabling the drawing cache is similar to
13800     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13801     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13802     * drawing cache has no effect on rendering because the system uses a different mechanism
13803     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13804     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13805     * for information on how to enable software and hardware layers.</p>
13806     *
13807     * <p>This API can be used to manually generate
13808     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13809     * {@link #getDrawingCache()}.</p>
13810     *
13811     * @param enabled true to enable the drawing cache, false otherwise
13812     *
13813     * @see #isDrawingCacheEnabled()
13814     * @see #getDrawingCache()
13815     * @see #buildDrawingCache()
13816     * @see #setLayerType(int, android.graphics.Paint)
13817     */
13818    public void setDrawingCacheEnabled(boolean enabled) {
13819        mCachingFailed = false;
13820        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13821    }
13822
13823    /**
13824     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13825     *
13826     * @return true if the drawing cache is enabled
13827     *
13828     * @see #setDrawingCacheEnabled(boolean)
13829     * @see #getDrawingCache()
13830     */
13831    @ViewDebug.ExportedProperty(category = "drawing")
13832    public boolean isDrawingCacheEnabled() {
13833        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13834    }
13835
13836    /**
13837     * Debugging utility which recursively outputs the dirty state of a view and its
13838     * descendants.
13839     *
13840     * @hide
13841     */
13842    @SuppressWarnings({"UnusedDeclaration"})
13843    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13844        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13845                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13846                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13847                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13848        if (clear) {
13849            mPrivateFlags &= clearMask;
13850        }
13851        if (this instanceof ViewGroup) {
13852            ViewGroup parent = (ViewGroup) this;
13853            final int count = parent.getChildCount();
13854            for (int i = 0; i < count; i++) {
13855                final View child = parent.getChildAt(i);
13856                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13857            }
13858        }
13859    }
13860
13861    /**
13862     * This method is used by ViewGroup to cause its children to restore or recreate their
13863     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13864     * to recreate its own display list, which would happen if it went through the normal
13865     * draw/dispatchDraw mechanisms.
13866     *
13867     * @hide
13868     */
13869    protected void dispatchGetDisplayList() {}
13870
13871    /**
13872     * A view that is not attached or hardware accelerated cannot create a display list.
13873     * This method checks these conditions and returns the appropriate result.
13874     *
13875     * @return true if view has the ability to create a display list, false otherwise.
13876     *
13877     * @hide
13878     */
13879    public boolean canHaveDisplayList() {
13880        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13881    }
13882
13883    /**
13884     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13885     * Otherwise, the same display list will be returned (after having been rendered into
13886     * along the way, depending on the invalidation state of the view).
13887     *
13888     * @param displayList The previous version of this displayList, could be null.
13889     * @param isLayer Whether the requester of the display list is a layer. If so,
13890     * the view will avoid creating a layer inside the resulting display list.
13891     * @return A new or reused DisplayList object.
13892     */
13893    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
13894        if (!canHaveDisplayList()) {
13895            return null;
13896        }
13897
13898        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13899                displayList == null || !displayList.isValid() ||
13900                (!isLayer && mRecreateDisplayList))) {
13901            // Don't need to recreate the display list, just need to tell our
13902            // children to restore/recreate theirs
13903            if (displayList != null && displayList.isValid() &&
13904                    !isLayer && !mRecreateDisplayList) {
13905                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13906                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13907                dispatchGetDisplayList();
13908
13909                return displayList;
13910            }
13911
13912            if (!isLayer) {
13913                // If we got here, we're recreating it. Mark it as such to ensure that
13914                // we copy in child display lists into ours in drawChild()
13915                mRecreateDisplayList = true;
13916            }
13917            if (displayList == null) {
13918                displayList = DisplayList.create(getClass().getName());
13919                // If we're creating a new display list, make sure our parent gets invalidated
13920                // since they will need to recreate their display list to account for this
13921                // new child display list.
13922                invalidateParentCaches();
13923            }
13924
13925            boolean caching = false;
13926            int width = mRight - mLeft;
13927            int height = mBottom - mTop;
13928            int layerType = getLayerType();
13929
13930            final HardwareCanvas canvas = displayList.start(width, height);
13931
13932            try {
13933                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13934                    if (layerType == LAYER_TYPE_HARDWARE) {
13935                        final HardwareLayer layer = getHardwareLayer();
13936                        if (layer != null && layer.isValid()) {
13937                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13938                        } else {
13939                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13940                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13941                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13942                        }
13943                        caching = true;
13944                    } else {
13945                        buildDrawingCache(true);
13946                        Bitmap cache = getDrawingCache(true);
13947                        if (cache != null) {
13948                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13949                            caching = true;
13950                        }
13951                    }
13952                } else {
13953
13954                    computeScroll();
13955
13956                    canvas.translate(-mScrollX, -mScrollY);
13957                    if (!isLayer) {
13958                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13959                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13960                    }
13961
13962                    // Fast path for layouts with no backgrounds
13963                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13964                        dispatchDraw(canvas);
13965                        if (mOverlay != null && !mOverlay.isEmpty()) {
13966                            mOverlay.getOverlayView().draw(canvas);
13967                        }
13968                    } else {
13969                        draw(canvas);
13970                    }
13971                }
13972            } finally {
13973                displayList.end();
13974                displayList.setCaching(caching);
13975                if (isLayer) {
13976                    displayList.setLeftTopRightBottom(0, 0, width, height);
13977                } else {
13978                    setDisplayListProperties(displayList);
13979                }
13980            }
13981        } else if (!isLayer) {
13982            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13983            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13984        }
13985
13986        return displayList;
13987    }
13988
13989    /**
13990     * <p>Returns a display list that can be used to draw this view again
13991     * without executing its draw method.</p>
13992     *
13993     * @return A DisplayList ready to replay, or null if caching is not enabled.
13994     *
13995     * @hide
13996     */
13997    public DisplayList getDisplayList() {
13998        mDisplayList = getDisplayList(mDisplayList, false);
13999        return mDisplayList;
14000    }
14001
14002    private void clearDisplayList() {
14003        if (mDisplayList != null) {
14004            mDisplayList.clear();
14005        }
14006
14007        if (mBackgroundDisplayList != null) {
14008            mBackgroundDisplayList.clear();
14009        }
14010    }
14011
14012    private void resetDisplayList() {
14013        if (mDisplayList != null) {
14014            mDisplayList.reset();
14015        }
14016
14017        if (mBackgroundDisplayList != null) {
14018            mBackgroundDisplayList.reset();
14019        }
14020    }
14021
14022    /**
14023     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14024     *
14025     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14026     *
14027     * @see #getDrawingCache(boolean)
14028     */
14029    public Bitmap getDrawingCache() {
14030        return getDrawingCache(false);
14031    }
14032
14033    /**
14034     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14035     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14036     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14037     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14038     * request the drawing cache by calling this method and draw it on screen if the
14039     * returned bitmap is not null.</p>
14040     *
14041     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14042     * this method will create a bitmap of the same size as this view. Because this bitmap
14043     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14044     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14045     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14046     * size than the view. This implies that your application must be able to handle this
14047     * size.</p>
14048     *
14049     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14050     *        the current density of the screen when the application is in compatibility
14051     *        mode.
14052     *
14053     * @return A bitmap representing this view or null if cache is disabled.
14054     *
14055     * @see #setDrawingCacheEnabled(boolean)
14056     * @see #isDrawingCacheEnabled()
14057     * @see #buildDrawingCache(boolean)
14058     * @see #destroyDrawingCache()
14059     */
14060    public Bitmap getDrawingCache(boolean autoScale) {
14061        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14062            return null;
14063        }
14064        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14065            buildDrawingCache(autoScale);
14066        }
14067        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14068    }
14069
14070    /**
14071     * <p>Frees the resources used by the drawing cache. If you call
14072     * {@link #buildDrawingCache()} manually without calling
14073     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14074     * should cleanup the cache with this method afterwards.</p>
14075     *
14076     * @see #setDrawingCacheEnabled(boolean)
14077     * @see #buildDrawingCache()
14078     * @see #getDrawingCache()
14079     */
14080    public void destroyDrawingCache() {
14081        if (mDrawingCache != null) {
14082            mDrawingCache.recycle();
14083            mDrawingCache = null;
14084        }
14085        if (mUnscaledDrawingCache != null) {
14086            mUnscaledDrawingCache.recycle();
14087            mUnscaledDrawingCache = null;
14088        }
14089    }
14090
14091    /**
14092     * Setting a solid background color for the drawing cache's bitmaps will improve
14093     * performance and memory usage. Note, though that this should only be used if this
14094     * view will always be drawn on top of a solid color.
14095     *
14096     * @param color The background color to use for the drawing cache's bitmap
14097     *
14098     * @see #setDrawingCacheEnabled(boolean)
14099     * @see #buildDrawingCache()
14100     * @see #getDrawingCache()
14101     */
14102    public void setDrawingCacheBackgroundColor(int color) {
14103        if (color != mDrawingCacheBackgroundColor) {
14104            mDrawingCacheBackgroundColor = color;
14105            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14106        }
14107    }
14108
14109    /**
14110     * @see #setDrawingCacheBackgroundColor(int)
14111     *
14112     * @return The background color to used for the drawing cache's bitmap
14113     */
14114    public int getDrawingCacheBackgroundColor() {
14115        return mDrawingCacheBackgroundColor;
14116    }
14117
14118    /**
14119     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14120     *
14121     * @see #buildDrawingCache(boolean)
14122     */
14123    public void buildDrawingCache() {
14124        buildDrawingCache(false);
14125    }
14126
14127    /**
14128     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14129     *
14130     * <p>If you call {@link #buildDrawingCache()} manually without calling
14131     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14132     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14133     *
14134     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14135     * this method will create a bitmap of the same size as this view. Because this bitmap
14136     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14137     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14138     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14139     * size than the view. This implies that your application must be able to handle this
14140     * size.</p>
14141     *
14142     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14143     * you do not need the drawing cache bitmap, calling this method will increase memory
14144     * usage and cause the view to be rendered in software once, thus negatively impacting
14145     * performance.</p>
14146     *
14147     * @see #getDrawingCache()
14148     * @see #destroyDrawingCache()
14149     */
14150    public void buildDrawingCache(boolean autoScale) {
14151        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14152                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14153            mCachingFailed = false;
14154
14155            int width = mRight - mLeft;
14156            int height = mBottom - mTop;
14157
14158            final AttachInfo attachInfo = mAttachInfo;
14159            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14160
14161            if (autoScale && scalingRequired) {
14162                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14163                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14164            }
14165
14166            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14167            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14168            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14169
14170            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14171            final long drawingCacheSize =
14172                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14173            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14174                if (width > 0 && height > 0) {
14175                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14176                            + projectedBitmapSize + " bytes, only "
14177                            + drawingCacheSize + " available");
14178                }
14179                destroyDrawingCache();
14180                mCachingFailed = true;
14181                return;
14182            }
14183
14184            boolean clear = true;
14185            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14186
14187            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14188                Bitmap.Config quality;
14189                if (!opaque) {
14190                    // Never pick ARGB_4444 because it looks awful
14191                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14192                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14193                        case DRAWING_CACHE_QUALITY_AUTO:
14194                        case DRAWING_CACHE_QUALITY_LOW:
14195                        case DRAWING_CACHE_QUALITY_HIGH:
14196                        default:
14197                            quality = Bitmap.Config.ARGB_8888;
14198                            break;
14199                    }
14200                } else {
14201                    // Optimization for translucent windows
14202                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14203                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14204                }
14205
14206                // Try to cleanup memory
14207                if (bitmap != null) bitmap.recycle();
14208
14209                try {
14210                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14211                            width, height, quality);
14212                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14213                    if (autoScale) {
14214                        mDrawingCache = bitmap;
14215                    } else {
14216                        mUnscaledDrawingCache = bitmap;
14217                    }
14218                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14219                } catch (OutOfMemoryError e) {
14220                    // If there is not enough memory to create the bitmap cache, just
14221                    // ignore the issue as bitmap caches are not required to draw the
14222                    // view hierarchy
14223                    if (autoScale) {
14224                        mDrawingCache = null;
14225                    } else {
14226                        mUnscaledDrawingCache = null;
14227                    }
14228                    mCachingFailed = true;
14229                    return;
14230                }
14231
14232                clear = drawingCacheBackgroundColor != 0;
14233            }
14234
14235            Canvas canvas;
14236            if (attachInfo != null) {
14237                canvas = attachInfo.mCanvas;
14238                if (canvas == null) {
14239                    canvas = new Canvas();
14240                }
14241                canvas.setBitmap(bitmap);
14242                // Temporarily clobber the cached Canvas in case one of our children
14243                // is also using a drawing cache. Without this, the children would
14244                // steal the canvas by attaching their own bitmap to it and bad, bad
14245                // thing would happen (invisible views, corrupted drawings, etc.)
14246                attachInfo.mCanvas = null;
14247            } else {
14248                // This case should hopefully never or seldom happen
14249                canvas = new Canvas(bitmap);
14250            }
14251
14252            if (clear) {
14253                bitmap.eraseColor(drawingCacheBackgroundColor);
14254            }
14255
14256            computeScroll();
14257            final int restoreCount = canvas.save();
14258
14259            if (autoScale && scalingRequired) {
14260                final float scale = attachInfo.mApplicationScale;
14261                canvas.scale(scale, scale);
14262            }
14263
14264            canvas.translate(-mScrollX, -mScrollY);
14265
14266            mPrivateFlags |= PFLAG_DRAWN;
14267            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14268                    mLayerType != LAYER_TYPE_NONE) {
14269                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14270            }
14271
14272            // Fast path for layouts with no backgrounds
14273            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14274                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14275                dispatchDraw(canvas);
14276                if (mOverlay != null && !mOverlay.isEmpty()) {
14277                    mOverlay.getOverlayView().draw(canvas);
14278                }
14279            } else {
14280                draw(canvas);
14281            }
14282
14283            canvas.restoreToCount(restoreCount);
14284            canvas.setBitmap(null);
14285
14286            if (attachInfo != null) {
14287                // Restore the cached Canvas for our siblings
14288                attachInfo.mCanvas = canvas;
14289            }
14290        }
14291    }
14292
14293    /**
14294     * Create a snapshot of the view into a bitmap.  We should probably make
14295     * some form of this public, but should think about the API.
14296     */
14297    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14298        int width = mRight - mLeft;
14299        int height = mBottom - mTop;
14300
14301        final AttachInfo attachInfo = mAttachInfo;
14302        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14303        width = (int) ((width * scale) + 0.5f);
14304        height = (int) ((height * scale) + 0.5f);
14305
14306        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14307                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14308        if (bitmap == null) {
14309            throw new OutOfMemoryError();
14310        }
14311
14312        Resources resources = getResources();
14313        if (resources != null) {
14314            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14315        }
14316
14317        Canvas canvas;
14318        if (attachInfo != null) {
14319            canvas = attachInfo.mCanvas;
14320            if (canvas == null) {
14321                canvas = new Canvas();
14322            }
14323            canvas.setBitmap(bitmap);
14324            // Temporarily clobber the cached Canvas in case one of our children
14325            // is also using a drawing cache. Without this, the children would
14326            // steal the canvas by attaching their own bitmap to it and bad, bad
14327            // things would happen (invisible views, corrupted drawings, etc.)
14328            attachInfo.mCanvas = null;
14329        } else {
14330            // This case should hopefully never or seldom happen
14331            canvas = new Canvas(bitmap);
14332        }
14333
14334        if ((backgroundColor & 0xff000000) != 0) {
14335            bitmap.eraseColor(backgroundColor);
14336        }
14337
14338        computeScroll();
14339        final int restoreCount = canvas.save();
14340        canvas.scale(scale, scale);
14341        canvas.translate(-mScrollX, -mScrollY);
14342
14343        // Temporarily remove the dirty mask
14344        int flags = mPrivateFlags;
14345        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14346
14347        // Fast path for layouts with no backgrounds
14348        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14349            dispatchDraw(canvas);
14350            if (mOverlay != null && !mOverlay.isEmpty()) {
14351                mOverlay.getOverlayView().draw(canvas);
14352            }
14353        } else {
14354            draw(canvas);
14355        }
14356
14357        mPrivateFlags = flags;
14358
14359        canvas.restoreToCount(restoreCount);
14360        canvas.setBitmap(null);
14361
14362        if (attachInfo != null) {
14363            // Restore the cached Canvas for our siblings
14364            attachInfo.mCanvas = canvas;
14365        }
14366
14367        return bitmap;
14368    }
14369
14370    /**
14371     * Indicates whether this View is currently in edit mode. A View is usually
14372     * in edit mode when displayed within a developer tool. For instance, if
14373     * this View is being drawn by a visual user interface builder, this method
14374     * should return true.
14375     *
14376     * Subclasses should check the return value of this method to provide
14377     * different behaviors if their normal behavior might interfere with the
14378     * host environment. For instance: the class spawns a thread in its
14379     * constructor, the drawing code relies on device-specific features, etc.
14380     *
14381     * This method is usually checked in the drawing code of custom widgets.
14382     *
14383     * @return True if this View is in edit mode, false otherwise.
14384     */
14385    public boolean isInEditMode() {
14386        return false;
14387    }
14388
14389    /**
14390     * If the View draws content inside its padding and enables fading edges,
14391     * it needs to support padding offsets. Padding offsets are added to the
14392     * fading edges to extend the length of the fade so that it covers pixels
14393     * drawn inside the padding.
14394     *
14395     * Subclasses of this class should override this method if they need
14396     * to draw content inside the padding.
14397     *
14398     * @return True if padding offset must be applied, false otherwise.
14399     *
14400     * @see #getLeftPaddingOffset()
14401     * @see #getRightPaddingOffset()
14402     * @see #getTopPaddingOffset()
14403     * @see #getBottomPaddingOffset()
14404     *
14405     * @since CURRENT
14406     */
14407    protected boolean isPaddingOffsetRequired() {
14408        return false;
14409    }
14410
14411    /**
14412     * Amount by which to extend the left fading region. Called only when
14413     * {@link #isPaddingOffsetRequired()} returns true.
14414     *
14415     * @return The left padding offset in pixels.
14416     *
14417     * @see #isPaddingOffsetRequired()
14418     *
14419     * @since CURRENT
14420     */
14421    protected int getLeftPaddingOffset() {
14422        return 0;
14423    }
14424
14425    /**
14426     * Amount by which to extend the right fading region. Called only when
14427     * {@link #isPaddingOffsetRequired()} returns true.
14428     *
14429     * @return The right padding offset in pixels.
14430     *
14431     * @see #isPaddingOffsetRequired()
14432     *
14433     * @since CURRENT
14434     */
14435    protected int getRightPaddingOffset() {
14436        return 0;
14437    }
14438
14439    /**
14440     * Amount by which to extend the top fading region. Called only when
14441     * {@link #isPaddingOffsetRequired()} returns true.
14442     *
14443     * @return The top padding offset in pixels.
14444     *
14445     * @see #isPaddingOffsetRequired()
14446     *
14447     * @since CURRENT
14448     */
14449    protected int getTopPaddingOffset() {
14450        return 0;
14451    }
14452
14453    /**
14454     * Amount by which to extend the bottom fading region. Called only when
14455     * {@link #isPaddingOffsetRequired()} returns true.
14456     *
14457     * @return The bottom padding offset in pixels.
14458     *
14459     * @see #isPaddingOffsetRequired()
14460     *
14461     * @since CURRENT
14462     */
14463    protected int getBottomPaddingOffset() {
14464        return 0;
14465    }
14466
14467    /**
14468     * @hide
14469     * @param offsetRequired
14470     */
14471    protected int getFadeTop(boolean offsetRequired) {
14472        int top = mPaddingTop;
14473        if (offsetRequired) top += getTopPaddingOffset();
14474        return top;
14475    }
14476
14477    /**
14478     * @hide
14479     * @param offsetRequired
14480     */
14481    protected int getFadeHeight(boolean offsetRequired) {
14482        int padding = mPaddingTop;
14483        if (offsetRequired) padding += getTopPaddingOffset();
14484        return mBottom - mTop - mPaddingBottom - padding;
14485    }
14486
14487    /**
14488     * <p>Indicates whether this view is attached to a hardware accelerated
14489     * window or not.</p>
14490     *
14491     * <p>Even if this method returns true, it does not mean that every call
14492     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14493     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14494     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14495     * window is hardware accelerated,
14496     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14497     * return false, and this method will return true.</p>
14498     *
14499     * @return True if the view is attached to a window and the window is
14500     *         hardware accelerated; false in any other case.
14501     */
14502    public boolean isHardwareAccelerated() {
14503        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14504    }
14505
14506    /**
14507     * Sets a rectangular area on this view to which the view will be clipped
14508     * when it is drawn. Setting the value to null will remove the clip bounds
14509     * and the view will draw normally, using its full bounds.
14510     *
14511     * @param clipBounds The rectangular area, in the local coordinates of
14512     * this view, to which future drawing operations will be clipped.
14513     */
14514    public void setClipBounds(Rect clipBounds) {
14515        if (clipBounds != null) {
14516            if (clipBounds.equals(mClipBounds)) {
14517                return;
14518            }
14519            if (mClipBounds == null) {
14520                invalidate();
14521                mClipBounds = new Rect(clipBounds);
14522            } else {
14523                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14524                        Math.min(mClipBounds.top, clipBounds.top),
14525                        Math.max(mClipBounds.right, clipBounds.right),
14526                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14527                mClipBounds.set(clipBounds);
14528            }
14529        } else {
14530            if (mClipBounds != null) {
14531                invalidate();
14532                mClipBounds = null;
14533            }
14534        }
14535    }
14536
14537    /**
14538     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14539     *
14540     * @return A copy of the current clip bounds if clip bounds are set,
14541     * otherwise null.
14542     */
14543    public Rect getClipBounds() {
14544        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14545    }
14546
14547    /**
14548     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14549     * case of an active Animation being run on the view.
14550     */
14551    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14552            Animation a, boolean scalingRequired) {
14553        Transformation invalidationTransform;
14554        final int flags = parent.mGroupFlags;
14555        final boolean initialized = a.isInitialized();
14556        if (!initialized) {
14557            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14558            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14559            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14560            onAnimationStart();
14561        }
14562
14563        final Transformation t = parent.getChildTransformation();
14564        boolean more = a.getTransformation(drawingTime, t, 1f);
14565        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14566            if (parent.mInvalidationTransformation == null) {
14567                parent.mInvalidationTransformation = new Transformation();
14568            }
14569            invalidationTransform = parent.mInvalidationTransformation;
14570            a.getTransformation(drawingTime, invalidationTransform, 1f);
14571        } else {
14572            invalidationTransform = t;
14573        }
14574
14575        if (more) {
14576            if (!a.willChangeBounds()) {
14577                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14578                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14579                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14580                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14581                    // The child need to draw an animation, potentially offscreen, so
14582                    // make sure we do not cancel invalidate requests
14583                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14584                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14585                }
14586            } else {
14587                if (parent.mInvalidateRegion == null) {
14588                    parent.mInvalidateRegion = new RectF();
14589                }
14590                final RectF region = parent.mInvalidateRegion;
14591                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14592                        invalidationTransform);
14593
14594                // The child need to draw an animation, potentially offscreen, so
14595                // make sure we do not cancel invalidate requests
14596                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14597
14598                final int left = mLeft + (int) region.left;
14599                final int top = mTop + (int) region.top;
14600                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14601                        top + (int) (region.height() + .5f));
14602            }
14603        }
14604        return more;
14605    }
14606
14607    /**
14608     * This method is called by getDisplayList() when a display list is created or re-rendered.
14609     * It sets or resets the current value of all properties on that display list (resetting is
14610     * necessary when a display list is being re-created, because we need to make sure that
14611     * previously-set transform values
14612     */
14613    void setDisplayListProperties(DisplayList displayList) {
14614        if (displayList != null) {
14615            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14616            displayList.setHasOverlappingRendering(hasOverlappingRendering());
14617            if (mParent instanceof ViewGroup) {
14618                displayList.setClipToBounds(
14619                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14620            }
14621            if (this instanceof ViewGroup) {
14622                displayList.setIsolatedZVolume(
14623                        (((ViewGroup) this).mGroupFlags & ViewGroup.FLAG_ISOLATED_Z_VOLUME) != 0);
14624            }
14625            displayList.setOutline(mOutline);
14626            displayList.setClipToOutline(getClipToOutline());
14627            displayList.setCastsShadow(getCastsShadow());
14628            displayList.setUsesGlobalCamera(getUsesGlobalCamera());
14629            float alpha = 1;
14630            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14631                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14632                ViewGroup parentVG = (ViewGroup) mParent;
14633                final Transformation t = parentVG.getChildTransformation();
14634                if (parentVG.getChildStaticTransformation(this, t)) {
14635                    final int transformType = t.getTransformationType();
14636                    if (transformType != Transformation.TYPE_IDENTITY) {
14637                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14638                            alpha = t.getAlpha();
14639                        }
14640                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14641                            displayList.setMatrix(t.getMatrix());
14642                        }
14643                    }
14644                }
14645            }
14646            if (mTransformationInfo != null) {
14647                alpha *= getFinalAlpha();
14648                if (alpha < 1) {
14649                    final int multipliedAlpha = (int) (255 * alpha);
14650                    if (onSetAlpha(multipliedAlpha)) {
14651                        alpha = 1;
14652                    }
14653                }
14654                displayList.setTransformationInfo(alpha,
14655                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
14656                        mTransformationInfo.mTranslationZ,
14657                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
14658                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
14659                        mTransformationInfo.mScaleY);
14660                if (mTransformationInfo.mCamera == null) {
14661                    mTransformationInfo.mCamera = new Camera();
14662                    mTransformationInfo.matrix3D = new Matrix();
14663                }
14664                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
14665                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
14666                    displayList.setPivotX(getPivotX());
14667                    displayList.setPivotY(getPivotY());
14668                }
14669            } else if (alpha < 1) {
14670                displayList.setAlpha(alpha);
14671            }
14672        }
14673    }
14674
14675    /**
14676     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14677     * This draw() method is an implementation detail and is not intended to be overridden or
14678     * to be called from anywhere else other than ViewGroup.drawChild().
14679     */
14680    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14681        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14682        boolean more = false;
14683        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14684        final int flags = parent.mGroupFlags;
14685
14686        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14687            parent.getChildTransformation().clear();
14688            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14689        }
14690
14691        Transformation transformToApply = null;
14692        boolean concatMatrix = false;
14693
14694        boolean scalingRequired = false;
14695        boolean caching;
14696        int layerType = getLayerType();
14697
14698        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14699        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14700                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14701            caching = true;
14702            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14703            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14704        } else {
14705            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14706        }
14707
14708        final Animation a = getAnimation();
14709        if (a != null) {
14710            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14711            concatMatrix = a.willChangeTransformationMatrix();
14712            if (concatMatrix) {
14713                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14714            }
14715            transformToApply = parent.getChildTransformation();
14716        } else {
14717            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
14718                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
14719                // No longer animating: clear out old animation matrix
14720                mDisplayList.setAnimationMatrix(null);
14721                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14722            }
14723            if (!useDisplayListProperties &&
14724                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14725                final Transformation t = parent.getChildTransformation();
14726                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14727                if (hasTransform) {
14728                    final int transformType = t.getTransformationType();
14729                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14730                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14731                }
14732            }
14733        }
14734
14735        concatMatrix |= !childHasIdentityMatrix;
14736
14737        // Sets the flag as early as possible to allow draw() implementations
14738        // to call invalidate() successfully when doing animations
14739        mPrivateFlags |= PFLAG_DRAWN;
14740
14741        if (!concatMatrix &&
14742                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14743                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14744                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14745                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14746            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14747            return more;
14748        }
14749        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14750
14751        if (hardwareAccelerated) {
14752            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14753            // retain the flag's value temporarily in the mRecreateDisplayList flag
14754            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14755            mPrivateFlags &= ~PFLAG_INVALIDATED;
14756        }
14757
14758        DisplayList displayList = null;
14759        Bitmap cache = null;
14760        boolean hasDisplayList = false;
14761        if (caching) {
14762            if (!hardwareAccelerated) {
14763                if (layerType != LAYER_TYPE_NONE) {
14764                    layerType = LAYER_TYPE_SOFTWARE;
14765                    buildDrawingCache(true);
14766                }
14767                cache = getDrawingCache(true);
14768            } else {
14769                switch (layerType) {
14770                    case LAYER_TYPE_SOFTWARE:
14771                        if (useDisplayListProperties) {
14772                            hasDisplayList = canHaveDisplayList();
14773                        } else {
14774                            buildDrawingCache(true);
14775                            cache = getDrawingCache(true);
14776                        }
14777                        break;
14778                    case LAYER_TYPE_HARDWARE:
14779                        if (useDisplayListProperties) {
14780                            hasDisplayList = canHaveDisplayList();
14781                        }
14782                        break;
14783                    case LAYER_TYPE_NONE:
14784                        // Delay getting the display list until animation-driven alpha values are
14785                        // set up and possibly passed on to the view
14786                        hasDisplayList = canHaveDisplayList();
14787                        break;
14788                }
14789            }
14790        }
14791        useDisplayListProperties &= hasDisplayList;
14792        if (useDisplayListProperties) {
14793            displayList = getDisplayList();
14794            if (!displayList.isValid()) {
14795                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14796                // to getDisplayList(), the display list will be marked invalid and we should not
14797                // try to use it again.
14798                displayList = null;
14799                hasDisplayList = false;
14800                useDisplayListProperties = false;
14801            }
14802        }
14803
14804        int sx = 0;
14805        int sy = 0;
14806        if (!hasDisplayList) {
14807            computeScroll();
14808            sx = mScrollX;
14809            sy = mScrollY;
14810        }
14811
14812        final boolean hasNoCache = cache == null || hasDisplayList;
14813        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14814                layerType != LAYER_TYPE_HARDWARE;
14815
14816        int restoreTo = -1;
14817        if (!useDisplayListProperties || transformToApply != null) {
14818            restoreTo = canvas.save();
14819        }
14820        if (offsetForScroll) {
14821            canvas.translate(mLeft - sx, mTop - sy);
14822        } else {
14823            if (!useDisplayListProperties) {
14824                canvas.translate(mLeft, mTop);
14825            }
14826            if (scalingRequired) {
14827                if (useDisplayListProperties) {
14828                    // TODO: Might not need this if we put everything inside the DL
14829                    restoreTo = canvas.save();
14830                }
14831                // mAttachInfo cannot be null, otherwise scalingRequired == false
14832                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14833                canvas.scale(scale, scale);
14834            }
14835        }
14836
14837        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14838        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14839                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14840            if (transformToApply != null || !childHasIdentityMatrix) {
14841                int transX = 0;
14842                int transY = 0;
14843
14844                if (offsetForScroll) {
14845                    transX = -sx;
14846                    transY = -sy;
14847                }
14848
14849                if (transformToApply != null) {
14850                    if (concatMatrix) {
14851                        if (useDisplayListProperties) {
14852                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14853                        } else {
14854                            // Undo the scroll translation, apply the transformation matrix,
14855                            // then redo the scroll translate to get the correct result.
14856                            canvas.translate(-transX, -transY);
14857                            canvas.concat(transformToApply.getMatrix());
14858                            canvas.translate(transX, transY);
14859                        }
14860                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14861                    }
14862
14863                    float transformAlpha = transformToApply.getAlpha();
14864                    if (transformAlpha < 1) {
14865                        alpha *= transformAlpha;
14866                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14867                    }
14868                }
14869
14870                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14871                    canvas.translate(-transX, -transY);
14872                    canvas.concat(getMatrix());
14873                    canvas.translate(transX, transY);
14874                }
14875            }
14876
14877            // Deal with alpha if it is or used to be <1
14878            if (alpha < 1 ||
14879                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14880                if (alpha < 1) {
14881                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14882                } else {
14883                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14884                }
14885                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14886                if (hasNoCache) {
14887                    final int multipliedAlpha = (int) (255 * alpha);
14888                    if (!onSetAlpha(multipliedAlpha)) {
14889                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14890                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14891                                layerType != LAYER_TYPE_NONE) {
14892                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14893                        }
14894                        if (useDisplayListProperties) {
14895                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14896                        } else  if (layerType == LAYER_TYPE_NONE) {
14897                            final int scrollX = hasDisplayList ? 0 : sx;
14898                            final int scrollY = hasDisplayList ? 0 : sy;
14899                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14900                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14901                        }
14902                    } else {
14903                        // Alpha is handled by the child directly, clobber the layer's alpha
14904                        mPrivateFlags |= PFLAG_ALPHA_SET;
14905                    }
14906                }
14907            }
14908        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14909            onSetAlpha(255);
14910            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14911        }
14912
14913        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14914                !useDisplayListProperties && cache == null) {
14915            if (offsetForScroll) {
14916                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14917            } else {
14918                if (!scalingRequired || cache == null) {
14919                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14920                } else {
14921                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14922                }
14923            }
14924        }
14925
14926        if (!useDisplayListProperties && hasDisplayList) {
14927            displayList = getDisplayList();
14928            if (!displayList.isValid()) {
14929                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14930                // to getDisplayList(), the display list will be marked invalid and we should not
14931                // try to use it again.
14932                displayList = null;
14933                hasDisplayList = false;
14934            }
14935        }
14936
14937        if (hasNoCache) {
14938            boolean layerRendered = false;
14939            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14940                final HardwareLayer layer = getHardwareLayer();
14941                if (layer != null && layer.isValid()) {
14942                    mLayerPaint.setAlpha((int) (alpha * 255));
14943                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14944                    layerRendered = true;
14945                } else {
14946                    final int scrollX = hasDisplayList ? 0 : sx;
14947                    final int scrollY = hasDisplayList ? 0 : sy;
14948                    canvas.saveLayer(scrollX, scrollY,
14949                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14950                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14951                }
14952            }
14953
14954            if (!layerRendered) {
14955                if (!hasDisplayList) {
14956                    // Fast path for layouts with no backgrounds
14957                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14958                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14959                        dispatchDraw(canvas);
14960                    } else {
14961                        draw(canvas);
14962                    }
14963                } else {
14964                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14965                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14966                }
14967            }
14968        } else if (cache != null) {
14969            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14970            Paint cachePaint;
14971
14972            if (layerType == LAYER_TYPE_NONE) {
14973                cachePaint = parent.mCachePaint;
14974                if (cachePaint == null) {
14975                    cachePaint = new Paint();
14976                    cachePaint.setDither(false);
14977                    parent.mCachePaint = cachePaint;
14978                }
14979                if (alpha < 1) {
14980                    cachePaint.setAlpha((int) (alpha * 255));
14981                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14982                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14983                    cachePaint.setAlpha(255);
14984                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14985                }
14986            } else {
14987                cachePaint = mLayerPaint;
14988                cachePaint.setAlpha((int) (alpha * 255));
14989            }
14990            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14991        }
14992
14993        if (restoreTo >= 0) {
14994            canvas.restoreToCount(restoreTo);
14995        }
14996
14997        if (a != null && !more) {
14998            if (!hardwareAccelerated && !a.getFillAfter()) {
14999                onSetAlpha(255);
15000            }
15001            parent.finishAnimatingView(this, a);
15002        }
15003
15004        if (more && hardwareAccelerated) {
15005            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15006                // alpha animations should cause the child to recreate its display list
15007                invalidate(true);
15008            }
15009        }
15010
15011        mRecreateDisplayList = false;
15012
15013        return more;
15014    }
15015
15016    /**
15017     * Manually render this view (and all of its children) to the given Canvas.
15018     * The view must have already done a full layout before this function is
15019     * called.  When implementing a view, implement
15020     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15021     * If you do need to override this method, call the superclass version.
15022     *
15023     * @param canvas The Canvas to which the View is rendered.
15024     */
15025    public void draw(Canvas canvas) {
15026        if (mClipBounds != null) {
15027            canvas.clipRect(mClipBounds);
15028        }
15029        final int privateFlags = mPrivateFlags;
15030        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15031                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15032        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15033
15034        /*
15035         * Draw traversal performs several drawing steps which must be executed
15036         * in the appropriate order:
15037         *
15038         *      1. Draw the background
15039         *      2. If necessary, save the canvas' layers to prepare for fading
15040         *      3. Draw view's content
15041         *      4. Draw children
15042         *      5. If necessary, draw the fading edges and restore layers
15043         *      6. Draw decorations (scrollbars for instance)
15044         */
15045
15046        // Step 1, draw the background, if needed
15047        int saveCount;
15048
15049        if (!dirtyOpaque) {
15050            drawBackground(canvas);
15051        }
15052
15053        // skip step 2 & 5 if possible (common case)
15054        final int viewFlags = mViewFlags;
15055        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15056        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15057        if (!verticalEdges && !horizontalEdges) {
15058            // Step 3, draw the content
15059            if (!dirtyOpaque) onDraw(canvas);
15060
15061            // Step 4, draw the children
15062            dispatchDraw(canvas);
15063
15064            // Step 6, draw decorations (scrollbars)
15065            onDrawScrollBars(canvas);
15066
15067            if (mOverlay != null && !mOverlay.isEmpty()) {
15068                mOverlay.getOverlayView().dispatchDraw(canvas);
15069            }
15070
15071            // we're done...
15072            return;
15073        }
15074
15075        /*
15076         * Here we do the full fledged routine...
15077         * (this is an uncommon case where speed matters less,
15078         * this is why we repeat some of the tests that have been
15079         * done above)
15080         */
15081
15082        boolean drawTop = false;
15083        boolean drawBottom = false;
15084        boolean drawLeft = false;
15085        boolean drawRight = false;
15086
15087        float topFadeStrength = 0.0f;
15088        float bottomFadeStrength = 0.0f;
15089        float leftFadeStrength = 0.0f;
15090        float rightFadeStrength = 0.0f;
15091
15092        // Step 2, save the canvas' layers
15093        int paddingLeft = mPaddingLeft;
15094
15095        final boolean offsetRequired = isPaddingOffsetRequired();
15096        if (offsetRequired) {
15097            paddingLeft += getLeftPaddingOffset();
15098        }
15099
15100        int left = mScrollX + paddingLeft;
15101        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15102        int top = mScrollY + getFadeTop(offsetRequired);
15103        int bottom = top + getFadeHeight(offsetRequired);
15104
15105        if (offsetRequired) {
15106            right += getRightPaddingOffset();
15107            bottom += getBottomPaddingOffset();
15108        }
15109
15110        final ScrollabilityCache scrollabilityCache = mScrollCache;
15111        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15112        int length = (int) fadeHeight;
15113
15114        // clip the fade length if top and bottom fades overlap
15115        // overlapping fades produce odd-looking artifacts
15116        if (verticalEdges && (top + length > bottom - length)) {
15117            length = (bottom - top) / 2;
15118        }
15119
15120        // also clip horizontal fades if necessary
15121        if (horizontalEdges && (left + length > right - length)) {
15122            length = (right - left) / 2;
15123        }
15124
15125        if (verticalEdges) {
15126            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15127            drawTop = topFadeStrength * fadeHeight > 1.0f;
15128            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15129            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15130        }
15131
15132        if (horizontalEdges) {
15133            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15134            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15135            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15136            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15137        }
15138
15139        saveCount = canvas.getSaveCount();
15140
15141        int solidColor = getSolidColor();
15142        if (solidColor == 0) {
15143            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15144
15145            if (drawTop) {
15146                canvas.saveLayer(left, top, right, top + length, null, flags);
15147            }
15148
15149            if (drawBottom) {
15150                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15151            }
15152
15153            if (drawLeft) {
15154                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15155            }
15156
15157            if (drawRight) {
15158                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15159            }
15160        } else {
15161            scrollabilityCache.setFadeColor(solidColor);
15162        }
15163
15164        // Step 3, draw the content
15165        if (!dirtyOpaque) onDraw(canvas);
15166
15167        // Step 4, draw the children
15168        dispatchDraw(canvas);
15169
15170        // Step 5, draw the fade effect and restore layers
15171        final Paint p = scrollabilityCache.paint;
15172        final Matrix matrix = scrollabilityCache.matrix;
15173        final Shader fade = scrollabilityCache.shader;
15174
15175        if (drawTop) {
15176            matrix.setScale(1, fadeHeight * topFadeStrength);
15177            matrix.postTranslate(left, top);
15178            fade.setLocalMatrix(matrix);
15179            canvas.drawRect(left, top, right, top + length, p);
15180        }
15181
15182        if (drawBottom) {
15183            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15184            matrix.postRotate(180);
15185            matrix.postTranslate(left, bottom);
15186            fade.setLocalMatrix(matrix);
15187            canvas.drawRect(left, bottom - length, right, bottom, p);
15188        }
15189
15190        if (drawLeft) {
15191            matrix.setScale(1, fadeHeight * leftFadeStrength);
15192            matrix.postRotate(-90);
15193            matrix.postTranslate(left, top);
15194            fade.setLocalMatrix(matrix);
15195            canvas.drawRect(left, top, left + length, bottom, p);
15196        }
15197
15198        if (drawRight) {
15199            matrix.setScale(1, fadeHeight * rightFadeStrength);
15200            matrix.postRotate(90);
15201            matrix.postTranslate(right, top);
15202            fade.setLocalMatrix(matrix);
15203            canvas.drawRect(right - length, top, right, bottom, p);
15204        }
15205
15206        canvas.restoreToCount(saveCount);
15207
15208        // Step 6, draw decorations (scrollbars)
15209        onDrawScrollBars(canvas);
15210
15211        if (mOverlay != null && !mOverlay.isEmpty()) {
15212            mOverlay.getOverlayView().dispatchDraw(canvas);
15213        }
15214    }
15215
15216    /**
15217     * Draws the background onto the specified canvas.
15218     *
15219     * @param canvas Canvas on which to draw the background
15220     */
15221    private void drawBackground(Canvas canvas) {
15222        final Drawable background = mBackground;
15223        if (background == null) {
15224            return;
15225        }
15226
15227        if (mBackgroundSizeChanged) {
15228            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15229            mBackgroundSizeChanged = false;
15230        }
15231
15232
15233        // Attempt to use a display list if requested.
15234        if (canvas != null && canvas.isHardwareAccelerated()) {
15235            mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList);
15236
15237            final DisplayList displayList = mBackgroundDisplayList;
15238            if (displayList != null && displayList.isValid()) {
15239                setBackgroundDisplayListProperties(displayList);
15240                ((HardwareCanvas) canvas).drawDisplayList(displayList);
15241                return;
15242            }
15243        }
15244
15245        final int scrollX = mScrollX;
15246        final int scrollY = mScrollY;
15247        if ((scrollX | scrollY) == 0) {
15248            background.draw(canvas);
15249        } else {
15250            canvas.translate(scrollX, scrollY);
15251            background.draw(canvas);
15252            canvas.translate(-scrollX, -scrollY);
15253        }
15254    }
15255
15256    /**
15257     * Set up background drawable display list properties.
15258     *
15259     * @param displayList Valid display list for the background drawable
15260     */
15261    private void setBackgroundDisplayListProperties(DisplayList displayList) {
15262        displayList.setTranslationX(mScrollX);
15263        displayList.setTranslationY(mScrollY);
15264    }
15265
15266    /**
15267     * Creates a new display list or updates the existing display list for the
15268     * specified Drawable.
15269     *
15270     * @param drawable Drawable for which to create a display list
15271     * @param displayList Existing display list, or {@code null}
15272     * @return A valid display list for the specified drawable
15273     */
15274    private static DisplayList getDrawableDisplayList(Drawable drawable, DisplayList displayList) {
15275        if (displayList == null) {
15276            displayList = DisplayList.create(drawable.getClass().getName());
15277        }
15278
15279        final Rect bounds = drawable.getBounds();
15280        final int width = bounds.width();
15281        final int height = bounds.height();
15282        final HardwareCanvas canvas = displayList.start(width, height);
15283        drawable.draw(canvas);
15284        displayList.end();
15285
15286        // Set up drawable properties that are view-independent.
15287        displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15288        displayList.setProjectBackwards(drawable.isProjected());
15289        displayList.setProjectionReceiver(true);
15290        displayList.setClipToBounds(false);
15291        return displayList;
15292    }
15293
15294    /**
15295     * Returns the overlay for this view, creating it if it does not yet exist.
15296     * Adding drawables to the overlay will cause them to be displayed whenever
15297     * the view itself is redrawn. Objects in the overlay should be actively
15298     * managed: remove them when they should not be displayed anymore. The
15299     * overlay will always have the same size as its host view.
15300     *
15301     * <p>Note: Overlays do not currently work correctly with {@link
15302     * SurfaceView} or {@link TextureView}; contents in overlays for these
15303     * types of views may not display correctly.</p>
15304     *
15305     * @return The ViewOverlay object for this view.
15306     * @see ViewOverlay
15307     */
15308    public ViewOverlay getOverlay() {
15309        if (mOverlay == null) {
15310            mOverlay = new ViewOverlay(mContext, this);
15311        }
15312        return mOverlay;
15313    }
15314
15315    /**
15316     * Override this if your view is known to always be drawn on top of a solid color background,
15317     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15318     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15319     * should be set to 0xFF.
15320     *
15321     * @see #setVerticalFadingEdgeEnabled(boolean)
15322     * @see #setHorizontalFadingEdgeEnabled(boolean)
15323     *
15324     * @return The known solid color background for this view, or 0 if the color may vary
15325     */
15326    @ViewDebug.ExportedProperty(category = "drawing")
15327    public int getSolidColor() {
15328        return 0;
15329    }
15330
15331    /**
15332     * Build a human readable string representation of the specified view flags.
15333     *
15334     * @param flags the view flags to convert to a string
15335     * @return a String representing the supplied flags
15336     */
15337    private static String printFlags(int flags) {
15338        String output = "";
15339        int numFlags = 0;
15340        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15341            output += "TAKES_FOCUS";
15342            numFlags++;
15343        }
15344
15345        switch (flags & VISIBILITY_MASK) {
15346        case INVISIBLE:
15347            if (numFlags > 0) {
15348                output += " ";
15349            }
15350            output += "INVISIBLE";
15351            // USELESS HERE numFlags++;
15352            break;
15353        case GONE:
15354            if (numFlags > 0) {
15355                output += " ";
15356            }
15357            output += "GONE";
15358            // USELESS HERE numFlags++;
15359            break;
15360        default:
15361            break;
15362        }
15363        return output;
15364    }
15365
15366    /**
15367     * Build a human readable string representation of the specified private
15368     * view flags.
15369     *
15370     * @param privateFlags the private view flags to convert to a string
15371     * @return a String representing the supplied flags
15372     */
15373    private static String printPrivateFlags(int privateFlags) {
15374        String output = "";
15375        int numFlags = 0;
15376
15377        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15378            output += "WANTS_FOCUS";
15379            numFlags++;
15380        }
15381
15382        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15383            if (numFlags > 0) {
15384                output += " ";
15385            }
15386            output += "FOCUSED";
15387            numFlags++;
15388        }
15389
15390        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15391            if (numFlags > 0) {
15392                output += " ";
15393            }
15394            output += "SELECTED";
15395            numFlags++;
15396        }
15397
15398        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15399            if (numFlags > 0) {
15400                output += " ";
15401            }
15402            output += "IS_ROOT_NAMESPACE";
15403            numFlags++;
15404        }
15405
15406        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15407            if (numFlags > 0) {
15408                output += " ";
15409            }
15410            output += "HAS_BOUNDS";
15411            numFlags++;
15412        }
15413
15414        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15415            if (numFlags > 0) {
15416                output += " ";
15417            }
15418            output += "DRAWN";
15419            // USELESS HERE numFlags++;
15420        }
15421        return output;
15422    }
15423
15424    /**
15425     * <p>Indicates whether or not this view's layout will be requested during
15426     * the next hierarchy layout pass.</p>
15427     *
15428     * @return true if the layout will be forced during next layout pass
15429     */
15430    public boolean isLayoutRequested() {
15431        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15432    }
15433
15434    /**
15435     * Return true if o is a ViewGroup that is laying out using optical bounds.
15436     * @hide
15437     */
15438    public static boolean isLayoutModeOptical(Object o) {
15439        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15440    }
15441
15442    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15443        Insets parentInsets = mParent instanceof View ?
15444                ((View) mParent).getOpticalInsets() : Insets.NONE;
15445        Insets childInsets = getOpticalInsets();
15446        return setFrame(
15447                left   + parentInsets.left - childInsets.left,
15448                top    + parentInsets.top  - childInsets.top,
15449                right  + parentInsets.left + childInsets.right,
15450                bottom + parentInsets.top  + childInsets.bottom);
15451    }
15452
15453    /**
15454     * Assign a size and position to a view and all of its
15455     * descendants
15456     *
15457     * <p>This is the second phase of the layout mechanism.
15458     * (The first is measuring). In this phase, each parent calls
15459     * layout on all of its children to position them.
15460     * This is typically done using the child measurements
15461     * that were stored in the measure pass().</p>
15462     *
15463     * <p>Derived classes should not override this method.
15464     * Derived classes with children should override
15465     * onLayout. In that method, they should
15466     * call layout on each of their children.</p>
15467     *
15468     * @param l Left position, relative to parent
15469     * @param t Top position, relative to parent
15470     * @param r Right position, relative to parent
15471     * @param b Bottom position, relative to parent
15472     */
15473    @SuppressWarnings({"unchecked"})
15474    public void layout(int l, int t, int r, int b) {
15475        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15476            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15477            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15478        }
15479
15480        int oldL = mLeft;
15481        int oldT = mTop;
15482        int oldB = mBottom;
15483        int oldR = mRight;
15484
15485        boolean changed = isLayoutModeOptical(mParent) ?
15486                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15487
15488        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15489            onLayout(changed, l, t, r, b);
15490            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15491
15492            ListenerInfo li = mListenerInfo;
15493            if (li != null && li.mOnLayoutChangeListeners != null) {
15494                ArrayList<OnLayoutChangeListener> listenersCopy =
15495                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15496                int numListeners = listenersCopy.size();
15497                for (int i = 0; i < numListeners; ++i) {
15498                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15499                }
15500            }
15501        }
15502
15503        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15504        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15505    }
15506
15507    /**
15508     * Called from layout when this view should
15509     * assign a size and position to each of its children.
15510     *
15511     * Derived classes with children should override
15512     * this method and call layout on each of
15513     * their children.
15514     * @param changed This is a new size or position for this view
15515     * @param left Left position, relative to parent
15516     * @param top Top position, relative to parent
15517     * @param right Right position, relative to parent
15518     * @param bottom Bottom position, relative to parent
15519     */
15520    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15521    }
15522
15523    /**
15524     * Assign a size and position to this view.
15525     *
15526     * This is called from layout.
15527     *
15528     * @param left Left position, relative to parent
15529     * @param top Top position, relative to parent
15530     * @param right Right position, relative to parent
15531     * @param bottom Bottom position, relative to parent
15532     * @return true if the new size and position are different than the
15533     *         previous ones
15534     * {@hide}
15535     */
15536    protected boolean setFrame(int left, int top, int right, int bottom) {
15537        boolean changed = false;
15538
15539        if (DBG) {
15540            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15541                    + right + "," + bottom + ")");
15542        }
15543
15544        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15545            changed = true;
15546
15547            // Remember our drawn bit
15548            int drawn = mPrivateFlags & PFLAG_DRAWN;
15549
15550            int oldWidth = mRight - mLeft;
15551            int oldHeight = mBottom - mTop;
15552            int newWidth = right - left;
15553            int newHeight = bottom - top;
15554            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15555
15556            // Invalidate our old position
15557            invalidate(sizeChanged);
15558
15559            mLeft = left;
15560            mTop = top;
15561            mRight = right;
15562            mBottom = bottom;
15563            if (mDisplayList != null) {
15564                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15565            }
15566
15567            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15568
15569
15570            if (sizeChanged) {
15571                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
15572                    // A change in dimension means an auto-centered pivot point changes, too
15573                    if (mTransformationInfo != null) {
15574                        mTransformationInfo.mMatrixDirty = true;
15575                    }
15576                }
15577                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15578            }
15579
15580            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15581                // If we are visible, force the DRAWN bit to on so that
15582                // this invalidate will go through (at least to our parent).
15583                // This is because someone may have invalidated this view
15584                // before this call to setFrame came in, thereby clearing
15585                // the DRAWN bit.
15586                mPrivateFlags |= PFLAG_DRAWN;
15587                invalidate(sizeChanged);
15588                // parent display list may need to be recreated based on a change in the bounds
15589                // of any child
15590                invalidateParentCaches();
15591            }
15592
15593            // Reset drawn bit to original value (invalidate turns it off)
15594            mPrivateFlags |= drawn;
15595
15596            mBackgroundSizeChanged = true;
15597
15598            notifySubtreeAccessibilityStateChangedIfNeeded();
15599        }
15600        return changed;
15601    }
15602
15603    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15604        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15605        if (mOverlay != null) {
15606            mOverlay.getOverlayView().setRight(newWidth);
15607            mOverlay.getOverlayView().setBottom(newHeight);
15608        }
15609    }
15610
15611    /**
15612     * Finalize inflating a view from XML.  This is called as the last phase
15613     * of inflation, after all child views have been added.
15614     *
15615     * <p>Even if the subclass overrides onFinishInflate, they should always be
15616     * sure to call the super method, so that we get called.
15617     */
15618    protected void onFinishInflate() {
15619    }
15620
15621    /**
15622     * Returns the resources associated with this view.
15623     *
15624     * @return Resources object.
15625     */
15626    public Resources getResources() {
15627        return mResources;
15628    }
15629
15630    /**
15631     * Invalidates the specified Drawable.
15632     *
15633     * @param drawable the drawable to invalidate
15634     */
15635    @Override
15636    public void invalidateDrawable(Drawable drawable) {
15637        if (verifyDrawable(drawable)) {
15638            if (drawable == mBackground && mBackgroundDisplayList != null) {
15639                // We'll need to redraw the display list.
15640                mBackgroundDisplayList.clear();
15641            }
15642
15643            final Rect dirty = drawable.getDirtyBounds();
15644            final int scrollX = mScrollX;
15645            final int scrollY = mScrollY;
15646
15647            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15648                    dirty.right + scrollX, dirty.bottom + scrollY);
15649        }
15650    }
15651
15652    /**
15653     * Schedules an action on a drawable to occur at a specified time.
15654     *
15655     * @param who the recipient of the action
15656     * @param what the action to run on the drawable
15657     * @param when the time at which the action must occur. Uses the
15658     *        {@link SystemClock#uptimeMillis} timebase.
15659     */
15660    @Override
15661    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15662        if (verifyDrawable(who) && what != null) {
15663            final long delay = when - SystemClock.uptimeMillis();
15664            if (mAttachInfo != null) {
15665                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15666                        Choreographer.CALLBACK_ANIMATION, what, who,
15667                        Choreographer.subtractFrameDelay(delay));
15668            } else {
15669                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15670            }
15671        }
15672    }
15673
15674    /**
15675     * Cancels a scheduled action on a drawable.
15676     *
15677     * @param who the recipient of the action
15678     * @param what the action to cancel
15679     */
15680    @Override
15681    public void unscheduleDrawable(Drawable who, Runnable what) {
15682        if (verifyDrawable(who) && what != null) {
15683            if (mAttachInfo != null) {
15684                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15685                        Choreographer.CALLBACK_ANIMATION, what, who);
15686            }
15687            ViewRootImpl.getRunQueue().removeCallbacks(what);
15688        }
15689    }
15690
15691    /**
15692     * Unschedule any events associated with the given Drawable.  This can be
15693     * used when selecting a new Drawable into a view, so that the previous
15694     * one is completely unscheduled.
15695     *
15696     * @param who The Drawable to unschedule.
15697     *
15698     * @see #drawableStateChanged
15699     */
15700    public void unscheduleDrawable(Drawable who) {
15701        if (mAttachInfo != null && who != null) {
15702            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15703                    Choreographer.CALLBACK_ANIMATION, null, who);
15704        }
15705    }
15706
15707    /**
15708     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15709     * that the View directionality can and will be resolved before its Drawables.
15710     *
15711     * Will call {@link View#onResolveDrawables} when resolution is done.
15712     *
15713     * @hide
15714     */
15715    protected void resolveDrawables() {
15716        // Drawables resolution may need to happen before resolving the layout direction (which is
15717        // done only during the measure() call).
15718        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15719        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15720        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15721        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15722        // direction to be resolved as its resolved value will be the same as its raw value.
15723        if (!isLayoutDirectionResolved() &&
15724                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15725            return;
15726        }
15727
15728        final int layoutDirection = isLayoutDirectionResolved() ?
15729                getLayoutDirection() : getRawLayoutDirection();
15730
15731        if (mBackground != null) {
15732            mBackground.setLayoutDirection(layoutDirection);
15733        }
15734        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15735        onResolveDrawables(layoutDirection);
15736    }
15737
15738    /**
15739     * Called when layout direction has been resolved.
15740     *
15741     * The default implementation does nothing.
15742     *
15743     * @param layoutDirection The resolved layout direction.
15744     *
15745     * @see #LAYOUT_DIRECTION_LTR
15746     * @see #LAYOUT_DIRECTION_RTL
15747     *
15748     * @hide
15749     */
15750    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15751    }
15752
15753    /**
15754     * @hide
15755     */
15756    protected void resetResolvedDrawables() {
15757        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15758    }
15759
15760    private boolean isDrawablesResolved() {
15761        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15762    }
15763
15764    /**
15765     * If your view subclass is displaying its own Drawable objects, it should
15766     * override this function and return true for any Drawable it is
15767     * displaying.  This allows animations for those drawables to be
15768     * scheduled.
15769     *
15770     * <p>Be sure to call through to the super class when overriding this
15771     * function.
15772     *
15773     * @param who The Drawable to verify.  Return true if it is one you are
15774     *            displaying, else return the result of calling through to the
15775     *            super class.
15776     *
15777     * @return boolean If true than the Drawable is being displayed in the
15778     *         view; else false and it is not allowed to animate.
15779     *
15780     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15781     * @see #drawableStateChanged()
15782     */
15783    protected boolean verifyDrawable(Drawable who) {
15784        return who == mBackground;
15785    }
15786
15787    /**
15788     * This function is called whenever the state of the view changes in such
15789     * a way that it impacts the state of drawables being shown.
15790     *
15791     * <p>Be sure to call through to the superclass when overriding this
15792     * function.
15793     *
15794     * @see Drawable#setState(int[])
15795     */
15796    protected void drawableStateChanged() {
15797        final Drawable d = mBackground;
15798        if (d != null && d.isStateful()) {
15799            d.setState(getDrawableState());
15800        }
15801    }
15802
15803    /**
15804     * Call this to force a view to update its drawable state. This will cause
15805     * drawableStateChanged to be called on this view. Views that are interested
15806     * in the new state should call getDrawableState.
15807     *
15808     * @see #drawableStateChanged
15809     * @see #getDrawableState
15810     */
15811    public void refreshDrawableState() {
15812        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15813        drawableStateChanged();
15814
15815        ViewParent parent = mParent;
15816        if (parent != null) {
15817            parent.childDrawableStateChanged(this);
15818        }
15819    }
15820
15821    /**
15822     * Return an array of resource IDs of the drawable states representing the
15823     * current state of the view.
15824     *
15825     * @return The current drawable state
15826     *
15827     * @see Drawable#setState(int[])
15828     * @see #drawableStateChanged()
15829     * @see #onCreateDrawableState(int)
15830     */
15831    public final int[] getDrawableState() {
15832        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15833            return mDrawableState;
15834        } else {
15835            mDrawableState = onCreateDrawableState(0);
15836            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15837            return mDrawableState;
15838        }
15839    }
15840
15841    /**
15842     * Generate the new {@link android.graphics.drawable.Drawable} state for
15843     * this view. This is called by the view
15844     * system when the cached Drawable state is determined to be invalid.  To
15845     * retrieve the current state, you should use {@link #getDrawableState}.
15846     *
15847     * @param extraSpace if non-zero, this is the number of extra entries you
15848     * would like in the returned array in which you can place your own
15849     * states.
15850     *
15851     * @return Returns an array holding the current {@link Drawable} state of
15852     * the view.
15853     *
15854     * @see #mergeDrawableStates(int[], int[])
15855     */
15856    protected int[] onCreateDrawableState(int extraSpace) {
15857        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15858                mParent instanceof View) {
15859            return ((View) mParent).onCreateDrawableState(extraSpace);
15860        }
15861
15862        int[] drawableState;
15863
15864        int privateFlags = mPrivateFlags;
15865
15866        int viewStateIndex = 0;
15867        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15868        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15869        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15870        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15871        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15872        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15873        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15874                HardwareRenderer.isAvailable()) {
15875            // This is set if HW acceleration is requested, even if the current
15876            // process doesn't allow it.  This is just to allow app preview
15877            // windows to better match their app.
15878            viewStateIndex |= VIEW_STATE_ACCELERATED;
15879        }
15880        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15881
15882        final int privateFlags2 = mPrivateFlags2;
15883        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15884        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15885
15886        drawableState = VIEW_STATE_SETS[viewStateIndex];
15887
15888        //noinspection ConstantIfStatement
15889        if (false) {
15890            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15891            Log.i("View", toString()
15892                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15893                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15894                    + " fo=" + hasFocus()
15895                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15896                    + " wf=" + hasWindowFocus()
15897                    + ": " + Arrays.toString(drawableState));
15898        }
15899
15900        if (extraSpace == 0) {
15901            return drawableState;
15902        }
15903
15904        final int[] fullState;
15905        if (drawableState != null) {
15906            fullState = new int[drawableState.length + extraSpace];
15907            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15908        } else {
15909            fullState = new int[extraSpace];
15910        }
15911
15912        return fullState;
15913    }
15914
15915    /**
15916     * Merge your own state values in <var>additionalState</var> into the base
15917     * state values <var>baseState</var> that were returned by
15918     * {@link #onCreateDrawableState(int)}.
15919     *
15920     * @param baseState The base state values returned by
15921     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15922     * own additional state values.
15923     *
15924     * @param additionalState The additional state values you would like
15925     * added to <var>baseState</var>; this array is not modified.
15926     *
15927     * @return As a convenience, the <var>baseState</var> array you originally
15928     * passed into the function is returned.
15929     *
15930     * @see #onCreateDrawableState(int)
15931     */
15932    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15933        final int N = baseState.length;
15934        int i = N - 1;
15935        while (i >= 0 && baseState[i] == 0) {
15936            i--;
15937        }
15938        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15939        return baseState;
15940    }
15941
15942    /**
15943     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15944     * on all Drawable objects associated with this view.
15945     */
15946    public void jumpDrawablesToCurrentState() {
15947        if (mBackground != null) {
15948            mBackground.jumpToCurrentState();
15949        }
15950    }
15951
15952    /**
15953     * Sets the background color for this view.
15954     * @param color the color of the background
15955     */
15956    @RemotableViewMethod
15957    public void setBackgroundColor(int color) {
15958        if (mBackground instanceof ColorDrawable) {
15959            ((ColorDrawable) mBackground.mutate()).setColor(color);
15960            computeOpaqueFlags();
15961            mBackgroundResource = 0;
15962        } else {
15963            setBackground(new ColorDrawable(color));
15964        }
15965    }
15966
15967    /**
15968     * Set the background to a given resource. The resource should refer to
15969     * a Drawable object or 0 to remove the background.
15970     * @param resid The identifier of the resource.
15971     *
15972     * @attr ref android.R.styleable#View_background
15973     */
15974    @RemotableViewMethod
15975    public void setBackgroundResource(int resid) {
15976        if (resid != 0 && resid == mBackgroundResource) {
15977            return;
15978        }
15979
15980        Drawable d= null;
15981        if (resid != 0) {
15982            d = mContext.getDrawable(resid);
15983        }
15984        setBackground(d);
15985
15986        mBackgroundResource = resid;
15987    }
15988
15989    /**
15990     * Set the background to a given Drawable, or remove the background. If the
15991     * background has padding, this View's padding is set to the background's
15992     * padding. However, when a background is removed, this View's padding isn't
15993     * touched. If setting the padding is desired, please use
15994     * {@link #setPadding(int, int, int, int)}.
15995     *
15996     * @param background The Drawable to use as the background, or null to remove the
15997     *        background
15998     */
15999    public void setBackground(Drawable background) {
16000        //noinspection deprecation
16001        setBackgroundDrawable(background);
16002    }
16003
16004    /**
16005     * @deprecated use {@link #setBackground(Drawable)} instead
16006     */
16007    @Deprecated
16008    public void setBackgroundDrawable(Drawable background) {
16009        computeOpaqueFlags();
16010
16011        if (background == mBackground) {
16012            return;
16013        }
16014
16015        boolean requestLayout = false;
16016
16017        mBackgroundResource = 0;
16018
16019        /*
16020         * Regardless of whether we're setting a new background or not, we want
16021         * to clear the previous drawable.
16022         */
16023        if (mBackground != null) {
16024            mBackground.setCallback(null);
16025            unscheduleDrawable(mBackground);
16026        }
16027
16028        if (background != null) {
16029            Rect padding = sThreadLocal.get();
16030            if (padding == null) {
16031                padding = new Rect();
16032                sThreadLocal.set(padding);
16033            }
16034            resetResolvedDrawables();
16035            background.setLayoutDirection(getLayoutDirection());
16036            if (background.getPadding(padding)) {
16037                resetResolvedPadding();
16038                switch (background.getLayoutDirection()) {
16039                    case LAYOUT_DIRECTION_RTL:
16040                        mUserPaddingLeftInitial = padding.right;
16041                        mUserPaddingRightInitial = padding.left;
16042                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16043                        break;
16044                    case LAYOUT_DIRECTION_LTR:
16045                    default:
16046                        mUserPaddingLeftInitial = padding.left;
16047                        mUserPaddingRightInitial = padding.right;
16048                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16049                }
16050                mLeftPaddingDefined = false;
16051                mRightPaddingDefined = false;
16052            }
16053
16054            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16055            // if it has a different minimum size, we should layout again
16056            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
16057                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16058                requestLayout = true;
16059            }
16060
16061            background.setCallback(this);
16062            if (background.isStateful()) {
16063                background.setState(getDrawableState());
16064            }
16065            background.setVisible(getVisibility() == VISIBLE, false);
16066            mBackground = background;
16067
16068            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16069                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16070                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16071                requestLayout = true;
16072            }
16073        } else {
16074            /* Remove the background */
16075            mBackground = null;
16076
16077            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16078                /*
16079                 * This view ONLY drew the background before and we're removing
16080                 * the background, so now it won't draw anything
16081                 * (hence we SKIP_DRAW)
16082                 */
16083                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16084                mPrivateFlags |= PFLAG_SKIP_DRAW;
16085            }
16086
16087            /*
16088             * When the background is set, we try to apply its padding to this
16089             * View. When the background is removed, we don't touch this View's
16090             * padding. This is noted in the Javadocs. Hence, we don't need to
16091             * requestLayout(), the invalidate() below is sufficient.
16092             */
16093
16094            // The old background's minimum size could have affected this
16095            // View's layout, so let's requestLayout
16096            requestLayout = true;
16097        }
16098
16099        computeOpaqueFlags();
16100
16101        if (requestLayout) {
16102            requestLayout();
16103        }
16104
16105        mBackgroundSizeChanged = true;
16106        invalidate(true);
16107    }
16108
16109    /**
16110     * Gets the background drawable
16111     *
16112     * @return The drawable used as the background for this view, if any.
16113     *
16114     * @see #setBackground(Drawable)
16115     *
16116     * @attr ref android.R.styleable#View_background
16117     */
16118    public Drawable getBackground() {
16119        return mBackground;
16120    }
16121
16122    /**
16123     * Sets the padding. The view may add on the space required to display
16124     * the scrollbars, depending on the style and visibility of the scrollbars.
16125     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16126     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16127     * from the values set in this call.
16128     *
16129     * @attr ref android.R.styleable#View_padding
16130     * @attr ref android.R.styleable#View_paddingBottom
16131     * @attr ref android.R.styleable#View_paddingLeft
16132     * @attr ref android.R.styleable#View_paddingRight
16133     * @attr ref android.R.styleable#View_paddingTop
16134     * @param left the left padding in pixels
16135     * @param top the top padding in pixels
16136     * @param right the right padding in pixels
16137     * @param bottom the bottom padding in pixels
16138     */
16139    public void setPadding(int left, int top, int right, int bottom) {
16140        resetResolvedPadding();
16141
16142        mUserPaddingStart = UNDEFINED_PADDING;
16143        mUserPaddingEnd = UNDEFINED_PADDING;
16144
16145        mUserPaddingLeftInitial = left;
16146        mUserPaddingRightInitial = right;
16147
16148        mLeftPaddingDefined = true;
16149        mRightPaddingDefined = true;
16150
16151        internalSetPadding(left, top, right, bottom);
16152    }
16153
16154    /**
16155     * @hide
16156     */
16157    protected void internalSetPadding(int left, int top, int right, int bottom) {
16158        mUserPaddingLeft = left;
16159        mUserPaddingRight = right;
16160        mUserPaddingBottom = bottom;
16161
16162        final int viewFlags = mViewFlags;
16163        boolean changed = false;
16164
16165        // Common case is there are no scroll bars.
16166        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16167            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16168                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16169                        ? 0 : getVerticalScrollbarWidth();
16170                switch (mVerticalScrollbarPosition) {
16171                    case SCROLLBAR_POSITION_DEFAULT:
16172                        if (isLayoutRtl()) {
16173                            left += offset;
16174                        } else {
16175                            right += offset;
16176                        }
16177                        break;
16178                    case SCROLLBAR_POSITION_RIGHT:
16179                        right += offset;
16180                        break;
16181                    case SCROLLBAR_POSITION_LEFT:
16182                        left += offset;
16183                        break;
16184                }
16185            }
16186            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16187                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16188                        ? 0 : getHorizontalScrollbarHeight();
16189            }
16190        }
16191
16192        if (mPaddingLeft != left) {
16193            changed = true;
16194            mPaddingLeft = left;
16195        }
16196        if (mPaddingTop != top) {
16197            changed = true;
16198            mPaddingTop = top;
16199        }
16200        if (mPaddingRight != right) {
16201            changed = true;
16202            mPaddingRight = right;
16203        }
16204        if (mPaddingBottom != bottom) {
16205            changed = true;
16206            mPaddingBottom = bottom;
16207        }
16208
16209        if (changed) {
16210            requestLayout();
16211        }
16212    }
16213
16214    /**
16215     * Sets the relative padding. The view may add on the space required to display
16216     * the scrollbars, depending on the style and visibility of the scrollbars.
16217     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16218     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16219     * from the values set in this call.
16220     *
16221     * @attr ref android.R.styleable#View_padding
16222     * @attr ref android.R.styleable#View_paddingBottom
16223     * @attr ref android.R.styleable#View_paddingStart
16224     * @attr ref android.R.styleable#View_paddingEnd
16225     * @attr ref android.R.styleable#View_paddingTop
16226     * @param start the start padding in pixels
16227     * @param top the top padding in pixels
16228     * @param end the end padding in pixels
16229     * @param bottom the bottom padding in pixels
16230     */
16231    public void setPaddingRelative(int start, int top, int end, int bottom) {
16232        resetResolvedPadding();
16233
16234        mUserPaddingStart = start;
16235        mUserPaddingEnd = end;
16236        mLeftPaddingDefined = true;
16237        mRightPaddingDefined = true;
16238
16239        switch(getLayoutDirection()) {
16240            case LAYOUT_DIRECTION_RTL:
16241                mUserPaddingLeftInitial = end;
16242                mUserPaddingRightInitial = start;
16243                internalSetPadding(end, top, start, bottom);
16244                break;
16245            case LAYOUT_DIRECTION_LTR:
16246            default:
16247                mUserPaddingLeftInitial = start;
16248                mUserPaddingRightInitial = end;
16249                internalSetPadding(start, top, end, bottom);
16250        }
16251    }
16252
16253    /**
16254     * Returns the top padding of this view.
16255     *
16256     * @return the top padding in pixels
16257     */
16258    public int getPaddingTop() {
16259        return mPaddingTop;
16260    }
16261
16262    /**
16263     * Returns the bottom padding of this view. If there are inset and enabled
16264     * scrollbars, this value may include the space required to display the
16265     * scrollbars as well.
16266     *
16267     * @return the bottom padding in pixels
16268     */
16269    public int getPaddingBottom() {
16270        return mPaddingBottom;
16271    }
16272
16273    /**
16274     * Returns the left padding of this view. If there are inset and enabled
16275     * scrollbars, this value may include the space required to display the
16276     * scrollbars as well.
16277     *
16278     * @return the left padding in pixels
16279     */
16280    public int getPaddingLeft() {
16281        if (!isPaddingResolved()) {
16282            resolvePadding();
16283        }
16284        return mPaddingLeft;
16285    }
16286
16287    /**
16288     * Returns the start padding of this view depending on its resolved layout direction.
16289     * If there are inset and enabled scrollbars, this value may include the space
16290     * required to display the scrollbars as well.
16291     *
16292     * @return the start padding in pixels
16293     */
16294    public int getPaddingStart() {
16295        if (!isPaddingResolved()) {
16296            resolvePadding();
16297        }
16298        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16299                mPaddingRight : mPaddingLeft;
16300    }
16301
16302    /**
16303     * Returns the right padding of this view. If there are inset and enabled
16304     * scrollbars, this value may include the space required to display the
16305     * scrollbars as well.
16306     *
16307     * @return the right padding in pixels
16308     */
16309    public int getPaddingRight() {
16310        if (!isPaddingResolved()) {
16311            resolvePadding();
16312        }
16313        return mPaddingRight;
16314    }
16315
16316    /**
16317     * Returns the end padding of this view depending on its resolved layout direction.
16318     * If there are inset and enabled scrollbars, this value may include the space
16319     * required to display the scrollbars as well.
16320     *
16321     * @return the end padding in pixels
16322     */
16323    public int getPaddingEnd() {
16324        if (!isPaddingResolved()) {
16325            resolvePadding();
16326        }
16327        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16328                mPaddingLeft : mPaddingRight;
16329    }
16330
16331    /**
16332     * Return if the padding as been set thru relative values
16333     * {@link #setPaddingRelative(int, int, int, int)} or thru
16334     * @attr ref android.R.styleable#View_paddingStart or
16335     * @attr ref android.R.styleable#View_paddingEnd
16336     *
16337     * @return true if the padding is relative or false if it is not.
16338     */
16339    public boolean isPaddingRelative() {
16340        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16341    }
16342
16343    Insets computeOpticalInsets() {
16344        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16345    }
16346
16347    /**
16348     * @hide
16349     */
16350    public void resetPaddingToInitialValues() {
16351        if (isRtlCompatibilityMode()) {
16352            mPaddingLeft = mUserPaddingLeftInitial;
16353            mPaddingRight = mUserPaddingRightInitial;
16354            return;
16355        }
16356        if (isLayoutRtl()) {
16357            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16358            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16359        } else {
16360            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16361            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16362        }
16363    }
16364
16365    /**
16366     * @hide
16367     */
16368    public Insets getOpticalInsets() {
16369        if (mLayoutInsets == null) {
16370            mLayoutInsets = computeOpticalInsets();
16371        }
16372        return mLayoutInsets;
16373    }
16374
16375    /**
16376     * Changes the selection state of this view. A view can be selected or not.
16377     * Note that selection is not the same as focus. Views are typically
16378     * selected in the context of an AdapterView like ListView or GridView;
16379     * the selected view is the view that is highlighted.
16380     *
16381     * @param selected true if the view must be selected, false otherwise
16382     */
16383    public void setSelected(boolean selected) {
16384        //noinspection DoubleNegation
16385        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16386            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16387            if (!selected) resetPressedState();
16388            invalidate(true);
16389            refreshDrawableState();
16390            dispatchSetSelected(selected);
16391            notifyViewAccessibilityStateChangedIfNeeded(
16392                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16393        }
16394    }
16395
16396    /**
16397     * Dispatch setSelected to all of this View's children.
16398     *
16399     * @see #setSelected(boolean)
16400     *
16401     * @param selected The new selected state
16402     */
16403    protected void dispatchSetSelected(boolean selected) {
16404    }
16405
16406    /**
16407     * Indicates the selection state of this view.
16408     *
16409     * @return true if the view is selected, false otherwise
16410     */
16411    @ViewDebug.ExportedProperty
16412    public boolean isSelected() {
16413        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16414    }
16415
16416    /**
16417     * Changes the activated state of this view. A view can be activated or not.
16418     * Note that activation is not the same as selection.  Selection is
16419     * a transient property, representing the view (hierarchy) the user is
16420     * currently interacting with.  Activation is a longer-term state that the
16421     * user can move views in and out of.  For example, in a list view with
16422     * single or multiple selection enabled, the views in the current selection
16423     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16424     * here.)  The activated state is propagated down to children of the view it
16425     * is set on.
16426     *
16427     * @param activated true if the view must be activated, false otherwise
16428     */
16429    public void setActivated(boolean activated) {
16430        //noinspection DoubleNegation
16431        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16432            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16433            invalidate(true);
16434            refreshDrawableState();
16435            dispatchSetActivated(activated);
16436        }
16437    }
16438
16439    /**
16440     * Dispatch setActivated to all of this View's children.
16441     *
16442     * @see #setActivated(boolean)
16443     *
16444     * @param activated The new activated state
16445     */
16446    protected void dispatchSetActivated(boolean activated) {
16447    }
16448
16449    /**
16450     * Indicates the activation state of this view.
16451     *
16452     * @return true if the view is activated, false otherwise
16453     */
16454    @ViewDebug.ExportedProperty
16455    public boolean isActivated() {
16456        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16457    }
16458
16459    /**
16460     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16461     * observer can be used to get notifications when global events, like
16462     * layout, happen.
16463     *
16464     * The returned ViewTreeObserver observer is not guaranteed to remain
16465     * valid for the lifetime of this View. If the caller of this method keeps
16466     * a long-lived reference to ViewTreeObserver, it should always check for
16467     * the return value of {@link ViewTreeObserver#isAlive()}.
16468     *
16469     * @return The ViewTreeObserver for this view's hierarchy.
16470     */
16471    public ViewTreeObserver getViewTreeObserver() {
16472        if (mAttachInfo != null) {
16473            return mAttachInfo.mTreeObserver;
16474        }
16475        if (mFloatingTreeObserver == null) {
16476            mFloatingTreeObserver = new ViewTreeObserver();
16477        }
16478        return mFloatingTreeObserver;
16479    }
16480
16481    /**
16482     * <p>Finds the topmost view in the current view hierarchy.</p>
16483     *
16484     * @return the topmost view containing this view
16485     */
16486    public View getRootView() {
16487        if (mAttachInfo != null) {
16488            final View v = mAttachInfo.mRootView;
16489            if (v != null) {
16490                return v;
16491            }
16492        }
16493
16494        View parent = this;
16495
16496        while (parent.mParent != null && parent.mParent instanceof View) {
16497            parent = (View) parent.mParent;
16498        }
16499
16500        return parent;
16501    }
16502
16503    /**
16504     * Transforms a motion event from view-local coordinates to on-screen
16505     * coordinates.
16506     *
16507     * @param ev the view-local motion event
16508     * @return false if the transformation could not be applied
16509     * @hide
16510     */
16511    public boolean toGlobalMotionEvent(MotionEvent ev) {
16512        final AttachInfo info = mAttachInfo;
16513        if (info == null) {
16514            return false;
16515        }
16516
16517        final Matrix m = info.mTmpMatrix;
16518        m.set(Matrix.IDENTITY_MATRIX);
16519        transformMatrixToGlobal(m);
16520        ev.transform(m);
16521        return true;
16522    }
16523
16524    /**
16525     * Transforms a motion event from on-screen coordinates to view-local
16526     * coordinates.
16527     *
16528     * @param ev the on-screen motion event
16529     * @return false if the transformation could not be applied
16530     * @hide
16531     */
16532    public boolean toLocalMotionEvent(MotionEvent ev) {
16533        final AttachInfo info = mAttachInfo;
16534        if (info == null) {
16535            return false;
16536        }
16537
16538        final Matrix m = info.mTmpMatrix;
16539        m.set(Matrix.IDENTITY_MATRIX);
16540        transformMatrixToLocal(m);
16541        ev.transform(m);
16542        return true;
16543    }
16544
16545    /**
16546     * Modifies the input matrix such that it maps view-local coordinates to
16547     * on-screen coordinates.
16548     *
16549     * @param m input matrix to modify
16550     */
16551    void transformMatrixToGlobal(Matrix m) {
16552        final ViewParent parent = mParent;
16553        if (parent instanceof View) {
16554            final View vp = (View) parent;
16555            vp.transformMatrixToGlobal(m);
16556            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16557        } else if (parent instanceof ViewRootImpl) {
16558            final ViewRootImpl vr = (ViewRootImpl) parent;
16559            vr.transformMatrixToGlobal(m);
16560            m.postTranslate(0, -vr.mCurScrollY);
16561        }
16562
16563        m.postTranslate(mLeft, mTop);
16564
16565        if (!hasIdentityMatrix()) {
16566            m.postConcat(getMatrix());
16567        }
16568    }
16569
16570    /**
16571     * Modifies the input matrix such that it maps on-screen coordinates to
16572     * view-local coordinates.
16573     *
16574     * @param m input matrix to modify
16575     */
16576    void transformMatrixToLocal(Matrix m) {
16577        final ViewParent parent = mParent;
16578        if (parent instanceof View) {
16579            final View vp = (View) parent;
16580            vp.transformMatrixToLocal(m);
16581            m.preTranslate(vp.mScrollX, vp.mScrollY);
16582        } else if (parent instanceof ViewRootImpl) {
16583            final ViewRootImpl vr = (ViewRootImpl) parent;
16584            vr.transformMatrixToLocal(m);
16585            m.preTranslate(0, vr.mCurScrollY);
16586        }
16587
16588        m.preTranslate(-mLeft, -mTop);
16589
16590        if (!hasIdentityMatrix()) {
16591            m.preConcat(getInverseMatrix());
16592        }
16593    }
16594
16595    /**
16596     * <p>Computes the coordinates of this view on the screen. The argument
16597     * must be an array of two integers. After the method returns, the array
16598     * contains the x and y location in that order.</p>
16599     *
16600     * @param location an array of two integers in which to hold the coordinates
16601     */
16602    public void getLocationOnScreen(int[] location) {
16603        getLocationInWindow(location);
16604
16605        final AttachInfo info = mAttachInfo;
16606        if (info != null) {
16607            location[0] += info.mWindowLeft;
16608            location[1] += info.mWindowTop;
16609        }
16610    }
16611
16612    /**
16613     * <p>Computes the coordinates of this view in its window. The argument
16614     * must be an array of two integers. After the method returns, the array
16615     * contains the x and y location in that order.</p>
16616     *
16617     * @param location an array of two integers in which to hold the coordinates
16618     */
16619    public void getLocationInWindow(int[] location) {
16620        if (location == null || location.length < 2) {
16621            throw new IllegalArgumentException("location must be an array of two integers");
16622        }
16623
16624        if (mAttachInfo == null) {
16625            // When the view is not attached to a window, this method does not make sense
16626            location[0] = location[1] = 0;
16627            return;
16628        }
16629
16630        float[] position = mAttachInfo.mTmpTransformLocation;
16631        position[0] = position[1] = 0.0f;
16632
16633        if (!hasIdentityMatrix()) {
16634            getMatrix().mapPoints(position);
16635        }
16636
16637        position[0] += mLeft;
16638        position[1] += mTop;
16639
16640        ViewParent viewParent = mParent;
16641        while (viewParent instanceof View) {
16642            final View view = (View) viewParent;
16643
16644            position[0] -= view.mScrollX;
16645            position[1] -= view.mScrollY;
16646
16647            if (!view.hasIdentityMatrix()) {
16648                view.getMatrix().mapPoints(position);
16649            }
16650
16651            position[0] += view.mLeft;
16652            position[1] += view.mTop;
16653
16654            viewParent = view.mParent;
16655         }
16656
16657        if (viewParent instanceof ViewRootImpl) {
16658            // *cough*
16659            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16660            position[1] -= vr.mCurScrollY;
16661        }
16662
16663        location[0] = (int) (position[0] + 0.5f);
16664        location[1] = (int) (position[1] + 0.5f);
16665    }
16666
16667    /**
16668     * {@hide}
16669     * @param id the id of the view to be found
16670     * @return the view of the specified id, null if cannot be found
16671     */
16672    protected View findViewTraversal(int id) {
16673        if (id == mID) {
16674            return this;
16675        }
16676        return null;
16677    }
16678
16679    /**
16680     * {@hide}
16681     * @param tag the tag of the view to be found
16682     * @return the view of specified tag, null if cannot be found
16683     */
16684    protected View findViewWithTagTraversal(Object tag) {
16685        if (tag != null && tag.equals(mTag)) {
16686            return this;
16687        }
16688        return null;
16689    }
16690
16691    /**
16692     * {@hide}
16693     * @param predicate The predicate to evaluate.
16694     * @param childToSkip If not null, ignores this child during the recursive traversal.
16695     * @return The first view that matches the predicate or null.
16696     */
16697    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16698        if (predicate.apply(this)) {
16699            return this;
16700        }
16701        return null;
16702    }
16703
16704    /**
16705     * Look for a child view with the given id.  If this view has the given
16706     * id, return this view.
16707     *
16708     * @param id The id to search for.
16709     * @return The view that has the given id in the hierarchy or null
16710     */
16711    public final View findViewById(int id) {
16712        if (id < 0) {
16713            return null;
16714        }
16715        return findViewTraversal(id);
16716    }
16717
16718    /**
16719     * Finds a view by its unuque and stable accessibility id.
16720     *
16721     * @param accessibilityId The searched accessibility id.
16722     * @return The found view.
16723     */
16724    final View findViewByAccessibilityId(int accessibilityId) {
16725        if (accessibilityId < 0) {
16726            return null;
16727        }
16728        return findViewByAccessibilityIdTraversal(accessibilityId);
16729    }
16730
16731    /**
16732     * Performs the traversal to find a view by its unuque and stable accessibility id.
16733     *
16734     * <strong>Note:</strong>This method does not stop at the root namespace
16735     * boundary since the user can touch the screen at an arbitrary location
16736     * potentially crossing the root namespace bounday which will send an
16737     * accessibility event to accessibility services and they should be able
16738     * to obtain the event source. Also accessibility ids are guaranteed to be
16739     * unique in the window.
16740     *
16741     * @param accessibilityId The accessibility id.
16742     * @return The found view.
16743     *
16744     * @hide
16745     */
16746    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16747        if (getAccessibilityViewId() == accessibilityId) {
16748            return this;
16749        }
16750        return null;
16751    }
16752
16753    /**
16754     * Look for a child view with the given tag.  If this view has the given
16755     * tag, return this view.
16756     *
16757     * @param tag The tag to search for, using "tag.equals(getTag())".
16758     * @return The View that has the given tag in the hierarchy or null
16759     */
16760    public final View findViewWithTag(Object tag) {
16761        if (tag == null) {
16762            return null;
16763        }
16764        return findViewWithTagTraversal(tag);
16765    }
16766
16767    /**
16768     * {@hide}
16769     * Look for a child view that matches the specified predicate.
16770     * If this view matches the predicate, return this view.
16771     *
16772     * @param predicate The predicate to evaluate.
16773     * @return The first view that matches the predicate or null.
16774     */
16775    public final View findViewByPredicate(Predicate<View> predicate) {
16776        return findViewByPredicateTraversal(predicate, null);
16777    }
16778
16779    /**
16780     * {@hide}
16781     * Look for a child view that matches the specified predicate,
16782     * starting with the specified view and its descendents and then
16783     * recusively searching the ancestors and siblings of that view
16784     * until this view is reached.
16785     *
16786     * This method is useful in cases where the predicate does not match
16787     * a single unique view (perhaps multiple views use the same id)
16788     * and we are trying to find the view that is "closest" in scope to the
16789     * starting view.
16790     *
16791     * @param start The view to start from.
16792     * @param predicate The predicate to evaluate.
16793     * @return The first view that matches the predicate or null.
16794     */
16795    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16796        View childToSkip = null;
16797        for (;;) {
16798            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16799            if (view != null || start == this) {
16800                return view;
16801            }
16802
16803            ViewParent parent = start.getParent();
16804            if (parent == null || !(parent instanceof View)) {
16805                return null;
16806            }
16807
16808            childToSkip = start;
16809            start = (View) parent;
16810        }
16811    }
16812
16813    /**
16814     * Sets the identifier for this view. The identifier does not have to be
16815     * unique in this view's hierarchy. The identifier should be a positive
16816     * number.
16817     *
16818     * @see #NO_ID
16819     * @see #getId()
16820     * @see #findViewById(int)
16821     *
16822     * @param id a number used to identify the view
16823     *
16824     * @attr ref android.R.styleable#View_id
16825     */
16826    public void setId(int id) {
16827        mID = id;
16828        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16829            mID = generateViewId();
16830        }
16831    }
16832
16833    /**
16834     * {@hide}
16835     *
16836     * @param isRoot true if the view belongs to the root namespace, false
16837     *        otherwise
16838     */
16839    public void setIsRootNamespace(boolean isRoot) {
16840        if (isRoot) {
16841            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16842        } else {
16843            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16844        }
16845    }
16846
16847    /**
16848     * {@hide}
16849     *
16850     * @return true if the view belongs to the root namespace, false otherwise
16851     */
16852    public boolean isRootNamespace() {
16853        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16854    }
16855
16856    /**
16857     * Returns this view's identifier.
16858     *
16859     * @return a positive integer used to identify the view or {@link #NO_ID}
16860     *         if the view has no ID
16861     *
16862     * @see #setId(int)
16863     * @see #findViewById(int)
16864     * @attr ref android.R.styleable#View_id
16865     */
16866    @ViewDebug.CapturedViewProperty
16867    public int getId() {
16868        return mID;
16869    }
16870
16871    /**
16872     * Returns this view's tag.
16873     *
16874     * @return the Object stored in this view as a tag, or {@code null} if not
16875     *         set
16876     *
16877     * @see #setTag(Object)
16878     * @see #getTag(int)
16879     */
16880    @ViewDebug.ExportedProperty
16881    public Object getTag() {
16882        return mTag;
16883    }
16884
16885    /**
16886     * Sets the tag associated with this view. A tag can be used to mark
16887     * a view in its hierarchy and does not have to be unique within the
16888     * hierarchy. Tags can also be used to store data within a view without
16889     * resorting to another data structure.
16890     *
16891     * @param tag an Object to tag the view with
16892     *
16893     * @see #getTag()
16894     * @see #setTag(int, Object)
16895     */
16896    public void setTag(final Object tag) {
16897        mTag = tag;
16898    }
16899
16900    /**
16901     * Returns the tag associated with this view and the specified key.
16902     *
16903     * @param key The key identifying the tag
16904     *
16905     * @return the Object stored in this view as a tag, or {@code null} if not
16906     *         set
16907     *
16908     * @see #setTag(int, Object)
16909     * @see #getTag()
16910     */
16911    public Object getTag(int key) {
16912        if (mKeyedTags != null) return mKeyedTags.get(key);
16913        return null;
16914    }
16915
16916    /**
16917     * Sets a tag associated with this view and a key. A tag can be used
16918     * to mark a view in its hierarchy and does not have to be unique within
16919     * the hierarchy. Tags can also be used to store data within a view
16920     * without resorting to another data structure.
16921     *
16922     * The specified key should be an id declared in the resources of the
16923     * application to ensure it is unique (see the <a
16924     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16925     * Keys identified as belonging to
16926     * the Android framework or not associated with any package will cause
16927     * an {@link IllegalArgumentException} to be thrown.
16928     *
16929     * @param key The key identifying the tag
16930     * @param tag An Object to tag the view with
16931     *
16932     * @throws IllegalArgumentException If they specified key is not valid
16933     *
16934     * @see #setTag(Object)
16935     * @see #getTag(int)
16936     */
16937    public void setTag(int key, final Object tag) {
16938        // If the package id is 0x00 or 0x01, it's either an undefined package
16939        // or a framework id
16940        if ((key >>> 24) < 2) {
16941            throw new IllegalArgumentException("The key must be an application-specific "
16942                    + "resource id.");
16943        }
16944
16945        setKeyedTag(key, tag);
16946    }
16947
16948    /**
16949     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16950     * framework id.
16951     *
16952     * @hide
16953     */
16954    public void setTagInternal(int key, Object tag) {
16955        if ((key >>> 24) != 0x1) {
16956            throw new IllegalArgumentException("The key must be a framework-specific "
16957                    + "resource id.");
16958        }
16959
16960        setKeyedTag(key, tag);
16961    }
16962
16963    private void setKeyedTag(int key, Object tag) {
16964        if (mKeyedTags == null) {
16965            mKeyedTags = new SparseArray<Object>(2);
16966        }
16967
16968        mKeyedTags.put(key, tag);
16969    }
16970
16971    /**
16972     * Prints information about this view in the log output, with the tag
16973     * {@link #VIEW_LOG_TAG}.
16974     *
16975     * @hide
16976     */
16977    public void debug() {
16978        debug(0);
16979    }
16980
16981    /**
16982     * Prints information about this view in the log output, with the tag
16983     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16984     * indentation defined by the <code>depth</code>.
16985     *
16986     * @param depth the indentation level
16987     *
16988     * @hide
16989     */
16990    protected void debug(int depth) {
16991        String output = debugIndent(depth - 1);
16992
16993        output += "+ " + this;
16994        int id = getId();
16995        if (id != -1) {
16996            output += " (id=" + id + ")";
16997        }
16998        Object tag = getTag();
16999        if (tag != null) {
17000            output += " (tag=" + tag + ")";
17001        }
17002        Log.d(VIEW_LOG_TAG, output);
17003
17004        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17005            output = debugIndent(depth) + " FOCUSED";
17006            Log.d(VIEW_LOG_TAG, output);
17007        }
17008
17009        output = debugIndent(depth);
17010        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17011                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17012                + "} ";
17013        Log.d(VIEW_LOG_TAG, output);
17014
17015        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17016                || mPaddingBottom != 0) {
17017            output = debugIndent(depth);
17018            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17019                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17020            Log.d(VIEW_LOG_TAG, output);
17021        }
17022
17023        output = debugIndent(depth);
17024        output += "mMeasureWidth=" + mMeasuredWidth +
17025                " mMeasureHeight=" + mMeasuredHeight;
17026        Log.d(VIEW_LOG_TAG, output);
17027
17028        output = debugIndent(depth);
17029        if (mLayoutParams == null) {
17030            output += "BAD! no layout params";
17031        } else {
17032            output = mLayoutParams.debug(output);
17033        }
17034        Log.d(VIEW_LOG_TAG, output);
17035
17036        output = debugIndent(depth);
17037        output += "flags={";
17038        output += View.printFlags(mViewFlags);
17039        output += "}";
17040        Log.d(VIEW_LOG_TAG, output);
17041
17042        output = debugIndent(depth);
17043        output += "privateFlags={";
17044        output += View.printPrivateFlags(mPrivateFlags);
17045        output += "}";
17046        Log.d(VIEW_LOG_TAG, output);
17047    }
17048
17049    /**
17050     * Creates a string of whitespaces used for indentation.
17051     *
17052     * @param depth the indentation level
17053     * @return a String containing (depth * 2 + 3) * 2 white spaces
17054     *
17055     * @hide
17056     */
17057    protected static String debugIndent(int depth) {
17058        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17059        for (int i = 0; i < (depth * 2) + 3; i++) {
17060            spaces.append(' ').append(' ');
17061        }
17062        return spaces.toString();
17063    }
17064
17065    /**
17066     * <p>Return the offset of the widget's text baseline from the widget's top
17067     * boundary. If this widget does not support baseline alignment, this
17068     * method returns -1. </p>
17069     *
17070     * @return the offset of the baseline within the widget's bounds or -1
17071     *         if baseline alignment is not supported
17072     */
17073    @ViewDebug.ExportedProperty(category = "layout")
17074    public int getBaseline() {
17075        return -1;
17076    }
17077
17078    /**
17079     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17080     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17081     * a layout pass.
17082     *
17083     * @return whether the view hierarchy is currently undergoing a layout pass
17084     */
17085    public boolean isInLayout() {
17086        ViewRootImpl viewRoot = getViewRootImpl();
17087        return (viewRoot != null && viewRoot.isInLayout());
17088    }
17089
17090    /**
17091     * Call this when something has changed which has invalidated the
17092     * layout of this view. This will schedule a layout pass of the view
17093     * tree. This should not be called while the view hierarchy is currently in a layout
17094     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17095     * end of the current layout pass (and then layout will run again) or after the current
17096     * frame is drawn and the next layout occurs.
17097     *
17098     * <p>Subclasses which override this method should call the superclass method to
17099     * handle possible request-during-layout errors correctly.</p>
17100     */
17101    public void requestLayout() {
17102        if (mMeasureCache != null) mMeasureCache.clear();
17103
17104        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17105            // Only trigger request-during-layout logic if this is the view requesting it,
17106            // not the views in its parent hierarchy
17107            ViewRootImpl viewRoot = getViewRootImpl();
17108            if (viewRoot != null && viewRoot.isInLayout()) {
17109                if (!viewRoot.requestLayoutDuringLayout(this)) {
17110                    return;
17111                }
17112            }
17113            mAttachInfo.mViewRequestingLayout = this;
17114        }
17115
17116        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17117        mPrivateFlags |= PFLAG_INVALIDATED;
17118
17119        if (mParent != null && !mParent.isLayoutRequested()) {
17120            mParent.requestLayout();
17121        }
17122        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17123            mAttachInfo.mViewRequestingLayout = null;
17124        }
17125    }
17126
17127    /**
17128     * Forces this view to be laid out during the next layout pass.
17129     * This method does not call requestLayout() or forceLayout()
17130     * on the parent.
17131     */
17132    public void forceLayout() {
17133        if (mMeasureCache != null) mMeasureCache.clear();
17134
17135        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17136        mPrivateFlags |= PFLAG_INVALIDATED;
17137    }
17138
17139    /**
17140     * <p>
17141     * This is called to find out how big a view should be. The parent
17142     * supplies constraint information in the width and height parameters.
17143     * </p>
17144     *
17145     * <p>
17146     * The actual measurement work of a view is performed in
17147     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17148     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17149     * </p>
17150     *
17151     *
17152     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17153     *        parent
17154     * @param heightMeasureSpec Vertical space requirements as imposed by the
17155     *        parent
17156     *
17157     * @see #onMeasure(int, int)
17158     */
17159    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17160        boolean optical = isLayoutModeOptical(this);
17161        if (optical != isLayoutModeOptical(mParent)) {
17162            Insets insets = getOpticalInsets();
17163            int oWidth  = insets.left + insets.right;
17164            int oHeight = insets.top  + insets.bottom;
17165            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17166            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17167        }
17168
17169        // Suppress sign extension for the low bytes
17170        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17171        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17172
17173        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17174                widthMeasureSpec != mOldWidthMeasureSpec ||
17175                heightMeasureSpec != mOldHeightMeasureSpec) {
17176
17177            // first clears the measured dimension flag
17178            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17179
17180            resolveRtlPropertiesIfNeeded();
17181
17182            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17183                    mMeasureCache.indexOfKey(key);
17184            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17185                // measure ourselves, this should set the measured dimension flag back
17186                onMeasure(widthMeasureSpec, heightMeasureSpec);
17187                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17188            } else {
17189                long value = mMeasureCache.valueAt(cacheIndex);
17190                // Casting a long to int drops the high 32 bits, no mask needed
17191                setMeasuredDimension((int) (value >> 32), (int) value);
17192                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17193            }
17194
17195            // flag not set, setMeasuredDimension() was not invoked, we raise
17196            // an exception to warn the developer
17197            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17198                throw new IllegalStateException("onMeasure() did not set the"
17199                        + " measured dimension by calling"
17200                        + " setMeasuredDimension()");
17201            }
17202
17203            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17204        }
17205
17206        mOldWidthMeasureSpec = widthMeasureSpec;
17207        mOldHeightMeasureSpec = heightMeasureSpec;
17208
17209        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17210                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17211    }
17212
17213    /**
17214     * <p>
17215     * Measure the view and its content to determine the measured width and the
17216     * measured height. This method is invoked by {@link #measure(int, int)} and
17217     * should be overriden by subclasses to provide accurate and efficient
17218     * measurement of their contents.
17219     * </p>
17220     *
17221     * <p>
17222     * <strong>CONTRACT:</strong> When overriding this method, you
17223     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17224     * measured width and height of this view. Failure to do so will trigger an
17225     * <code>IllegalStateException</code>, thrown by
17226     * {@link #measure(int, int)}. Calling the superclass'
17227     * {@link #onMeasure(int, int)} is a valid use.
17228     * </p>
17229     *
17230     * <p>
17231     * The base class implementation of measure defaults to the background size,
17232     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17233     * override {@link #onMeasure(int, int)} to provide better measurements of
17234     * their content.
17235     * </p>
17236     *
17237     * <p>
17238     * If this method is overridden, it is the subclass's responsibility to make
17239     * sure the measured height and width are at least the view's minimum height
17240     * and width ({@link #getSuggestedMinimumHeight()} and
17241     * {@link #getSuggestedMinimumWidth()}).
17242     * </p>
17243     *
17244     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17245     *                         The requirements are encoded with
17246     *                         {@link android.view.View.MeasureSpec}.
17247     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17248     *                         The requirements are encoded with
17249     *                         {@link android.view.View.MeasureSpec}.
17250     *
17251     * @see #getMeasuredWidth()
17252     * @see #getMeasuredHeight()
17253     * @see #setMeasuredDimension(int, int)
17254     * @see #getSuggestedMinimumHeight()
17255     * @see #getSuggestedMinimumWidth()
17256     * @see android.view.View.MeasureSpec#getMode(int)
17257     * @see android.view.View.MeasureSpec#getSize(int)
17258     */
17259    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17260        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17261                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17262    }
17263
17264    /**
17265     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17266     * measured width and measured height. Failing to do so will trigger an
17267     * exception at measurement time.</p>
17268     *
17269     * @param measuredWidth The measured width of this view.  May be a complex
17270     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17271     * {@link #MEASURED_STATE_TOO_SMALL}.
17272     * @param measuredHeight The measured height of this view.  May be a complex
17273     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17274     * {@link #MEASURED_STATE_TOO_SMALL}.
17275     */
17276    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17277        boolean optical = isLayoutModeOptical(this);
17278        if (optical != isLayoutModeOptical(mParent)) {
17279            Insets insets = getOpticalInsets();
17280            int opticalWidth  = insets.left + insets.right;
17281            int opticalHeight = insets.top  + insets.bottom;
17282
17283            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17284            measuredHeight += optical ? opticalHeight : -opticalHeight;
17285        }
17286        mMeasuredWidth = measuredWidth;
17287        mMeasuredHeight = measuredHeight;
17288
17289        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17290    }
17291
17292    /**
17293     * Merge two states as returned by {@link #getMeasuredState()}.
17294     * @param curState The current state as returned from a view or the result
17295     * of combining multiple views.
17296     * @param newState The new view state to combine.
17297     * @return Returns a new integer reflecting the combination of the two
17298     * states.
17299     */
17300    public static int combineMeasuredStates(int curState, int newState) {
17301        return curState | newState;
17302    }
17303
17304    /**
17305     * Version of {@link #resolveSizeAndState(int, int, int)}
17306     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17307     */
17308    public static int resolveSize(int size, int measureSpec) {
17309        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17310    }
17311
17312    /**
17313     * Utility to reconcile a desired size and state, with constraints imposed
17314     * by a MeasureSpec.  Will take the desired size, unless a different size
17315     * is imposed by the constraints.  The returned value is a compound integer,
17316     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17317     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17318     * size is smaller than the size the view wants to be.
17319     *
17320     * @param size How big the view wants to be
17321     * @param measureSpec Constraints imposed by the parent
17322     * @return Size information bit mask as defined by
17323     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17324     */
17325    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17326        int result = size;
17327        int specMode = MeasureSpec.getMode(measureSpec);
17328        int specSize =  MeasureSpec.getSize(measureSpec);
17329        switch (specMode) {
17330        case MeasureSpec.UNSPECIFIED:
17331            result = size;
17332            break;
17333        case MeasureSpec.AT_MOST:
17334            if (specSize < size) {
17335                result = specSize | MEASURED_STATE_TOO_SMALL;
17336            } else {
17337                result = size;
17338            }
17339            break;
17340        case MeasureSpec.EXACTLY:
17341            result = specSize;
17342            break;
17343        }
17344        return result | (childMeasuredState&MEASURED_STATE_MASK);
17345    }
17346
17347    /**
17348     * Utility to return a default size. Uses the supplied size if the
17349     * MeasureSpec imposed no constraints. Will get larger if allowed
17350     * by the MeasureSpec.
17351     *
17352     * @param size Default size for this view
17353     * @param measureSpec Constraints imposed by the parent
17354     * @return The size this view should be.
17355     */
17356    public static int getDefaultSize(int size, int measureSpec) {
17357        int result = size;
17358        int specMode = MeasureSpec.getMode(measureSpec);
17359        int specSize = MeasureSpec.getSize(measureSpec);
17360
17361        switch (specMode) {
17362        case MeasureSpec.UNSPECIFIED:
17363            result = size;
17364            break;
17365        case MeasureSpec.AT_MOST:
17366        case MeasureSpec.EXACTLY:
17367            result = specSize;
17368            break;
17369        }
17370        return result;
17371    }
17372
17373    /**
17374     * Returns the suggested minimum height that the view should use. This
17375     * returns the maximum of the view's minimum height
17376     * and the background's minimum height
17377     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17378     * <p>
17379     * When being used in {@link #onMeasure(int, int)}, the caller should still
17380     * ensure the returned height is within the requirements of the parent.
17381     *
17382     * @return The suggested minimum height of the view.
17383     */
17384    protected int getSuggestedMinimumHeight() {
17385        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17386
17387    }
17388
17389    /**
17390     * Returns the suggested minimum width that the view should use. This
17391     * returns the maximum of the view's minimum width)
17392     * and the background's minimum width
17393     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17394     * <p>
17395     * When being used in {@link #onMeasure(int, int)}, the caller should still
17396     * ensure the returned width is within the requirements of the parent.
17397     *
17398     * @return The suggested minimum width of the view.
17399     */
17400    protected int getSuggestedMinimumWidth() {
17401        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17402    }
17403
17404    /**
17405     * Returns the minimum height of the view.
17406     *
17407     * @return the minimum height the view will try to be.
17408     *
17409     * @see #setMinimumHeight(int)
17410     *
17411     * @attr ref android.R.styleable#View_minHeight
17412     */
17413    public int getMinimumHeight() {
17414        return mMinHeight;
17415    }
17416
17417    /**
17418     * Sets the minimum height of the view. It is not guaranteed the view will
17419     * be able to achieve this minimum height (for example, if its parent layout
17420     * constrains it with less available height).
17421     *
17422     * @param minHeight The minimum height the view will try to be.
17423     *
17424     * @see #getMinimumHeight()
17425     *
17426     * @attr ref android.R.styleable#View_minHeight
17427     */
17428    public void setMinimumHeight(int minHeight) {
17429        mMinHeight = minHeight;
17430        requestLayout();
17431    }
17432
17433    /**
17434     * Returns the minimum width of the view.
17435     *
17436     * @return the minimum width the view will try to be.
17437     *
17438     * @see #setMinimumWidth(int)
17439     *
17440     * @attr ref android.R.styleable#View_minWidth
17441     */
17442    public int getMinimumWidth() {
17443        return mMinWidth;
17444    }
17445
17446    /**
17447     * Sets the minimum width of the view. It is not guaranteed the view will
17448     * be able to achieve this minimum width (for example, if its parent layout
17449     * constrains it with less available width).
17450     *
17451     * @param minWidth The minimum width the view will try to be.
17452     *
17453     * @see #getMinimumWidth()
17454     *
17455     * @attr ref android.R.styleable#View_minWidth
17456     */
17457    public void setMinimumWidth(int minWidth) {
17458        mMinWidth = minWidth;
17459        requestLayout();
17460
17461    }
17462
17463    /**
17464     * Get the animation currently associated with this view.
17465     *
17466     * @return The animation that is currently playing or
17467     *         scheduled to play for this view.
17468     */
17469    public Animation getAnimation() {
17470        return mCurrentAnimation;
17471    }
17472
17473    /**
17474     * Start the specified animation now.
17475     *
17476     * @param animation the animation to start now
17477     */
17478    public void startAnimation(Animation animation) {
17479        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17480        setAnimation(animation);
17481        invalidateParentCaches();
17482        invalidate(true);
17483    }
17484
17485    /**
17486     * Cancels any animations for this view.
17487     */
17488    public void clearAnimation() {
17489        if (mCurrentAnimation != null) {
17490            mCurrentAnimation.detach();
17491        }
17492        mCurrentAnimation = null;
17493        invalidateParentIfNeeded();
17494    }
17495
17496    /**
17497     * Sets the next animation to play for this view.
17498     * If you want the animation to play immediately, use
17499     * {@link #startAnimation(android.view.animation.Animation)} instead.
17500     * This method provides allows fine-grained
17501     * control over the start time and invalidation, but you
17502     * must make sure that 1) the animation has a start time set, and
17503     * 2) the view's parent (which controls animations on its children)
17504     * will be invalidated when the animation is supposed to
17505     * start.
17506     *
17507     * @param animation The next animation, or null.
17508     */
17509    public void setAnimation(Animation animation) {
17510        mCurrentAnimation = animation;
17511
17512        if (animation != null) {
17513            // If the screen is off assume the animation start time is now instead of
17514            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17515            // would cause the animation to start when the screen turns back on
17516            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
17517                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17518                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17519            }
17520            animation.reset();
17521        }
17522    }
17523
17524    /**
17525     * Invoked by a parent ViewGroup to notify the start of the animation
17526     * currently associated with this view. If you override this method,
17527     * always call super.onAnimationStart();
17528     *
17529     * @see #setAnimation(android.view.animation.Animation)
17530     * @see #getAnimation()
17531     */
17532    protected void onAnimationStart() {
17533        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17534    }
17535
17536    /**
17537     * Invoked by a parent ViewGroup to notify the end of the animation
17538     * currently associated with this view. If you override this method,
17539     * always call super.onAnimationEnd();
17540     *
17541     * @see #setAnimation(android.view.animation.Animation)
17542     * @see #getAnimation()
17543     */
17544    protected void onAnimationEnd() {
17545        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17546    }
17547
17548    /**
17549     * Invoked if there is a Transform that involves alpha. Subclass that can
17550     * draw themselves with the specified alpha should return true, and then
17551     * respect that alpha when their onDraw() is called. If this returns false
17552     * then the view may be redirected to draw into an offscreen buffer to
17553     * fulfill the request, which will look fine, but may be slower than if the
17554     * subclass handles it internally. The default implementation returns false.
17555     *
17556     * @param alpha The alpha (0..255) to apply to the view's drawing
17557     * @return true if the view can draw with the specified alpha.
17558     */
17559    protected boolean onSetAlpha(int alpha) {
17560        return false;
17561    }
17562
17563    /**
17564     * This is used by the RootView to perform an optimization when
17565     * the view hierarchy contains one or several SurfaceView.
17566     * SurfaceView is always considered transparent, but its children are not,
17567     * therefore all View objects remove themselves from the global transparent
17568     * region (passed as a parameter to this function).
17569     *
17570     * @param region The transparent region for this ViewAncestor (window).
17571     *
17572     * @return Returns true if the effective visibility of the view at this
17573     * point is opaque, regardless of the transparent region; returns false
17574     * if it is possible for underlying windows to be seen behind the view.
17575     *
17576     * {@hide}
17577     */
17578    public boolean gatherTransparentRegion(Region region) {
17579        final AttachInfo attachInfo = mAttachInfo;
17580        if (region != null && attachInfo != null) {
17581            final int pflags = mPrivateFlags;
17582            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17583                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17584                // remove it from the transparent region.
17585                final int[] location = attachInfo.mTransparentLocation;
17586                getLocationInWindow(location);
17587                region.op(location[0], location[1], location[0] + mRight - mLeft,
17588                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17589            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17590                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17591                // exists, so we remove the background drawable's non-transparent
17592                // parts from this transparent region.
17593                applyDrawableToTransparentRegion(mBackground, region);
17594            }
17595        }
17596        return true;
17597    }
17598
17599    /**
17600     * Play a sound effect for this view.
17601     *
17602     * <p>The framework will play sound effects for some built in actions, such as
17603     * clicking, but you may wish to play these effects in your widget,
17604     * for instance, for internal navigation.
17605     *
17606     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17607     * {@link #isSoundEffectsEnabled()} is true.
17608     *
17609     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17610     */
17611    public void playSoundEffect(int soundConstant) {
17612        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17613            return;
17614        }
17615        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17616    }
17617
17618    /**
17619     * BZZZTT!!1!
17620     *
17621     * <p>Provide haptic feedback to the user for this view.
17622     *
17623     * <p>The framework will provide haptic feedback for some built in actions,
17624     * such as long presses, but you may wish to provide feedback for your
17625     * own widget.
17626     *
17627     * <p>The feedback will only be performed if
17628     * {@link #isHapticFeedbackEnabled()} is true.
17629     *
17630     * @param feedbackConstant One of the constants defined in
17631     * {@link HapticFeedbackConstants}
17632     */
17633    public boolean performHapticFeedback(int feedbackConstant) {
17634        return performHapticFeedback(feedbackConstant, 0);
17635    }
17636
17637    /**
17638     * BZZZTT!!1!
17639     *
17640     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17641     *
17642     * @param feedbackConstant One of the constants defined in
17643     * {@link HapticFeedbackConstants}
17644     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17645     */
17646    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17647        if (mAttachInfo == null) {
17648            return false;
17649        }
17650        //noinspection SimplifiableIfStatement
17651        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17652                && !isHapticFeedbackEnabled()) {
17653            return false;
17654        }
17655        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17656                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17657    }
17658
17659    /**
17660     * Request that the visibility of the status bar or other screen/window
17661     * decorations be changed.
17662     *
17663     * <p>This method is used to put the over device UI into temporary modes
17664     * where the user's attention is focused more on the application content,
17665     * by dimming or hiding surrounding system affordances.  This is typically
17666     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17667     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17668     * to be placed behind the action bar (and with these flags other system
17669     * affordances) so that smooth transitions between hiding and showing them
17670     * can be done.
17671     *
17672     * <p>Two representative examples of the use of system UI visibility is
17673     * implementing a content browsing application (like a magazine reader)
17674     * and a video playing application.
17675     *
17676     * <p>The first code shows a typical implementation of a View in a content
17677     * browsing application.  In this implementation, the application goes
17678     * into a content-oriented mode by hiding the status bar and action bar,
17679     * and putting the navigation elements into lights out mode.  The user can
17680     * then interact with content while in this mode.  Such an application should
17681     * provide an easy way for the user to toggle out of the mode (such as to
17682     * check information in the status bar or access notifications).  In the
17683     * implementation here, this is done simply by tapping on the content.
17684     *
17685     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17686     *      content}
17687     *
17688     * <p>This second code sample shows a typical implementation of a View
17689     * in a video playing application.  In this situation, while the video is
17690     * playing the application would like to go into a complete full-screen mode,
17691     * to use as much of the display as possible for the video.  When in this state
17692     * the user can not interact with the application; the system intercepts
17693     * touching on the screen to pop the UI out of full screen mode.  See
17694     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17695     *
17696     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17697     *      content}
17698     *
17699     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17700     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17701     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17702     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17703     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17704     */
17705    public void setSystemUiVisibility(int visibility) {
17706        if (visibility != mSystemUiVisibility) {
17707            mSystemUiVisibility = visibility;
17708            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17709                mParent.recomputeViewAttributes(this);
17710            }
17711        }
17712    }
17713
17714    /**
17715     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17716     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17717     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17718     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17719     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17720     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17721     */
17722    public int getSystemUiVisibility() {
17723        return mSystemUiVisibility;
17724    }
17725
17726    /**
17727     * Returns the current system UI visibility that is currently set for
17728     * the entire window.  This is the combination of the
17729     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17730     * views in the window.
17731     */
17732    public int getWindowSystemUiVisibility() {
17733        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17734    }
17735
17736    /**
17737     * Override to find out when the window's requested system UI visibility
17738     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17739     * This is different from the callbacks received through
17740     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17741     * in that this is only telling you about the local request of the window,
17742     * not the actual values applied by the system.
17743     */
17744    public void onWindowSystemUiVisibilityChanged(int visible) {
17745    }
17746
17747    /**
17748     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17749     * the view hierarchy.
17750     */
17751    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17752        onWindowSystemUiVisibilityChanged(visible);
17753    }
17754
17755    /**
17756     * Set a listener to receive callbacks when the visibility of the system bar changes.
17757     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17758     */
17759    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17760        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17761        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17762            mParent.recomputeViewAttributes(this);
17763        }
17764    }
17765
17766    /**
17767     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17768     * the view hierarchy.
17769     */
17770    public void dispatchSystemUiVisibilityChanged(int visibility) {
17771        ListenerInfo li = mListenerInfo;
17772        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17773            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17774                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17775        }
17776    }
17777
17778    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17779        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17780        if (val != mSystemUiVisibility) {
17781            setSystemUiVisibility(val);
17782            return true;
17783        }
17784        return false;
17785    }
17786
17787    /** @hide */
17788    public void setDisabledSystemUiVisibility(int flags) {
17789        if (mAttachInfo != null) {
17790            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17791                mAttachInfo.mDisabledSystemUiVisibility = flags;
17792                if (mParent != null) {
17793                    mParent.recomputeViewAttributes(this);
17794                }
17795            }
17796        }
17797    }
17798
17799    /**
17800     * Creates an image that the system displays during the drag and drop
17801     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17802     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17803     * appearance as the given View. The default also positions the center of the drag shadow
17804     * directly under the touch point. If no View is provided (the constructor with no parameters
17805     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17806     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17807     * default is an invisible drag shadow.
17808     * <p>
17809     * You are not required to use the View you provide to the constructor as the basis of the
17810     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17811     * anything you want as the drag shadow.
17812     * </p>
17813     * <p>
17814     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17815     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17816     *  size and position of the drag shadow. It uses this data to construct a
17817     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17818     *  so that your application can draw the shadow image in the Canvas.
17819     * </p>
17820     *
17821     * <div class="special reference">
17822     * <h3>Developer Guides</h3>
17823     * <p>For a guide to implementing drag and drop features, read the
17824     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17825     * </div>
17826     */
17827    public static class DragShadowBuilder {
17828        private final WeakReference<View> mView;
17829
17830        /**
17831         * Constructs a shadow image builder based on a View. By default, the resulting drag
17832         * shadow will have the same appearance and dimensions as the View, with the touch point
17833         * over the center of the View.
17834         * @param view A View. Any View in scope can be used.
17835         */
17836        public DragShadowBuilder(View view) {
17837            mView = new WeakReference<View>(view);
17838        }
17839
17840        /**
17841         * Construct a shadow builder object with no associated View.  This
17842         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17843         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17844         * to supply the drag shadow's dimensions and appearance without
17845         * reference to any View object. If they are not overridden, then the result is an
17846         * invisible drag shadow.
17847         */
17848        public DragShadowBuilder() {
17849            mView = new WeakReference<View>(null);
17850        }
17851
17852        /**
17853         * Returns the View object that had been passed to the
17854         * {@link #View.DragShadowBuilder(View)}
17855         * constructor.  If that View parameter was {@code null} or if the
17856         * {@link #View.DragShadowBuilder()}
17857         * constructor was used to instantiate the builder object, this method will return
17858         * null.
17859         *
17860         * @return The View object associate with this builder object.
17861         */
17862        @SuppressWarnings({"JavadocReference"})
17863        final public View getView() {
17864            return mView.get();
17865        }
17866
17867        /**
17868         * Provides the metrics for the shadow image. These include the dimensions of
17869         * the shadow image, and the point within that shadow that should
17870         * be centered under the touch location while dragging.
17871         * <p>
17872         * The default implementation sets the dimensions of the shadow to be the
17873         * same as the dimensions of the View itself and centers the shadow under
17874         * the touch point.
17875         * </p>
17876         *
17877         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17878         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17879         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17880         * image.
17881         *
17882         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17883         * shadow image that should be underneath the touch point during the drag and drop
17884         * operation. Your application must set {@link android.graphics.Point#x} to the
17885         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17886         */
17887        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17888            final View view = mView.get();
17889            if (view != null) {
17890                shadowSize.set(view.getWidth(), view.getHeight());
17891                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17892            } else {
17893                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17894            }
17895        }
17896
17897        /**
17898         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17899         * based on the dimensions it received from the
17900         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17901         *
17902         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17903         */
17904        public void onDrawShadow(Canvas canvas) {
17905            final View view = mView.get();
17906            if (view != null) {
17907                view.draw(canvas);
17908            } else {
17909                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17910            }
17911        }
17912    }
17913
17914    /**
17915     * Starts a drag and drop operation. When your application calls this method, it passes a
17916     * {@link android.view.View.DragShadowBuilder} object to the system. The
17917     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17918     * to get metrics for the drag shadow, and then calls the object's
17919     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17920     * <p>
17921     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17922     *  drag events to all the View objects in your application that are currently visible. It does
17923     *  this either by calling the View object's drag listener (an implementation of
17924     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17925     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17926     *  Both are passed a {@link android.view.DragEvent} object that has a
17927     *  {@link android.view.DragEvent#getAction()} value of
17928     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17929     * </p>
17930     * <p>
17931     * Your application can invoke startDrag() on any attached View object. The View object does not
17932     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17933     * be related to the View the user selected for dragging.
17934     * </p>
17935     * @param data A {@link android.content.ClipData} object pointing to the data to be
17936     * transferred by the drag and drop operation.
17937     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17938     * drag shadow.
17939     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17940     * drop operation. This Object is put into every DragEvent object sent by the system during the
17941     * current drag.
17942     * <p>
17943     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17944     * to the target Views. For example, it can contain flags that differentiate between a
17945     * a copy operation and a move operation.
17946     * </p>
17947     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17948     * so the parameter should be set to 0.
17949     * @return {@code true} if the method completes successfully, or
17950     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17951     * do a drag, and so no drag operation is in progress.
17952     */
17953    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17954            Object myLocalState, int flags) {
17955        if (ViewDebug.DEBUG_DRAG) {
17956            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17957        }
17958        boolean okay = false;
17959
17960        Point shadowSize = new Point();
17961        Point shadowTouchPoint = new Point();
17962        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17963
17964        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17965                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17966            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17967        }
17968
17969        if (ViewDebug.DEBUG_DRAG) {
17970            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17971                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17972        }
17973        Surface surface = new Surface();
17974        try {
17975            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17976                    flags, shadowSize.x, shadowSize.y, surface);
17977            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17978                    + " surface=" + surface);
17979            if (token != null) {
17980                Canvas canvas = surface.lockCanvas(null);
17981                try {
17982                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17983                    shadowBuilder.onDrawShadow(canvas);
17984                } finally {
17985                    surface.unlockCanvasAndPost(canvas);
17986                }
17987
17988                final ViewRootImpl root = getViewRootImpl();
17989
17990                // Cache the local state object for delivery with DragEvents
17991                root.setLocalDragState(myLocalState);
17992
17993                // repurpose 'shadowSize' for the last touch point
17994                root.getLastTouchPoint(shadowSize);
17995
17996                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17997                        shadowSize.x, shadowSize.y,
17998                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17999                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18000
18001                // Off and running!  Release our local surface instance; the drag
18002                // shadow surface is now managed by the system process.
18003                surface.release();
18004            }
18005        } catch (Exception e) {
18006            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18007            surface.destroy();
18008        }
18009
18010        return okay;
18011    }
18012
18013    /**
18014     * Handles drag events sent by the system following a call to
18015     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18016     *<p>
18017     * When the system calls this method, it passes a
18018     * {@link android.view.DragEvent} object. A call to
18019     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18020     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18021     * operation.
18022     * @param event The {@link android.view.DragEvent} sent by the system.
18023     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18024     * in DragEvent, indicating the type of drag event represented by this object.
18025     * @return {@code true} if the method was successful, otherwise {@code false}.
18026     * <p>
18027     *  The method should return {@code true} in response to an action type of
18028     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18029     *  operation.
18030     * </p>
18031     * <p>
18032     *  The method should also return {@code true} in response to an action type of
18033     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18034     *  {@code false} if it didn't.
18035     * </p>
18036     */
18037    public boolean onDragEvent(DragEvent event) {
18038        return false;
18039    }
18040
18041    /**
18042     * Detects if this View is enabled and has a drag event listener.
18043     * If both are true, then it calls the drag event listener with the
18044     * {@link android.view.DragEvent} it received. If the drag event listener returns
18045     * {@code true}, then dispatchDragEvent() returns {@code true}.
18046     * <p>
18047     * For all other cases, the method calls the
18048     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18049     * method and returns its result.
18050     * </p>
18051     * <p>
18052     * This ensures that a drag event is always consumed, even if the View does not have a drag
18053     * event listener. However, if the View has a listener and the listener returns true, then
18054     * onDragEvent() is not called.
18055     * </p>
18056     */
18057    public boolean dispatchDragEvent(DragEvent event) {
18058        ListenerInfo li = mListenerInfo;
18059        //noinspection SimplifiableIfStatement
18060        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18061                && li.mOnDragListener.onDrag(this, event)) {
18062            return true;
18063        }
18064        return onDragEvent(event);
18065    }
18066
18067    boolean canAcceptDrag() {
18068        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18069    }
18070
18071    /**
18072     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18073     * it is ever exposed at all.
18074     * @hide
18075     */
18076    public void onCloseSystemDialogs(String reason) {
18077    }
18078
18079    /**
18080     * Given a Drawable whose bounds have been set to draw into this view,
18081     * update a Region being computed for
18082     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18083     * that any non-transparent parts of the Drawable are removed from the
18084     * given transparent region.
18085     *
18086     * @param dr The Drawable whose transparency is to be applied to the region.
18087     * @param region A Region holding the current transparency information,
18088     * where any parts of the region that are set are considered to be
18089     * transparent.  On return, this region will be modified to have the
18090     * transparency information reduced by the corresponding parts of the
18091     * Drawable that are not transparent.
18092     * {@hide}
18093     */
18094    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18095        if (DBG) {
18096            Log.i("View", "Getting transparent region for: " + this);
18097        }
18098        final Region r = dr.getTransparentRegion();
18099        final Rect db = dr.getBounds();
18100        final AttachInfo attachInfo = mAttachInfo;
18101        if (r != null && attachInfo != null) {
18102            final int w = getRight()-getLeft();
18103            final int h = getBottom()-getTop();
18104            if (db.left > 0) {
18105                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18106                r.op(0, 0, db.left, h, Region.Op.UNION);
18107            }
18108            if (db.right < w) {
18109                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18110                r.op(db.right, 0, w, h, Region.Op.UNION);
18111            }
18112            if (db.top > 0) {
18113                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18114                r.op(0, 0, w, db.top, Region.Op.UNION);
18115            }
18116            if (db.bottom < h) {
18117                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18118                r.op(0, db.bottom, w, h, Region.Op.UNION);
18119            }
18120            final int[] location = attachInfo.mTransparentLocation;
18121            getLocationInWindow(location);
18122            r.translate(location[0], location[1]);
18123            region.op(r, Region.Op.INTERSECT);
18124        } else {
18125            region.op(db, Region.Op.DIFFERENCE);
18126        }
18127    }
18128
18129    private void checkForLongClick(int delayOffset) {
18130        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18131            mHasPerformedLongPress = false;
18132
18133            if (mPendingCheckForLongPress == null) {
18134                mPendingCheckForLongPress = new CheckForLongPress();
18135            }
18136            mPendingCheckForLongPress.rememberWindowAttachCount();
18137            postDelayed(mPendingCheckForLongPress,
18138                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18139        }
18140    }
18141
18142    /**
18143     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18144     * LayoutInflater} class, which provides a full range of options for view inflation.
18145     *
18146     * @param context The Context object for your activity or application.
18147     * @param resource The resource ID to inflate
18148     * @param root A view group that will be the parent.  Used to properly inflate the
18149     * layout_* parameters.
18150     * @see LayoutInflater
18151     */
18152    public static View inflate(Context context, int resource, ViewGroup root) {
18153        LayoutInflater factory = LayoutInflater.from(context);
18154        return factory.inflate(resource, root);
18155    }
18156
18157    /**
18158     * Scroll the view with standard behavior for scrolling beyond the normal
18159     * content boundaries. Views that call this method should override
18160     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18161     * results of an over-scroll operation.
18162     *
18163     * Views can use this method to handle any touch or fling-based scrolling.
18164     *
18165     * @param deltaX Change in X in pixels
18166     * @param deltaY Change in Y in pixels
18167     * @param scrollX Current X scroll value in pixels before applying deltaX
18168     * @param scrollY Current Y scroll value in pixels before applying deltaY
18169     * @param scrollRangeX Maximum content scroll range along the X axis
18170     * @param scrollRangeY Maximum content scroll range along the Y axis
18171     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18172     *          along the X axis.
18173     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18174     *          along the Y axis.
18175     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18176     * @return true if scrolling was clamped to an over-scroll boundary along either
18177     *          axis, false otherwise.
18178     */
18179    @SuppressWarnings({"UnusedParameters"})
18180    protected boolean overScrollBy(int deltaX, int deltaY,
18181            int scrollX, int scrollY,
18182            int scrollRangeX, int scrollRangeY,
18183            int maxOverScrollX, int maxOverScrollY,
18184            boolean isTouchEvent) {
18185        final int overScrollMode = mOverScrollMode;
18186        final boolean canScrollHorizontal =
18187                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18188        final boolean canScrollVertical =
18189                computeVerticalScrollRange() > computeVerticalScrollExtent();
18190        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18191                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18192        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18193                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18194
18195        int newScrollX = scrollX + deltaX;
18196        if (!overScrollHorizontal) {
18197            maxOverScrollX = 0;
18198        }
18199
18200        int newScrollY = scrollY + deltaY;
18201        if (!overScrollVertical) {
18202            maxOverScrollY = 0;
18203        }
18204
18205        // Clamp values if at the limits and record
18206        final int left = -maxOverScrollX;
18207        final int right = maxOverScrollX + scrollRangeX;
18208        final int top = -maxOverScrollY;
18209        final int bottom = maxOverScrollY + scrollRangeY;
18210
18211        boolean clampedX = false;
18212        if (newScrollX > right) {
18213            newScrollX = right;
18214            clampedX = true;
18215        } else if (newScrollX < left) {
18216            newScrollX = left;
18217            clampedX = true;
18218        }
18219
18220        boolean clampedY = false;
18221        if (newScrollY > bottom) {
18222            newScrollY = bottom;
18223            clampedY = true;
18224        } else if (newScrollY < top) {
18225            newScrollY = top;
18226            clampedY = true;
18227        }
18228
18229        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18230
18231        return clampedX || clampedY;
18232    }
18233
18234    /**
18235     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18236     * respond to the results of an over-scroll operation.
18237     *
18238     * @param scrollX New X scroll value in pixels
18239     * @param scrollY New Y scroll value in pixels
18240     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18241     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18242     */
18243    protected void onOverScrolled(int scrollX, int scrollY,
18244            boolean clampedX, boolean clampedY) {
18245        // Intentionally empty.
18246    }
18247
18248    /**
18249     * Returns the over-scroll mode for this view. The result will be
18250     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18251     * (allow over-scrolling only if the view content is larger than the container),
18252     * or {@link #OVER_SCROLL_NEVER}.
18253     *
18254     * @return This view's over-scroll mode.
18255     */
18256    public int getOverScrollMode() {
18257        return mOverScrollMode;
18258    }
18259
18260    /**
18261     * Set the over-scroll mode for this view. Valid over-scroll modes are
18262     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18263     * (allow over-scrolling only if the view content is larger than the container),
18264     * or {@link #OVER_SCROLL_NEVER}.
18265     *
18266     * Setting the over-scroll mode of a view will have an effect only if the
18267     * view is capable of scrolling.
18268     *
18269     * @param overScrollMode The new over-scroll mode for this view.
18270     */
18271    public void setOverScrollMode(int overScrollMode) {
18272        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18273                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18274                overScrollMode != OVER_SCROLL_NEVER) {
18275            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18276        }
18277        mOverScrollMode = overScrollMode;
18278    }
18279
18280    /**
18281     * Gets a scale factor that determines the distance the view should scroll
18282     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18283     * @return The vertical scroll scale factor.
18284     * @hide
18285     */
18286    protected float getVerticalScrollFactor() {
18287        if (mVerticalScrollFactor == 0) {
18288            TypedValue outValue = new TypedValue();
18289            if (!mContext.getTheme().resolveAttribute(
18290                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18291                throw new IllegalStateException(
18292                        "Expected theme to define listPreferredItemHeight.");
18293            }
18294            mVerticalScrollFactor = outValue.getDimension(
18295                    mContext.getResources().getDisplayMetrics());
18296        }
18297        return mVerticalScrollFactor;
18298    }
18299
18300    /**
18301     * Gets a scale factor that determines the distance the view should scroll
18302     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18303     * @return The horizontal scroll scale factor.
18304     * @hide
18305     */
18306    protected float getHorizontalScrollFactor() {
18307        // TODO: Should use something else.
18308        return getVerticalScrollFactor();
18309    }
18310
18311    /**
18312     * Return the value specifying the text direction or policy that was set with
18313     * {@link #setTextDirection(int)}.
18314     *
18315     * @return the defined text direction. It can be one of:
18316     *
18317     * {@link #TEXT_DIRECTION_INHERIT},
18318     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18319     * {@link #TEXT_DIRECTION_ANY_RTL},
18320     * {@link #TEXT_DIRECTION_LTR},
18321     * {@link #TEXT_DIRECTION_RTL},
18322     * {@link #TEXT_DIRECTION_LOCALE}
18323     *
18324     * @attr ref android.R.styleable#View_textDirection
18325     *
18326     * @hide
18327     */
18328    @ViewDebug.ExportedProperty(category = "text", mapping = {
18329            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18330            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18331            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18332            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18333            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18334            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18335    })
18336    public int getRawTextDirection() {
18337        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18338    }
18339
18340    /**
18341     * Set the text direction.
18342     *
18343     * @param textDirection the direction to set. Should be one of:
18344     *
18345     * {@link #TEXT_DIRECTION_INHERIT},
18346     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18347     * {@link #TEXT_DIRECTION_ANY_RTL},
18348     * {@link #TEXT_DIRECTION_LTR},
18349     * {@link #TEXT_DIRECTION_RTL},
18350     * {@link #TEXT_DIRECTION_LOCALE}
18351     *
18352     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18353     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18354     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18355     *
18356     * @attr ref android.R.styleable#View_textDirection
18357     */
18358    public void setTextDirection(int textDirection) {
18359        if (getRawTextDirection() != textDirection) {
18360            // Reset the current text direction and the resolved one
18361            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18362            resetResolvedTextDirection();
18363            // Set the new text direction
18364            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18365            // Do resolution
18366            resolveTextDirection();
18367            // Notify change
18368            onRtlPropertiesChanged(getLayoutDirection());
18369            // Refresh
18370            requestLayout();
18371            invalidate(true);
18372        }
18373    }
18374
18375    /**
18376     * Return the resolved text direction.
18377     *
18378     * @return the resolved text direction. Returns one of:
18379     *
18380     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18381     * {@link #TEXT_DIRECTION_ANY_RTL},
18382     * {@link #TEXT_DIRECTION_LTR},
18383     * {@link #TEXT_DIRECTION_RTL},
18384     * {@link #TEXT_DIRECTION_LOCALE}
18385     *
18386     * @attr ref android.R.styleable#View_textDirection
18387     */
18388    @ViewDebug.ExportedProperty(category = "text", mapping = {
18389            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18390            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18391            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18392            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18393            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18394            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18395    })
18396    public int getTextDirection() {
18397        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18398    }
18399
18400    /**
18401     * Resolve the text direction.
18402     *
18403     * @return true if resolution has been done, false otherwise.
18404     *
18405     * @hide
18406     */
18407    public boolean resolveTextDirection() {
18408        // Reset any previous text direction resolution
18409        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18410
18411        if (hasRtlSupport()) {
18412            // Set resolved text direction flag depending on text direction flag
18413            final int textDirection = getRawTextDirection();
18414            switch(textDirection) {
18415                case TEXT_DIRECTION_INHERIT:
18416                    if (!canResolveTextDirection()) {
18417                        // We cannot do the resolution if there is no parent, so use the default one
18418                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18419                        // Resolution will need to happen again later
18420                        return false;
18421                    }
18422
18423                    // Parent has not yet resolved, so we still return the default
18424                    try {
18425                        if (!mParent.isTextDirectionResolved()) {
18426                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18427                            // Resolution will need to happen again later
18428                            return false;
18429                        }
18430                    } catch (AbstractMethodError e) {
18431                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18432                                " does not fully implement ViewParent", e);
18433                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18434                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18435                        return true;
18436                    }
18437
18438                    // Set current resolved direction to the same value as the parent's one
18439                    int parentResolvedDirection;
18440                    try {
18441                        parentResolvedDirection = mParent.getTextDirection();
18442                    } catch (AbstractMethodError e) {
18443                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18444                                " does not fully implement ViewParent", e);
18445                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18446                    }
18447                    switch (parentResolvedDirection) {
18448                        case TEXT_DIRECTION_FIRST_STRONG:
18449                        case TEXT_DIRECTION_ANY_RTL:
18450                        case TEXT_DIRECTION_LTR:
18451                        case TEXT_DIRECTION_RTL:
18452                        case TEXT_DIRECTION_LOCALE:
18453                            mPrivateFlags2 |=
18454                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18455                            break;
18456                        default:
18457                            // Default resolved direction is "first strong" heuristic
18458                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18459                    }
18460                    break;
18461                case TEXT_DIRECTION_FIRST_STRONG:
18462                case TEXT_DIRECTION_ANY_RTL:
18463                case TEXT_DIRECTION_LTR:
18464                case TEXT_DIRECTION_RTL:
18465                case TEXT_DIRECTION_LOCALE:
18466                    // Resolved direction is the same as text direction
18467                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18468                    break;
18469                default:
18470                    // Default resolved direction is "first strong" heuristic
18471                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18472            }
18473        } else {
18474            // Default resolved direction is "first strong" heuristic
18475            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18476        }
18477
18478        // Set to resolved
18479        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18480        return true;
18481    }
18482
18483    /**
18484     * Check if text direction resolution can be done.
18485     *
18486     * @return true if text direction resolution can be done otherwise return false.
18487     */
18488    public boolean canResolveTextDirection() {
18489        switch (getRawTextDirection()) {
18490            case TEXT_DIRECTION_INHERIT:
18491                if (mParent != null) {
18492                    try {
18493                        return mParent.canResolveTextDirection();
18494                    } catch (AbstractMethodError e) {
18495                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18496                                " does not fully implement ViewParent", e);
18497                    }
18498                }
18499                return false;
18500
18501            default:
18502                return true;
18503        }
18504    }
18505
18506    /**
18507     * Reset resolved text direction. Text direction will be resolved during a call to
18508     * {@link #onMeasure(int, int)}.
18509     *
18510     * @hide
18511     */
18512    public void resetResolvedTextDirection() {
18513        // Reset any previous text direction resolution
18514        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18515        // Set to default value
18516        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18517    }
18518
18519    /**
18520     * @return true if text direction is inherited.
18521     *
18522     * @hide
18523     */
18524    public boolean isTextDirectionInherited() {
18525        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18526    }
18527
18528    /**
18529     * @return true if text direction is resolved.
18530     */
18531    public boolean isTextDirectionResolved() {
18532        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18533    }
18534
18535    /**
18536     * Return the value specifying the text alignment or policy that was set with
18537     * {@link #setTextAlignment(int)}.
18538     *
18539     * @return the defined text alignment. It can be one of:
18540     *
18541     * {@link #TEXT_ALIGNMENT_INHERIT},
18542     * {@link #TEXT_ALIGNMENT_GRAVITY},
18543     * {@link #TEXT_ALIGNMENT_CENTER},
18544     * {@link #TEXT_ALIGNMENT_TEXT_START},
18545     * {@link #TEXT_ALIGNMENT_TEXT_END},
18546     * {@link #TEXT_ALIGNMENT_VIEW_START},
18547     * {@link #TEXT_ALIGNMENT_VIEW_END}
18548     *
18549     * @attr ref android.R.styleable#View_textAlignment
18550     *
18551     * @hide
18552     */
18553    @ViewDebug.ExportedProperty(category = "text", mapping = {
18554            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18555            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18556            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18557            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18558            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18559            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18560            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18561    })
18562    @TextAlignment
18563    public int getRawTextAlignment() {
18564        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18565    }
18566
18567    /**
18568     * Set the text alignment.
18569     *
18570     * @param textAlignment The text alignment to set. Should be one of
18571     *
18572     * {@link #TEXT_ALIGNMENT_INHERIT},
18573     * {@link #TEXT_ALIGNMENT_GRAVITY},
18574     * {@link #TEXT_ALIGNMENT_CENTER},
18575     * {@link #TEXT_ALIGNMENT_TEXT_START},
18576     * {@link #TEXT_ALIGNMENT_TEXT_END},
18577     * {@link #TEXT_ALIGNMENT_VIEW_START},
18578     * {@link #TEXT_ALIGNMENT_VIEW_END}
18579     *
18580     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18581     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18582     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18583     *
18584     * @attr ref android.R.styleable#View_textAlignment
18585     */
18586    public void setTextAlignment(@TextAlignment int textAlignment) {
18587        if (textAlignment != getRawTextAlignment()) {
18588            // Reset the current and resolved text alignment
18589            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18590            resetResolvedTextAlignment();
18591            // Set the new text alignment
18592            mPrivateFlags2 |=
18593                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18594            // Do resolution
18595            resolveTextAlignment();
18596            // Notify change
18597            onRtlPropertiesChanged(getLayoutDirection());
18598            // Refresh
18599            requestLayout();
18600            invalidate(true);
18601        }
18602    }
18603
18604    /**
18605     * Return the resolved text alignment.
18606     *
18607     * @return the resolved text alignment. Returns one of:
18608     *
18609     * {@link #TEXT_ALIGNMENT_GRAVITY},
18610     * {@link #TEXT_ALIGNMENT_CENTER},
18611     * {@link #TEXT_ALIGNMENT_TEXT_START},
18612     * {@link #TEXT_ALIGNMENT_TEXT_END},
18613     * {@link #TEXT_ALIGNMENT_VIEW_START},
18614     * {@link #TEXT_ALIGNMENT_VIEW_END}
18615     *
18616     * @attr ref android.R.styleable#View_textAlignment
18617     */
18618    @ViewDebug.ExportedProperty(category = "text", mapping = {
18619            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18620            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18621            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18622            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18623            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18624            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18625            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18626    })
18627    @TextAlignment
18628    public int getTextAlignment() {
18629        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18630                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18631    }
18632
18633    /**
18634     * Resolve the text alignment.
18635     *
18636     * @return true if resolution has been done, false otherwise.
18637     *
18638     * @hide
18639     */
18640    public boolean resolveTextAlignment() {
18641        // Reset any previous text alignment resolution
18642        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18643
18644        if (hasRtlSupport()) {
18645            // Set resolved text alignment flag depending on text alignment flag
18646            final int textAlignment = getRawTextAlignment();
18647            switch (textAlignment) {
18648                case TEXT_ALIGNMENT_INHERIT:
18649                    // Check if we can resolve the text alignment
18650                    if (!canResolveTextAlignment()) {
18651                        // We cannot do the resolution if there is no parent so use the default
18652                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18653                        // Resolution will need to happen again later
18654                        return false;
18655                    }
18656
18657                    // Parent has not yet resolved, so we still return the default
18658                    try {
18659                        if (!mParent.isTextAlignmentResolved()) {
18660                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18661                            // Resolution will need to happen again later
18662                            return false;
18663                        }
18664                    } catch (AbstractMethodError e) {
18665                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18666                                " does not fully implement ViewParent", e);
18667                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18668                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18669                        return true;
18670                    }
18671
18672                    int parentResolvedTextAlignment;
18673                    try {
18674                        parentResolvedTextAlignment = mParent.getTextAlignment();
18675                    } catch (AbstractMethodError e) {
18676                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18677                                " does not fully implement ViewParent", e);
18678                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18679                    }
18680                    switch (parentResolvedTextAlignment) {
18681                        case TEXT_ALIGNMENT_GRAVITY:
18682                        case TEXT_ALIGNMENT_TEXT_START:
18683                        case TEXT_ALIGNMENT_TEXT_END:
18684                        case TEXT_ALIGNMENT_CENTER:
18685                        case TEXT_ALIGNMENT_VIEW_START:
18686                        case TEXT_ALIGNMENT_VIEW_END:
18687                            // Resolved text alignment is the same as the parent resolved
18688                            // text alignment
18689                            mPrivateFlags2 |=
18690                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18691                            break;
18692                        default:
18693                            // Use default resolved text alignment
18694                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18695                    }
18696                    break;
18697                case TEXT_ALIGNMENT_GRAVITY:
18698                case TEXT_ALIGNMENT_TEXT_START:
18699                case TEXT_ALIGNMENT_TEXT_END:
18700                case TEXT_ALIGNMENT_CENTER:
18701                case TEXT_ALIGNMENT_VIEW_START:
18702                case TEXT_ALIGNMENT_VIEW_END:
18703                    // Resolved text alignment is the same as text alignment
18704                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18705                    break;
18706                default:
18707                    // Use default resolved text alignment
18708                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18709            }
18710        } else {
18711            // Use default resolved text alignment
18712            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18713        }
18714
18715        // Set the resolved
18716        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18717        return true;
18718    }
18719
18720    /**
18721     * Check if text alignment resolution can be done.
18722     *
18723     * @return true if text alignment resolution can be done otherwise return false.
18724     */
18725    public boolean canResolveTextAlignment() {
18726        switch (getRawTextAlignment()) {
18727            case TEXT_DIRECTION_INHERIT:
18728                if (mParent != null) {
18729                    try {
18730                        return mParent.canResolveTextAlignment();
18731                    } catch (AbstractMethodError e) {
18732                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18733                                " does not fully implement ViewParent", e);
18734                    }
18735                }
18736                return false;
18737
18738            default:
18739                return true;
18740        }
18741    }
18742
18743    /**
18744     * Reset resolved text alignment. Text alignment will be resolved during a call to
18745     * {@link #onMeasure(int, int)}.
18746     *
18747     * @hide
18748     */
18749    public void resetResolvedTextAlignment() {
18750        // Reset any previous text alignment resolution
18751        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18752        // Set to default
18753        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18754    }
18755
18756    /**
18757     * @return true if text alignment is inherited.
18758     *
18759     * @hide
18760     */
18761    public boolean isTextAlignmentInherited() {
18762        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18763    }
18764
18765    /**
18766     * @return true if text alignment is resolved.
18767     */
18768    public boolean isTextAlignmentResolved() {
18769        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18770    }
18771
18772    /**
18773     * Generate a value suitable for use in {@link #setId(int)}.
18774     * This value will not collide with ID values generated at build time by aapt for R.id.
18775     *
18776     * @return a generated ID value
18777     */
18778    public static int generateViewId() {
18779        for (;;) {
18780            final int result = sNextGeneratedId.get();
18781            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18782            int newValue = result + 1;
18783            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18784            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18785                return result;
18786            }
18787        }
18788    }
18789
18790    //
18791    // Properties
18792    //
18793    /**
18794     * A Property wrapper around the <code>alpha</code> functionality handled by the
18795     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18796     */
18797    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18798        @Override
18799        public void setValue(View object, float value) {
18800            object.setAlpha(value);
18801        }
18802
18803        @Override
18804        public Float get(View object) {
18805            return object.getAlpha();
18806        }
18807    };
18808
18809    /**
18810     * A Property wrapper around the <code>translationX</code> functionality handled by the
18811     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18812     */
18813    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18814        @Override
18815        public void setValue(View object, float value) {
18816            object.setTranslationX(value);
18817        }
18818
18819                @Override
18820        public Float get(View object) {
18821            return object.getTranslationX();
18822        }
18823    };
18824
18825    /**
18826     * A Property wrapper around the <code>translationY</code> functionality handled by the
18827     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18828     */
18829    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18830        @Override
18831        public void setValue(View object, float value) {
18832            object.setTranslationY(value);
18833        }
18834
18835        @Override
18836        public Float get(View object) {
18837            return object.getTranslationY();
18838        }
18839    };
18840
18841    /**
18842     * A Property wrapper around the <code>translationZ</code> functionality handled by the
18843     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
18844     */
18845    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
18846        @Override
18847        public void setValue(View object, float value) {
18848            object.setTranslationZ(value);
18849        }
18850
18851        @Override
18852        public Float get(View object) {
18853            return object.getTranslationZ();
18854        }
18855    };
18856
18857    /**
18858     * A Property wrapper around the <code>x</code> functionality handled by the
18859     * {@link View#setX(float)} and {@link View#getX()} methods.
18860     */
18861    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18862        @Override
18863        public void setValue(View object, float value) {
18864            object.setX(value);
18865        }
18866
18867        @Override
18868        public Float get(View object) {
18869            return object.getX();
18870        }
18871    };
18872
18873    /**
18874     * A Property wrapper around the <code>y</code> functionality handled by the
18875     * {@link View#setY(float)} and {@link View#getY()} methods.
18876     */
18877    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18878        @Override
18879        public void setValue(View object, float value) {
18880            object.setY(value);
18881        }
18882
18883        @Override
18884        public Float get(View object) {
18885            return object.getY();
18886        }
18887    };
18888
18889    /**
18890     * A Property wrapper around the <code>rotation</code> functionality handled by the
18891     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18892     */
18893    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18894        @Override
18895        public void setValue(View object, float value) {
18896            object.setRotation(value);
18897        }
18898
18899        @Override
18900        public Float get(View object) {
18901            return object.getRotation();
18902        }
18903    };
18904
18905    /**
18906     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18907     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18908     */
18909    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18910        @Override
18911        public void setValue(View object, float value) {
18912            object.setRotationX(value);
18913        }
18914
18915        @Override
18916        public Float get(View object) {
18917            return object.getRotationX();
18918        }
18919    };
18920
18921    /**
18922     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18923     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18924     */
18925    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18926        @Override
18927        public void setValue(View object, float value) {
18928            object.setRotationY(value);
18929        }
18930
18931        @Override
18932        public Float get(View object) {
18933            return object.getRotationY();
18934        }
18935    };
18936
18937    /**
18938     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18939     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18940     */
18941    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18942        @Override
18943        public void setValue(View object, float value) {
18944            object.setScaleX(value);
18945        }
18946
18947        @Override
18948        public Float get(View object) {
18949            return object.getScaleX();
18950        }
18951    };
18952
18953    /**
18954     * A Property wrapper around the <code>scaleY</code> functionality handled by the
18955     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
18956     */
18957    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
18958        @Override
18959        public void setValue(View object, float value) {
18960            object.setScaleY(value);
18961        }
18962
18963        @Override
18964        public Float get(View object) {
18965            return object.getScaleY();
18966        }
18967    };
18968
18969    /**
18970     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
18971     * Each MeasureSpec represents a requirement for either the width or the height.
18972     * A MeasureSpec is comprised of a size and a mode. There are three possible
18973     * modes:
18974     * <dl>
18975     * <dt>UNSPECIFIED</dt>
18976     * <dd>
18977     * The parent has not imposed any constraint on the child. It can be whatever size
18978     * it wants.
18979     * </dd>
18980     *
18981     * <dt>EXACTLY</dt>
18982     * <dd>
18983     * The parent has determined an exact size for the child. The child is going to be
18984     * given those bounds regardless of how big it wants to be.
18985     * </dd>
18986     *
18987     * <dt>AT_MOST</dt>
18988     * <dd>
18989     * The child can be as large as it wants up to the specified size.
18990     * </dd>
18991     * </dl>
18992     *
18993     * MeasureSpecs are implemented as ints to reduce object allocation. This class
18994     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
18995     */
18996    public static class MeasureSpec {
18997        private static final int MODE_SHIFT = 30;
18998        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
18999
19000        /**
19001         * Measure specification mode: The parent has not imposed any constraint
19002         * on the child. It can be whatever size it wants.
19003         */
19004        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19005
19006        /**
19007         * Measure specification mode: The parent has determined an exact size
19008         * for the child. The child is going to be given those bounds regardless
19009         * of how big it wants to be.
19010         */
19011        public static final int EXACTLY     = 1 << MODE_SHIFT;
19012
19013        /**
19014         * Measure specification mode: The child can be as large as it wants up
19015         * to the specified size.
19016         */
19017        public static final int AT_MOST     = 2 << MODE_SHIFT;
19018
19019        /**
19020         * Creates a measure specification based on the supplied size and mode.
19021         *
19022         * The mode must always be one of the following:
19023         * <ul>
19024         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19025         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19026         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19027         * </ul>
19028         *
19029         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19030         * implementation was such that the order of arguments did not matter
19031         * and overflow in either value could impact the resulting MeasureSpec.
19032         * {@link android.widget.RelativeLayout} was affected by this bug.
19033         * Apps targeting API levels greater than 17 will get the fixed, more strict
19034         * behavior.</p>
19035         *
19036         * @param size the size of the measure specification
19037         * @param mode the mode of the measure specification
19038         * @return the measure specification based on size and mode
19039         */
19040        public static int makeMeasureSpec(int size, int mode) {
19041            if (sUseBrokenMakeMeasureSpec) {
19042                return size + mode;
19043            } else {
19044                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19045            }
19046        }
19047
19048        /**
19049         * Extracts the mode from the supplied measure specification.
19050         *
19051         * @param measureSpec the measure specification to extract the mode from
19052         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19053         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19054         *         {@link android.view.View.MeasureSpec#EXACTLY}
19055         */
19056        public static int getMode(int measureSpec) {
19057            return (measureSpec & MODE_MASK);
19058        }
19059
19060        /**
19061         * Extracts the size from the supplied measure specification.
19062         *
19063         * @param measureSpec the measure specification to extract the size from
19064         * @return the size in pixels defined in the supplied measure specification
19065         */
19066        public static int getSize(int measureSpec) {
19067            return (measureSpec & ~MODE_MASK);
19068        }
19069
19070        static int adjust(int measureSpec, int delta) {
19071            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
19072        }
19073
19074        /**
19075         * Returns a String representation of the specified measure
19076         * specification.
19077         *
19078         * @param measureSpec the measure specification to convert to a String
19079         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19080         */
19081        public static String toString(int measureSpec) {
19082            int mode = getMode(measureSpec);
19083            int size = getSize(measureSpec);
19084
19085            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19086
19087            if (mode == UNSPECIFIED)
19088                sb.append("UNSPECIFIED ");
19089            else if (mode == EXACTLY)
19090                sb.append("EXACTLY ");
19091            else if (mode == AT_MOST)
19092                sb.append("AT_MOST ");
19093            else
19094                sb.append(mode).append(" ");
19095
19096            sb.append(size);
19097            return sb.toString();
19098        }
19099    }
19100
19101    class CheckForLongPress implements Runnable {
19102
19103        private int mOriginalWindowAttachCount;
19104
19105        public void run() {
19106            if (isPressed() && (mParent != null)
19107                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19108                if (performLongClick()) {
19109                    mHasPerformedLongPress = true;
19110                }
19111            }
19112        }
19113
19114        public void rememberWindowAttachCount() {
19115            mOriginalWindowAttachCount = mWindowAttachCount;
19116        }
19117    }
19118
19119    private final class CheckForTap implements Runnable {
19120        public void run() {
19121            mPrivateFlags &= ~PFLAG_PREPRESSED;
19122            setPressed(true);
19123            checkForLongClick(ViewConfiguration.getTapTimeout());
19124        }
19125    }
19126
19127    private final class PerformClick implements Runnable {
19128        public void run() {
19129            performClick();
19130        }
19131    }
19132
19133    /** @hide */
19134    public void hackTurnOffWindowResizeAnim(boolean off) {
19135        mAttachInfo.mTurnOffWindowResizeAnim = off;
19136    }
19137
19138    /**
19139     * This method returns a ViewPropertyAnimator object, which can be used to animate
19140     * specific properties on this View.
19141     *
19142     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19143     */
19144    public ViewPropertyAnimator animate() {
19145        if (mAnimator == null) {
19146            mAnimator = new ViewPropertyAnimator(this);
19147        }
19148        return mAnimator;
19149    }
19150
19151    /**
19152     * Specifies that the shared name of the View to be shared with another Activity.
19153     * When transitioning between Activities, the name links a UI element in the starting
19154     * Activity to UI element in the called Activity. Names should be unique in the
19155     * View hierarchy.
19156     *
19157     * @param sharedElementName The cross-Activity View identifier. The called Activity will use
19158     *                 the name to match the location with a View in its layout.
19159     * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.os.Bundle)
19160     */
19161    public void setSharedElementName(String sharedElementName) {
19162        setTagInternal(com.android.internal.R.id.shared_element_name, sharedElementName);
19163    }
19164
19165    /**
19166     * Returns the shared name of the View to be shared with another Activity.
19167     * When transitioning between Activities, the name links a UI element in the starting
19168     * Activity to UI element in the called Activity. Names should be unique in the
19169     * View hierarchy.
19170     *
19171     * <p>This returns null if the View is not a shared element or the name if it is.</p>
19172     *
19173     * @return The name used for this View for cross-Activity transitions or null if
19174     * this View has not been identified as shared.
19175     */
19176    public String getSharedElementName() {
19177        return (String) getTag(com.android.internal.R.id.shared_element_name);
19178    }
19179
19180    /**
19181     * Interface definition for a callback to be invoked when a hardware key event is
19182     * dispatched to this view. The callback will be invoked before the key event is
19183     * given to the view. This is only useful for hardware keyboards; a software input
19184     * method has no obligation to trigger this listener.
19185     */
19186    public interface OnKeyListener {
19187        /**
19188         * Called when a hardware key is dispatched to a view. This allows listeners to
19189         * get a chance to respond before the target view.
19190         * <p>Key presses in software keyboards will generally NOT trigger this method,
19191         * although some may elect to do so in some situations. Do not assume a
19192         * software input method has to be key-based; even if it is, it may use key presses
19193         * in a different way than you expect, so there is no way to reliably catch soft
19194         * input key presses.
19195         *
19196         * @param v The view the key has been dispatched to.
19197         * @param keyCode The code for the physical key that was pressed
19198         * @param event The KeyEvent object containing full information about
19199         *        the event.
19200         * @return True if the listener has consumed the event, false otherwise.
19201         */
19202        boolean onKey(View v, int keyCode, KeyEvent event);
19203    }
19204
19205    /**
19206     * Interface definition for a callback to be invoked when a touch event is
19207     * dispatched to this view. The callback will be invoked before the touch
19208     * event is given to the view.
19209     */
19210    public interface OnTouchListener {
19211        /**
19212         * Called when a touch event is dispatched to a view. This allows listeners to
19213         * get a chance to respond before the target view.
19214         *
19215         * @param v The view the touch event has been dispatched to.
19216         * @param event The MotionEvent object containing full information about
19217         *        the event.
19218         * @return True if the listener has consumed the event, false otherwise.
19219         */
19220        boolean onTouch(View v, MotionEvent event);
19221    }
19222
19223    /**
19224     * Interface definition for a callback to be invoked when a hover event is
19225     * dispatched to this view. The callback will be invoked before the hover
19226     * event is given to the view.
19227     */
19228    public interface OnHoverListener {
19229        /**
19230         * Called when a hover event is dispatched to a view. This allows listeners to
19231         * get a chance to respond before the target view.
19232         *
19233         * @param v The view the hover event has been dispatched to.
19234         * @param event The MotionEvent object containing full information about
19235         *        the event.
19236         * @return True if the listener has consumed the event, false otherwise.
19237         */
19238        boolean onHover(View v, MotionEvent event);
19239    }
19240
19241    /**
19242     * Interface definition for a callback to be invoked when a generic motion event is
19243     * dispatched to this view. The callback will be invoked before the generic motion
19244     * event is given to the view.
19245     */
19246    public interface OnGenericMotionListener {
19247        /**
19248         * Called when a generic motion event is dispatched to a view. This allows listeners to
19249         * get a chance to respond before the target view.
19250         *
19251         * @param v The view the generic motion event has been dispatched to.
19252         * @param event The MotionEvent object containing full information about
19253         *        the event.
19254         * @return True if the listener has consumed the event, false otherwise.
19255         */
19256        boolean onGenericMotion(View v, MotionEvent event);
19257    }
19258
19259    /**
19260     * Interface definition for a callback to be invoked when a view has been clicked and held.
19261     */
19262    public interface OnLongClickListener {
19263        /**
19264         * Called when a view has been clicked and held.
19265         *
19266         * @param v The view that was clicked and held.
19267         *
19268         * @return true if the callback consumed the long click, false otherwise.
19269         */
19270        boolean onLongClick(View v);
19271    }
19272
19273    /**
19274     * Interface definition for a callback to be invoked when a drag is being dispatched
19275     * to this view.  The callback will be invoked before the hosting view's own
19276     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19277     * onDrag(event) behavior, it should return 'false' from this callback.
19278     *
19279     * <div class="special reference">
19280     * <h3>Developer Guides</h3>
19281     * <p>For a guide to implementing drag and drop features, read the
19282     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19283     * </div>
19284     */
19285    public interface OnDragListener {
19286        /**
19287         * Called when a drag event is dispatched to a view. This allows listeners
19288         * to get a chance to override base View behavior.
19289         *
19290         * @param v The View that received the drag event.
19291         * @param event The {@link android.view.DragEvent} object for the drag event.
19292         * @return {@code true} if the drag event was handled successfully, or {@code false}
19293         * if the drag event was not handled. Note that {@code false} will trigger the View
19294         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19295         */
19296        boolean onDrag(View v, DragEvent event);
19297    }
19298
19299    /**
19300     * Interface definition for a callback to be invoked when the focus state of
19301     * a view changed.
19302     */
19303    public interface OnFocusChangeListener {
19304        /**
19305         * Called when the focus state of a view has changed.
19306         *
19307         * @param v The view whose state has changed.
19308         * @param hasFocus The new focus state of v.
19309         */
19310        void onFocusChange(View v, boolean hasFocus);
19311    }
19312
19313    /**
19314     * Interface definition for a callback to be invoked when a view is clicked.
19315     */
19316    public interface OnClickListener {
19317        /**
19318         * Called when a view has been clicked.
19319         *
19320         * @param v The view that was clicked.
19321         */
19322        void onClick(View v);
19323    }
19324
19325    /**
19326     * Interface definition for a callback to be invoked when the context menu
19327     * for this view is being built.
19328     */
19329    public interface OnCreateContextMenuListener {
19330        /**
19331         * Called when the context menu for this view is being built. It is not
19332         * safe to hold onto the menu after this method returns.
19333         *
19334         * @param menu The context menu that is being built
19335         * @param v The view for which the context menu is being built
19336         * @param menuInfo Extra information about the item for which the
19337         *            context menu should be shown. This information will vary
19338         *            depending on the class of v.
19339         */
19340        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19341    }
19342
19343    /**
19344     * Interface definition for a callback to be invoked when the status bar changes
19345     * visibility.  This reports <strong>global</strong> changes to the system UI
19346     * state, not what the application is requesting.
19347     *
19348     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19349     */
19350    public interface OnSystemUiVisibilityChangeListener {
19351        /**
19352         * Called when the status bar changes visibility because of a call to
19353         * {@link View#setSystemUiVisibility(int)}.
19354         *
19355         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19356         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19357         * This tells you the <strong>global</strong> state of these UI visibility
19358         * flags, not what your app is currently applying.
19359         */
19360        public void onSystemUiVisibilityChange(int visibility);
19361    }
19362
19363    /**
19364     * Interface definition for a callback to be invoked when this view is attached
19365     * or detached from its window.
19366     */
19367    public interface OnAttachStateChangeListener {
19368        /**
19369         * Called when the view is attached to a window.
19370         * @param v The view that was attached
19371         */
19372        public void onViewAttachedToWindow(View v);
19373        /**
19374         * Called when the view is detached from a window.
19375         * @param v The view that was detached
19376         */
19377        public void onViewDetachedFromWindow(View v);
19378    }
19379
19380    /**
19381     * Listener for applying window insets on a view in a custom way.
19382     *
19383     * <p>Apps may choose to implement this interface if they want to apply custom policy
19384     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19385     * is set, its
19386     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19387     * method will be called instead of the View's own
19388     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19389     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19390     * the View's normal behavior as part of its own.</p>
19391     */
19392    public interface OnApplyWindowInsetsListener {
19393        /**
19394         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19395         * on a View, this listener method will be called instead of the view's own
19396         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19397         *
19398         * @param v The view applying window insets
19399         * @param insets The insets to apply
19400         * @return The insets supplied, minus any insets that were consumed
19401         */
19402        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19403    }
19404
19405    private final class UnsetPressedState implements Runnable {
19406        public void run() {
19407            setPressed(false);
19408        }
19409    }
19410
19411    /**
19412     * Base class for derived classes that want to save and restore their own
19413     * state in {@link android.view.View#onSaveInstanceState()}.
19414     */
19415    public static class BaseSavedState extends AbsSavedState {
19416        /**
19417         * Constructor used when reading from a parcel. Reads the state of the superclass.
19418         *
19419         * @param source
19420         */
19421        public BaseSavedState(Parcel source) {
19422            super(source);
19423        }
19424
19425        /**
19426         * Constructor called by derived classes when creating their SavedState objects
19427         *
19428         * @param superState The state of the superclass of this view
19429         */
19430        public BaseSavedState(Parcelable superState) {
19431            super(superState);
19432        }
19433
19434        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19435                new Parcelable.Creator<BaseSavedState>() {
19436            public BaseSavedState createFromParcel(Parcel in) {
19437                return new BaseSavedState(in);
19438            }
19439
19440            public BaseSavedState[] newArray(int size) {
19441                return new BaseSavedState[size];
19442            }
19443        };
19444    }
19445
19446    /**
19447     * A set of information given to a view when it is attached to its parent
19448     * window.
19449     */
19450    static class AttachInfo {
19451        interface Callbacks {
19452            void playSoundEffect(int effectId);
19453            boolean performHapticFeedback(int effectId, boolean always);
19454        }
19455
19456        /**
19457         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19458         * to a Handler. This class contains the target (View) to invalidate and
19459         * the coordinates of the dirty rectangle.
19460         *
19461         * For performance purposes, this class also implements a pool of up to
19462         * POOL_LIMIT objects that get reused. This reduces memory allocations
19463         * whenever possible.
19464         */
19465        static class InvalidateInfo {
19466            private static final int POOL_LIMIT = 10;
19467
19468            private static final SynchronizedPool<InvalidateInfo> sPool =
19469                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19470
19471            View target;
19472
19473            int left;
19474            int top;
19475            int right;
19476            int bottom;
19477
19478            public static InvalidateInfo obtain() {
19479                InvalidateInfo instance = sPool.acquire();
19480                return (instance != null) ? instance : new InvalidateInfo();
19481            }
19482
19483            public void recycle() {
19484                target = null;
19485                sPool.release(this);
19486            }
19487        }
19488
19489        final IWindowSession mSession;
19490
19491        final IWindow mWindow;
19492
19493        final IBinder mWindowToken;
19494
19495        final Display mDisplay;
19496
19497        final Callbacks mRootCallbacks;
19498
19499        IWindowId mIWindowId;
19500        WindowId mWindowId;
19501
19502        /**
19503         * The top view of the hierarchy.
19504         */
19505        View mRootView;
19506
19507        IBinder mPanelParentWindowToken;
19508
19509        boolean mHardwareAccelerated;
19510        boolean mHardwareAccelerationRequested;
19511        HardwareRenderer mHardwareRenderer;
19512
19513        boolean mScreenOn;
19514
19515        /**
19516         * Scale factor used by the compatibility mode
19517         */
19518        float mApplicationScale;
19519
19520        /**
19521         * Indicates whether the application is in compatibility mode
19522         */
19523        boolean mScalingRequired;
19524
19525        /**
19526         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19527         */
19528        boolean mTurnOffWindowResizeAnim;
19529
19530        /**
19531         * Left position of this view's window
19532         */
19533        int mWindowLeft;
19534
19535        /**
19536         * Top position of this view's window
19537         */
19538        int mWindowTop;
19539
19540        /**
19541         * Indicates whether views need to use 32-bit drawing caches
19542         */
19543        boolean mUse32BitDrawingCache;
19544
19545        /**
19546         * For windows that are full-screen but using insets to layout inside
19547         * of the screen areas, these are the current insets to appear inside
19548         * the overscan area of the display.
19549         */
19550        final Rect mOverscanInsets = new Rect();
19551
19552        /**
19553         * For windows that are full-screen but using insets to layout inside
19554         * of the screen decorations, these are the current insets for the
19555         * content of the window.
19556         */
19557        final Rect mContentInsets = new Rect();
19558
19559        /**
19560         * For windows that are full-screen but using insets to layout inside
19561         * of the screen decorations, these are the current insets for the
19562         * actual visible parts of the window.
19563         */
19564        final Rect mVisibleInsets = new Rect();
19565
19566        /**
19567         * The internal insets given by this window.  This value is
19568         * supplied by the client (through
19569         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19570         * be given to the window manager when changed to be used in laying
19571         * out windows behind it.
19572         */
19573        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19574                = new ViewTreeObserver.InternalInsetsInfo();
19575
19576        /**
19577         * Set to true when mGivenInternalInsets is non-empty.
19578         */
19579        boolean mHasNonEmptyGivenInternalInsets;
19580
19581        /**
19582         * All views in the window's hierarchy that serve as scroll containers,
19583         * used to determine if the window can be resized or must be panned
19584         * to adjust for a soft input area.
19585         */
19586        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19587
19588        final KeyEvent.DispatcherState mKeyDispatchState
19589                = new KeyEvent.DispatcherState();
19590
19591        /**
19592         * Indicates whether the view's window currently has the focus.
19593         */
19594        boolean mHasWindowFocus;
19595
19596        /**
19597         * The current visibility of the window.
19598         */
19599        int mWindowVisibility;
19600
19601        /**
19602         * Indicates the time at which drawing started to occur.
19603         */
19604        long mDrawingTime;
19605
19606        /**
19607         * Indicates whether or not ignoring the DIRTY_MASK flags.
19608         */
19609        boolean mIgnoreDirtyState;
19610
19611        /**
19612         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19613         * to avoid clearing that flag prematurely.
19614         */
19615        boolean mSetIgnoreDirtyState = false;
19616
19617        /**
19618         * Indicates whether the view's window is currently in touch mode.
19619         */
19620        boolean mInTouchMode;
19621
19622        /**
19623         * Indicates that ViewAncestor should trigger a global layout change
19624         * the next time it performs a traversal
19625         */
19626        boolean mRecomputeGlobalAttributes;
19627
19628        /**
19629         * Always report new attributes at next traversal.
19630         */
19631        boolean mForceReportNewAttributes;
19632
19633        /**
19634         * Set during a traveral if any views want to keep the screen on.
19635         */
19636        boolean mKeepScreenOn;
19637
19638        /**
19639         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19640         */
19641        int mSystemUiVisibility;
19642
19643        /**
19644         * Hack to force certain system UI visibility flags to be cleared.
19645         */
19646        int mDisabledSystemUiVisibility;
19647
19648        /**
19649         * Last global system UI visibility reported by the window manager.
19650         */
19651        int mGlobalSystemUiVisibility;
19652
19653        /**
19654         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19655         * attached.
19656         */
19657        boolean mHasSystemUiListeners;
19658
19659        /**
19660         * Set if the window has requested to extend into the overscan region
19661         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19662         */
19663        boolean mOverscanRequested;
19664
19665        /**
19666         * Set if the visibility of any views has changed.
19667         */
19668        boolean mViewVisibilityChanged;
19669
19670        /**
19671         * Set to true if a view has been scrolled.
19672         */
19673        boolean mViewScrollChanged;
19674
19675        /**
19676         * Global to the view hierarchy used as a temporary for dealing with
19677         * x/y points in the transparent region computations.
19678         */
19679        final int[] mTransparentLocation = new int[2];
19680
19681        /**
19682         * Global to the view hierarchy used as a temporary for dealing with
19683         * x/y points in the ViewGroup.invalidateChild implementation.
19684         */
19685        final int[] mInvalidateChildLocation = new int[2];
19686
19687
19688        /**
19689         * Global to the view hierarchy used as a temporary for dealing with
19690         * x/y location when view is transformed.
19691         */
19692        final float[] mTmpTransformLocation = new float[2];
19693
19694        /**
19695         * The view tree observer used to dispatch global events like
19696         * layout, pre-draw, touch mode change, etc.
19697         */
19698        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19699
19700        /**
19701         * A Canvas used by the view hierarchy to perform bitmap caching.
19702         */
19703        Canvas mCanvas;
19704
19705        /**
19706         * The view root impl.
19707         */
19708        final ViewRootImpl mViewRootImpl;
19709
19710        /**
19711         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19712         * handler can be used to pump events in the UI events queue.
19713         */
19714        final Handler mHandler;
19715
19716        /**
19717         * Temporary for use in computing invalidate rectangles while
19718         * calling up the hierarchy.
19719         */
19720        final Rect mTmpInvalRect = new Rect();
19721
19722        /**
19723         * Temporary for use in computing hit areas with transformed views
19724         */
19725        final RectF mTmpTransformRect = new RectF();
19726
19727        /**
19728         * Temporary for use in transforming invalidation rect
19729         */
19730        final Matrix mTmpMatrix = new Matrix();
19731
19732        /**
19733         * Temporary for use in transforming invalidation rect
19734         */
19735        final Transformation mTmpTransformation = new Transformation();
19736
19737        /**
19738         * Temporary list for use in collecting focusable descendents of a view.
19739         */
19740        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19741
19742        /**
19743         * The id of the window for accessibility purposes.
19744         */
19745        int mAccessibilityWindowId = View.NO_ID;
19746
19747        /**
19748         * Flags related to accessibility processing.
19749         *
19750         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19751         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19752         */
19753        int mAccessibilityFetchFlags;
19754
19755        /**
19756         * The drawable for highlighting accessibility focus.
19757         */
19758        Drawable mAccessibilityFocusDrawable;
19759
19760        /**
19761         * Show where the margins, bounds and layout bounds are for each view.
19762         */
19763        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19764
19765        /**
19766         * Point used to compute visible regions.
19767         */
19768        final Point mPoint = new Point();
19769
19770        /**
19771         * Used to track which View originated a requestLayout() call, used when
19772         * requestLayout() is called during layout.
19773         */
19774        View mViewRequestingLayout;
19775
19776        /**
19777         * Creates a new set of attachment information with the specified
19778         * events handler and thread.
19779         *
19780         * @param handler the events handler the view must use
19781         */
19782        AttachInfo(IWindowSession session, IWindow window, Display display,
19783                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19784            mSession = session;
19785            mWindow = window;
19786            mWindowToken = window.asBinder();
19787            mDisplay = display;
19788            mViewRootImpl = viewRootImpl;
19789            mHandler = handler;
19790            mRootCallbacks = effectPlayer;
19791        }
19792    }
19793
19794    /**
19795     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19796     * is supported. This avoids keeping too many unused fields in most
19797     * instances of View.</p>
19798     */
19799    private static class ScrollabilityCache implements Runnable {
19800
19801        /**
19802         * Scrollbars are not visible
19803         */
19804        public static final int OFF = 0;
19805
19806        /**
19807         * Scrollbars are visible
19808         */
19809        public static final int ON = 1;
19810
19811        /**
19812         * Scrollbars are fading away
19813         */
19814        public static final int FADING = 2;
19815
19816        public boolean fadeScrollBars;
19817
19818        public int fadingEdgeLength;
19819        public int scrollBarDefaultDelayBeforeFade;
19820        public int scrollBarFadeDuration;
19821
19822        public int scrollBarSize;
19823        public ScrollBarDrawable scrollBar;
19824        public float[] interpolatorValues;
19825        public View host;
19826
19827        public final Paint paint;
19828        public final Matrix matrix;
19829        public Shader shader;
19830
19831        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19832
19833        private static final float[] OPAQUE = { 255 };
19834        private static final float[] TRANSPARENT = { 0.0f };
19835
19836        /**
19837         * When fading should start. This time moves into the future every time
19838         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19839         */
19840        public long fadeStartTime;
19841
19842
19843        /**
19844         * The current state of the scrollbars: ON, OFF, or FADING
19845         */
19846        public int state = OFF;
19847
19848        private int mLastColor;
19849
19850        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19851            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19852            scrollBarSize = configuration.getScaledScrollBarSize();
19853            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19854            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19855
19856            paint = new Paint();
19857            matrix = new Matrix();
19858            // use use a height of 1, and then wack the matrix each time we
19859            // actually use it.
19860            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19861            paint.setShader(shader);
19862            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19863
19864            this.host = host;
19865        }
19866
19867        public void setFadeColor(int color) {
19868            if (color != mLastColor) {
19869                mLastColor = color;
19870
19871                if (color != 0) {
19872                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19873                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19874                    paint.setShader(shader);
19875                    // Restore the default transfer mode (src_over)
19876                    paint.setXfermode(null);
19877                } else {
19878                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19879                    paint.setShader(shader);
19880                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19881                }
19882            }
19883        }
19884
19885        public void run() {
19886            long now = AnimationUtils.currentAnimationTimeMillis();
19887            if (now >= fadeStartTime) {
19888
19889                // the animation fades the scrollbars out by changing
19890                // the opacity (alpha) from fully opaque to fully
19891                // transparent
19892                int nextFrame = (int) now;
19893                int framesCount = 0;
19894
19895                Interpolator interpolator = scrollBarInterpolator;
19896
19897                // Start opaque
19898                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19899
19900                // End transparent
19901                nextFrame += scrollBarFadeDuration;
19902                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19903
19904                state = FADING;
19905
19906                // Kick off the fade animation
19907                host.invalidate(true);
19908            }
19909        }
19910    }
19911
19912    /**
19913     * Resuable callback for sending
19914     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19915     */
19916    private class SendViewScrolledAccessibilityEvent implements Runnable {
19917        public volatile boolean mIsPending;
19918
19919        public void run() {
19920            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19921            mIsPending = false;
19922        }
19923    }
19924
19925    /**
19926     * <p>
19927     * This class represents a delegate that can be registered in a {@link View}
19928     * to enhance accessibility support via composition rather via inheritance.
19929     * It is specifically targeted to widget developers that extend basic View
19930     * classes i.e. classes in package android.view, that would like their
19931     * applications to be backwards compatible.
19932     * </p>
19933     * <div class="special reference">
19934     * <h3>Developer Guides</h3>
19935     * <p>For more information about making applications accessible, read the
19936     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
19937     * developer guide.</p>
19938     * </div>
19939     * <p>
19940     * A scenario in which a developer would like to use an accessibility delegate
19941     * is overriding a method introduced in a later API version then the minimal API
19942     * version supported by the application. For example, the method
19943     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
19944     * in API version 4 when the accessibility APIs were first introduced. If a
19945     * developer would like his application to run on API version 4 devices (assuming
19946     * all other APIs used by the application are version 4 or lower) and take advantage
19947     * of this method, instead of overriding the method which would break the application's
19948     * backwards compatibility, he can override the corresponding method in this
19949     * delegate and register the delegate in the target View if the API version of
19950     * the system is high enough i.e. the API version is same or higher to the API
19951     * version that introduced
19952     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
19953     * </p>
19954     * <p>
19955     * Here is an example implementation:
19956     * </p>
19957     * <code><pre><p>
19958     * if (Build.VERSION.SDK_INT >= 14) {
19959     *     // If the API version is equal of higher than the version in
19960     *     // which onInitializeAccessibilityNodeInfo was introduced we
19961     *     // register a delegate with a customized implementation.
19962     *     View view = findViewById(R.id.view_id);
19963     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
19964     *         public void onInitializeAccessibilityNodeInfo(View host,
19965     *                 AccessibilityNodeInfo info) {
19966     *             // Let the default implementation populate the info.
19967     *             super.onInitializeAccessibilityNodeInfo(host, info);
19968     *             // Set some other information.
19969     *             info.setEnabled(host.isEnabled());
19970     *         }
19971     *     });
19972     * }
19973     * </code></pre></p>
19974     * <p>
19975     * This delegate contains methods that correspond to the accessibility methods
19976     * in View. If a delegate has been specified the implementation in View hands
19977     * off handling to the corresponding method in this delegate. The default
19978     * implementation the delegate methods behaves exactly as the corresponding
19979     * method in View for the case of no accessibility delegate been set. Hence,
19980     * to customize the behavior of a View method, clients can override only the
19981     * corresponding delegate method without altering the behavior of the rest
19982     * accessibility related methods of the host view.
19983     * </p>
19984     */
19985    public static class AccessibilityDelegate {
19986
19987        /**
19988         * Sends an accessibility event of the given type. If accessibility is not
19989         * enabled this method has no effect.
19990         * <p>
19991         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
19992         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
19993         * been set.
19994         * </p>
19995         *
19996         * @param host The View hosting the delegate.
19997         * @param eventType The type of the event to send.
19998         *
19999         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20000         */
20001        public void sendAccessibilityEvent(View host, int eventType) {
20002            host.sendAccessibilityEventInternal(eventType);
20003        }
20004
20005        /**
20006         * Performs the specified accessibility action on the view. For
20007         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20008         * <p>
20009         * The default implementation behaves as
20010         * {@link View#performAccessibilityAction(int, Bundle)
20011         *  View#performAccessibilityAction(int, Bundle)} for the case of
20012         *  no accessibility delegate been set.
20013         * </p>
20014         *
20015         * @param action The action to perform.
20016         * @return Whether the action was performed.
20017         *
20018         * @see View#performAccessibilityAction(int, Bundle)
20019         *      View#performAccessibilityAction(int, Bundle)
20020         */
20021        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20022            return host.performAccessibilityActionInternal(action, args);
20023        }
20024
20025        /**
20026         * Sends an accessibility event. This method behaves exactly as
20027         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20028         * empty {@link AccessibilityEvent} and does not perform a check whether
20029         * accessibility is enabled.
20030         * <p>
20031         * The default implementation behaves as
20032         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20033         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20034         * the case of no accessibility delegate been set.
20035         * </p>
20036         *
20037         * @param host The View hosting the delegate.
20038         * @param event The event to send.
20039         *
20040         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20041         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20042         */
20043        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20044            host.sendAccessibilityEventUncheckedInternal(event);
20045        }
20046
20047        /**
20048         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20049         * to its children for adding their text content to the event.
20050         * <p>
20051         * The default implementation behaves as
20052         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20053         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20054         * the case of no accessibility delegate been set.
20055         * </p>
20056         *
20057         * @param host The View hosting the delegate.
20058         * @param event The event.
20059         * @return True if the event population was completed.
20060         *
20061         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20062         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20063         */
20064        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20065            return host.dispatchPopulateAccessibilityEventInternal(event);
20066        }
20067
20068        /**
20069         * Gives a chance to the host View to populate the accessibility event with its
20070         * text content.
20071         * <p>
20072         * The default implementation behaves as
20073         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20074         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20075         * the case of no accessibility delegate been set.
20076         * </p>
20077         *
20078         * @param host The View hosting the delegate.
20079         * @param event The accessibility event which to populate.
20080         *
20081         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20082         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20083         */
20084        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20085            host.onPopulateAccessibilityEventInternal(event);
20086        }
20087
20088        /**
20089         * Initializes an {@link AccessibilityEvent} with information about the
20090         * the host View which is the event source.
20091         * <p>
20092         * The default implementation behaves as
20093         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20094         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20095         * the case of no accessibility delegate been set.
20096         * </p>
20097         *
20098         * @param host The View hosting the delegate.
20099         * @param event The event to initialize.
20100         *
20101         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20102         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20103         */
20104        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20105            host.onInitializeAccessibilityEventInternal(event);
20106        }
20107
20108        /**
20109         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20110         * <p>
20111         * The default implementation behaves as
20112         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20113         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20114         * the case of no accessibility delegate been set.
20115         * </p>
20116         *
20117         * @param host The View hosting the delegate.
20118         * @param info The instance to initialize.
20119         *
20120         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20121         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20122         */
20123        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20124            host.onInitializeAccessibilityNodeInfoInternal(info);
20125        }
20126
20127        /**
20128         * Called when a child of the host View has requested sending an
20129         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20130         * to augment the event.
20131         * <p>
20132         * The default implementation behaves as
20133         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20134         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20135         * the case of no accessibility delegate been set.
20136         * </p>
20137         *
20138         * @param host The View hosting the delegate.
20139         * @param child The child which requests sending the event.
20140         * @param event The event to be sent.
20141         * @return True if the event should be sent
20142         *
20143         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20144         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20145         */
20146        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20147                AccessibilityEvent event) {
20148            return host.onRequestSendAccessibilityEventInternal(child, event);
20149        }
20150
20151        /**
20152         * Gets the provider for managing a virtual view hierarchy rooted at this View
20153         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20154         * that explore the window content.
20155         * <p>
20156         * The default implementation behaves as
20157         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20158         * the case of no accessibility delegate been set.
20159         * </p>
20160         *
20161         * @return The provider.
20162         *
20163         * @see AccessibilityNodeProvider
20164         */
20165        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20166            return null;
20167        }
20168
20169        /**
20170         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20171         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20172         * This method is responsible for obtaining an accessibility node info from a
20173         * pool of reusable instances and calling
20174         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20175         * view to initialize the former.
20176         * <p>
20177         * <strong>Note:</strong> The client is responsible for recycling the obtained
20178         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20179         * creation.
20180         * </p>
20181         * <p>
20182         * The default implementation behaves as
20183         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20184         * the case of no accessibility delegate been set.
20185         * </p>
20186         * @return A populated {@link AccessibilityNodeInfo}.
20187         *
20188         * @see AccessibilityNodeInfo
20189         *
20190         * @hide
20191         */
20192        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20193            return host.createAccessibilityNodeInfoInternal();
20194        }
20195    }
20196
20197    private class MatchIdPredicate implements Predicate<View> {
20198        public int mId;
20199
20200        @Override
20201        public boolean apply(View view) {
20202            return (view.mID == mId);
20203        }
20204    }
20205
20206    private class MatchLabelForPredicate implements Predicate<View> {
20207        private int mLabeledId;
20208
20209        @Override
20210        public boolean apply(View view) {
20211            return (view.mLabelForId == mLabeledId);
20212        }
20213    }
20214
20215    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20216        private int mChangeTypes = 0;
20217        private boolean mPosted;
20218        private boolean mPostedWithDelay;
20219        private long mLastEventTimeMillis;
20220
20221        @Override
20222        public void run() {
20223            mPosted = false;
20224            mPostedWithDelay = false;
20225            mLastEventTimeMillis = SystemClock.uptimeMillis();
20226            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20227                final AccessibilityEvent event = AccessibilityEvent.obtain();
20228                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20229                event.setContentChangeTypes(mChangeTypes);
20230                sendAccessibilityEventUnchecked(event);
20231            }
20232            mChangeTypes = 0;
20233        }
20234
20235        public void runOrPost(int changeType) {
20236            mChangeTypes |= changeType;
20237
20238            // If this is a live region or the child of a live region, collect
20239            // all events from this frame and send them on the next frame.
20240            if (inLiveRegion()) {
20241                // If we're already posted with a delay, remove that.
20242                if (mPostedWithDelay) {
20243                    removeCallbacks(this);
20244                    mPostedWithDelay = false;
20245                }
20246                // Only post if we're not already posted.
20247                if (!mPosted) {
20248                    post(this);
20249                    mPosted = true;
20250                }
20251                return;
20252            }
20253
20254            if (mPosted) {
20255                return;
20256            }
20257            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20258            final long minEventIntevalMillis =
20259                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20260            if (timeSinceLastMillis >= minEventIntevalMillis) {
20261                removeCallbacks(this);
20262                run();
20263            } else {
20264                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20265                mPosted = true;
20266                mPostedWithDelay = true;
20267            }
20268        }
20269    }
20270
20271    private boolean inLiveRegion() {
20272        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20273            return true;
20274        }
20275
20276        ViewParent parent = getParent();
20277        while (parent instanceof View) {
20278            if (((View) parent).getAccessibilityLiveRegion()
20279                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20280                return true;
20281            }
20282            parent = parent.getParent();
20283        }
20284
20285        return false;
20286    }
20287
20288    /**
20289     * Dump all private flags in readable format, useful for documentation and
20290     * sanity checking.
20291     */
20292    private static void dumpFlags() {
20293        final HashMap<String, String> found = Maps.newHashMap();
20294        try {
20295            for (Field field : View.class.getDeclaredFields()) {
20296                final int modifiers = field.getModifiers();
20297                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20298                    if (field.getType().equals(int.class)) {
20299                        final int value = field.getInt(null);
20300                        dumpFlag(found, field.getName(), value);
20301                    } else if (field.getType().equals(int[].class)) {
20302                        final int[] values = (int[]) field.get(null);
20303                        for (int i = 0; i < values.length; i++) {
20304                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20305                        }
20306                    }
20307                }
20308            }
20309        } catch (IllegalAccessException e) {
20310            throw new RuntimeException(e);
20311        }
20312
20313        final ArrayList<String> keys = Lists.newArrayList();
20314        keys.addAll(found.keySet());
20315        Collections.sort(keys);
20316        for (String key : keys) {
20317            Log.d(VIEW_LOG_TAG, found.get(key));
20318        }
20319    }
20320
20321    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20322        // Sort flags by prefix, then by bits, always keeping unique keys
20323        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20324        final int prefix = name.indexOf('_');
20325        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20326        final String output = bits + " " + name;
20327        found.put(key, output);
20328    }
20329}
20330