Home | History | Annotate | Download | only in view
      1 /*
      2  * Copyright (C) 2006 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.view;
     18 
     19 import android.content.ClipData;
     20 import android.content.Context;
     21 import android.content.res.Configuration;
     22 import android.content.res.Resources;
     23 import android.content.res.TypedArray;
     24 import android.graphics.Bitmap;
     25 import android.graphics.Camera;
     26 import android.graphics.Canvas;
     27 import android.graphics.Insets;
     28 import android.graphics.Interpolator;
     29 import android.graphics.LinearGradient;
     30 import android.graphics.Matrix;
     31 import android.graphics.Paint;
     32 import android.graphics.PixelFormat;
     33 import android.graphics.Point;
     34 import android.graphics.PorterDuff;
     35 import android.graphics.PorterDuffXfermode;
     36 import android.graphics.Rect;
     37 import android.graphics.RectF;
     38 import android.graphics.Region;
     39 import android.graphics.Shader;
     40 import android.graphics.drawable.ColorDrawable;
     41 import android.graphics.drawable.Drawable;
     42 import android.os.Bundle;
     43 import android.os.Handler;
     44 import android.os.IBinder;
     45 import android.os.Parcel;
     46 import android.os.Parcelable;
     47 import android.os.RemoteException;
     48 import android.os.SystemClock;
     49 import android.os.SystemProperties;
     50 import android.util.AttributeSet;
     51 import android.util.FloatProperty;
     52 import android.util.LocaleUtil;
     53 import android.util.Log;
     54 import android.util.Pool;
     55 import android.util.Poolable;
     56 import android.util.PoolableManager;
     57 import android.util.Pools;
     58 import android.util.Property;
     59 import android.util.SparseArray;
     60 import android.util.TypedValue;
     61 import android.view.ContextMenu.ContextMenuInfo;
     62 import android.view.AccessibilityIterators.TextSegmentIterator;
     63 import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
     64 import android.view.AccessibilityIterators.WordTextSegmentIterator;
     65 import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
     66 import android.view.accessibility.AccessibilityEvent;
     67 import android.view.accessibility.AccessibilityEventSource;
     68 import android.view.accessibility.AccessibilityManager;
     69 import android.view.accessibility.AccessibilityNodeInfo;
     70 import android.view.accessibility.AccessibilityNodeProvider;
     71 import android.view.animation.Animation;
     72 import android.view.animation.AnimationUtils;
     73 import android.view.animation.Transformation;
     74 import android.view.inputmethod.EditorInfo;
     75 import android.view.inputmethod.InputConnection;
     76 import android.view.inputmethod.InputMethodManager;
     77 import android.widget.ScrollBarDrawable;
     78 
     79 import static android.os.Build.VERSION_CODES.*;
     80 import static java.lang.Math.max;
     81 
     82 import com.android.internal.R;
     83 import com.android.internal.util.Predicate;
     84 import com.android.internal.view.menu.MenuBuilder;
     85 
     86 import java.lang.ref.WeakReference;
     87 import java.lang.reflect.InvocationTargetException;
     88 import java.lang.reflect.Method;
     89 import java.util.ArrayList;
     90 import java.util.Arrays;
     91 import java.util.Locale;
     92 import java.util.concurrent.CopyOnWriteArrayList;
     93 
     94 /**
     95  * <p>
     96  * This class represents the basic building block for user interface components. A View
     97  * occupies a rectangular area on the screen and is responsible for drawing and
     98  * event handling. View is the base class for <em>widgets</em>, which are
     99  * used to create interactive UI components (buttons, text fields, etc.). The
    100  * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
    101  * are invisible containers that hold other Views (or other ViewGroups) and define
    102  * their layout properties.
    103  * </p>
    104  *
    105  * <div class="special reference">
    106  * <h3>Developer Guides</h3>
    107  * <p>For information about using this class to develop your application's user interface,
    108  * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
    109  * </div>
    110  *
    111  * <a name="Using"></a>
    112  * <h3>Using Views</h3>
    113  * <p>
    114  * All of the views in a window are arranged in a single tree. You can add views
    115  * either from code or by specifying a tree of views in one or more XML layout
    116  * files. There are many specialized subclasses of views that act as controls or
    117  * are capable of displaying text, images, or other content.
    118  * </p>
    119  * <p>
    120  * Once you have created a tree of views, there are typically a few types of
    121  * common operations you may wish to perform:
    122  * <ul>
    123  * <li><strong>Set properties:</strong> for example setting the text of a
    124  * {@link android.widget.TextView}. The available properties and the methods
    125  * that set them will vary among the different subclasses of views. Note that
    126  * properties that are known at build time can be set in the XML layout
    127  * files.</li>
    128  * <li><strong>Set focus:</strong> The framework will handled moving focus in
    129  * response to user input. To force focus to a specific view, call
    130  * {@link #requestFocus}.</li>
    131  * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
    132  * that will be notified when something interesting happens to the view. For
    133  * example, all views will let you set a listener to be notified when the view
    134  * gains or loses focus. You can register such a listener using
    135  * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
    136  * Other view subclasses offer more specialized listeners. For example, a Button
    137  * exposes a listener to notify clients when the button is clicked.</li>
    138  * <li><strong>Set visibility:</strong> You can hide or show views using
    139  * {@link #setVisibility(int)}.</li>
    140  * </ul>
    141  * </p>
    142  * <p><em>
    143  * Note: The Android framework is responsible for measuring, laying out and
    144  * drawing views. You should not call methods that perform these actions on
    145  * views yourself unless you are actually implementing a
    146  * {@link android.view.ViewGroup}.
    147  * </em></p>
    148  *
    149  * <a name="Lifecycle"></a>
    150  * <h3>Implementing a Custom View</h3>
    151  *
    152  * <p>
    153  * To implement a custom view, you will usually begin by providing overrides for
    154  * some of the standard methods that the framework calls on all views. You do
    155  * not need to override all of these methods. In fact, you can start by just
    156  * overriding {@link #onDraw(android.graphics.Canvas)}.
    157  * <table border="2" width="85%" align="center" cellpadding="5">
    158  *     <thead>
    159  *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
    160  *     </thead>
    161  *
    162  *     <tbody>
    163  *     <tr>
    164  *         <td rowspan="2">Creation</td>
    165  *         <td>Constructors</td>
    166  *         <td>There is a form of the constructor that are called when the view
    167  *         is created from code and a form that is called when the view is
    168  *         inflated from a layout file. The second form should parse and apply
    169  *         any attributes defined in the layout file.
    170  *         </td>
    171  *     </tr>
    172  *     <tr>
    173  *         <td><code>{@link #onFinishInflate()}</code></td>
    174  *         <td>Called after a view and all of its children has been inflated
    175  *         from XML.</td>
    176  *     </tr>
    177  *
    178  *     <tr>
    179  *         <td rowspan="3">Layout</td>
    180  *         <td><code>{@link #onMeasure(int, int)}</code></td>
    181  *         <td>Called to determine the size requirements for this view and all
    182  *         of its children.
    183  *         </td>
    184  *     </tr>
    185  *     <tr>
    186  *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
    187  *         <td>Called when this view should assign a size and position to all
    188  *         of its children.
    189  *         </td>
    190  *     </tr>
    191  *     <tr>
    192  *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
    193  *         <td>Called when the size of this view has changed.
    194  *         </td>
    195  *     </tr>
    196  *
    197  *     <tr>
    198  *         <td>Drawing</td>
    199  *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
    200  *         <td>Called when the view should render its content.
    201  *         </td>
    202  *     </tr>
    203  *
    204  *     <tr>
    205  *         <td rowspan="4">Event processing</td>
    206  *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
    207  *         <td>Called when a new hardware key event occurs.
    208  *         </td>
    209  *     </tr>
    210  *     <tr>
    211  *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
    212  *         <td>Called when a hardware key up event occurs.
    213  *         </td>
    214  *     </tr>
    215  *     <tr>
    216  *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
    217  *         <td>Called when a trackball motion event occurs.
    218  *         </td>
    219  *     </tr>
    220  *     <tr>
    221  *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
    222  *         <td>Called when a touch screen motion event occurs.
    223  *         </td>
    224  *     </tr>
    225  *
    226  *     <tr>
    227  *         <td rowspan="2">Focus</td>
    228  *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
    229  *         <td>Called when the view gains or loses focus.
    230  *         </td>
    231  *     </tr>
    232  *
    233  *     <tr>
    234  *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
    235  *         <td>Called when the window containing the view gains or loses focus.
    236  *         </td>
    237  *     </tr>
    238  *
    239  *     <tr>
    240  *         <td rowspan="3">Attaching</td>
    241  *         <td><code>{@link #onAttachedToWindow()}</code></td>
    242  *         <td>Called when the view is attached to a window.
    243  *         </td>
    244  *     </tr>
    245  *
    246  *     <tr>
    247  *         <td><code>{@link #onDetachedFromWindow}</code></td>
    248  *         <td>Called when the view is detached from its window.
    249  *         </td>
    250  *     </tr>
    251  *
    252  *     <tr>
    253  *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
    254  *         <td>Called when the visibility of the window containing the view
    255  *         has changed.
    256  *         </td>
    257  *     </tr>
    258  *     </tbody>
    259  *
    260  * </table>
    261  * </p>
    262  *
    263  * <a name="IDs"></a>
    264  * <h3>IDs</h3>
    265  * Views may have an integer id associated with them. These ids are typically
    266  * assigned in the layout XML files, and are used to find specific views within
    267  * the view tree. A common pattern is to:
    268  * <ul>
    269  * <li>Define a Button in the layout file and assign it a unique ID.
    270  * <pre>
    271  * &lt;Button
    272  *     android:id="@+id/my_button"
    273  *     android:layout_width="wrap_content"
    274  *     android:layout_height="wrap_content"
    275  *     android:text="@string/my_button_text"/&gt;
    276  * </pre></li>
    277  * <li>From the onCreate method of an Activity, find the Button
    278  * <pre class="prettyprint">
    279  *      Button myButton = (Button) findViewById(R.id.my_button);
    280  * </pre></li>
    281  * </ul>
    282  * <p>
    283  * View IDs need not be unique throughout the tree, but it is good practice to
    284  * ensure that they are at least unique within the part of the tree you are
    285  * searching.
    286  * </p>
    287  *
    288  * <a name="Position"></a>
    289  * <h3>Position</h3>
    290  * <p>
    291  * The geometry of a view is that of a rectangle. A view has a location,
    292  * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
    293  * two dimensions, expressed as a width and a height. The unit for location
    294  * and dimensions is the pixel.
    295  * </p>
    296  *
    297  * <p>
    298  * It is possible to retrieve the location of a view by invoking the methods
    299  * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
    300  * coordinate of the rectangle representing the view. The latter returns the
    301  * top, or Y, coordinate of the rectangle representing the view. These methods
    302  * both return the location of the view relative to its parent. For instance,
    303  * when getLeft() returns 20, that means the view is located 20 pixels to the
    304  * right of the left edge of its direct parent.
    305  * </p>
    306  *
    307  * <p>
    308  * In addition, several convenience methods are offered to avoid unnecessary
    309  * computations, namely {@link #getRight()} and {@link #getBottom()}.
    310  * These methods return the coordinates of the right and bottom edges of the
    311  * rectangle representing the view. For instance, calling {@link #getRight()}
    312  * is similar to the following computation: <code>getLeft() + getWidth()</code>
    313  * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
    314  * </p>
    315  *
    316  * <a name="SizePaddingMargins"></a>
    317  * <h3>Size, padding and margins</h3>
    318  * <p>
    319  * The size of a view is expressed with a width and a height. A view actually
    320  * possess two pairs of width and height values.
    321  * </p>
    322  *
    323  * <p>
    324  * The first pair is known as <em>measured width</em> and
    325  * <em>measured height</em>. These dimensions define how big a view wants to be
    326  * within its parent (see <a href="#Layout">Layout</a> for more details.) The
    327  * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
    328  * and {@link #getMeasuredHeight()}.
    329  * </p>
    330  *
    331  * <p>
    332  * The second pair is simply known as <em>width</em> and <em>height</em>, or
    333  * sometimes <em>drawing width</em> and <em>drawing height</em>. These
    334  * dimensions define the actual size of the view on screen, at drawing time and
    335  * after layout. These values may, but do not have to, be different from the
    336  * measured width and height. The width and height can be obtained by calling
    337  * {@link #getWidth()} and {@link #getHeight()}.
    338  * </p>
    339  *
    340  * <p>
    341  * To measure its dimensions, a view takes into account its padding. The padding
    342  * is expressed in pixels for the left, top, right and bottom parts of the view.
    343  * Padding can be used to offset the content of the view by a specific amount of
    344  * pixels. For instance, a left padding of 2 will push the view's content by
    345  * 2 pixels to the right of the left edge. Padding can be set using the
    346  * {@link #setPadding(int, int, int, int)} method and queried by calling
    347  * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, {@link #getPaddingRight()},
    348  * {@link #getPaddingBottom()}.
    349  * </p>
    350  *
    351  * <p>
    352  * Even though a view can define a padding, it does not provide any support for
    353  * margins. However, view groups provide such a support. Refer to
    354  * {@link android.view.ViewGroup} and
    355  * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
    356  * </p>
    357  *
    358  * <a name="Layout"></a>
    359  * <h3>Layout</h3>
    360  * <p>
    361  * Layout is a two pass process: a measure pass and a layout pass. The measuring
    362  * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
    363  * of the view tree. Each view pushes dimension specifications down the tree
    364  * during the recursion. At the end of the measure pass, every view has stored
    365  * its measurements. The second pass happens in
    366  * {@link #layout(int,int,int,int)} and is also top-down. During
    367  * this pass each parent is responsible for positioning all of its children
    368  * using the sizes computed in the measure pass.
    369  * </p>
    370  *
    371  * <p>
    372  * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
    373  * {@link #getMeasuredHeight()} values must be set, along with those for all of
    374  * that view's descendants. A view's measured width and measured height values
    375  * must respect the constraints imposed by the view's parents. This guarantees
    376  * that at the end of the measure pass, all parents accept all of their
    377  * children's measurements. A parent view may call measure() more than once on
    378  * its children. For example, the parent may measure each child once with
    379  * unspecified dimensions to find out how big they want to be, then call
    380  * measure() on them again with actual numbers if the sum of all the children's
    381  * unconstrained sizes is too big or too small.
    382  * </p>
    383  *
    384  * <p>
    385  * The measure pass uses two classes to communicate dimensions. The
    386  * {@link MeasureSpec} class is used by views to tell their parents how they
    387  * want to be measured and positioned. The base LayoutParams class just
    388  * describes how big the view wants to be for both width and height. For each
    389  * dimension, it can specify one of:
    390  * <ul>
    391  * <li> an exact number
    392  * <li>MATCH_PARENT, which means the view wants to be as big as its parent
    393  * (minus padding)
    394  * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
    395  * enclose its content (plus padding).
    396  * </ul>
    397  * There are subclasses of LayoutParams for different subclasses of ViewGroup.
    398  * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
    399  * an X and Y value.
    400  * </p>
    401  *
    402  * <p>
    403  * MeasureSpecs are used to push requirements down the tree from parent to
    404  * child. A MeasureSpec can be in one of three modes:
    405  * <ul>
    406  * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
    407  * of a child view. For example, a LinearLayout may call measure() on its child
    408  * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
    409  * tall the child view wants to be given a width of 240 pixels.
    410  * <li>EXACTLY: This is used by the parent to impose an exact size on the
    411  * child. The child must use this size, and guarantee that all of its
    412  * descendants will fit within this size.
    413  * <li>AT_MOST: This is used by the parent to impose a maximum size on the
    414  * child. The child must gurantee that it and all of its descendants will fit
    415  * within this size.
    416  * </ul>
    417  * </p>
    418  *
    419  * <p>
    420  * To intiate a layout, call {@link #requestLayout}. This method is typically
    421  * called by a view on itself when it believes that is can no longer fit within
    422  * its current bounds.
    423  * </p>
    424  *
    425  * <a name="Drawing"></a>
    426  * <h3>Drawing</h3>
    427  * <p>
    428  * Drawing is handled by walking the tree and rendering each view that
    429  * intersects the invalid region. Because the tree is traversed in-order,
    430  * this means that parents will draw before (i.e., behind) their children, with
    431  * siblings drawn in the order they appear in the tree.
    432  * If you set a background drawable for a View, then the View will draw it for you
    433  * before calling back to its <code>onDraw()</code> method.
    434  * </p>
    435  *
    436  * <p>
    437  * Note that the framework will not draw views that are not in the invalid region.
    438  * </p>
    439  *
    440  * <p>
    441  * To force a view to draw, call {@link #invalidate()}.
    442  * </p>
    443  *
    444  * <a name="EventHandlingThreading"></a>
    445  * <h3>Event Handling and Threading</h3>
    446  * <p>
    447  * The basic cycle of a view is as follows:
    448  * <ol>
    449  * <li>An event comes in and is dispatched to the appropriate view. The view
    450  * handles the event and notifies any listeners.</li>
    451  * <li>If in the course of processing the event, the view's bounds may need
    452  * to be changed, the view will call {@link #requestLayout()}.</li>
    453  * <li>Similarly, if in the course of processing the event the view's appearance
    454  * may need to be changed, the view will call {@link #invalidate()}.</li>
    455  * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
    456  * the framework will take care of measuring, laying out, and drawing the tree
    457  * as appropriate.</li>
    458  * </ol>
    459  * </p>
    460  *
    461  * <p><em>Note: The entire view tree is single threaded. You must always be on
    462  * the UI thread when calling any method on any view.</em>
    463  * If you are doing work on other threads and want to update the state of a view
    464  * from that thread, you should use a {@link Handler}.
    465  * </p>
    466  *
    467  * <a name="FocusHandling"></a>
    468  * <h3>Focus Handling</h3>
    469  * <p>
    470  * The framework will handle routine focus movement in response to user input.
    471  * This includes changing the focus as views are removed or hidden, or as new
    472  * views become available. Views indicate their willingness to take focus
    473  * through the {@link #isFocusable} method. To change whether a view can take
    474  * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
    475  * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
    476  * and can change this via {@link #setFocusableInTouchMode(boolean)}.
    477  * </p>
    478  * <p>
    479  * Focus movement is based on an algorithm which finds the nearest neighbor in a
    480  * given direction. In rare cases, the default algorithm may not match the
    481  * intended behavior of the developer. In these situations, you can provide
    482  * explicit overrides by using these XML attributes in the layout file:
    483  * <pre>
    484  * nextFocusDown
    485  * nextFocusLeft
    486  * nextFocusRight
    487  * nextFocusUp
    488  * </pre>
    489  * </p>
    490  *
    491  *
    492  * <p>
    493  * To get a particular view to take focus, call {@link #requestFocus()}.
    494  * </p>
    495  *
    496  * <a name="TouchMode"></a>
    497  * <h3>Touch Mode</h3>
    498  * <p>
    499  * When a user is navigating a user interface via directional keys such as a D-pad, it is
    500  * necessary to give focus to actionable items such as buttons so the user can see
    501  * what will take input.  If the device has touch capabilities, however, and the user
    502  * begins interacting with the interface by touching it, it is no longer necessary to
    503  * always highlight, or give focus to, a particular view.  This motivates a mode
    504  * for interaction named 'touch mode'.
    505  * </p>
    506  * <p>
    507  * For a touch capable device, once the user touches the screen, the device
    508  * will enter touch mode.  From this point onward, only views for which
    509  * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
    510  * Other views that are touchable, like buttons, will not take focus when touched; they will
    511  * only fire the on click listeners.
    512  * </p>
    513  * <p>
    514  * Any time a user hits a directional key, such as a D-pad direction, the view device will
    515  * exit touch mode, and find a view to take focus, so that the user may resume interacting
    516  * with the user interface without touching the screen again.
    517  * </p>
    518  * <p>
    519  * The touch mode state is maintained across {@link android.app.Activity}s.  Call
    520  * {@link #isInTouchMode} to see whether the device is currently in touch mode.
    521  * </p>
    522  *
    523  * <a name="Scrolling"></a>
    524  * <h3>Scrolling</h3>
    525  * <p>
    526  * The framework provides basic support for views that wish to internally
    527  * scroll their content. This includes keeping track of the X and Y scroll
    528  * offset as well as mechanisms for drawing scrollbars. See
    529  * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
    530  * {@link #awakenScrollBars()} for more details.
    531  * </p>
    532  *
    533  * <a name="Tags"></a>
    534  * <h3>Tags</h3>
    535  * <p>
    536  * Unlike IDs, tags are not used to identify views. Tags are essentially an
    537  * extra piece of information that can be associated with a view. They are most
    538  * often used as a convenience to store data related to views in the views
    539  * themselves rather than by putting them in a separate structure.
    540  * </p>
    541  *
    542  * <a name="Properties"></a>
    543  * <h3>Properties</h3>
    544  * <p>
    545  * The View class exposes an {@link #ALPHA} property, as well as several transform-related
    546  * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
    547  * available both in the {@link Property} form as well as in similarly-named setter/getter
    548  * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
    549  * be used to set persistent state associated with these rendering-related properties on the view.
    550  * The properties and methods can also be used in conjunction with
    551  * {@link android.animation.Animator Animator}-based animations, described more in the
    552  * <a href="#Animation">Animation</a> section.
    553  * </p>
    554  *
    555  * <a name="Animation"></a>
    556  * <h3>Animation</h3>
    557  * <p>
    558  * Starting with Android 3.0, the preferred way of animating views is to use the
    559  * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
    560  * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
    561  * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
    562  * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
    563  * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
    564  * makes animating these View properties particularly easy and efficient.
    565  * </p>
    566  * <p>
    567  * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
    568  * You can attach an {@link Animation} object to a view using
    569  * {@link #setAnimation(Animation)} or
    570  * {@link #startAnimation(Animation)}. The animation can alter the scale,
    571  * rotation, translation and alpha of a view over time. If the animation is
    572  * attached to a view that has children, the animation will affect the entire
    573  * subtree rooted by that node. When an animation is started, the framework will
    574  * take care of redrawing the appropriate views until the animation completes.
    575  * </p>
    576  *
    577  * <a name="Security"></a>
    578  * <h3>Security</h3>
    579  * <p>
    580  * Sometimes it is essential that an application be able to verify that an action
    581  * is being performed with the full knowledge and consent of the user, such as
    582  * granting a permission request, making a purchase or clicking on an advertisement.
    583  * Unfortunately, a malicious application could try to spoof the user into
    584  * performing these actions, unaware, by concealing the intended purpose of the view.
    585  * As a remedy, the framework offers a touch filtering mechanism that can be used to
    586  * improve the security of views that provide access to sensitive functionality.
    587  * </p><p>
    588  * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
    589  * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
    590  * will discard touches that are received whenever the view's window is obscured by
    591  * another visible window.  As a result, the view will not receive touches whenever a
    592  * toast, dialog or other window appears above the view's window.
    593  * </p><p>
    594  * For more fine-grained control over security, consider overriding the
    595  * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
    596  * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
    597  * </p>
    598  *
    599  * @attr ref android.R.styleable#View_alpha
    600  * @attr ref android.R.styleable#View_background
    601  * @attr ref android.R.styleable#View_clickable
    602  * @attr ref android.R.styleable#View_contentDescription
    603  * @attr ref android.R.styleable#View_drawingCacheQuality
    604  * @attr ref android.R.styleable#View_duplicateParentState
    605  * @attr ref android.R.styleable#View_id
    606  * @attr ref android.R.styleable#View_requiresFadingEdge
    607  * @attr ref android.R.styleable#View_fadeScrollbars
    608  * @attr ref android.R.styleable#View_fadingEdgeLength
    609  * @attr ref android.R.styleable#View_filterTouchesWhenObscured
    610  * @attr ref android.R.styleable#View_fitsSystemWindows
    611  * @attr ref android.R.styleable#View_isScrollContainer
    612  * @attr ref android.R.styleable#View_focusable
    613  * @attr ref android.R.styleable#View_focusableInTouchMode
    614  * @attr ref android.R.styleable#View_hapticFeedbackEnabled
    615  * @attr ref android.R.styleable#View_keepScreenOn
    616  * @attr ref android.R.styleable#View_layerType
    617  * @attr ref android.R.styleable#View_longClickable
    618  * @attr ref android.R.styleable#View_minHeight
    619  * @attr ref android.R.styleable#View_minWidth
    620  * @attr ref android.R.styleable#View_nextFocusDown
    621  * @attr ref android.R.styleable#View_nextFocusLeft
    622  * @attr ref android.R.styleable#View_nextFocusRight
    623  * @attr ref android.R.styleable#View_nextFocusUp
    624  * @attr ref android.R.styleable#View_onClick
    625  * @attr ref android.R.styleable#View_padding
    626  * @attr ref android.R.styleable#View_paddingBottom
    627  * @attr ref android.R.styleable#View_paddingLeft
    628  * @attr ref android.R.styleable#View_paddingRight
    629  * @attr ref android.R.styleable#View_paddingTop
    630  * @attr ref android.R.styleable#View_saveEnabled
    631  * @attr ref android.R.styleable#View_rotation
    632  * @attr ref android.R.styleable#View_rotationX
    633  * @attr ref android.R.styleable#View_rotationY
    634  * @attr ref android.R.styleable#View_scaleX
    635  * @attr ref android.R.styleable#View_scaleY
    636  * @attr ref android.R.styleable#View_scrollX
    637  * @attr ref android.R.styleable#View_scrollY
    638  * @attr ref android.R.styleable#View_scrollbarSize
    639  * @attr ref android.R.styleable#View_scrollbarStyle
    640  * @attr ref android.R.styleable#View_scrollbars
    641  * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
    642  * @attr ref android.R.styleable#View_scrollbarFadeDuration
    643  * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
    644  * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
    645  * @attr ref android.R.styleable#View_scrollbarThumbVertical
    646  * @attr ref android.R.styleable#View_scrollbarTrackVertical
    647  * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
    648  * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
    649  * @attr ref android.R.styleable#View_soundEffectsEnabled
    650  * @attr ref android.R.styleable#View_tag
    651  * @attr ref android.R.styleable#View_transformPivotX
    652  * @attr ref android.R.styleable#View_transformPivotY
    653  * @attr ref android.R.styleable#View_translationX
    654  * @attr ref android.R.styleable#View_translationY
    655  * @attr ref android.R.styleable#View_visibility
    656  *
    657  * @see android.view.ViewGroup
    658  */
    659 public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
    660         AccessibilityEventSource {
    661     private static final boolean DBG = false;
    662 
    663     /**
    664      * The logging tag used by this class with android.util.Log.
    665      */
    666     protected static final String VIEW_LOG_TAG = "View";
    667 
    668     /**
    669      * When set to true, apps will draw debugging information about their layouts.
    670      *
    671      * @hide
    672      */
    673     public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
    674 
    675     /**
    676      * Used to mark a View that has no ID.
    677      */
    678     public static final int NO_ID = -1;
    679 
    680     /**
    681      * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
    682      * calling setFlags.
    683      */
    684     private static final int NOT_FOCUSABLE = 0x00000000;
    685 
    686     /**
    687      * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
    688      * setFlags.
    689      */
    690     private static final int FOCUSABLE = 0x00000001;
    691 
    692     /**
    693      * Mask for use with setFlags indicating bits used for focus.
    694      */
    695     private static final int FOCUSABLE_MASK = 0x00000001;
    696 
    697     /**
    698      * This view will adjust its padding to fit sytem windows (e.g. status bar)
    699      */
    700     private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
    701 
    702     /**
    703      * This view is visible.
    704      * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
    705      * android:visibility}.
    706      */
    707     public static final int VISIBLE = 0x00000000;
    708 
    709     /**
    710      * This view is invisible, but it still takes up space for layout purposes.
    711      * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
    712      * android:visibility}.
    713      */
    714     public static final int INVISIBLE = 0x00000004;
    715 
    716     /**
    717      * This view is invisible, and it doesn't take any space for layout
    718      * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
    719      * android:visibility}.
    720      */
    721     public static final int GONE = 0x00000008;
    722 
    723     /**
    724      * Mask for use with setFlags indicating bits used for visibility.
    725      * {@hide}
    726      */
    727     static final int VISIBILITY_MASK = 0x0000000C;
    728 
    729     private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
    730 
    731     /**
    732      * This view is enabled. Interpretation varies by subclass.
    733      * Use with ENABLED_MASK when calling setFlags.
    734      * {@hide}
    735      */
    736     static final int ENABLED = 0x00000000;
    737 
    738     /**
    739      * This view is disabled. Interpretation varies by subclass.
    740      * Use with ENABLED_MASK when calling setFlags.
    741      * {@hide}
    742      */
    743     static final int DISABLED = 0x00000020;
    744 
    745    /**
    746     * Mask for use with setFlags indicating bits used for indicating whether
    747     * this view is enabled
    748     * {@hide}
    749     */
    750     static final int ENABLED_MASK = 0x00000020;
    751 
    752     /**
    753      * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
    754      * called and further optimizations will be performed. It is okay to have
    755      * this flag set and a background. Use with DRAW_MASK when calling setFlags.
    756      * {@hide}
    757      */
    758     static final int WILL_NOT_DRAW = 0x00000080;
    759 
    760     /**
    761      * Mask for use with setFlags indicating bits used for indicating whether
    762      * this view is will draw
    763      * {@hide}
    764      */
    765     static final int DRAW_MASK = 0x00000080;
    766 
    767     /**
    768      * <p>This view doesn't show scrollbars.</p>
    769      * {@hide}
    770      */
    771     static final int SCROLLBARS_NONE = 0x00000000;
    772 
    773     /**
    774      * <p>This view shows horizontal scrollbars.</p>
    775      * {@hide}
    776      */
    777     static final int SCROLLBARS_HORIZONTAL = 0x00000100;
    778 
    779     /**
    780      * <p>This view shows vertical scrollbars.</p>
    781      * {@hide}
    782      */
    783     static final int SCROLLBARS_VERTICAL = 0x00000200;
    784 
    785     /**
    786      * <p>Mask for use with setFlags indicating bits used for indicating which
    787      * scrollbars are enabled.</p>
    788      * {@hide}
    789      */
    790     static final int SCROLLBARS_MASK = 0x00000300;
    791 
    792     /**
    793      * Indicates that the view should filter touches when its window is obscured.
    794      * Refer to the class comments for more information about this security feature.
    795      * {@hide}
    796      */
    797     static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
    798 
    799     /**
    800      * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
    801      * that they are optional and should be skipped if the window has
    802      * requested system UI flags that ignore those insets for layout.
    803      */
    804     static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
    805 
    806     /**
    807      * <p>This view doesn't show fading edges.</p>
    808      * {@hide}
    809      */
    810     static final int FADING_EDGE_NONE = 0x00000000;
    811 
    812     /**
    813      * <p>This view shows horizontal fading edges.</p>
    814      * {@hide}
    815      */
    816     static final int FADING_EDGE_HORIZONTAL = 0x00001000;
    817 
    818     /**
    819      * <p>This view shows vertical fading edges.</p>
    820      * {@hide}
    821      */
    822     static final int FADING_EDGE_VERTICAL = 0x00002000;
    823 
    824     /**
    825      * <p>Mask for use with setFlags indicating bits used for indicating which
    826      * fading edges are enabled.</p>
    827      * {@hide}
    828      */
    829     static final int FADING_EDGE_MASK = 0x00003000;
    830 
    831     /**
    832      * <p>Indicates this view can be clicked. When clickable, a View reacts
    833      * to clicks by notifying the OnClickListener.<p>
    834      * {@hide}
    835      */
    836     static final int CLICKABLE = 0x00004000;
    837 
    838     /**
    839      * <p>Indicates this view is caching its drawing into a bitmap.</p>
    840      * {@hide}
    841      */
    842     static final int DRAWING_CACHE_ENABLED = 0x00008000;
    843 
    844     /**
    845      * <p>Indicates that no icicle should be saved for this view.<p>
    846      * {@hide}
    847      */
    848     static final int SAVE_DISABLED = 0x000010000;
    849 
    850     /**
    851      * <p>Mask for use with setFlags indicating bits used for the saveEnabled
    852      * property.</p>
    853      * {@hide}
    854      */
    855     static final int SAVE_DISABLED_MASK = 0x000010000;
    856 
    857     /**
    858      * <p>Indicates that no drawing cache should ever be created for this view.<p>
    859      * {@hide}
    860      */
    861     static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
    862 
    863     /**
    864      * <p>Indicates this view can take / keep focus when int touch mode.</p>
    865      * {@hide}
    866      */
    867     static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
    868 
    869     /**
    870      * <p>Enables low quality mode for the drawing cache.</p>
    871      */
    872     public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
    873 
    874     /**
    875      * <p>Enables high quality mode for the drawing cache.</p>
    876      */
    877     public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
    878 
    879     /**
    880      * <p>Enables automatic quality mode for the drawing cache.</p>
    881      */
    882     public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
    883 
    884     private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
    885             DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
    886     };
    887 
    888     /**
    889      * <p>Mask for use with setFlags indicating bits used for the cache
    890      * quality property.</p>
    891      * {@hide}
    892      */
    893     static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
    894 
    895     /**
    896      * <p>
    897      * Indicates this view can be long clicked. When long clickable, a View
    898      * reacts to long clicks by notifying the OnLongClickListener or showing a
    899      * context menu.
    900      * </p>
    901      * {@hide}
    902      */
    903     static final int LONG_CLICKABLE = 0x00200000;
    904 
    905     /**
    906      * <p>Indicates that this view gets its drawable states from its direct parent
    907      * and ignores its original internal states.</p>
    908      *
    909      * @hide
    910      */
    911     static final int DUPLICATE_PARENT_STATE = 0x00400000;
    912 
    913     /**
    914      * The scrollbar style to display the scrollbars inside the content area,
    915      * without increasing the padding. The scrollbars will be overlaid with
    916      * translucency on the view's content.
    917      */
    918     public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
    919 
    920     /**
    921      * The scrollbar style to display the scrollbars inside the padded area,
    922      * increasing the padding of the view. The scrollbars will not overlap the
    923      * content area of the view.
    924      */
    925     public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
    926 
    927     /**
    928      * The scrollbar style to display the scrollbars at the edge of the view,
    929      * without increasing the padding. The scrollbars will be overlaid with
    930      * translucency.
    931      */
    932     public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
    933 
    934     /**
    935      * The scrollbar style to display the scrollbars at the edge of the view,
    936      * increasing the padding of the view. The scrollbars will only overlap the
    937      * background, if any.
    938      */
    939     public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
    940 
    941     /**
    942      * Mask to check if the scrollbar style is overlay or inset.
    943      * {@hide}
    944      */
    945     static final int SCROLLBARS_INSET_MASK = 0x01000000;
    946 
    947     /**
    948      * Mask to check if the scrollbar style is inside or outside.
    949      * {@hide}
    950      */
    951     static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
    952 
    953     /**
    954      * Mask for scrollbar style.
    955      * {@hide}
    956      */
    957     static final int SCROLLBARS_STYLE_MASK = 0x03000000;
    958 
    959     /**
    960      * View flag indicating that the screen should remain on while the
    961      * window containing this view is visible to the user.  This effectively
    962      * takes care of automatically setting the WindowManager's
    963      * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
    964      */
    965     public static final int KEEP_SCREEN_ON = 0x04000000;
    966 
    967     /**
    968      * View flag indicating whether this view should have sound effects enabled
    969      * for events such as clicking and touching.
    970      */
    971     public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
    972 
    973     /**
    974      * View flag indicating whether this view should have haptic feedback
    975      * enabled for events such as long presses.
    976      */
    977     public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
    978 
    979     /**
    980      * <p>Indicates that the view hierarchy should stop saving state when
    981      * it reaches this view.  If state saving is initiated immediately at
    982      * the view, it will be allowed.
    983      * {@hide}
    984      */
    985     static final int PARENT_SAVE_DISABLED = 0x20000000;
    986 
    987     /**
    988      * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
    989      * {@hide}
    990      */
    991     static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
    992 
    993     /**
    994      * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
    995      * should add all focusable Views regardless if they are focusable in touch mode.
    996      */
    997     public static final int FOCUSABLES_ALL = 0x00000000;
    998 
    999     /**
   1000      * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
   1001      * should add only Views focusable in touch mode.
   1002      */
   1003     public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
   1004 
   1005     /**
   1006      * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
   1007      * should add only accessibility focusable Views.
   1008      *
   1009      * @hide
   1010      */
   1011     public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
   1012 
   1013     /**
   1014      * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
   1015      * item.
   1016      */
   1017     public static final int FOCUS_BACKWARD = 0x00000001;
   1018 
   1019     /**
   1020      * Use with {@link #focusSearch(int)}. Move focus to the next selectable
   1021      * item.
   1022      */
   1023     public static final int FOCUS_FORWARD = 0x00000002;
   1024 
   1025     /**
   1026      * Use with {@link #focusSearch(int)}. Move focus to the left.
   1027      */
   1028     public static final int FOCUS_LEFT = 0x00000011;
   1029 
   1030     /**
   1031      * Use with {@link #focusSearch(int)}. Move focus up.
   1032      */
   1033     public static final int FOCUS_UP = 0x00000021;
   1034 
   1035     /**
   1036      * Use with {@link #focusSearch(int)}. Move focus to the right.
   1037      */
   1038     public static final int FOCUS_RIGHT = 0x00000042;
   1039 
   1040     /**
   1041      * Use with {@link #focusSearch(int)}. Move focus down.
   1042      */
   1043     public static final int FOCUS_DOWN = 0x00000082;
   1044 
   1045     // Accessibility focus directions.
   1046 
   1047     /**
   1048      * The accessibility focus which is the current user position when
   1049      * interacting with the accessibility framework.
   1050      *
   1051      * @hide
   1052      */
   1053     public static final int FOCUS_ACCESSIBILITY =  0x00001000;
   1054 
   1055     /**
   1056      * Use with {@link #focusSearch(int)}. Move acessibility focus left.
   1057      *
   1058      * @hide
   1059      */
   1060     public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
   1061 
   1062     /**
   1063      * Use with {@link #focusSearch(int)}. Move acessibility focus up.
   1064      *
   1065      * @hide
   1066      */
   1067     public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
   1068 
   1069     /**
   1070      * Use with {@link #focusSearch(int)}. Move acessibility focus right.
   1071      *
   1072      * @hide
   1073      */
   1074     public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
   1075 
   1076     /**
   1077      * Use with {@link #focusSearch(int)}. Move acessibility focus down.
   1078      *
   1079      * @hide
   1080      */
   1081     public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
   1082 
   1083     /**
   1084      * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
   1085      *
   1086      * @hide
   1087      */
   1088     public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
   1089 
   1090     /**
   1091      * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
   1092      *
   1093      * @hide
   1094      */
   1095     public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
   1096 
   1097     /**
   1098      * Bits of {@link #getMeasuredWidthAndState()} and
   1099      * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
   1100      */
   1101     public static final int MEASURED_SIZE_MASK = 0x00ffffff;
   1102 
   1103     /**
   1104      * Bits of {@link #getMeasuredWidthAndState()} and
   1105      * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
   1106      */
   1107     public static final int MEASURED_STATE_MASK = 0xff000000;
   1108 
   1109     /**
   1110      * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
   1111      * for functions that combine both width and height into a single int,
   1112      * such as {@link #getMeasuredState()} and the childState argument of
   1113      * {@link #resolveSizeAndState(int, int, int)}.
   1114      */
   1115     public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
   1116 
   1117     /**
   1118      * Bit of {@link #getMeasuredWidthAndState()} and
   1119      * {@link #getMeasuredWidthAndState()} that indicates the measured size
   1120      * is smaller that the space the view would like to have.
   1121      */
   1122     public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
   1123 
   1124     /**
   1125      * Base View state sets
   1126      */
   1127     // Singles
   1128     /**
   1129      * Indicates the view has no states set. States are used with
   1130      * {@link android.graphics.drawable.Drawable} to change the drawing of the
   1131      * view depending on its state.
   1132      *
   1133      * @see android.graphics.drawable.Drawable
   1134      * @see #getDrawableState()
   1135      */
   1136     protected static final int[] EMPTY_STATE_SET;
   1137     /**
   1138      * Indicates the view is enabled. States are used with
   1139      * {@link android.graphics.drawable.Drawable} to change the drawing of the
   1140      * view depending on its state.
   1141      *
   1142      * @see android.graphics.drawable.Drawable
   1143      * @see #getDrawableState()
   1144      */
   1145     protected static final int[] ENABLED_STATE_SET;
   1146     /**
   1147      * Indicates the view is focused. States are used with
   1148      * {@link android.graphics.drawable.Drawable} to change the drawing of the
   1149      * view depending on its state.
   1150      *
   1151      * @see android.graphics.drawable.Drawable
   1152      * @see #getDrawableState()
   1153      */
   1154     protected static final int[] FOCUSED_STATE_SET;
   1155     /**
   1156      * Indicates the view is selected. States are used with
   1157      * {@link android.graphics.drawable.Drawable} to change the drawing of the
   1158      * view depending on its state.
   1159      *
   1160      * @see android.graphics.drawable.Drawable
   1161      * @see #getDrawableState()
   1162      */
   1163     protected static final int[] SELECTED_STATE_SET;
   1164     /**
   1165      * Indicates the view is pressed. States are used with
   1166      * {@link android.graphics.drawable.Drawable} to change the drawing of the
   1167      * view depending on its state.
   1168      *
   1169      * @see android.graphics.drawable.Drawable
   1170      * @see #getDrawableState()
   1171      * @hide
   1172      */
   1173     protected static final int[] PRESSED_STATE_SET;
   1174     /**
   1175      * Indicates the view's window has focus. States are used with
   1176      * {@link android.graphics.drawable.Drawable} to change the drawing of the
   1177      * view depending on its state.
   1178      *
   1179      * @see android.graphics.drawable.Drawable
   1180      * @see #getDrawableState()
   1181      */
   1182     protected static final int[] WINDOW_FOCUSED_STATE_SET;
   1183     // Doubles
   1184     /**
   1185      * Indicates the view is enabled and has the focus.
   1186      *
   1187      * @see #ENABLED_STATE_SET
   1188      * @see #FOCUSED_STATE_SET
   1189      */
   1190     protected static final int[] ENABLED_FOCUSED_STATE_SET;
   1191     /**
   1192      * Indicates the view is enabled and selected.
   1193      *
   1194      * @see #ENABLED_STATE_SET
   1195      * @see #SELECTED_STATE_SET
   1196      */
   1197     protected static final int[] ENABLED_SELECTED_STATE_SET;
   1198     /**
   1199      * Indicates the view is enabled and that its window has focus.
   1200      *
   1201      * @see #ENABLED_STATE_SET
   1202      * @see #WINDOW_FOCUSED_STATE_SET
   1203      */
   1204     protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
   1205     /**
   1206      * Indicates the view is focused and selected.
   1207      *
   1208      * @see #FOCUSED_STATE_SET
   1209      * @see #SELECTED_STATE_SET
   1210      */
   1211     protected static final int[] FOCUSED_SELECTED_STATE_SET;
   1212     /**
   1213      * Indicates the view has the focus and that its window has the focus.
   1214      *
   1215      * @see #FOCUSED_STATE_SET
   1216      * @see #WINDOW_FOCUSED_STATE_SET
   1217      */
   1218     protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
   1219     /**
   1220      * Indicates the view is selected and that its window has the focus.
   1221      *
   1222      * @see #SELECTED_STATE_SET
   1223      * @see #WINDOW_FOCUSED_STATE_SET
   1224      */
   1225     protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
   1226     // Triples
   1227     /**
   1228      * Indicates the view is enabled, focused and selected.
   1229      *
   1230      * @see #ENABLED_STATE_SET
   1231      * @see #FOCUSED_STATE_SET
   1232      * @see #SELECTED_STATE_SET
   1233      */
   1234     protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
   1235     /**
   1236      * Indicates the view is enabled, focused and its window has the focus.
   1237      *
   1238      * @see #ENABLED_STATE_SET
   1239      * @see #FOCUSED_STATE_SET
   1240      * @see #WINDOW_FOCUSED_STATE_SET
   1241      */
   1242     protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
   1243     /**
   1244      * Indicates the view is enabled, selected and its window has the focus.
   1245      *
   1246      * @see #ENABLED_STATE_SET
   1247      * @see #SELECTED_STATE_SET
   1248      * @see #WINDOW_FOCUSED_STATE_SET
   1249      */
   1250     protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
   1251     /**
   1252      * Indicates the view is focused, selected and its window has the focus.
   1253      *
   1254      * @see #FOCUSED_STATE_SET
   1255      * @see #SELECTED_STATE_SET
   1256      * @see #WINDOW_FOCUSED_STATE_SET
   1257      */
   1258     protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
   1259     /**
   1260      * Indicates the view is enabled, focused, selected and its window
   1261      * has the focus.
   1262      *
   1263      * @see #ENABLED_STATE_SET
   1264      * @see #FOCUSED_STATE_SET
   1265      * @see #SELECTED_STATE_SET
   1266      * @see #WINDOW_FOCUSED_STATE_SET
   1267      */
   1268     protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
   1269     /**
   1270      * Indicates the view is pressed and its window has the focus.
   1271      *
   1272      * @see #PRESSED_STATE_SET
   1273      * @see #WINDOW_FOCUSED_STATE_SET
   1274      */
   1275     protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
   1276     /**
   1277      * Indicates the view is pressed and selected.
   1278      *
   1279      * @see #PRESSED_STATE_SET
   1280      * @see #SELECTED_STATE_SET
   1281      */
   1282     protected static final int[] PRESSED_SELECTED_STATE_SET;
   1283     /**
   1284      * Indicates the view is pressed, selected and its window has the focus.
   1285      *
   1286      * @see #PRESSED_STATE_SET
   1287      * @see #SELECTED_STATE_SET
   1288      * @see #WINDOW_FOCUSED_STATE_SET
   1289      */
   1290     protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
   1291     /**
   1292      * Indicates the view is pressed and focused.
   1293      *
   1294      * @see #PRESSED_STATE_SET
   1295      * @see #FOCUSED_STATE_SET
   1296      */
   1297     protected static final int[] PRESSED_FOCUSED_STATE_SET;
   1298     /**
   1299      * Indicates the view is pressed, focused and its window has the focus.
   1300      *
   1301      * @see #PRESSED_STATE_SET
   1302      * @see #FOCUSED_STATE_SET
   1303      * @see #WINDOW_FOCUSED_STATE_SET
   1304      */
   1305     protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
   1306     /**
   1307      * Indicates the view is pressed, focused and selected.
   1308      *
   1309      * @see #PRESSED_STATE_SET
   1310      * @see #SELECTED_STATE_SET
   1311      * @see #FOCUSED_STATE_SET
   1312      */
   1313     protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
   1314     /**
   1315      * Indicates the view is pressed, focused, selected and its window has the focus.
   1316      *
   1317      * @see #PRESSED_STATE_SET
   1318      * @see #FOCUSED_STATE_SET
   1319      * @see #SELECTED_STATE_SET
   1320      * @see #WINDOW_FOCUSED_STATE_SET
   1321      */
   1322     protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
   1323     /**
   1324      * Indicates the view is pressed and enabled.
   1325      *
   1326      * @see #PRESSED_STATE_SET
   1327      * @see #ENABLED_STATE_SET
   1328      */
   1329     protected static final int[] PRESSED_ENABLED_STATE_SET;
   1330     /**
   1331      * Indicates the view is pressed, enabled and its window has the focus.
   1332      *
   1333      * @see #PRESSED_STATE_SET
   1334      * @see #ENABLED_STATE_SET
   1335      * @see #WINDOW_FOCUSED_STATE_SET
   1336      */
   1337     protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
   1338     /**
   1339      * Indicates the view is pressed, enabled and selected.
   1340      *
   1341      * @see #PRESSED_STATE_SET
   1342      * @see #ENABLED_STATE_SET
   1343      * @see #SELECTED_STATE_SET
   1344      */
   1345     protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
   1346     /**
   1347      * Indicates the view is pressed, enabled, selected and its window has the
   1348      * focus.
   1349      *
   1350      * @see #PRESSED_STATE_SET
   1351      * @see #ENABLED_STATE_SET
   1352      * @see #SELECTED_STATE_SET
   1353      * @see #WINDOW_FOCUSED_STATE_SET
   1354      */
   1355     protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
   1356     /**
   1357      * Indicates the view is pressed, enabled and focused.
   1358      *
   1359      * @see #PRESSED_STATE_SET
   1360      * @see #ENABLED_STATE_SET
   1361      * @see #FOCUSED_STATE_SET
   1362      */
   1363     protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
   1364     /**
   1365      * Indicates the view is pressed, enabled, focused and its window has the
   1366      * focus.
   1367      *
   1368      * @see #PRESSED_STATE_SET
   1369      * @see #ENABLED_STATE_SET
   1370      * @see #FOCUSED_STATE_SET
   1371      * @see #WINDOW_FOCUSED_STATE_SET
   1372      */
   1373     protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
   1374     /**
   1375      * Indicates the view is pressed, enabled, focused and selected.
   1376      *
   1377      * @see #PRESSED_STATE_SET
   1378      * @see #ENABLED_STATE_SET
   1379      * @see #SELECTED_STATE_SET
   1380      * @see #FOCUSED_STATE_SET
   1381      */
   1382     protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
   1383     /**
   1384      * Indicates the view is pressed, enabled, focused, selected and its window
   1385      * has the focus.
   1386      *
   1387      * @see #PRESSED_STATE_SET
   1388      * @see #ENABLED_STATE_SET
   1389      * @see #SELECTED_STATE_SET
   1390      * @see #FOCUSED_STATE_SET
   1391      * @see #WINDOW_FOCUSED_STATE_SET
   1392      */
   1393     protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
   1394 
   1395     /**
   1396      * The order here is very important to {@link #getDrawableState()}
   1397      */
   1398     private static final int[][] VIEW_STATE_SETS;
   1399 
   1400     static final int VIEW_STATE_WINDOW_FOCUSED = 1;
   1401     static final int VIEW_STATE_SELECTED = 1 << 1;
   1402     static final int VIEW_STATE_FOCUSED = 1 << 2;
   1403     static final int VIEW_STATE_ENABLED = 1 << 3;
   1404     static final int VIEW_STATE_PRESSED = 1 << 4;
   1405     static final int VIEW_STATE_ACTIVATED = 1 << 5;
   1406     static final int VIEW_STATE_ACCELERATED = 1 << 6;
   1407     static final int VIEW_STATE_HOVERED = 1 << 7;
   1408     static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
   1409     static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
   1410 
   1411     static final int[] VIEW_STATE_IDS = new int[] {
   1412         R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
   1413         R.attr.state_selected,          VIEW_STATE_SELECTED,
   1414         R.attr.state_focused,           VIEW_STATE_FOCUSED,
   1415         R.attr.state_enabled,           VIEW_STATE_ENABLED,
   1416         R.attr.state_pressed,           VIEW_STATE_PRESSED,
   1417         R.attr.state_activated,         VIEW_STATE_ACTIVATED,
   1418         R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
   1419         R.attr.state_hovered,           VIEW_STATE_HOVERED,
   1420         R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
   1421         R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
   1422     };
   1423 
   1424     static {
   1425         if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
   1426             throw new IllegalStateException(
   1427                     "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
   1428         }
   1429         int[] orderedIds = new int[VIEW_STATE_IDS.length];
   1430         for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
   1431             int viewState = R.styleable.ViewDrawableStates[i];
   1432             for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
   1433                 if (VIEW_STATE_IDS[j] == viewState) {
   1434                     orderedIds[i * 2] = viewState;
   1435                     orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
   1436                 }
   1437             }
   1438         }
   1439         final int NUM_BITS = VIEW_STATE_IDS.length / 2;
   1440         VIEW_STATE_SETS = new int[1 << NUM_BITS][];
   1441         for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
   1442             int numBits = Integer.bitCount(i);
   1443             int[] set = new int[numBits];
   1444             int pos = 0;
   1445             for (int j = 0; j < orderedIds.length; j += 2) {
   1446                 if ((i & orderedIds[j+1]) != 0) {
   1447                     set[pos++] = orderedIds[j];
   1448                 }
   1449             }
   1450             VIEW_STATE_SETS[i] = set;
   1451         }
   1452 
   1453         EMPTY_STATE_SET = VIEW_STATE_SETS[0];
   1454         WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
   1455         SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
   1456         SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1457                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
   1458         FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
   1459         FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1460                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
   1461         FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
   1462                 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
   1463         FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1464                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
   1465                 | VIEW_STATE_FOCUSED];
   1466         ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
   1467         ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1468                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
   1469         ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
   1470                 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
   1471         ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1472                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
   1473                 | VIEW_STATE_ENABLED];
   1474         ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1475                 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
   1476         ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1477                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
   1478                 | VIEW_STATE_ENABLED];
   1479         ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
   1480                 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
   1481                 | VIEW_STATE_ENABLED];
   1482         ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1483                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
   1484                 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
   1485 
   1486         PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
   1487         PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1488                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
   1489         PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
   1490                 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
   1491         PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1492                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
   1493                 | VIEW_STATE_PRESSED];
   1494         PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1495                 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
   1496         PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1497                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
   1498                 | VIEW_STATE_PRESSED];
   1499         PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
   1500                 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
   1501                 | VIEW_STATE_PRESSED];
   1502         PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1503                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
   1504                 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
   1505         PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
   1506                 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
   1507         PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1508                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
   1509                 | VIEW_STATE_PRESSED];
   1510         PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
   1511                 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
   1512                 | VIEW_STATE_PRESSED];
   1513         PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1514                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
   1515                 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
   1516         PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1517                 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
   1518                 | VIEW_STATE_PRESSED];
   1519         PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1520                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
   1521                 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
   1522         PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
   1523                 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
   1524                 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
   1525         PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
   1526                 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
   1527                 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
   1528                 | VIEW_STATE_PRESSED];
   1529     }
   1530 
   1531     /**
   1532      * Accessibility event types that are dispatched for text population.
   1533      */
   1534     private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
   1535             AccessibilityEvent.TYPE_VIEW_CLICKED
   1536             | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
   1537             | AccessibilityEvent.TYPE_VIEW_SELECTED
   1538             | AccessibilityEvent.TYPE_VIEW_FOCUSED
   1539             | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
   1540             | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
   1541             | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
   1542             | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
   1543             | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
   1544             | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
   1545             | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
   1546 
   1547     /**
   1548      * Temporary Rect currently for use in setBackground().  This will probably
   1549      * be extended in the future to hold our own class with more than just
   1550      * a Rect. :)
   1551      */
   1552     static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
   1553 
   1554     /**
   1555      * Map used to store views' tags.
   1556      */
   1557     private SparseArray<Object> mKeyedTags;
   1558 
   1559     /**
   1560      * The next available accessiiblity id.
   1561      */
   1562     private static int sNextAccessibilityViewId;
   1563 
   1564     /**
   1565      * The animation currently associated with this view.
   1566      * @hide
   1567      */
   1568     protected Animation mCurrentAnimation = null;
   1569 
   1570     /**
   1571      * Width as measured during measure pass.
   1572      * {@hide}
   1573      */
   1574     @ViewDebug.ExportedProperty(category = "measurement")
   1575     int mMeasuredWidth;
   1576 
   1577     /**
   1578      * Height as measured during measure pass.
   1579      * {@hide}
   1580      */
   1581     @ViewDebug.ExportedProperty(category = "measurement")
   1582     int mMeasuredHeight;
   1583 
   1584     /**
   1585      * Flag to indicate that this view was marked INVALIDATED, or had its display list
   1586      * invalidated, prior to the current drawing iteration. If true, the view must re-draw
   1587      * its display list. This flag, used only when hw accelerated, allows us to clear the
   1588      * flag while retaining this information until it's needed (at getDisplayList() time and
   1589      * in drawChild(), when we decide to draw a view's children's display lists into our own).
   1590      *
   1591      * {@hide}
   1592      */
   1593     boolean mRecreateDisplayList = false;
   1594 
   1595     /**
   1596      * The view's identifier.
   1597      * {@hide}
   1598      *
   1599      * @see #setId(int)
   1600      * @see #getId()
   1601      */
   1602     @ViewDebug.ExportedProperty(resolveId = true)
   1603     int mID = NO_ID;
   1604 
   1605     /**
   1606      * The stable ID of this view for accessibility purposes.
   1607      */
   1608     int mAccessibilityViewId = NO_ID;
   1609 
   1610     /**
   1611      * @hide
   1612      */
   1613     private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
   1614 
   1615     /**
   1616      * The view's tag.
   1617      * {@hide}
   1618      *
   1619      * @see #setTag(Object)
   1620      * @see #getTag()
   1621      */
   1622     protected Object mTag;
   1623 
   1624     // for mPrivateFlags:
   1625     /** {@hide} */
   1626     static final int WANTS_FOCUS                    = 0x00000001;
   1627     /** {@hide} */
   1628     static final int FOCUSED                        = 0x00000002;
   1629     /** {@hide} */
   1630     static final int SELECTED                       = 0x00000004;
   1631     /** {@hide} */
   1632     static final int IS_ROOT_NAMESPACE              = 0x00000008;
   1633     /** {@hide} */
   1634     static final int HAS_BOUNDS                     = 0x00000010;
   1635     /** {@hide} */
   1636     static final int DRAWN                          = 0x00000020;
   1637     /**
   1638      * When this flag is set, this view is running an animation on behalf of its
   1639      * children and should therefore not cancel invalidate requests, even if they
   1640      * lie outside of this view's bounds.
   1641      *
   1642      * {@hide}
   1643      */
   1644     static final int DRAW_ANIMATION                 = 0x00000040;
   1645     /** {@hide} */
   1646     static final int SKIP_DRAW                      = 0x00000080;
   1647     /** {@hide} */
   1648     static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
   1649     /** {@hide} */
   1650     static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
   1651     /** {@hide} */
   1652     static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
   1653     /** {@hide} */
   1654     static final int MEASURED_DIMENSION_SET         = 0x00000800;
   1655     /** {@hide} */
   1656     static final int FORCE_LAYOUT                   = 0x00001000;
   1657     /** {@hide} */
   1658     static final int LAYOUT_REQUIRED                = 0x00002000;
   1659 
   1660     private static final int PRESSED                = 0x00004000;
   1661 
   1662     /** {@hide} */
   1663     static final int DRAWING_CACHE_VALID            = 0x00008000;
   1664     /**
   1665      * Flag used to indicate that this view should be drawn once more (and only once
   1666      * more) after its animation has completed.
   1667      * {@hide}
   1668      */
   1669     static final int ANIMATION_STARTED              = 0x00010000;
   1670 
   1671     private static final int SAVE_STATE_CALLED      = 0x00020000;
   1672 
   1673     /**
   1674      * Indicates that the View returned true when onSetAlpha() was called and that
   1675      * the alpha must be restored.
   1676      * {@hide}
   1677      */
   1678     static final int ALPHA_SET                      = 0x00040000;
   1679 
   1680     /**
   1681      * Set by {@link #setScrollContainer(boolean)}.
   1682      */
   1683     static final int SCROLL_CONTAINER               = 0x00080000;
   1684 
   1685     /**
   1686      * Set by {@link #setScrollContainer(boolean)}.
   1687      */
   1688     static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
   1689 
   1690     /**
   1691      * View flag indicating whether this view was invalidated (fully or partially.)
   1692      *
   1693      * @hide
   1694      */
   1695     static final int DIRTY                          = 0x00200000;
   1696 
   1697     /**
   1698      * View flag indicating whether this view was invalidated by an opaque
   1699      * invalidate request.
   1700      *
   1701      * @hide
   1702      */
   1703     static final int DIRTY_OPAQUE                   = 0x00400000;
   1704 
   1705     /**
   1706      * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
   1707      *
   1708      * @hide
   1709      */
   1710     static final int DIRTY_MASK                     = 0x00600000;
   1711 
   1712     /**
   1713      * Indicates whether the background is opaque.
   1714      *
   1715      * @hide
   1716      */
   1717     static final int OPAQUE_BACKGROUND              = 0x00800000;
   1718 
   1719     /**
   1720      * Indicates whether the scrollbars are opaque.
   1721      *
   1722      * @hide
   1723      */
   1724     static final int OPAQUE_SCROLLBARS              = 0x01000000;
   1725 
   1726     /**
   1727      * Indicates whether the view is opaque.
   1728      *
   1729      * @hide
   1730      */
   1731     static final int OPAQUE_MASK                    = 0x01800000;
   1732 
   1733     /**
   1734      * Indicates a prepressed state;
   1735      * the short time between ACTION_DOWN and recognizing
   1736      * a 'real' press. Prepressed is used to recognize quick taps
   1737      * even when they are shorter than ViewConfiguration.getTapTimeout().
   1738      *
   1739      * @hide
   1740      */
   1741     private static final int PREPRESSED             = 0x02000000;
   1742 
   1743     /**
   1744      * Indicates whether the view is temporarily detached.
   1745      *
   1746      * @hide
   1747      */
   1748     static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
   1749 
   1750     /**
   1751      * Indicates that we should awaken scroll bars once attached
   1752      *
   1753      * @hide
   1754      */
   1755     private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
   1756 
   1757     /**
   1758      * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
   1759      * @hide
   1760      */
   1761     private static final int HOVERED              = 0x10000000;
   1762 
   1763     /**
   1764      * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
   1765      * for transform operations
   1766      *
   1767      * @hide
   1768      */
   1769     private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
   1770 
   1771     /** {@hide} */
   1772     static final int ACTIVATED                    = 0x40000000;
   1773 
   1774     /**
   1775      * Indicates that this view was specifically invalidated, not just dirtied because some
   1776      * child view was invalidated. The flag is used to determine when we need to recreate
   1777      * a view's display list (as opposed to just returning a reference to its existing
   1778      * display list).
   1779      *
   1780      * @hide
   1781      */
   1782     static final int INVALIDATED                  = 0x80000000;
   1783 
   1784     /* Masks for mPrivateFlags2 */
   1785 
   1786     /**
   1787      * Indicates that this view has reported that it can accept the current drag's content.
   1788      * Cleared when the drag operation concludes.
   1789      * @hide
   1790      */
   1791     static final int DRAG_CAN_ACCEPT              = 0x00000001;
   1792 
   1793     /**
   1794      * Indicates that this view is currently directly under the drag location in a
   1795      * drag-and-drop operation involving content that it can accept.  Cleared when
   1796      * the drag exits the view, or when the drag operation concludes.
   1797      * @hide
   1798      */
   1799     static final int DRAG_HOVERED                 = 0x00000002;
   1800 
   1801     /**
   1802      * Horizontal layout direction of this view is from Left to Right.
   1803      * Use with {@link #setLayoutDirection}.
   1804      * @hide
   1805      */
   1806     public static final int LAYOUT_DIRECTION_LTR = 0;
   1807 
   1808     /**
   1809      * Horizontal layout direction of this view is from Right to Left.
   1810      * Use with {@link #setLayoutDirection}.
   1811      * @hide
   1812      */
   1813     public static final int LAYOUT_DIRECTION_RTL = 1;
   1814 
   1815     /**
   1816      * Horizontal layout direction of this view is inherited from its parent.
   1817      * Use with {@link #setLayoutDirection}.
   1818      * @hide
   1819      */
   1820     public static final int LAYOUT_DIRECTION_INHERIT = 2;
   1821 
   1822     /**
   1823      * Horizontal layout direction of this view is from deduced from the default language
   1824      * script for the locale. Use with {@link #setLayoutDirection}.
   1825      * @hide
   1826      */
   1827     public static final int LAYOUT_DIRECTION_LOCALE = 3;
   1828 
   1829     /**
   1830      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
   1831      * @hide
   1832      */
   1833     static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
   1834 
   1835     /**
   1836      * Mask for use with private flags indicating bits used for horizontal layout direction.
   1837      * @hide
   1838      */
   1839     static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
   1840 
   1841     /**
   1842      * Indicates whether the view horizontal layout direction has been resolved and drawn to the
   1843      * right-to-left direction.
   1844      * @hide
   1845      */
   1846     static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
   1847 
   1848     /**
   1849      * Indicates whether the view horizontal layout direction has been resolved.
   1850      * @hide
   1851      */
   1852     static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
   1853 
   1854     /**
   1855      * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
   1856      * @hide
   1857      */
   1858     static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
   1859 
   1860     /*
   1861      * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
   1862      * flag value.
   1863      * @hide
   1864      */
   1865     private static final int[] LAYOUT_DIRECTION_FLAGS = {
   1866             LAYOUT_DIRECTION_LTR,
   1867             LAYOUT_DIRECTION_RTL,
   1868             LAYOUT_DIRECTION_INHERIT,
   1869             LAYOUT_DIRECTION_LOCALE
   1870     };
   1871 
   1872     /**
   1873      * Default horizontal layout direction.
   1874      * @hide
   1875      */
   1876     private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
   1877 
   1878     /**
   1879      * Indicates that the view is tracking some sort of transient state
   1880      * that the app should not need to be aware of, but that the framework
   1881      * should take special care to preserve.
   1882      *
   1883      * @hide
   1884      */
   1885     static final int HAS_TRANSIENT_STATE = 0x00000100;
   1886 
   1887 
   1888     /**
   1889      * Text direction is inherited thru {@link ViewGroup}
   1890      * @hide
   1891      */
   1892     public static final int TEXT_DIRECTION_INHERIT = 0;
   1893 
   1894     /**
   1895      * Text direction is using "first strong algorithm". The first strong directional character
   1896      * determines the paragraph direction. If there is no strong directional character, the
   1897      * paragraph direction is the view's resolved layout direction.
   1898      * @hide
   1899      */
   1900     public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
   1901 
   1902     /**
   1903      * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
   1904      * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
   1905      * If there are neither, the paragraph direction is the view's resolved layout direction.
   1906      * @hide
   1907      */
   1908     public static final int TEXT_DIRECTION_ANY_RTL = 2;
   1909 
   1910     /**
   1911      * Text direction is forced to LTR.
   1912      * @hide
   1913      */
   1914     public static final int TEXT_DIRECTION_LTR = 3;
   1915 
   1916     /**
   1917      * Text direction is forced to RTL.
   1918      * @hide
   1919      */
   1920     public static final int TEXT_DIRECTION_RTL = 4;
   1921 
   1922     /**
   1923      * Text direction is coming from the system Locale.
   1924      * @hide
   1925      */
   1926     public static final int TEXT_DIRECTION_LOCALE = 5;
   1927 
   1928     /**
   1929      * Default text direction is inherited
   1930      * @hide
   1931      */
   1932     protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
   1933 
   1934     /**
   1935      * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
   1936      * @hide
   1937      */
   1938     static final int TEXT_DIRECTION_MASK_SHIFT = 6;
   1939 
   1940     /**
   1941      * Mask for use with private flags indicating bits used for text direction.
   1942      * @hide
   1943      */
   1944     static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
   1945 
   1946     /**
   1947      * Array of text direction flags for mapping attribute "textDirection" to correct
   1948      * flag value.
   1949      * @hide
   1950      */
   1951     private static final int[] TEXT_DIRECTION_FLAGS = {
   1952             TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
   1953             TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
   1954             TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
   1955             TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
   1956             TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
   1957             TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
   1958     };
   1959 
   1960     /**
   1961      * Indicates whether the view text direction has been resolved.
   1962      * @hide
   1963      */
   1964     static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
   1965 
   1966     /**
   1967      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
   1968      * @hide
   1969      */
   1970     static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
   1971 
   1972     /**
   1973      * Mask for use with private flags indicating bits used for resolved text direction.
   1974      * @hide
   1975      */
   1976     static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
   1977 
   1978     /**
   1979      * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
   1980      * @hide
   1981      */
   1982     static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
   1983             TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
   1984 
   1985     /*
   1986      * Default text alignment. The text alignment of this View is inherited from its parent.
   1987      * Use with {@link #setTextAlignment(int)}
   1988      * @hide
   1989      */
   1990     public static final int TEXT_ALIGNMENT_INHERIT = 0;
   1991 
   1992     /**
   1993      * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
   1994      * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraphs text direction.
   1995      *
   1996      * Use with {@link #setTextAlignment(int)}
   1997      * @hide
   1998      */
   1999     public static final int TEXT_ALIGNMENT_GRAVITY = 1;
   2000 
   2001     /**
   2002      * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
   2003      *
   2004      * Use with {@link #setTextAlignment(int)}
   2005      * @hide
   2006      */
   2007     public static final int TEXT_ALIGNMENT_TEXT_START = 2;
   2008 
   2009     /**
   2010      * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
   2011      *
   2012      * Use with {@link #setTextAlignment(int)}
   2013      * @hide
   2014      */
   2015     public static final int TEXT_ALIGNMENT_TEXT_END = 3;
   2016 
   2017     /**
   2018      * Center the paragraph, e.g. ALIGN_CENTER.
   2019      *
   2020      * Use with {@link #setTextAlignment(int)}
   2021      * @hide
   2022      */
   2023     public static final int TEXT_ALIGNMENT_CENTER = 4;
   2024 
   2025     /**
   2026      * Align to the start of the view, which is ALIGN_LEFT if the views resolved
   2027      * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
   2028      *
   2029      * Use with {@link #setTextAlignment(int)}
   2030      * @hide
   2031      */
   2032     public static final int TEXT_ALIGNMENT_VIEW_START = 5;
   2033 
   2034     /**
   2035      * Align to the end of the view, which is ALIGN_RIGHT if the views resolved
   2036      * layoutDirection is LTR, and ALIGN_LEFT otherwise.
   2037      *
   2038      * Use with {@link #setTextAlignment(int)}
   2039      * @hide
   2040      */
   2041     public static final int TEXT_ALIGNMENT_VIEW_END = 6;
   2042 
   2043     /**
   2044      * Default text alignment is inherited
   2045      * @hide
   2046      */
   2047     protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
   2048 
   2049     /**
   2050       * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
   2051       * @hide
   2052       */
   2053     static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
   2054 
   2055     /**
   2056       * Mask for use with private flags indicating bits used for text alignment.
   2057       * @hide
   2058       */
   2059     static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
   2060 
   2061     /**
   2062      * Array of text direction flags for mapping attribute "textAlignment" to correct
   2063      * flag value.
   2064      * @hide
   2065      */
   2066     private static final int[] TEXT_ALIGNMENT_FLAGS = {
   2067             TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
   2068             TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
   2069             TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
   2070             TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
   2071             TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
   2072             TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
   2073             TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
   2074     };
   2075 
   2076     /**
   2077      * Indicates whether the view text alignment has been resolved.
   2078      * @hide
   2079      */
   2080     static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
   2081 
   2082     /**
   2083      * Bit shift to get the resolved text alignment.
   2084      * @hide
   2085      */
   2086     static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
   2087 
   2088     /**
   2089      * Mask for use with private flags indicating bits used for text alignment.
   2090      * @hide
   2091      */
   2092     static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
   2093 
   2094     /**
   2095      * Indicates whether if the view text alignment has been resolved to gravity
   2096      */
   2097     public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
   2098             TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
   2099 
   2100     // Accessiblity constants for mPrivateFlags2
   2101 
   2102     /**
   2103      * Shift for the bits in {@link #mPrivateFlags2} related to the
   2104      * "importantForAccessibility" attribute.
   2105      */
   2106     static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
   2107 
   2108     /**
   2109      * Automatically determine whether a view is important for accessibility.
   2110      */
   2111     public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
   2112 
   2113     /**
   2114      * The view is important for accessibility.
   2115      */
   2116     public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
   2117 
   2118     /**
   2119      * The view is not important for accessibility.
   2120      */
   2121     public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
   2122 
   2123     /**
   2124      * The default whether the view is important for accessiblity.
   2125      */
   2126     static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
   2127 
   2128     /**
   2129      * Mask for obtainig the bits which specify how to determine
   2130      * whether a view is important for accessibility.
   2131      */
   2132     static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
   2133         | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
   2134         << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
   2135 
   2136     /**
   2137      * Flag indicating whether a view has accessibility focus.
   2138      */
   2139     static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
   2140 
   2141     /**
   2142      * Flag indicating whether a view state for accessibility has changed.
   2143      */
   2144     static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
   2145 
   2146     /**
   2147      * Flag indicating whether a view failed the quickReject() check in draw(). This condition
   2148      * is used to check whether later changes to the view's transform should invalidate the
   2149      * view to force the quickReject test to run again.
   2150      */
   2151     static final int VIEW_QUICK_REJECTED = 0x10000000;
   2152 
   2153     // Accessiblity constants for mPrivateFlags2
   2154 
   2155     /**
   2156      * Shift for the bits in {@link #mPrivateFlags2} related to the
   2157      * "accessibilityFocusable" attribute.
   2158      */
   2159     static final int ACCESSIBILITY_FOCUSABLE_SHIFT = 29;
   2160 
   2161     /**
   2162      * The system determines whether the view can take accessibility focus - default (recommended).
   2163      * <p>
   2164      * Such a view is consideted by the focus search if it is:
   2165      * <ul>
   2166      * <li>
   2167      * Important for accessibility and actionable (clickable, long clickable, focusable)
   2168      * </li>
   2169      * <li>
   2170      * Important for accessibility, not actionable (clickable, long clickable, focusable),
   2171      * and does not have an actionable predecessor.
   2172      * </li>
   2173      * </ul>
   2174      * An accessibility srvice can request putting accessibility focus on such a view.
   2175      * </p>
   2176      *
   2177      * @hide
   2178      */
   2179     public static final int ACCESSIBILITY_FOCUSABLE_AUTO = 0x00000000;
   2180 
   2181     /**
   2182      * The view can take accessibility focus.
   2183      * <p>
   2184      * A view that can take accessibility focus is always considered during focus
   2185      * search and an accessibility service can request putting accessibility focus
   2186      * on it.
   2187      * </p>
   2188      *
   2189      * @hide
   2190      */
   2191     public static final int ACCESSIBILITY_FOCUSABLE_YES = 0x00000001;
   2192 
   2193     /**
   2194      * The view can not take accessibility focus.
   2195      * <p>
   2196      * A view that can not take accessibility focus is never considered during focus
   2197      * search and an accessibility service can not request putting accessibility focus
   2198      * on it.
   2199      * </p>
   2200      *
   2201      * @hide
   2202      */
   2203     public static final int ACCESSIBILITY_FOCUSABLE_NO = 0x00000002;
   2204 
   2205     /**
   2206      * The default whether the view is accessiblity focusable.
   2207      */
   2208     static final int ACCESSIBILITY_FOCUSABLE_DEFAULT = ACCESSIBILITY_FOCUSABLE_AUTO;
   2209 
   2210     /**
   2211      * Mask for obtainig the bits which specifies how to determine
   2212      * whether a view is accessibility focusable.
   2213      */
   2214     static final int ACCESSIBILITY_FOCUSABLE_MASK = (ACCESSIBILITY_FOCUSABLE_AUTO
   2215         | ACCESSIBILITY_FOCUSABLE_YES | ACCESSIBILITY_FOCUSABLE_NO)
   2216         << ACCESSIBILITY_FOCUSABLE_SHIFT;
   2217 
   2218 
   2219     /* End of masks for mPrivateFlags2 */
   2220 
   2221     /* Masks for mPrivateFlags3 */
   2222 
   2223     /**
   2224      * Flag indicating that view has a transform animation set on it. This is used to track whether
   2225      * an animation is cleared between successive frames, in order to tell the associated
   2226      * DisplayList to clear its animation matrix.
   2227      */
   2228     static final int VIEW_IS_ANIMATING_TRANSFORM = 0x1;
   2229 
   2230     /**
   2231      * Flag indicating that view has an alpha animation set on it. This is used to track whether an
   2232      * animation is cleared between successive frames, in order to tell the associated
   2233      * DisplayList to restore its alpha value.
   2234      */
   2235     static final int VIEW_IS_ANIMATING_ALPHA = 0x2;
   2236 
   2237 
   2238     /* End of masks for mPrivateFlags3 */
   2239 
   2240     static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
   2241 
   2242     /**
   2243      * Always allow a user to over-scroll this view, provided it is a
   2244      * view that can scroll.
   2245      *
   2246      * @see #getOverScrollMode()
   2247      * @see #setOverScrollMode(int)
   2248      */
   2249     public static final int OVER_SCROLL_ALWAYS = 0;
   2250 
   2251     /**
   2252      * Allow a user to over-scroll this view only if the content is large
   2253      * enough to meaningfully scroll, provided it is a view that can scroll.
   2254      *
   2255      * @see #getOverScrollMode()
   2256      * @see #setOverScrollMode(int)
   2257      */
   2258     public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
   2259 
   2260     /**
   2261      * Never allow a user to over-scroll this view.
   2262      *
   2263      * @see #getOverScrollMode()
   2264      * @see #setOverScrollMode(int)
   2265      */
   2266     public static final int OVER_SCROLL_NEVER = 2;
   2267 
   2268     /**
   2269      * Special constant for {@link #setSystemUiVisibility(int)}: View has
   2270      * requested the system UI (status bar) to be visible (the default).
   2271      *
   2272      * @see #setSystemUiVisibility(int)
   2273      */
   2274     public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
   2275 
   2276     /**
   2277      * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
   2278      * system UI to enter an unobtrusive "low profile" mode.
   2279      *
   2280      * <p>This is for use in games, book readers, video players, or any other
   2281      * "immersive" application where the usual system chrome is deemed too distracting.
   2282      *
   2283      * <p>In low profile mode, the status bar and/or navigation icons may dim.
   2284      *
   2285      * @see #setSystemUiVisibility(int)
   2286      */
   2287     public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
   2288 
   2289     /**
   2290      * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
   2291      * system navigation be temporarily hidden.
   2292      *
   2293      * <p>This is an even less obtrusive state than that called for by
   2294      * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
   2295      * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
   2296      * those to disappear. This is useful (in conjunction with the
   2297      * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
   2298      * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
   2299      * window flags) for displaying content using every last pixel on the display.
   2300      *
   2301      * <p>There is a limitation: because navigation controls are so important, the least user
   2302      * interaction will cause them to reappear immediately.  When this happens, both
   2303      * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
   2304      * so that both elements reappear at the same time.
   2305      *
   2306      * @see #setSystemUiVisibility(int)
   2307      */
   2308     public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
   2309 
   2310     /**
   2311      * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
   2312      * into the normal fullscreen mode so that its content can take over the screen
   2313      * while still allowing the user to interact with the application.
   2314      *
   2315      * <p>This has the same visual effect as
   2316      * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
   2317      * WindowManager.LayoutParams.FLAG_FULLSCREEN},
   2318      * meaning that non-critical screen decorations (such as the status bar) will be
   2319      * hidden while the user is in the View's window, focusing the experience on
   2320      * that content.  Unlike the window flag, if you are using ActionBar in
   2321      * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
   2322      * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
   2323      * hide the action bar.
   2324      *
   2325      * <p>This approach to going fullscreen is best used over the window flag when
   2326      * it is a transient state -- that is, the application does this at certain
   2327      * points in its user interaction where it wants to allow the user to focus
   2328      * on content, but not as a continuous state.  For situations where the application
   2329      * would like to simply stay full screen the entire time (such as a game that
   2330      * wants to take over the screen), the
   2331      * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
   2332      * is usually a better approach.  The state set here will be removed by the system
   2333      * in various situations (such as the user moving to another application) like
   2334      * the other system UI states.
   2335      *
   2336      * <p>When using this flag, the application should provide some easy facility
   2337      * for the user to go out of it.  A common example would be in an e-book
   2338      * reader, where tapping on the screen brings back whatever screen and UI
   2339      * decorations that had been hidden while the user was immersed in reading
   2340      * the book.
   2341      *
   2342      * @see #setSystemUiVisibility(int)
   2343      */
   2344     public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
   2345 
   2346     /**
   2347      * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
   2348      * flags, we would like a stable view of the content insets given to
   2349      * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
   2350      * will always represent the worst case that the application can expect
   2351      * as a continuous state.  In the stock Android UI this is the space for
   2352      * the system bar, nav bar, and status bar, but not more transient elements
   2353      * such as an input method.
   2354      *
   2355      * The stable layout your UI sees is based on the system UI modes you can
   2356      * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
   2357      * then you will get a stable layout for changes of the
   2358      * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
   2359      * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
   2360      * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
   2361      * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
   2362      * with a stable layout.  (Note that you should avoid using
   2363      * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
   2364      *
   2365      * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
   2366      * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
   2367      * then a hidden status bar will be considered a "stable" state for purposes
   2368      * here.  This allows your UI to continually hide the status bar, while still
   2369      * using the system UI flags to hide the action bar while still retaining
   2370      * a stable layout.  Note that changing the window fullscreen flag will never
   2371      * provide a stable layout for a clean transition.
   2372      *
   2373      * <p>If you are using ActionBar in
   2374      * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
   2375      * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
   2376      * insets it adds to those given to the application.
   2377      */
   2378     public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
   2379 
   2380     /**
   2381      * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
   2382      * to be layed out as if it has requested
   2383      * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
   2384      * allows it to avoid artifacts when switching in and out of that mode, at
   2385      * the expense that some of its user interface may be covered by screen
   2386      * decorations when they are shown.  You can perform layout of your inner
   2387      * UI elements to account for the navagation system UI through the
   2388      * {@link #fitSystemWindows(Rect)} method.
   2389      */
   2390     public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
   2391 
   2392     /**
   2393      * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
   2394      * to be layed out as if it has requested
   2395      * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
   2396      * allows it to avoid artifacts when switching in and out of that mode, at
   2397      * the expense that some of its user interface may be covered by screen
   2398      * decorations when they are shown.  You can perform layout of your inner
   2399      * UI elements to account for non-fullscreen system UI through the
   2400      * {@link #fitSystemWindows(Rect)} method.
   2401      */
   2402     public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
   2403 
   2404     /**
   2405      * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
   2406      */
   2407     public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
   2408 
   2409     /**
   2410      * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
   2411      */
   2412     public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
   2413 
   2414     /**
   2415      * @hide
   2416      *
   2417      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
   2418      * out of the public fields to keep the undefined bits out of the developer's way.
   2419      *
   2420      * Flag to make the status bar not expandable.  Unless you also
   2421      * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
   2422      */
   2423     public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
   2424 
   2425     /**
   2426      * @hide
   2427      *
   2428      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
   2429      * out of the public fields to keep the undefined bits out of the developer's way.
   2430      *
   2431      * Flag to hide notification icons and scrolling ticker text.
   2432      */
   2433     public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
   2434 
   2435     /**
   2436      * @hide
   2437      *
   2438      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
   2439      * out of the public fields to keep the undefined bits out of the developer's way.
   2440      *
   2441      * Flag to disable incoming notification alerts.  This will not block
   2442      * icons, but it will block sound, vibrating and other visual or aural notifications.
   2443      */
   2444     public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
   2445 
   2446     /**
   2447      * @hide
   2448      *
   2449      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
   2450      * out of the public fields to keep the undefined bits out of the developer's way.
   2451      *
   2452      * Flag to hide only the scrolling ticker.  Note that
   2453      * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
   2454      * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
   2455      */
   2456     public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
   2457 
   2458     /**
   2459      * @hide
   2460      *
   2461      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
   2462      * out of the public fields to keep the undefined bits out of the developer's way.
   2463      *
   2464      * Flag to hide the center system info area.
   2465      */
   2466     public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
   2467 
   2468     /**
   2469      * @hide
   2470      *
   2471      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
   2472      * out of the public fields to keep the undefined bits out of the developer's way.
   2473      *
   2474      * Flag to hide only the home button.  Don't use this
   2475      * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
   2476      */
   2477     public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
   2478 
   2479     /**
   2480      * @hide
   2481      *
   2482      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
   2483      * out of the public fields to keep the undefined bits out of the developer's way.
   2484      *
   2485      * Flag to hide only the back button. Don't use this
   2486      * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
   2487      */
   2488     public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
   2489 
   2490     /**
   2491      * @hide
   2492      *
   2493      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
   2494      * out of the public fields to keep the undefined bits out of the developer's way.
   2495      *
   2496      * Flag to hide only the clock.  You might use this if your activity has
   2497      * its own clock making the status bar's clock redundant.
   2498      */
   2499     public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
   2500 
   2501     /**
   2502      * @hide
   2503      *
   2504      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
   2505      * out of the public fields to keep the undefined bits out of the developer's way.
   2506      *
   2507      * Flag to hide only the recent apps button. Don't use this
   2508      * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
   2509      */
   2510     public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
   2511 
   2512     /**
   2513      * @hide
   2514      */
   2515     public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
   2516 
   2517     /**
   2518      * These are the system UI flags that can be cleared by events outside
   2519      * of an application.  Currently this is just the ability to tap on the
   2520      * screen while hiding the navigation bar to have it return.
   2521      * @hide
   2522      */
   2523     public static final int SYSTEM_UI_CLEARABLE_FLAGS =
   2524             SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
   2525             | SYSTEM_UI_FLAG_FULLSCREEN;
   2526 
   2527     /**
   2528      * Flags that can impact the layout in relation to system UI.
   2529      */
   2530     public static final int SYSTEM_UI_LAYOUT_FLAGS =
   2531             SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
   2532             | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
   2533 
   2534     /**
   2535      * Find views that render the specified text.
   2536      *
   2537      * @see #findViewsWithText(ArrayList, CharSequence, int)
   2538      */
   2539     public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
   2540 
   2541     /**
   2542      * Find find views that contain the specified content description.
   2543      *
   2544      * @see #findViewsWithText(ArrayList, CharSequence, int)
   2545      */
   2546     public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
   2547 
   2548     /**
   2549      * Find views that contain {@link AccessibilityNodeProvider}. Such
   2550      * a View is a root of virtual view hierarchy and may contain the searched
   2551      * text. If this flag is set Views with providers are automatically
   2552      * added and it is a responsibility of the client to call the APIs of
   2553      * the provider to determine whether the virtual tree rooted at this View
   2554      * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
   2555      * represeting the virtual views with this text.
   2556      *
   2557      * @see #findViewsWithText(ArrayList, CharSequence, int)
   2558      *
   2559      * @hide
   2560      */
   2561     public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
   2562 
   2563     /**
   2564      * The undefined cursor position.
   2565      */
   2566     private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
   2567 
   2568     /**
   2569      * Indicates that the screen has changed state and is now off.
   2570      *
   2571      * @see #onScreenStateChanged(int)
   2572      */
   2573     public static final int SCREEN_STATE_OFF = 0x0;
   2574 
   2575     /**
   2576      * Indicates that the screen has changed state and is now on.
   2577      *
   2578      * @see #onScreenStateChanged(int)
   2579      */
   2580     public static final int SCREEN_STATE_ON = 0x1;
   2581 
   2582     /**
   2583      * Controls the over-scroll mode for this view.
   2584      * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
   2585      * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
   2586      * and {@link #OVER_SCROLL_NEVER}.
   2587      */
   2588     private int mOverScrollMode;
   2589 
   2590     /**
   2591      * The parent this view is attached to.
   2592      * {@hide}
   2593      *
   2594      * @see #getParent()
   2595      */
   2596     protected ViewParent mParent;
   2597 
   2598     /**
   2599      * {@hide}
   2600      */
   2601     AttachInfo mAttachInfo;
   2602 
   2603     /**
   2604      * {@hide}
   2605      */
   2606     @ViewDebug.ExportedProperty(flagMapping = {
   2607         @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
   2608                 name = "FORCE_LAYOUT"),
   2609         @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
   2610                 name = "LAYOUT_REQUIRED"),
   2611         @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
   2612             name = "DRAWING_CACHE_INVALID", outputIf = false),
   2613         @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
   2614         @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
   2615         @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
   2616         @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
   2617     })
   2618     int mPrivateFlags;
   2619     int mPrivateFlags2;
   2620     int mPrivateFlags3;
   2621 
   2622     /**
   2623      * This view's request for the visibility of the status bar.
   2624      * @hide
   2625      */
   2626     @ViewDebug.ExportedProperty(flagMapping = {
   2627         @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
   2628                                 equals = SYSTEM_UI_FLAG_LOW_PROFILE,
   2629                                 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
   2630         @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
   2631                                 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
   2632                                 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
   2633         @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
   2634                                 equals = SYSTEM_UI_FLAG_VISIBLE,
   2635                                 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
   2636     })
   2637     int mSystemUiVisibility;
   2638 
   2639     /**
   2640      * Reference count for transient state.
   2641      * @see #setHasTransientState(boolean)
   2642      */
   2643     int mTransientStateCount = 0;
   2644 
   2645     /**
   2646      * Count of how many windows this view has been attached to.
   2647      */
   2648     int mWindowAttachCount;
   2649 
   2650     /**
   2651      * The layout parameters associated with this view and used by the parent
   2652      * {@link android.view.ViewGroup} to determine how this view should be
   2653      * laid out.
   2654      * {@hide}
   2655      */
   2656     protected ViewGroup.LayoutParams mLayoutParams;
   2657 
   2658     /**
   2659      * The view flags hold various views states.
   2660      * {@hide}
   2661      */
   2662     @ViewDebug.ExportedProperty
   2663     int mViewFlags;
   2664 
   2665     static class TransformationInfo {
   2666         /**
   2667          * The transform matrix for the View. This transform is calculated internally
   2668          * based on the rotation, scaleX, and scaleY properties. The identity matrix
   2669          * is used by default. Do *not* use this variable directly; instead call
   2670          * getMatrix(), which will automatically recalculate the matrix if necessary
   2671          * to get the correct matrix based on the latest rotation and scale properties.
   2672          */
   2673         private final Matrix mMatrix = new Matrix();
   2674 
   2675         /**
   2676          * The transform matrix for the View. This transform is calculated internally
   2677          * based on the rotation, scaleX, and scaleY properties. The identity matrix
   2678          * is used by default. Do *not* use this variable directly; instead call
   2679          * getInverseMatrix(), which will automatically recalculate the matrix if necessary
   2680          * to get the correct matrix based on the latest rotation and scale properties.
   2681          */
   2682         private Matrix mInverseMatrix;
   2683 
   2684         /**
   2685          * An internal variable that tracks whether we need to recalculate the
   2686          * transform matrix, based on whether the rotation or scaleX/Y properties
   2687          * have changed since the matrix was last calculated.
   2688          */
   2689         boolean mMatrixDirty = false;
   2690 
   2691         /**
   2692          * An internal variable that tracks whether we need to recalculate the
   2693          * transform matrix, based on whether the rotation or scaleX/Y properties
   2694          * have changed since the matrix was last calculated.
   2695          */
   2696         private boolean mInverseMatrixDirty = true;
   2697 
   2698         /**
   2699          * A variable that tracks whether we need to recalculate the
   2700          * transform matrix, based on whether the rotation or scaleX/Y properties
   2701          * have changed since the matrix was last calculated. This variable
   2702          * is only valid after a call to updateMatrix() or to a function that
   2703          * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
   2704          */
   2705         private boolean mMatrixIsIdentity = true;
   2706 
   2707         /**
   2708          * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
   2709          */
   2710         private Camera mCamera = null;
   2711 
   2712         /**
   2713          * This matrix is used when computing the matrix for 3D rotations.
   2714          */
   2715         private Matrix matrix3D = null;
   2716 
   2717         /**
   2718          * These prev values are used to recalculate a centered pivot point when necessary. The
   2719          * pivot point is only used in matrix operations (when rotation, scale, or translation are
   2720          * set), so thes values are only used then as well.
   2721          */
   2722         private int mPrevWidth = -1;
   2723         private int mPrevHeight = -1;
   2724 
   2725         /**
   2726          * The degrees rotation around the vertical axis through the pivot point.
   2727          */
   2728         @ViewDebug.ExportedProperty
   2729         float mRotationY = 0f;
   2730 
   2731         /**
   2732          * The degrees rotation around the horizontal axis through the pivot point.
   2733          */
   2734         @ViewDebug.ExportedProperty
   2735         float mRotationX = 0f;
   2736 
   2737         /**
   2738          * The degrees rotation around the pivot point.
   2739          */
   2740         @ViewDebug.ExportedProperty
   2741         float mRotation = 0f;
   2742 
   2743         /**
   2744          * The amount of translation of the object away from its left property (post-layout).
   2745          */
   2746         @ViewDebug.ExportedProperty
   2747         float mTranslationX = 0f;
   2748 
   2749         /**
   2750          * The amount of translation of the object away from its top property (post-layout).
   2751          */
   2752         @ViewDebug.ExportedProperty
   2753         float mTranslationY = 0f;
   2754 
   2755         /**
   2756          * The amount of scale in the x direction around the pivot point. A
   2757          * value of 1 means no scaling is applied.
   2758          */
   2759         @ViewDebug.ExportedProperty
   2760         float mScaleX = 1f;
   2761 
   2762         /**
   2763          * The amount of scale in the y direction around the pivot point. A
   2764          * value of 1 means no scaling is applied.
   2765          */
   2766         @ViewDebug.ExportedProperty
   2767         float mScaleY = 1f;
   2768 
   2769         /**
   2770          * The x location of the point around which the view is rotated and scaled.
   2771          */
   2772         @ViewDebug.ExportedProperty
   2773         float mPivotX = 0f;
   2774 
   2775         /**
   2776          * The y location of the point around which the view is rotated and scaled.
   2777          */
   2778         @ViewDebug.ExportedProperty
   2779         float mPivotY = 0f;
   2780 
   2781         /**
   2782          * The opacity of the View. This is a value from 0 to 1, where 0 means
   2783          * completely transparent and 1 means completely opaque.
   2784          */
   2785         @ViewDebug.ExportedProperty
   2786         float mAlpha = 1f;
   2787     }
   2788 
   2789     TransformationInfo mTransformationInfo;
   2790 
   2791     private boolean mLastIsOpaque;
   2792 
   2793     /**
   2794      * Convenience value to check for float values that are close enough to zero to be considered
   2795      * zero.
   2796      */
   2797     private static final float NONZERO_EPSILON = .001f;
   2798 
   2799     /**
   2800      * The distance in pixels from the left edge of this view's parent
   2801      * to the left edge of this view.
   2802      * {@hide}
   2803      */
   2804     @ViewDebug.ExportedProperty(category = "layout")
   2805     protected int mLeft;
   2806     /**
   2807      * The distance in pixels from the left edge of this view's parent
   2808      * to the right edge of this view.
   2809      * {@hide}
   2810      */
   2811     @ViewDebug.ExportedProperty(category = "layout")
   2812     protected int mRight;
   2813     /**
   2814      * The distance in pixels from the top edge of this view's parent
   2815      * to the top edge of this view.
   2816      * {@hide}
   2817      */
   2818     @ViewDebug.ExportedProperty(category = "layout")
   2819     protected int mTop;
   2820     /**
   2821      * The distance in pixels from the top edge of this view's parent
   2822      * to the bottom edge of this view.
   2823      * {@hide}
   2824      */
   2825     @ViewDebug.ExportedProperty(category = "layout")
   2826     protected int mBottom;
   2827 
   2828     /**
   2829      * The offset, in pixels, by which the content of this view is scrolled
   2830      * horizontally.
   2831      * {@hide}
   2832      */
   2833     @ViewDebug.ExportedProperty(category = "scrolling")
   2834     protected int mScrollX;
   2835     /**
   2836      * The offset, in pixels, by which the content of this view is scrolled
   2837      * vertically.
   2838      * {@hide}
   2839      */
   2840     @ViewDebug.ExportedProperty(category = "scrolling")
   2841     protected int mScrollY;
   2842 
   2843     /**
   2844      * The left padding in pixels, that is the distance in pixels between the
   2845      * left edge of this view and the left edge of its content.
   2846      * {@hide}
   2847      */
   2848     @ViewDebug.ExportedProperty(category = "padding")
   2849     protected int mPaddingLeft;
   2850     /**
   2851      * The right padding in pixels, that is the distance in pixels between the
   2852      * right edge of this view and the right edge of its content.
   2853      * {@hide}
   2854      */
   2855     @ViewDebug.ExportedProperty(category = "padding")
   2856     protected int mPaddingRight;
   2857     /**
   2858      * The top padding in pixels, that is the distance in pixels between the
   2859      * top edge of this view and the top edge of its content.
   2860      * {@hide}
   2861      */
   2862     @ViewDebug.ExportedProperty(category = "padding")
   2863     protected int mPaddingTop;
   2864     /**
   2865      * The bottom padding in pixels, that is the distance in pixels between the
   2866      * bottom edge of this view and the bottom edge of its content.
   2867      * {@hide}
   2868      */
   2869     @ViewDebug.ExportedProperty(category = "padding")
   2870     protected int mPaddingBottom;
   2871 
   2872     /**
   2873      * The layout insets in pixels, that is the distance in pixels between the
   2874      * visible edges of this view its bounds.
   2875      */
   2876     private Insets mLayoutInsets;
   2877 
   2878     /**
   2879      * Briefly describes the view and is primarily used for accessibility support.
   2880      */
   2881     private CharSequence mContentDescription;
   2882 
   2883     /**
   2884      * Cache the paddingRight set by the user to append to the scrollbar's size.
   2885      *
   2886      * @hide
   2887      */
   2888     @ViewDebug.ExportedProperty(category = "padding")
   2889     protected int mUserPaddingRight;
   2890 
   2891     /**
   2892      * Cache the paddingBottom set by the user to append to the scrollbar's size.
   2893      *
   2894      * @hide
   2895      */
   2896     @ViewDebug.ExportedProperty(category = "padding")
   2897     protected int mUserPaddingBottom;
   2898 
   2899     /**
   2900      * Cache the paddingLeft set by the user to append to the scrollbar's size.
   2901      *
   2902      * @hide
   2903      */
   2904     @ViewDebug.ExportedProperty(category = "padding")
   2905     protected int mUserPaddingLeft;
   2906 
   2907     /**
   2908      * Cache if the user padding is relative.
   2909      *
   2910      */
   2911     @ViewDebug.ExportedProperty(category = "padding")
   2912     boolean mUserPaddingRelative;
   2913 
   2914     /**
   2915      * Cache the paddingStart set by the user to append to the scrollbar's size.
   2916      *
   2917      */
   2918     @ViewDebug.ExportedProperty(category = "padding")
   2919     int mUserPaddingStart;
   2920 
   2921     /**
   2922      * Cache the paddingEnd set by the user to append to the scrollbar's size.
   2923      *
   2924      */
   2925     @ViewDebug.ExportedProperty(category = "padding")
   2926     int mUserPaddingEnd;
   2927 
   2928     /**
   2929      * @hide
   2930      */
   2931     int mOldWidthMeasureSpec = Integer.MIN_VALUE;
   2932     /**
   2933      * @hide
   2934      */
   2935     int mOldHeightMeasureSpec = Integer.MIN_VALUE;
   2936 
   2937     private Drawable mBackground;
   2938 
   2939     private int mBackgroundResource;
   2940     private boolean mBackgroundSizeChanged;
   2941 
   2942     static class ListenerInfo {
   2943         /**
   2944          * Listener used to dispatch focus change events.
   2945          * This field should be made private, so it is hidden from the SDK.
   2946          * {@hide}
   2947          */
   2948         protected OnFocusChangeListener mOnFocusChangeListener;
   2949 
   2950         /**
   2951          * Listeners for layout change events.
   2952          */
   2953         private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
   2954 
   2955         /**
   2956          * Listeners for attach events.
   2957          */
   2958         private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
   2959 
   2960         /**
   2961          * Listener used to dispatch click events.
   2962          * This field should be made private, so it is hidden from the SDK.
   2963          * {@hide}
   2964          */
   2965         public OnClickListener mOnClickListener;
   2966 
   2967         /**
   2968          * Listener used to dispatch long click events.
   2969          * This field should be made private, so it is hidden from the SDK.
   2970          * {@hide}
   2971          */
   2972         protected OnLongClickListener mOnLongClickListener;
   2973 
   2974         /**
   2975          * Listener used to build the context menu.
   2976          * This field should be made private, so it is hidden from the SDK.
   2977          * {@hide}
   2978          */
   2979         protected OnCreateContextMenuListener mOnCreateContextMenuListener;
   2980 
   2981         private OnKeyListener mOnKeyListener;
   2982 
   2983         private OnTouchListener mOnTouchListener;
   2984 
   2985         private OnHoverListener mOnHoverListener;
   2986 
   2987         private OnGenericMotionListener mOnGenericMotionListener;
   2988 
   2989         private OnDragListener mOnDragListener;
   2990 
   2991         private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
   2992     }
   2993 
   2994     ListenerInfo mListenerInfo;
   2995 
   2996     /**
   2997      * The application environment this view lives in.
   2998      * This field should be made private, so it is hidden from the SDK.
   2999      * {@hide}
   3000      */
   3001     protected Context mContext;
   3002 
   3003     private final Resources mResources;
   3004 
   3005     private ScrollabilityCache mScrollCache;
   3006 
   3007     private int[] mDrawableState = null;
   3008 
   3009     /**
   3010      * Set to true when drawing cache is enabled and cannot be created.
   3011      *
   3012      * @hide
   3013      */
   3014     public boolean mCachingFailed;
   3015 
   3016     private Bitmap mDrawingCache;
   3017     private Bitmap mUnscaledDrawingCache;
   3018     private HardwareLayer mHardwareLayer;
   3019     DisplayList mDisplayList;
   3020 
   3021     /**
   3022      * When this view has focus and the next focus is {@link #FOCUS_LEFT},
   3023      * the user may specify which view to go to next.
   3024      */
   3025     private int mNextFocusLeftId = View.NO_ID;
   3026 
   3027     /**
   3028      * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
   3029      * the user may specify which view to go to next.
   3030      */
   3031     private int mNextFocusRightId = View.NO_ID;
   3032 
   3033     /**
   3034      * When this view has focus and the next focus is {@link #FOCUS_UP},
   3035      * the user may specify which view to go to next.
   3036      */
   3037     private int mNextFocusUpId = View.NO_ID;
   3038 
   3039     /**
   3040      * When this view has focus and the next focus is {@link #FOCUS_DOWN},
   3041      * the user may specify which view to go to next.
   3042      */
   3043     private int mNextFocusDownId = View.NO_ID;
   3044 
   3045     /**
   3046      * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
   3047      * the user may specify which view to go to next.
   3048      */
   3049     int mNextFocusForwardId = View.NO_ID;
   3050 
   3051     private CheckForLongPress mPendingCheckForLongPress;
   3052     private CheckForTap mPendingCheckForTap = null;
   3053     private PerformClick mPerformClick;
   3054     private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
   3055 
   3056     private UnsetPressedState mUnsetPressedState;
   3057 
   3058     /**
   3059      * Whether the long press's action has been invoked.  The tap's action is invoked on the
   3060      * up event while a long press is invoked as soon as the long press duration is reached, so
   3061      * a long press could be performed before the tap is checked, in which case the tap's action
   3062      * should not be invoked.
   3063      */
   3064     private boolean mHasPerformedLongPress;
   3065 
   3066     /**
   3067      * The minimum height of the view. We'll try our best to have the height
   3068      * of this view to at least this amount.
   3069      */
   3070     @ViewDebug.ExportedProperty(category = "measurement")
   3071     private int mMinHeight;
   3072 
   3073     /**
   3074      * The minimum width of the view. We'll try our best to have the width
   3075      * of this view to at least this amount.
   3076      */
   3077     @ViewDebug.ExportedProperty(category = "measurement")
   3078     private int mMinWidth;
   3079 
   3080     /**
   3081      * The delegate to handle touch events that are physically in this view
   3082      * but should be handled by another view.
   3083      */
   3084     private TouchDelegate mTouchDelegate = null;
   3085 
   3086     /**
   3087      * Solid color to use as a background when creating the drawing cache. Enables
   3088      * the cache to use 16 bit bitmaps instead of 32 bit.
   3089      */
   3090     private int mDrawingCacheBackgroundColor = 0;
   3091 
   3092     /**
   3093      * Special tree observer used when mAttachInfo is null.
   3094      */
   3095     private ViewTreeObserver mFloatingTreeObserver;
   3096 
   3097     /**
   3098      * Cache the touch slop from the context that created the view.
   3099      */
   3100     private int mTouchSlop;
   3101 
   3102     /**
   3103      * Object that handles automatic animation of view properties.
   3104      */
   3105     private ViewPropertyAnimator mAnimator = null;
   3106 
   3107     /**
   3108      * Flag indicating that a drag can cross window boundaries.  When
   3109      * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
   3110      * with this flag set, all visible applications will be able to participate
   3111      * in the drag operation and receive the dragged content.
   3112      *
   3113      * @hide
   3114      */
   3115     public static final int DRAG_FLAG_GLOBAL = 1;
   3116 
   3117     /**
   3118      * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
   3119      */
   3120     private float mVerticalScrollFactor;
   3121 
   3122     /**
   3123      * Position of the vertical scroll bar.
   3124      */
   3125     private int mVerticalScrollbarPosition;
   3126 
   3127     /**
   3128      * Position the scroll bar at the default position as determined by the system.
   3129      */
   3130     public static final int SCROLLBAR_POSITION_DEFAULT = 0;
   3131 
   3132     /**
   3133      * Position the scroll bar along the left edge.
   3134      */
   3135     public static final int SCROLLBAR_POSITION_LEFT = 1;
   3136 
   3137     /**
   3138      * Position the scroll bar along the right edge.
   3139      */
   3140     public static final int SCROLLBAR_POSITION_RIGHT = 2;
   3141 
   3142     /**
   3143      * Indicates that the view does not have a layer.
   3144      *
   3145      * @see #getLayerType()
   3146      * @see #setLayerType(int, android.graphics.Paint)
   3147      * @see #LAYER_TYPE_SOFTWARE
   3148      * @see #LAYER_TYPE_HARDWARE
   3149      */
   3150     public static final int LAYER_TYPE_NONE = 0;
   3151 
   3152     /**
   3153      * <p>Indicates that the view has a software layer. A software layer is backed
   3154      * by a bitmap and causes the view to be rendered using Android's software
   3155      * rendering pipeline, even if hardware acceleration is enabled.</p>
   3156      *
   3157      * <p>Software layers have various usages:</p>
   3158      * <p>When the application is not using hardware acceleration, a software layer
   3159      * is useful to apply a specific color filter and/or blending mode and/or
   3160      * translucency to a view and all its children.</p>
   3161      * <p>When the application is using hardware acceleration, a software layer
   3162      * is useful to render drawing primitives not supported by the hardware
   3163      * accelerated pipeline. It can also be used to cache a complex view tree
   3164      * into a texture and reduce the complexity of drawing operations. For instance,
   3165      * when animating a complex view tree with a translation, a software layer can
   3166      * be used to render the view tree only once.</p>
   3167      * <p>Software layers should be avoided when the affected view tree updates
   3168      * often. Every update will require to re-render the software layer, which can
   3169      * potentially be slow (particularly when hardware acceleration is turned on
   3170      * since the layer will have to be uploaded into a hardware texture after every
   3171      * update.)</p>
   3172      *
   3173      * @see #getLayerType()
   3174      * @see #setLayerType(int, android.graphics.Paint)
   3175      * @see #LAYER_TYPE_NONE
   3176      * @see #LAYER_TYPE_HARDWARE
   3177      */
   3178     public static final int LAYER_TYPE_SOFTWARE = 1;
   3179 
   3180     /**
   3181      * <p>Indicates that the view has a hardware layer. A hardware layer is backed
   3182      * by a hardware specific texture (generally Frame Buffer Objects or FBO on
   3183      * OpenGL hardware) and causes the view to be rendered using Android's hardware
   3184      * rendering pipeline, but only if hardware acceleration is turned on for the
   3185      * view hierarchy. When hardware acceleration is turned off, hardware layers
   3186      * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
   3187      *
   3188      * <p>A hardware layer is useful to apply a specific color filter and/or
   3189      * blending mode and/or translucency to a view and all its children.</p>
   3190      * <p>A hardware layer can be used to cache a complex view tree into a
   3191      * texture and reduce the complexity of drawing operations. For instance,
   3192      * when animating a complex view tree with a translation, a hardware layer can
   3193      * be used to render the view tree only once.</p>
   3194      * <p>A hardware layer can also be used to increase the rendering quality when
   3195      * rotation transformations are applied on a view. It can also be used to
   3196      * prevent potential clipping issues when applying 3D transforms on a view.</p>
   3197      *
   3198      * @see #getLayerType()
   3199      * @see #setLayerType(int, android.graphics.Paint)
   3200      * @see #LAYER_TYPE_NONE
   3201      * @see #LAYER_TYPE_SOFTWARE
   3202      */
   3203     public static final int LAYER_TYPE_HARDWARE = 2;
   3204 
   3205     @ViewDebug.ExportedProperty(category = "drawing", mapping = {
   3206             @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
   3207             @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
   3208             @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
   3209     })
   3210     int mLayerType = LAYER_TYPE_NONE;
   3211     Paint mLayerPaint;
   3212     Rect mLocalDirtyRect;
   3213 
   3214     /**
   3215      * Set to true when the view is sending hover accessibility events because it
   3216      * is the innermost hovered view.
   3217      */
   3218     private boolean mSendingHoverAccessibilityEvents;
   3219 
   3220     /**
   3221      * Simple constructor to use when creating a view from code.
   3222      *
   3223      * @param context The Context the view is running in, through which it can
   3224      *        access the current theme, resources, etc.
   3225      */
   3226     public View(Context context) {
   3227         mContext = context;
   3228         mResources = context != null ? context.getResources() : null;
   3229         mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
   3230         // Set layout and text direction defaults
   3231         mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
   3232                 (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
   3233                 (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
   3234                 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT) |
   3235                 (ACCESSIBILITY_FOCUSABLE_DEFAULT << ACCESSIBILITY_FOCUSABLE_SHIFT);
   3236         mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
   3237         setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
   3238         mUserPaddingStart = -1;
   3239         mUserPaddingEnd = -1;
   3240         mUserPaddingRelative = false;
   3241     }
   3242 
   3243     /**
   3244      * Delegate for injecting accessiblity functionality.
   3245      */
   3246     AccessibilityDelegate mAccessibilityDelegate;
   3247 
   3248     /**
   3249      * Consistency verifier for debugging purposes.
   3250      * @hide
   3251      */
   3252     protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
   3253             InputEventConsistencyVerifier.isInstrumentationEnabled() ?
   3254                     new InputEventConsistencyVerifier(this, 0) : null;
   3255 
   3256     /**
   3257      * Constructor that is called when inflating a view from XML. This is called
   3258      * when a view is being constructed from an XML file, supplying attributes
   3259      * that were specified in the XML file. This version uses a default style of
   3260      * 0, so the only attribute values applied are those in the Context's Theme
   3261      * and the given AttributeSet.
   3262      *
   3263      * <p>
   3264      * The method onFinishInflate() will be called after all children have been
   3265      * added.
   3266      *
   3267      * @param context The Context the view is running in, through which it can
   3268      *        access the current theme, resources, etc.
   3269      * @param attrs The attributes of the XML tag that is inflating the view.
   3270      * @see #View(Context, AttributeSet, int)
   3271      */
   3272     public View(Context context, AttributeSet attrs) {
   3273         this(context, attrs, 0);
   3274     }
   3275 
   3276     /**
   3277      * Perform inflation from XML and apply a class-specific base style. This
   3278      * constructor of View allows subclasses to use their own base style when
   3279      * they are inflating. For example, a Button class's constructor would call
   3280      * this version of the super class constructor and supply
   3281      * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
   3282      * the theme's button style to modify all of the base view attributes (in
   3283      * particular its background) as well as the Button class's attributes.
   3284      *
   3285      * @param context The Context the view is running in, through which it can
   3286      *        access the current theme, resources, etc.
   3287      * @param attrs The attributes of the XML tag that is inflating the view.
   3288      * @param defStyle The default style to apply to this view. If 0, no style
   3289      *        will be applied (beyond what is included in the theme). This may
   3290      *        either be an attribute resource, whose value will be retrieved
   3291      *        from the current theme, or an explicit style resource.
   3292      * @see #View(Context, AttributeSet)
   3293      */
   3294     public View(Context context, AttributeSet attrs, int defStyle) {
   3295         this(context);
   3296 
   3297         TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
   3298                 defStyle, 0);
   3299 
   3300         Drawable background = null;
   3301 
   3302         int leftPadding = -1;
   3303         int topPadding = -1;
   3304         int rightPadding = -1;
   3305         int bottomPadding = -1;
   3306         int startPadding = -1;
   3307         int endPadding = -1;
   3308 
   3309         int padding = -1;
   3310 
   3311         int viewFlagValues = 0;
   3312         int viewFlagMasks = 0;
   3313 
   3314         boolean setScrollContainer = false;
   3315 
   3316         int x = 0;
   3317         int y = 0;
   3318 
   3319         float tx = 0;
   3320         float ty = 0;
   3321         float rotation = 0;
   3322         float rotationX = 0;
   3323         float rotationY = 0;
   3324         float sx = 1f;
   3325         float sy = 1f;
   3326         boolean transformSet = false;
   3327 
   3328         int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
   3329 
   3330         int overScrollMode = mOverScrollMode;
   3331         final int N = a.getIndexCount();
   3332         for (int i = 0; i < N; i++) {
   3333             int attr = a.getIndex(i);
   3334             switch (attr) {
   3335                 case com.android.internal.R.styleable.View_background:
   3336                     background = a.getDrawable(attr);
   3337                     break;
   3338                 case com.android.internal.R.styleable.View_padding:
   3339                     padding = a.getDimensionPixelSize(attr, -1);
   3340                     break;
   3341                  case com.android.internal.R.styleable.View_paddingLeft:
   3342                     leftPadding = a.getDimensionPixelSize(attr, -1);
   3343                     break;
   3344                 case com.android.internal.R.styleable.View_paddingTop:
   3345                     topPadding = a.getDimensionPixelSize(attr, -1);
   3346                     break;
   3347                 case com.android.internal.R.styleable.View_paddingRight:
   3348                     rightPadding = a.getDimensionPixelSize(attr, -1);
   3349                     break;
   3350                 case com.android.internal.R.styleable.View_paddingBottom:
   3351                     bottomPadding = a.getDimensionPixelSize(attr, -1);
   3352                     break;
   3353                 case com.android.internal.R.styleable.View_paddingStart:
   3354                     startPadding = a.getDimensionPixelSize(attr, -1);
   3355                     break;
   3356                 case com.android.internal.R.styleable.View_paddingEnd:
   3357                     endPadding = a.getDimensionPixelSize(attr, -1);
   3358                     break;
   3359                 case com.android.internal.R.styleable.View_scrollX:
   3360                     x = a.getDimensionPixelOffset(attr, 0);
   3361                     break;
   3362                 case com.android.internal.R.styleable.View_scrollY:
   3363                     y = a.getDimensionPixelOffset(attr, 0);
   3364                     break;
   3365                 case com.android.internal.R.styleable.View_alpha:
   3366                     setAlpha(a.getFloat(attr, 1f));
   3367                     break;
   3368                 case com.android.internal.R.styleable.View_transformPivotX:
   3369                     setPivotX(a.getDimensionPixelOffset(attr, 0));
   3370                     break;
   3371                 case com.android.internal.R.styleable.View_transformPivotY:
   3372                     setPivotY(a.getDimensionPixelOffset(attr, 0));
   3373                     break;
   3374                 case com.android.internal.R.styleable.View_translationX:
   3375                     tx = a.getDimensionPixelOffset(attr, 0);
   3376                     transformSet = true;
   3377                     break;
   3378                 case com.android.internal.R.styleable.View_translationY:
   3379                     ty = a.getDimensionPixelOffset(attr, 0);
   3380                     transformSet = true;
   3381                     break;
   3382                 case com.android.internal.R.styleable.View_rotation:
   3383                     rotation = a.getFloat(attr, 0);
   3384                     transformSet = true;
   3385                     break;
   3386                 case com.android.internal.R.styleable.View_rotationX:
   3387                     rotationX = a.getFloat(attr, 0);
   3388                     transformSet = true;
   3389                     break;
   3390                 case com.android.internal.R.styleable.View_rotationY:
   3391                     rotationY = a.getFloat(attr, 0);
   3392                     transformSet = true;
   3393                     break;
   3394                 case com.android.internal.R.styleable.View_scaleX:
   3395                     sx = a.getFloat(attr, 1f);
   3396                     transformSet = true;
   3397                     break;
   3398                 case com.android.internal.R.styleable.View_scaleY:
   3399                     sy = a.getFloat(attr, 1f);
   3400                     transformSet = true;
   3401                     break;
   3402                 case com.android.internal.R.styleable.View_id:
   3403                     mID = a.getResourceId(attr, NO_ID);
   3404                     break;
   3405                 case com.android.internal.R.styleable.View_tag:
   3406                     mTag = a.getText(attr);
   3407                     break;
   3408                 case com.android.internal.R.styleable.View_fitsSystemWindows:
   3409                     if (a.getBoolean(attr, false)) {
   3410                         viewFlagValues |= FITS_SYSTEM_WINDOWS;
   3411                         viewFlagMasks |= FITS_SYSTEM_WINDOWS;
   3412                     }
   3413                     break;
   3414                 case com.android.internal.R.styleable.View_focusable:
   3415                     if (a.getBoolean(attr, false)) {
   3416                         viewFlagValues |= FOCUSABLE;
   3417                         viewFlagMasks |= FOCUSABLE_MASK;
   3418                     }
   3419                     break;
   3420                 case com.android.internal.R.styleable.View_focusableInTouchMode:
   3421                     if (a.getBoolean(attr, false)) {
   3422                         viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
   3423                         viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
   3424                     }
   3425                     break;
   3426                 case com.android.internal.R.styleable.View_clickable:
   3427                     if (a.getBoolean(attr, false)) {
   3428                         viewFlagValues |= CLICKABLE;
   3429                         viewFlagMasks |= CLICKABLE;
   3430                     }
   3431                     break;
   3432                 case com.android.internal.R.styleable.View_longClickable:
   3433                     if (a.getBoolean(attr, false)) {
   3434                         viewFlagValues |= LONG_CLICKABLE;
   3435                         viewFlagMasks |= LONG_CLICKABLE;
   3436                     }
   3437                     break;
   3438                 case com.android.internal.R.styleable.View_saveEnabled:
   3439                     if (!a.getBoolean(attr, true)) {
   3440                         viewFlagValues |= SAVE_DISABLED;
   3441                         viewFlagMasks |= SAVE_DISABLED_MASK;
   3442                     }
   3443                     break;
   3444                 case com.android.internal.R.styleable.View_duplicateParentState:
   3445                     if (a.getBoolean(attr, false)) {
   3446                         viewFlagValues |= DUPLICATE_PARENT_STATE;
   3447                         viewFlagMasks |= DUPLICATE_PARENT_STATE;
   3448                     }
   3449                     break;
   3450                 case com.android.internal.R.styleable.View_visibility:
   3451                     final int visibility = a.getInt(attr, 0);
   3452                     if (visibility != 0) {
   3453                         viewFlagValues |= VISIBILITY_FLAGS[visibility];
   3454                         viewFlagMasks |= VISIBILITY_MASK;
   3455                     }
   3456                     break;
   3457                 case com.android.internal.R.styleable.View_layoutDirection:
   3458                     // Clear any layout direction flags (included resolved bits) already set
   3459                     mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
   3460                     // Set the layout direction flags depending on the value of the attribute
   3461                     final int layoutDirection = a.getInt(attr, -1);
   3462                     final int value = (layoutDirection != -1) ?
   3463                             LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
   3464                     mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
   3465                     break;
   3466                 case com.android.internal.R.styleable.View_drawingCacheQuality:
   3467                     final int cacheQuality = a.getInt(attr, 0);
   3468                     if (cacheQuality != 0) {
   3469                         viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
   3470                         viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
   3471                     }
   3472                     break;
   3473                 case com.android.internal.R.styleable.View_contentDescription:
   3474                     setContentDescription(a.getString(attr));
   3475                     break;
   3476                 case com.android.internal.R.styleable.View_soundEffectsEnabled:
   3477                     if (!a.getBoolean(attr, true)) {
   3478                         viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
   3479                         viewFlagMasks |= SOUND_EFFECTS_ENABLED;
   3480                     }
   3481                     break;
   3482                 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
   3483                     if (!a.getBoolean(attr, true)) {
   3484                         viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
   3485                         viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
   3486                     }
   3487                     break;
   3488                 case R.styleable.View_scrollbars:
   3489                     final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
   3490                     if (scrollbars != SCROLLBARS_NONE) {
   3491                         viewFlagValues |= scrollbars;
   3492                         viewFlagMasks |= SCROLLBARS_MASK;
   3493                         initializeScrollbars(a);
   3494                     }
   3495                     break;
   3496                 //noinspection deprecation
   3497                 case R.styleable.View_fadingEdge:
   3498                     if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
   3499                         // Ignore the attribute starting with ICS
   3500                         break;
   3501                     }
   3502                     // With builds < ICS, fall through and apply fading edges
   3503                 case R.styleable.View_requiresFadingEdge:
   3504                     final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
   3505                     if (fadingEdge != FADING_EDGE_NONE) {
   3506                         viewFlagValues |= fadingEdge;
   3507                         viewFlagMasks |= FADING_EDGE_MASK;
   3508                         initializeFadingEdge(a);
   3509                     }
   3510                     break;
   3511                 case R.styleable.View_scrollbarStyle:
   3512                     scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
   3513                     if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
   3514                         viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
   3515                         viewFlagMasks |= SCROLLBARS_STYLE_MASK;
   3516                     }
   3517                     break;
   3518                 case R.styleable.View_isScrollContainer:
   3519                     setScrollContainer = true;
   3520                     if (a.getBoolean(attr, false)) {
   3521                         setScrollContainer(true);
   3522                     }
   3523                     break;
   3524                 case com.android.internal.R.styleable.View_keepScreenOn:
   3525                     if (a.getBoolean(attr, false)) {
   3526                         viewFlagValues |= KEEP_SCREEN_ON;
   3527                         viewFlagMasks |= KEEP_SCREEN_ON;
   3528                     }
   3529                     break;
   3530                 case R.styleable.View_filterTouchesWhenObscured:
   3531                     if (a.getBoolean(attr, false)) {
   3532                         viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
   3533                         viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
   3534                     }
   3535                     break;
   3536                 case R.styleable.View_nextFocusLeft:
   3537                     mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
   3538                     break;
   3539                 case R.styleable.View_nextFocusRight:
   3540                     mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
   3541                     break;
   3542                 case R.styleable.View_nextFocusUp:
   3543                     mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
   3544                     break;
   3545                 case R.styleable.View_nextFocusDown:
   3546                     mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
   3547                     break;
   3548                 case R.styleable.View_nextFocusForward:
   3549                     mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
   3550                     break;
   3551                 case R.styleable.View_minWidth:
   3552                     mMinWidth = a.getDimensionPixelSize(attr, 0);
   3553                     break;
   3554                 case R.styleable.View_minHeight:
   3555                     mMinHeight = a.getDimensionPixelSize(attr, 0);
   3556                     break;
   3557                 case R.styleable.View_onClick:
   3558                     if (context.isRestricted()) {
   3559                         throw new IllegalStateException("The android:onClick attribute cannot "
   3560                                 + "be used within a restricted context");
   3561                     }
   3562 
   3563                     final String handlerName = a.getString(attr);
   3564                     if (handlerName != null) {
   3565                         setOnClickListener(new OnClickListener() {
   3566                             private Method mHandler;
   3567 
   3568                             public void onClick(View v) {
   3569                                 if (mHandler == null) {
   3570                                     try {
   3571                                         mHandler = getContext().getClass().getMethod(handlerName,
   3572                                                 View.class);
   3573                                     } catch (NoSuchMethodException e) {
   3574                                         int id = getId();
   3575                                         String idText = id == NO_ID ? "" : " with id '"
   3576                                                 + getContext().getResources().getResourceEntryName(
   3577                                                     id) + "'";
   3578                                         throw new IllegalStateException("Could not find a method " +
   3579                                                 handlerName + "(View) in the activity "
   3580                                                 + getContext().getClass() + " for onClick handler"
   3581                                                 + " on view " + View.this.getClass() + idText, e);
   3582                                     }
   3583                                 }
   3584 
   3585                                 try {
   3586                                     mHandler.invoke(getContext(), View.this);
   3587                                 } catch (IllegalAccessException e) {
   3588                                     throw new IllegalStateException("Could not execute non "
   3589                                             + "public method of the activity", e);
   3590                                 } catch (InvocationTargetException e) {
   3591                                     throw new IllegalStateException("Could not execute "
   3592                                             + "method of the activity", e);
   3593                                 }
   3594                             }
   3595                         });
   3596                     }
   3597                     break;
   3598                 case R.styleable.View_overScrollMode:
   3599                     overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
   3600                     break;
   3601                 case R.styleable.View_verticalScrollbarPosition:
   3602                     mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
   3603                     break;
   3604                 case R.styleable.View_layerType:
   3605                     setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
   3606                     break;
   3607                 case R.styleable.View_textDirection:
   3608                     // Clear any text direction flag already set
   3609                     mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
   3610                     // Set the text direction flags depending on the value of the attribute
   3611                     final int textDirection = a.getInt(attr, -1);
   3612                     if (textDirection != -1) {
   3613                         mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
   3614                     }
   3615                     break;
   3616                 case R.styleable.View_textAlignment:
   3617                     // Clear any text alignment flag already set
   3618                     mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
   3619                     // Set the text alignment flag depending on the value of the attribute
   3620                     final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
   3621                     mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
   3622                     break;
   3623                 case R.styleable.View_importantForAccessibility:
   3624                     setImportantForAccessibility(a.getInt(attr,
   3625                             IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
   3626                     break;
   3627             }
   3628         }
   3629 
   3630         a.recycle();
   3631 
   3632         setOverScrollMode(overScrollMode);
   3633 
   3634         if (background != null) {
   3635             setBackground(background);
   3636         }
   3637 
   3638         // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
   3639         // layout direction). Those cached values will be used later during padding resolution.
   3640         mUserPaddingStart = startPadding;
   3641         mUserPaddingEnd = endPadding;
   3642 
   3643         updateUserPaddingRelative();
   3644 
   3645         if (padding >= 0) {
   3646             leftPadding = padding;
   3647             topPadding = padding;
   3648             rightPadding = padding;
   3649             bottomPadding = padding;
   3650         }
   3651 
   3652         // If the user specified the padding (either with android:padding or
   3653         // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
   3654         // use the default padding or the padding from the background drawable
   3655         // (stored at this point in mPadding*)
   3656         setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
   3657                 topPadding >= 0 ? topPadding : mPaddingTop,
   3658                 rightPadding >= 0 ? rightPadding : mPaddingRight,
   3659                 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
   3660 
   3661         if (viewFlagMasks != 0) {
   3662             setFlags(viewFlagValues, viewFlagMasks);
   3663         }
   3664 
   3665         // Needs to be called after mViewFlags is set
   3666         if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
   3667             recomputePadding();
   3668         }
   3669 
   3670         if (x != 0 || y != 0) {
   3671             scrollTo(x, y);
   3672         }
   3673 
   3674         if (transformSet) {
   3675             setTranslationX(tx);
   3676             setTranslationY(ty);
   3677             setRotation(rotation);
   3678             setRotationX(rotationX);
   3679             setRotationY(rotationY);
   3680             setScaleX(sx);
   3681             setScaleY(sy);
   3682         }
   3683 
   3684         if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
   3685             setScrollContainer(true);
   3686         }
   3687 
   3688         computeOpaqueFlags();
   3689     }
   3690 
   3691     private void updateUserPaddingRelative() {
   3692         mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
   3693     }
   3694 
   3695     /**
   3696      * Non-public constructor for use in testing
   3697      */
   3698     View() {
   3699         mResources = null;
   3700     }
   3701 
   3702     /**
   3703      * <p>
   3704      * Initializes the fading edges from a given set of styled attributes. This
   3705      * method should be called by subclasses that need fading edges and when an
   3706      * instance of these subclasses is created programmatically rather than
   3707      * being inflated from XML. This method is automatically called when the XML
   3708      * is inflated.
   3709      * </p>
   3710      *
   3711      * @param a the styled attributes set to initialize the fading edges from
   3712      */
   3713     protected void initializeFadingEdge(TypedArray a) {
   3714         initScrollCache();
   3715 
   3716         mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
   3717                 R.styleable.View_fadingEdgeLength,
   3718                 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
   3719     }
   3720 
   3721     /**
   3722      * Returns the size of the vertical faded edges used to indicate that more
   3723      * content in this view is visible.
   3724      *
   3725      * @return The size in pixels of the vertical faded edge or 0 if vertical
   3726      *         faded edges are not enabled for this view.
   3727      * @attr ref android.R.styleable#View_fadingEdgeLength
   3728      */
   3729     public int getVerticalFadingEdgeLength() {
   3730         if (isVerticalFadingEdgeEnabled()) {
   3731             ScrollabilityCache cache = mScrollCache;
   3732             if (cache != null) {
   3733                 return cache.fadingEdgeLength;
   3734             }
   3735         }
   3736         return 0;
   3737     }
   3738 
   3739     /**
   3740      * Set the size of the faded edge used to indicate that more content in this
   3741      * view is available.  Will not change whether the fading edge is enabled; use
   3742      * {@link #setVerticalFadingEdgeEnabled(boolean)} or
   3743      * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
   3744      * for the vertical or horizontal fading edges.
   3745      *
   3746      * @param length The size in pixels of the faded edge used to indicate that more
   3747      *        content in this view is visible.
   3748      */
   3749     public void setFadingEdgeLength(int length) {
   3750         initScrollCache();
   3751         mScrollCache.fadingEdgeLength = length;
   3752     }
   3753 
   3754     /**
   3755      * Returns the size of the horizontal faded edges used to indicate that more
   3756      * content in this view is visible.
   3757      *
   3758      * @return The size in pixels of the horizontal faded edge or 0 if horizontal
   3759      *         faded edges are not enabled for this view.
   3760      * @attr ref android.R.styleable#View_fadingEdgeLength
   3761      */
   3762     public int getHorizontalFadingEdgeLength() {
   3763         if (isHorizontalFadingEdgeEnabled()) {
   3764             ScrollabilityCache cache = mScrollCache;
   3765             if (cache != null) {
   3766                 return cache.fadingEdgeLength;
   3767             }
   3768         }
   3769         return 0;
   3770     }
   3771 
   3772     /**
   3773      * Returns the width of the vertical scrollbar.
   3774      *
   3775      * @return The width in pixels of the vertical scrollbar or 0 if there
   3776      *         is no vertical scrollbar.
   3777      */
   3778     public int getVerticalScrollbarWidth() {
   3779         ScrollabilityCache cache = mScrollCache;
   3780         if (cache != null) {
   3781             ScrollBarDrawable scrollBar = cache.scrollBar;
   3782             if (scrollBar != null) {
   3783                 int size = scrollBar.getSize(true);
   3784                 if (size <= 0) {
   3785                     size = cache.scrollBarSize;
   3786                 }
   3787                 return size;
   3788             }
   3789             return 0;
   3790         }
   3791         return 0;
   3792     }
   3793 
   3794     /**
   3795      * Returns the height of the horizontal scrollbar.
   3796      *
   3797      * @return The height in pixels of the horizontal scrollbar or 0 if
   3798      *         there is no horizontal scrollbar.
   3799      */
   3800     protected int getHorizontalScrollbarHeight() {
   3801         ScrollabilityCache cache = mScrollCache;
   3802         if (cache != null) {
   3803             ScrollBarDrawable scrollBar = cache.scrollBar;
   3804             if (scrollBar != null) {
   3805                 int size = scrollBar.getSize(false);
   3806                 if (size <= 0) {
   3807                     size = cache.scrollBarSize;
   3808                 }
   3809                 return size;
   3810             }
   3811             return 0;
   3812         }
   3813         return 0;
   3814     }
   3815 
   3816     /**
   3817      * <p>
   3818      * Initializes the scrollbars from a given set of styled attributes. This
   3819      * method should be called by subclasses that need scrollbars and when an
   3820      * instance of these subclasses is created programmatically rather than
   3821      * being inflated from XML. This method is automatically called when the XML
   3822      * is inflated.
   3823      * </p>
   3824      *
   3825      * @param a the styled attributes set to initialize the scrollbars from
   3826      */
   3827     protected void initializeScrollbars(TypedArray a) {
   3828         initScrollCache();
   3829 
   3830         final ScrollabilityCache scrollabilityCache = mScrollCache;
   3831 
   3832         if (scrollabilityCache.scrollBar == null) {
   3833             scrollabilityCache.scrollBar = new ScrollBarDrawable();
   3834         }
   3835 
   3836         final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
   3837 
   3838         if (!fadeScrollbars) {
   3839             scrollabilityCache.state = ScrollabilityCache.ON;
   3840         }
   3841         scrollabilityCache.fadeScrollBars = fadeScrollbars;
   3842 
   3843 
   3844         scrollabilityCache.scrollBarFadeDuration = a.getInt(
   3845                 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
   3846                         .getScrollBarFadeDuration());
   3847         scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
   3848                 R.styleable.View_scrollbarDefaultDelayBeforeFade,
   3849                 ViewConfiguration.getScrollDefaultDelay());
   3850 
   3851 
   3852         scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
   3853                 com.android.internal.R.styleable.View_scrollbarSize,
   3854                 ViewConfiguration.get(mContext).getScaledScrollBarSize());
   3855 
   3856         Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
   3857         scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
   3858 
   3859         Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
   3860         if (thumb != null) {
   3861             scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
   3862         }
   3863 
   3864         boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
   3865                 false);
   3866         if (alwaysDraw) {
   3867             scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
   3868         }
   3869 
   3870         track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
   3871         scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
   3872 
   3873         thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
   3874         if (thumb != null) {
   3875             scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
   3876         }
   3877 
   3878         alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
   3879                 false);
   3880         if (alwaysDraw) {
   3881             scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
   3882         }
   3883 
   3884         // Re-apply user/background padding so that scrollbar(s) get added
   3885         resolvePadding();
   3886     }
   3887 
   3888     /**
   3889      * <p>
   3890      * Initalizes the scrollability cache if necessary.
   3891      * </p>
   3892      */
   3893     private void initScrollCache() {
   3894         if (mScrollCache == null) {
   3895             mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
   3896         }
   3897     }
   3898 
   3899     private ScrollabilityCache getScrollCache() {
   3900         initScrollCache();
   3901         return mScrollCache;
   3902     }
   3903 
   3904     /**
   3905      * Set the position of the vertical scroll bar. Should be one of
   3906      * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
   3907      * {@link #SCROLLBAR_POSITION_RIGHT}.
   3908      *
   3909      * @param position Where the vertical scroll bar should be positioned.
   3910      */
   3911     public void setVerticalScrollbarPosition(int position) {
   3912         if (mVerticalScrollbarPosition != position) {
   3913             mVerticalScrollbarPosition = position;
   3914             computeOpaqueFlags();
   3915             resolvePadding();
   3916         }
   3917     }
   3918 
   3919     /**
   3920      * @return The position where the vertical scroll bar will show, if applicable.
   3921      * @see #setVerticalScrollbarPosition(int)
   3922      */
   3923     public int getVerticalScrollbarPosition() {
   3924         return mVerticalScrollbarPosition;
   3925     }
   3926 
   3927     ListenerInfo getListenerInfo() {
   3928         if (mListenerInfo != null) {
   3929             return mListenerInfo;
   3930         }
   3931         mListenerInfo = new ListenerInfo();
   3932         return mListenerInfo;
   3933     }
   3934 
   3935     /**
   3936      * Register a callback to be invoked when focus of this view changed.
   3937      *
   3938      * @param l The callback that will run.
   3939      */
   3940     public void setOnFocusChangeListener(OnFocusChangeListener l) {
   3941         getListenerInfo().mOnFocusChangeListener = l;
   3942     }
   3943 
   3944     /**
   3945      * Add a listener that will be called when the bounds of the view change due to
   3946      * layout processing.
   3947      *
   3948      * @param listener The listener that will be called when layout bounds change.
   3949      */
   3950     public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
   3951         ListenerInfo li = getListenerInfo();
   3952         if (li.mOnLayoutChangeListeners == null) {
   3953             li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
   3954         }
   3955         if (!li.mOnLayoutChangeListeners.contains(listener)) {
   3956             li.mOnLayoutChangeListeners.add(listener);
   3957         }
   3958     }
   3959 
   3960     /**
   3961      * Remove a listener for layout changes.
   3962      *
   3963      * @param listener The listener for layout bounds change.
   3964      */
   3965     public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
   3966         ListenerInfo li = mListenerInfo;
   3967         if (li == null || li.mOnLayoutChangeListeners == null) {
   3968             return;
   3969         }
   3970         li.mOnLayoutChangeListeners.remove(listener);
   3971     }
   3972 
   3973     /**
   3974      * Add a listener for attach state changes.
   3975      *
   3976      * This listener will be called whenever this view is attached or detached
   3977      * from a window. Remove the listener using
   3978      * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
   3979      *
   3980      * @param listener Listener to attach
   3981      * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
   3982      */
   3983     public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
   3984         ListenerInfo li = getListenerInfo();
   3985         if (li.mOnAttachStateChangeListeners == null) {
   3986             li.mOnAttachStateChangeListeners
   3987                     = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
   3988         }
   3989         li.mOnAttachStateChangeListeners.add(listener);
   3990     }
   3991 
   3992     /**
   3993      * Remove a listener for attach state changes. The listener will receive no further
   3994      * notification of window attach/detach events.
   3995      *
   3996      * @param listener Listener to remove
   3997      * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
   3998      */
   3999     public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
   4000         ListenerInfo li = mListenerInfo;
   4001         if (li == null || li.mOnAttachStateChangeListeners == null) {
   4002             return;
   4003         }
   4004         li.mOnAttachStateChangeListeners.remove(listener);
   4005     }
   4006 
   4007     /**
   4008      * Returns the focus-change callback registered for this view.
   4009      *
   4010      * @return The callback, or null if one is not registered.
   4011      */
   4012     public OnFocusChangeListener getOnFocusChangeListener() {
   4013         ListenerInfo li = mListenerInfo;
   4014         return li != null ? li.mOnFocusChangeListener : null;
   4015     }
   4016 
   4017     /**
   4018      * Register a callback to be invoked when this view is clicked. If this view is not
   4019      * clickable, it becomes clickable.
   4020      *
   4021      * @param l The callback that will run
   4022      *
   4023      * @see #setClickable(boolean)
   4024      */
   4025     public void setOnClickListener(OnClickListener l) {
   4026         if (!isClickable()) {
   4027             setClickable(true);
   4028         }
   4029         getListenerInfo().mOnClickListener = l;
   4030     }
   4031 
   4032     /**
   4033      * Return whether this view has an attached OnClickListener.  Returns
   4034      * true if there is a listener, false if there is none.
   4035      */
   4036     public boolean hasOnClickListeners() {
   4037         ListenerInfo li = mListenerInfo;
   4038         return (li != null && li.mOnClickListener != null);
   4039     }
   4040 
   4041     /**
   4042      * Register a callback to be invoked when this view is clicked and held. If this view is not
   4043      * long clickable, it becomes long clickable.
   4044      *
   4045      * @param l The callback that will run
   4046      *
   4047      * @see #setLongClickable(boolean)
   4048      */
   4049     public void setOnLongClickListener(OnLongClickListener l) {
   4050         if (!isLongClickable()) {
   4051             setLongClickable(true);
   4052         }
   4053         getListenerInfo().mOnLongClickListener = l;
   4054     }
   4055 
   4056     /**
   4057      * Register a callback to be invoked when the context menu for this view is
   4058      * being built. If this view is not long clickable, it becomes long clickable.
   4059      *
   4060      * @param l The callback that will run
   4061      *
   4062      */
   4063     public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
   4064         if (!isLongClickable()) {
   4065             setLongClickable(true);
   4066         }
   4067         getListenerInfo().mOnCreateContextMenuListener = l;
   4068     }
   4069 
   4070     /**
   4071      * Call this view's OnClickListener, if it is defined.  Performs all normal
   4072      * actions associated with clicking: reporting accessibility event, playing
   4073      * a sound, etc.
   4074      *
   4075      * @return True there was an assigned OnClickListener that was called, false
   4076      *         otherwise is returned.
   4077      */
   4078     public boolean performClick() {
   4079         sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
   4080 
   4081         ListenerInfo li = mListenerInfo;
   4082         if (li != null && li.mOnClickListener != null) {
   4083             playSoundEffect(SoundEffectConstants.CLICK);
   4084             li.mOnClickListener.onClick(this);
   4085             return true;
   4086         }
   4087 
   4088         return false;
   4089     }
   4090 
   4091     /**
   4092      * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
   4093      * this only calls the listener, and does not do any associated clicking
   4094      * actions like reporting an accessibility event.
   4095      *
   4096      * @return True there was an assigned OnClickListener that was called, false
   4097      *         otherwise is returned.
   4098      */
   4099     public boolean callOnClick() {
   4100         ListenerInfo li = mListenerInfo;
   4101         if (li != null && li.mOnClickListener != null) {
   4102             li.mOnClickListener.onClick(this);
   4103             return true;
   4104         }
   4105         return false;
   4106     }
   4107 
   4108     /**
   4109      * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
   4110      * OnLongClickListener did not consume the event.
   4111      *
   4112      * @return True if one of the above receivers consumed the event, false otherwise.
   4113      */
   4114     public boolean performLongClick() {
   4115         sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
   4116 
   4117         boolean handled = false;
   4118         ListenerInfo li = mListenerInfo;
   4119         if (li != null && li.mOnLongClickListener != null) {
   4120             handled = li.mOnLongClickListener.onLongClick(View.this);
   4121         }
   4122         if (!handled) {
   4123             handled = showContextMenu();
   4124         }
   4125         if (handled) {
   4126             performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
   4127         }
   4128         return handled;
   4129     }
   4130 
   4131     /**
   4132      * Performs button-related actions during a touch down event.
   4133      *
   4134      * @param event The event.
   4135      * @return True if the down was consumed.
   4136      *
   4137      * @hide
   4138      */
   4139     protected boolean performButtonActionOnTouchDown(MotionEvent event) {
   4140         if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
   4141             if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
   4142                 return true;
   4143             }
   4144         }
   4145         return false;
   4146     }
   4147 
   4148     /**
   4149      * Bring up the context menu for this view.
   4150      *
   4151      * @return Whether a context menu was displayed.
   4152      */
   4153     public boolean showContextMenu() {
   4154         return getParent().showContextMenuForChild(this);
   4155     }
   4156 
   4157     /**
   4158      * Bring up the context menu for this view, referring to the item under the specified point.
   4159      *
   4160      * @param x The referenced x coordinate.
   4161      * @param y The referenced y coordinate.
   4162      * @param metaState The keyboard modifiers that were pressed.
   4163      * @return Whether a context menu was displayed.
   4164      *
   4165      * @hide
   4166      */
   4167     public boolean showContextMenu(float x, float y, int metaState) {
   4168         return showContextMenu();
   4169     }
   4170 
   4171     /**
   4172      * Start an action mode.
   4173      *
   4174      * @param callback Callback that will control the lifecycle of the action mode
   4175      * @return The new action mode if it is started, null otherwise
   4176      *
   4177      * @see ActionMode
   4178      */
   4179     public ActionMode startActionMode(ActionMode.Callback callback) {
   4180         ViewParent parent = getParent();
   4181         if (parent == null) return null;
   4182         return parent.startActionModeForChild(this, callback);
   4183     }
   4184 
   4185     /**
   4186      * Register a callback to be invoked when a hardware key is pressed in this view.
   4187      * Key presses in software input methods will generally not trigger the methods of
   4188      * this listener.
   4189      * @param l the key listener to attach to this view
   4190      */
   4191     public void setOnKeyListener(OnKeyListener l) {
   4192         getListenerInfo().mOnKeyListener = l;
   4193     }
   4194 
   4195     /**
   4196      * Register a callback to be invoked when a touch event is sent to this view.
   4197      * @param l the touch listener to attach to this view
   4198      */
   4199     public void setOnTouchListener(OnTouchListener l) {
   4200         getListenerInfo().mOnTouchListener = l;
   4201     }
   4202 
   4203     /**
   4204      * Register a callback to be invoked when a generic motion event is sent to this view.
   4205      * @param l the generic motion listener to attach to this view
   4206      */
   4207     public void setOnGenericMotionListener(OnGenericMotionListener l) {
   4208         getListenerInfo().mOnGenericMotionListener = l;
   4209     }
   4210 
   4211     /**
   4212      * Register a callback to be invoked when a hover event is sent to this view.
   4213      * @param l the hover listener to attach to this view
   4214      */
   4215     public void setOnHoverListener(OnHoverListener l) {
   4216         getListenerInfo().mOnHoverListener = l;
   4217     }
   4218 
   4219     /**
   4220      * Register a drag event listener callback object for this View. The parameter is
   4221      * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
   4222      * View, the system calls the
   4223      * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
   4224      * @param l An implementation of {@link android.view.View.OnDragListener}.
   4225      */
   4226     public void setOnDragListener(OnDragListener l) {
   4227         getListenerInfo().mOnDragListener = l;
   4228     }
   4229 
   4230     /**
   4231      * Give this view focus. This will cause
   4232      * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
   4233      *
   4234      * Note: this does not check whether this {@link View} should get focus, it just
   4235      * gives it focus no matter what.  It should only be called internally by framework
   4236      * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
   4237      *
   4238      * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
   4239      *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
   4240      *        focus moved when requestFocus() is called. It may not always
   4241      *        apply, in which case use the default View.FOCUS_DOWN.
   4242      * @param previouslyFocusedRect The rectangle of the view that had focus
   4243      *        prior in this View's coordinate system.
   4244      */
   4245     void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
   4246         if (DBG) {
   4247             System.out.println(this + " requestFocus()");
   4248         }
   4249 
   4250         if ((mPrivateFlags & FOCUSED) == 0) {
   4251             mPrivateFlags |= FOCUSED;
   4252 
   4253             if (mParent != null) {
   4254                 mParent.requestChildFocus(this, this);
   4255             }
   4256 
   4257             onFocusChanged(true, direction, previouslyFocusedRect);
   4258             refreshDrawableState();
   4259 
   4260             if (AccessibilityManager.getInstance(mContext).isEnabled()) {
   4261                 notifyAccessibilityStateChanged();
   4262             }
   4263         }
   4264     }
   4265 
   4266     /**
   4267      * Request that a rectangle of this view be visible on the screen,
   4268      * scrolling if necessary just enough.
   4269      *
   4270      * <p>A View should call this if it maintains some notion of which part
   4271      * of its content is interesting.  For example, a text editing view
   4272      * should call this when its cursor moves.
   4273      *
   4274      * @param rectangle The rectangle.
   4275      * @return Whether any parent scrolled.
   4276      */
   4277     public boolean requestRectangleOnScreen(Rect rectangle) {
   4278         return requestRectangleOnScreen(rectangle, false);
   4279     }
   4280 
   4281     /**
   4282      * Request that a rectangle of this view be visible on the screen,
   4283      * scrolling if necessary just enough.
   4284      *
   4285      * <p>A View should call this if it maintains some notion of which part
   4286      * of its content is interesting.  For example, a text editing view
   4287      * should call this when its cursor moves.
   4288      *
   4289      * <p>When <code>immediate</code> is set to true, scrolling will not be
   4290      * animated.
   4291      *
   4292      * @param rectangle The rectangle.
   4293      * @param immediate True to forbid animated scrolling, false otherwise
   4294      * @return Whether any parent scrolled.
   4295      */
   4296     public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
   4297         View child = this;
   4298         ViewParent parent = mParent;
   4299         boolean scrolled = false;
   4300         while (parent != null) {
   4301             scrolled |= parent.requestChildRectangleOnScreen(child,
   4302                     rectangle, immediate);
   4303 
   4304             // offset rect so next call has the rectangle in the
   4305             // coordinate system of its direct child.
   4306             rectangle.offset(child.getLeft(), child.getTop());
   4307             rectangle.offset(-child.getScrollX(), -child.getScrollY());
   4308 
   4309             if (!(parent instanceof View)) {
   4310                 break;
   4311             }
   4312 
   4313             child = (View) parent;
   4314             parent = child.getParent();
   4315         }
   4316         return scrolled;
   4317     }
   4318 
   4319     /**
   4320      * Called when this view wants to give up focus. If focus is cleared
   4321      * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
   4322      * <p>
   4323      * <strong>Note:</strong> When a View clears focus the framework is trying
   4324      * to give focus to the first focusable View from the top. Hence, if this
   4325      * View is the first from the top that can take focus, then all callbacks
   4326      * related to clearing focus will be invoked after wich the framework will
   4327      * give focus to this view.
   4328      * </p>
   4329      */
   4330     public void clearFocus() {
   4331         if (DBG) {
   4332             System.out.println(this + " clearFocus()");
   4333         }
   4334 
   4335         if ((mPrivateFlags & FOCUSED) != 0) {
   4336             mPrivateFlags &= ~FOCUSED;
   4337 
   4338             if (mParent != null) {
   4339                 mParent.clearChildFocus(this);
   4340             }
   4341 
   4342             onFocusChanged(false, 0, null);
   4343 
   4344             refreshDrawableState();
   4345 
   4346             ensureInputFocusOnFirstFocusable();
   4347 
   4348             if (AccessibilityManager.getInstance(mContext).isEnabled()) {
   4349                 notifyAccessibilityStateChanged();
   4350             }
   4351         }
   4352     }
   4353 
   4354     void ensureInputFocusOnFirstFocusable() {
   4355         View root = getRootView();
   4356         if (root != null) {
   4357             root.requestFocus();
   4358         }
   4359     }
   4360 
   4361     /**
   4362      * Called internally by the view system when a new view is getting focus.
   4363      * This is what clears the old focus.
   4364      */
   4365     void unFocus() {
   4366         if (DBG) {
   4367             System.out.println(this + " unFocus()");
   4368         }
   4369 
   4370         if ((mPrivateFlags & FOCUSED) != 0) {
   4371             mPrivateFlags &= ~FOCUSED;
   4372 
   4373             onFocusChanged(false, 0, null);
   4374             refreshDrawableState();
   4375 
   4376             if (AccessibilityManager.getInstance(mContext).isEnabled()) {
   4377                 notifyAccessibilityStateChanged();
   4378             }
   4379         }
   4380     }
   4381 
   4382     /**
   4383      * Returns true if this view has focus iteself, or is the ancestor of the
   4384      * view that has focus.
   4385      *
   4386      * @return True if this view has or contains focus, false otherwise.
   4387      */
   4388     @ViewDebug.ExportedProperty(category = "focus")
   4389     public boolean hasFocus() {
   4390         return (mPrivateFlags & FOCUSED) != 0;
   4391     }
   4392 
   4393     /**
   4394      * Returns true if this view is focusable or if it contains a reachable View
   4395      * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
   4396      * is a View whose parents do not block descendants focus.
   4397      *
   4398      * Only {@link #VISIBLE} views are considered focusable.
   4399      *
   4400      * @return True if the view is focusable or if the view contains a focusable
   4401      *         View, false otherwise.
   4402      *
   4403      * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
   4404      */
   4405     public boolean hasFocusable() {
   4406         return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
   4407     }
   4408 
   4409     /**
   4410      * Called by the view system when the focus state of this view changes.
   4411      * When the focus change event is caused by directional navigation, direction
   4412      * and previouslyFocusedRect provide insight into where the focus is coming from.
   4413      * When overriding, be sure to call up through to the super class so that
   4414      * the standard focus handling will occur.
   4415      *
   4416      * @param gainFocus True if the View has focus; false otherwise.
   4417      * @param direction The direction focus has moved when requestFocus()
   4418      *                  is called to give this view focus. Values are
   4419      *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
   4420      *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
   4421      *                  It may not always apply, in which case use the default.
   4422      * @param previouslyFocusedRect The rectangle, in this view's coordinate
   4423      *        system, of the previously focused view.  If applicable, this will be
   4424      *        passed in as finer grained information about where the focus is coming
   4425      *        from (in addition to direction).  Will be <code>null</code> otherwise.
   4426      */
   4427     protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
   4428         if (gainFocus) {
   4429             if (AccessibilityManager.getInstance(mContext).isEnabled()) {
   4430                 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
   4431             }
   4432         }
   4433 
   4434         InputMethodManager imm = InputMethodManager.peekInstance();
   4435         if (!gainFocus) {
   4436             if (isPressed()) {
   4437                 setPressed(false);
   4438             }
   4439             if (imm != null && mAttachInfo != null
   4440                     && mAttachInfo.mHasWindowFocus) {
   4441                 imm.focusOut(this);
   4442             }
   4443             onFocusLost();
   4444         } else if (imm != null && mAttachInfo != null
   4445                 && mAttachInfo.mHasWindowFocus) {
   4446             imm.focusIn(this);
   4447         }
   4448 
   4449         invalidate(true);
   4450         ListenerInfo li = mListenerInfo;
   4451         if (li != null && li.mOnFocusChangeListener != null) {
   4452             li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
   4453         }
   4454 
   4455         if (mAttachInfo != null) {
   4456             mAttachInfo.mKeyDispatchState.reset(this);
   4457         }
   4458     }
   4459 
   4460     /**
   4461      * Sends an accessibility event of the given type. If accessiiblity is
   4462      * not enabled this method has no effect. The default implementation calls
   4463      * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
   4464      * to populate information about the event source (this View), then calls
   4465      * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
   4466      * populate the text content of the event source including its descendants,
   4467      * and last calls
   4468      * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
   4469      * on its parent to resuest sending of the event to interested parties.
   4470      * <p>
   4471      * If an {@link AccessibilityDelegate} has been specified via calling
   4472      * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
   4473      * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
   4474      * responsible for handling this call.
   4475      * </p>
   4476      *
   4477      * @param eventType The type of the event to send, as defined by several types from
   4478      * {@link android.view.accessibility.AccessibilityEvent}, such as
   4479      * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
   4480      * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
   4481      *
   4482      * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
   4483      * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
   4484      * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
   4485      * @see AccessibilityDelegate
   4486      */
   4487     public void sendAccessibilityEvent(int eventType) {
   4488         if (mAccessibilityDelegate != null) {
   4489             mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
   4490         } else {
   4491             sendAccessibilityEventInternal(eventType);
   4492         }
   4493     }
   4494 
   4495     /**
   4496      * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
   4497      * {@link AccessibilityEvent} to make an announcement which is related to some
   4498      * sort of a context change for which none of the events representing UI transitions
   4499      * is a good fit. For example, announcing a new page in a book. If accessibility
   4500      * is not enabled this method does nothing.
   4501      *
   4502      * @param text The announcement text.
   4503      */
   4504     public void announceForAccessibility(CharSequence text) {
   4505         if (AccessibilityManager.getInstance(mContext).isEnabled()) {
   4506             AccessibilityEvent event = AccessibilityEvent.obtain(
   4507                     AccessibilityEvent.TYPE_ANNOUNCEMENT);
   4508             event.getText().add(text);
   4509             sendAccessibilityEventUnchecked(event);
   4510         }
   4511     }
   4512 
   4513     /**
   4514      * @see #sendAccessibilityEvent(int)
   4515      *
   4516      * Note: Called from the default {@link AccessibilityDelegate}.
   4517      */
   4518     void sendAccessibilityEventInternal(int eventType) {
   4519         if (AccessibilityManager.getInstance(mContext).isEnabled()) {
   4520             sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
   4521         }
   4522     }
   4523 
   4524     /**
   4525      * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
   4526      * takes as an argument an empty {@link AccessibilityEvent} and does not
   4527      * perform a check whether accessibility is enabled.
   4528      * <p>
   4529      * If an {@link AccessibilityDelegate} has been specified via calling
   4530      * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
   4531      * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
   4532      * is responsible for handling this call.
   4533      * </p>
   4534      *
   4535      * @param event The event to send.
   4536      *
   4537      * @see #sendAccessibilityEvent(int)
   4538      */
   4539     public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
   4540         if (mAccessibilityDelegate != null) {
   4541             mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
   4542         } else {
   4543             sendAccessibilityEventUncheckedInternal(event);
   4544         }
   4545     }
   4546 
   4547     /**
   4548      * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
   4549      *
   4550      * Note: Called from the default {@link AccessibilityDelegate}.
   4551      */
   4552     void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
   4553         if (!isShown()) {
   4554             return;
   4555         }
   4556         onInitializeAccessibilityEvent(event);
   4557         // Only a subset of accessibility events populates text content.
   4558         if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
   4559             dispatchPopulateAccessibilityEvent(event);
   4560         }
   4561         // In the beginning we called #isShown(), so we know that getParent() is not null.
   4562         getParent().requestSendAccessibilityEvent(this, event);
   4563     }
   4564 
   4565     /**
   4566      * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
   4567      * to its children for adding their text content to the event. Note that the
   4568      * event text is populated in a separate dispatch path since we add to the
   4569      * event not only the text of the source but also the text of all its descendants.
   4570      * A typical implementation will call
   4571      * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
   4572      * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
   4573      * on each child. Override this method if custom population of the event text
   4574      * content is required.
   4575      * <p>
   4576      * If an {@link AccessibilityDelegate} has been specified via calling
   4577      * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
   4578      * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
   4579      * is responsible for handling this call.
   4580      * </p>
   4581      * <p>
   4582      * <em>Note:</em> Accessibility events of certain types are not dispatched for
   4583      * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
   4584      * </p>
   4585      *
   4586      * @param event The event.
   4587      *
   4588      * @return True if the event population was completed.
   4589      */
   4590     public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
   4591         if (mAccessibilityDelegate != null) {
   4592             return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
   4593         } else {
   4594             return dispatchPopulateAccessibilityEventInternal(event);
   4595         }
   4596     }
   4597 
   4598     /**
   4599      * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
   4600      *
   4601      * Note: Called from the default {@link AccessibilityDelegate}.
   4602      */
   4603     boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
   4604         onPopulateAccessibilityEvent(event);
   4605         return false;
   4606     }
   4607 
   4608     /**
   4609      * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
   4610      * giving a chance to this View to populate the accessibility event with its
   4611      * text content. While this method is free to modify event
   4612      * attributes other than text content, doing so should normally be performed in
   4613      * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
   4614      * <p>
   4615      * Example: Adding formatted date string to an accessibility event in addition
   4616      *          to the text added by the super implementation:
   4617      * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
   4618      *     super.onPopulateAccessibilityEvent(event);
   4619      *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
   4620      *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
   4621      *         mCurrentDate.getTimeInMillis(), flags);
   4622      *     event.getText().add(selectedDateUtterance);
   4623      * }</pre>
   4624      * <p>
   4625      * If an {@link AccessibilityDelegate} has been specified via calling
   4626      * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
   4627      * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
   4628      * is responsible for handling this call.
   4629      * </p>
   4630      * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
   4631      * information to the event, in case the default implementation has basic information to add.
   4632      * </p>
   4633      *
   4634      * @param event The accessibility event which to populate.
   4635      *
   4636      * @see #sendAccessibilityEvent(int)
   4637      * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
   4638      */
   4639     public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
   4640         if (mAccessibilityDelegate != null) {
   4641             mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
   4642         } else {
   4643             onPopulateAccessibilityEventInternal(event);
   4644         }
   4645     }
   4646 
   4647     /**
   4648      * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
   4649      *
   4650      * Note: Called from the default {@link AccessibilityDelegate}.
   4651      */
   4652     void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
   4653 
   4654     }
   4655 
   4656     /**
   4657      * Initializes an {@link AccessibilityEvent} with information about
   4658      * this View which is the event source. In other words, the source of
   4659      * an accessibility event is the view whose state change triggered firing
   4660      * the event.
   4661      * <p>
   4662      * Example: Setting the password property of an event in addition
   4663      *          to properties set by the super implementation:
   4664      * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
   4665      *     super.onInitializeAccessibilityEvent(event);
   4666      *     event.setPassword(true);
   4667      * }</pre>
   4668      * <p>
   4669      * If an {@link AccessibilityDelegate} has been specified via calling
   4670      * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
   4671      * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
   4672      * is responsible for handling this call.
   4673      * </p>
   4674      * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
   4675      * information to the event, in case the default implementation has basic information to add.
   4676      * </p>
   4677      * @param event The event to initialize.
   4678      *
   4679      * @see #sendAccessibilityEvent(int)
   4680      * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
   4681      */
   4682     public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
   4683         if (mAccessibilityDelegate != null) {
   4684             mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
   4685         } else {
   4686             onInitializeAccessibilityEventInternal(event);
   4687         }
   4688     }
   4689 
   4690     /**
   4691      * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
   4692      *
   4693      * Note: Called from the default {@link AccessibilityDelegate}.
   4694      */
   4695     void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
   4696         event.setSource(this);
   4697         event.setClassName(View.class.getName());
   4698         event.setPackageName(getContext().getPackageName());
   4699         event.setEnabled(isEnabled());
   4700         event.setContentDescription(mContentDescription);
   4701 
   4702         if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
   4703             ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
   4704             getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
   4705                     FOCUSABLES_ALL);
   4706             event.setItemCount(focusablesTempList.size());
   4707             event.setCurrentItemIndex(focusablesTempList.indexOf(this));
   4708             focusablesTempList.clear();
   4709         }
   4710     }
   4711 
   4712     /**
   4713      * Returns an {@link AccessibilityNodeInfo} representing this view from the
   4714      * point of view of an {@link android.accessibilityservice.AccessibilityService}.
   4715      * This method is responsible for obtaining an accessibility node info from a
   4716      * pool of reusable instances and calling
   4717      * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
   4718      * initialize the former.
   4719      * <p>
   4720      * Note: The client is responsible for recycling the obtained instance by calling
   4721      *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
   4722      * </p>
   4723      *
   4724      * @return A populated {@link AccessibilityNodeInfo}.
   4725      *
   4726      * @see AccessibilityNodeInfo
   4727      */
   4728     public AccessibilityNodeInfo createAccessibilityNodeInfo() {
   4729         AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
   4730         if (provider != null) {
   4731             return provider.createAccessibilityNodeInfo(View.NO_ID);
   4732         } else {
   4733             AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
   4734             onInitializeAccessibilityNodeInfo(info);
   4735             return info;
   4736         }
   4737     }
   4738 
   4739     /**
   4740      * Initializes an {@link AccessibilityNodeInfo} with information about this view.
   4741      * The base implementation sets:
   4742      * <ul>
   4743      *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
   4744      *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
   4745      *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
   4746      *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
   4747      *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
   4748      *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
   4749      *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
   4750      *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
   4751      *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
   4752      *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
   4753      *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
   4754      *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
   4755      * </ul>
   4756      * <p>
   4757      * Subclasses should override this method, call the super implementation,
   4758      * and set additional attributes.
   4759      * </p>
   4760      * <p>
   4761      * If an {@link AccessibilityDelegate} has been specified via calling
   4762      * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
   4763      * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
   4764      * is responsible for handling this call.
   4765      * </p>
   4766      *
   4767      * @param info The instance to initialize.
   4768      */
   4769     public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
   4770         if (mAccessibilityDelegate != null) {
   4771             mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
   4772         } else {
   4773             onInitializeAccessibilityNodeInfoInternal(info);
   4774         }
   4775     }
   4776 
   4777     /**
   4778      * Gets the location of this view in screen coordintates.
   4779      *
   4780      * @param outRect The output location
   4781      */
   4782     private void getBoundsOnScreen(Rect outRect) {
   4783         if (mAttachInfo == null) {
   4784             return;
   4785         }
   4786 
   4787         RectF position = mAttachInfo.mTmpTransformRect;
   4788         position.set(0, 0, mRight - mLeft, mBottom - mTop);
   4789 
   4790         if (!hasIdentityMatrix()) {
   4791             getMatrix().mapRect(position);
   4792         }
   4793 
   4794         position.offset(mLeft, mTop);
   4795 
   4796         ViewParent parent = mParent;
   4797         while (parent instanceof View) {
   4798             View parentView = (View) parent;
   4799 
   4800             position.offset(-parentView.mScrollX, -parentView.mScrollY);
   4801 
   4802             if (!parentView.hasIdentityMatrix()) {
   4803                 parentView.getMatrix().mapRect(position);
   4804             }
   4805 
   4806             position.offset(parentView.mLeft, parentView.mTop);
   4807 
   4808             parent = parentView.mParent;
   4809         }
   4810 
   4811         if (parent instanceof ViewRootImpl) {
   4812             ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
   4813             position.offset(0, -viewRootImpl.mCurScrollY);
   4814         }
   4815 
   4816         position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
   4817 
   4818         outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
   4819                 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
   4820     }
   4821 
   4822     /**
   4823      * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
   4824      *
   4825      * Note: Called from the default {@link AccessibilityDelegate}.
   4826      */
   4827     void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
   4828         Rect bounds = mAttachInfo.mTmpInvalRect;
   4829         getDrawingRect(bounds);
   4830         info.setBoundsInParent(bounds);
   4831 
   4832         getBoundsOnScreen(bounds);
   4833         info.setBoundsInScreen(bounds);
   4834 
   4835         ViewParent parent = getParentForAccessibility();
   4836         if (parent instanceof View) {
   4837             info.setParent((View) parent);
   4838         }
   4839 
   4840         info.setVisibleToUser(isVisibleToUser());
   4841 
   4842         info.setPackageName(mContext.getPackageName());
   4843         info.setClassName(View.class.getName());
   4844         info.setContentDescription(getContentDescription());
   4845 
   4846         info.setEnabled(isEnabled());
   4847         info.setClickable(isClickable());
   4848         info.setFocusable(isFocusable());
   4849         info.setFocused(isFocused());
   4850         info.setAccessibilityFocused(isAccessibilityFocused());
   4851         info.setSelected(isSelected());
   4852         info.setLongClickable(isLongClickable());
   4853 
   4854         // TODO: These make sense only if we are in an AdapterView but all
   4855         // views can be selected. Maybe from accessiiblity perspective
   4856         // we should report as selectable view in an AdapterView.
   4857         info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
   4858         info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
   4859 
   4860         if (isFocusable()) {
   4861             if (isFocused()) {
   4862                 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
   4863             } else {
   4864                 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
   4865             }
   4866         }
   4867 
   4868         if (!isAccessibilityFocused()) {
   4869             final int mode = getAccessibilityFocusable();
   4870             if (mode == ACCESSIBILITY_FOCUSABLE_YES || mode == ACCESSIBILITY_FOCUSABLE_AUTO) {
   4871                 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
   4872             }
   4873         } else {
   4874             info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
   4875         }
   4876 
   4877         if (isClickable() && isEnabled()) {
   4878             info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
   4879         }
   4880 
   4881         if (isLongClickable() && isEnabled()) {
   4882             info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
   4883         }
   4884 
   4885         if (mContentDescription != null && mContentDescription.length() > 0) {
   4886             info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
   4887             info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
   4888             info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
   4889                     | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
   4890                     | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
   4891         }
   4892     }
   4893 
   4894     /**
   4895      * Returns the delta between the actual and last reported window left.
   4896      *
   4897      * @hide
   4898      */
   4899     public int getActualAndReportedWindowLeftDelta() {
   4900         if (mAttachInfo != null) {
   4901             return mAttachInfo.mActualWindowLeft - mAttachInfo.mWindowLeft;
   4902         }
   4903         return 0;
   4904     }
   4905 
   4906     /**
   4907      * Returns the delta between the actual and last reported window top.
   4908      *
   4909      * @hide
   4910      */
   4911     public int getActualAndReportedWindowTopDelta() {
   4912         if (mAttachInfo != null) {
   4913             return mAttachInfo.mActualWindowTop - mAttachInfo.mWindowTop;
   4914         }
   4915         return 0;
   4916     }
   4917 
   4918     /**
   4919      * Computes whether this view is visible to the user. Such a view is
   4920      * attached, visible, all its predecessors are visible, it is not clipped
   4921      * entirely by its predecessors, and has an alpha greater than zero.
   4922      *
   4923      * @return Whether the view is visible on the screen.
   4924      *
   4925      * @hide
   4926      */
   4927     protected boolean isVisibleToUser() {
   4928         return isVisibleToUser(null);
   4929     }
   4930 
   4931     /**
   4932      * Computes whether the given portion of this view is visible to the user. Such a view is
   4933      * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
   4934      * the specified portion is not clipped entirely by its predecessors.
   4935      *
   4936      * @param boundInView the portion of the view to test; coordinates should be relative; may be
   4937      *                    <code>null</code>, and the entire view will be tested in this case.
   4938      *                    When <code>true</code> is returned by the function, the actual visible
   4939      *                    region will be stored in this parameter; that is, if boundInView is fully
   4940      *                    contained within the view, no modification will be made, otherwise regions
   4941      *                    outside of the visible area of the view will be clipped.
   4942      *
   4943      * @return Whether the specified portion of the view is visible on the screen.
   4944      *
   4945      * @hide
   4946      */
   4947     protected boolean isVisibleToUser(Rect boundInView) {
   4948         Rect visibleRect = mAttachInfo.mTmpInvalRect;
   4949         Point offset = mAttachInfo.mPoint;
   4950         // The first two checks are made also made by isShown() which
   4951         // however traverses the tree up to the parent to catch that.
   4952         // Therefore, we do some fail fast check to minimize the up
   4953         // tree traversal.
   4954         boolean isVisible = mAttachInfo != null
   4955             && mAttachInfo.mWindowVisibility == View.VISIBLE
   4956             && getAlpha() > 0
   4957             && isShown()
   4958             && getGlobalVisibleRect(visibleRect, offset);
   4959             if (isVisible && boundInView != null) {
   4960                 visibleRect.offset(-offset.x, -offset.y);
   4961                 isVisible &= boundInView.intersect(visibleRect);
   4962             }
   4963             return isVisible;
   4964     }
   4965 
   4966     /**
   4967      * Sets a delegate for implementing accessibility support via compositon as
   4968      * opposed to inheritance. The delegate's primary use is for implementing
   4969      * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
   4970      *
   4971      * @param delegate The delegate instance.
   4972      *
   4973      * @see AccessibilityDelegate
   4974      */
   4975     public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
   4976         mAccessibilityDelegate = delegate;
   4977     }
   4978 
   4979     /**
   4980      * Gets the provider for managing a virtual view hierarchy rooted at this View
   4981      * and reported to {@link android.accessibilityservice.AccessibilityService}s
   4982      * that explore the window content.
   4983      * <p>
   4984      * If this method returns an instance, this instance is responsible for managing
   4985      * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
   4986      * View including the one representing the View itself. Similarly the returned
   4987      * instance is responsible for performing accessibility actions on any virtual
   4988      * view or the root view itself.
   4989      * </p>
   4990      * <p>
   4991      * If an {@link AccessibilityDelegate} has been specified via calling
   4992      * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
   4993      * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
   4994      * is responsible for handling this call.
   4995      * </p>
   4996      *
   4997      * @return The provider.
   4998      *
   4999      * @see AccessibilityNodeProvider
   5000      */
   5001     public AccessibilityNodeProvider getAccessibilityNodeProvider() {
   5002         if (mAccessibilityDelegate != null) {
   5003             return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
   5004         } else {
   5005             return null;
   5006         }
   5007     }
   5008 
   5009     /**
   5010      * Gets the unique identifier of this view on the screen for accessibility purposes.
   5011      * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
   5012      *
   5013      * @return The view accessibility id.
   5014      *
   5015      * @hide
   5016      */
   5017     public int getAccessibilityViewId() {
   5018         if (mAccessibilityViewId == NO_ID) {
   5019             mAccessibilityViewId = sNextAccessibilityViewId++;
   5020         }
   5021         return mAccessibilityViewId;
   5022     }
   5023 
   5024     /**
   5025      * Gets the unique identifier of the window in which this View reseides.
   5026      *
   5027      * @return The window accessibility id.
   5028      *
   5029      * @hide
   5030      */
   5031     public int getAccessibilityWindowId() {
   5032         return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
   5033     }
   5034 
   5035     /**
   5036      * Gets the {@link View} description. It briefly describes the view and is
   5037      * primarily used for accessibility support. Set this property to enable
   5038      * better accessibility support for your application. This is especially
   5039      * true for views that do not have textual representation (For example,
   5040      * ImageButton).
   5041      *
   5042      * @return The content description.
   5043      *
   5044      * @attr ref android.R.styleable#View_contentDescription
   5045      */
   5046     @ViewDebug.ExportedProperty(category = "accessibility")
   5047     public CharSequence getContentDescription() {
   5048         return mContentDescription;
   5049     }
   5050 
   5051     /**
   5052      * Sets the {@link View} description. It briefly describes the view and is
   5053      * primarily used for accessibility support. Set this property to enable
   5054      * better accessibility support for your application. This is especially
   5055      * true for views that do not have textual representation (For example,
   5056      * ImageButton).
   5057      *
   5058      * @param contentDescription The content description.
   5059      *
   5060      * @attr ref android.R.styleable#View_contentDescription
   5061      */
   5062     @RemotableViewMethod
   5063     public void setContentDescription(CharSequence contentDescription) {
   5064         mContentDescription = contentDescription;
   5065         final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
   5066         if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
   5067              setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
   5068         }
   5069     }
   5070 
   5071     /**
   5072      * Invoked whenever this view loses focus, either by losing window focus or by losing
   5073      * focus within its window. This method can be used to clear any state tied to the
   5074      * focus. For instance, if a button is held pressed with the trackball and the window
   5075      * loses focus, this method can be used to cancel the press.
   5076      *
   5077      * Subclasses of View overriding this method should always call super.onFocusLost().
   5078      *
   5079      * @see #onFocusChanged(boolean, int, android.graphics.Rect)
   5080      * @see #onWindowFocusChanged(boolean)
   5081      *
   5082      * @hide pending API council approval
   5083      */
   5084     protected void onFocusLost() {
   5085         resetPressedState();
   5086     }
   5087 
   5088     private void resetPressedState() {
   5089         if ((mViewFlags & ENABLED_MASK) == DISABLED) {
   5090             return;
   5091         }
   5092 
   5093         if (isPressed()) {
   5094             setPressed(false);
   5095 
   5096             if (!mHasPerformedLongPress) {
   5097                 removeLongPressCallback();
   5098             }
   5099         }
   5100     }
   5101 
   5102     /**
   5103      * Returns true if this view has focus
   5104      *
   5105      * @return True if this view has focus, false otherwise.
   5106      */
   5107     @ViewDebug.ExportedProperty(category = "focus")
   5108     public boolean isFocused() {
   5109         return (mPrivateFlags & FOCUSED) != 0;
   5110     }
   5111 
   5112     /**
   5113      * Find the view in the hierarchy rooted at this view that currently has
   5114      * focus.
   5115      *
   5116      * @return The view that currently has focus, or null if no focused view can
   5117      *         be found.
   5118      */
   5119     public View findFocus() {
   5120         return (mPrivateFlags & FOCUSED) != 0 ? this : null;
   5121     }
   5122 
   5123     /**
   5124      * Indicates whether this view is one of the set of scrollable containers in
   5125      * its window.
   5126      *
   5127      * @return whether this view is one of the set of scrollable containers in
   5128      * its window
   5129      *
   5130      * @attr ref android.R.styleable#View_isScrollContainer
   5131      */
   5132     public boolean isScrollContainer() {
   5133         return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
   5134     }
   5135 
   5136     /**
   5137      * Change whether this view is one of the set of scrollable containers in
   5138      * its window.  This will be used to determine whether the window can
   5139      * resize or must pan when a soft input area is open -- scrollable
   5140      * containers allow the window to use resize mode since the container
   5141      * will appropriately shrink.
   5142      *
   5143      * @attr ref android.R.styleable#View_isScrollContainer
   5144      */
   5145     public void setScrollContainer(boolean isScrollContainer) {
   5146         if (isScrollContainer) {
   5147             if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
   5148                 mAttachInfo.mScrollContainers.add(this);
   5149                 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
   5150             }
   5151             mPrivateFlags |= SCROLL_CONTAINER;
   5152         } else {
   5153             if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
   5154                 mAttachInfo.mScrollContainers.remove(this);
   5155             }
   5156             mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
   5157         }
   5158     }
   5159 
   5160     /**
   5161      * Returns the quality of the drawing cache.
   5162      *
   5163      * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
   5164      *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
   5165      *
   5166      * @see #setDrawingCacheQuality(int)
   5167      * @see #setDrawingCacheEnabled(boolean)
   5168      * @see #isDrawingCacheEnabled()
   5169      *
   5170      * @attr ref android.R.styleable#View_drawingCacheQuality
   5171      */
   5172     public int getDrawingCacheQuality() {
   5173         return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
   5174     }
   5175 
   5176     /**
   5177      * Set the drawing cache quality of this view. This value is used only when the
   5178      * drawing cache is enabled
   5179      *
   5180      * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
   5181      *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
   5182      *
   5183      * @see #getDrawingCacheQuality()
   5184      * @see #setDrawingCacheEnabled(boolean)
   5185      * @see #isDrawingCacheEnabled()
   5186      *
   5187      * @attr ref android.R.styleable#View_drawingCacheQuality
   5188      */
   5189     public void setDrawingCacheQuality(int quality) {
   5190         setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
   5191     }
   5192 
   5193     /**
   5194      * Returns whether the screen should remain on, corresponding to the current
   5195      * value of {@link #KEEP_SCREEN_ON}.
   5196      *
   5197      * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
   5198      *
   5199      * @see #setKeepScreenOn(boolean)
   5200      *
   5201      * @attr ref android.R.styleable#View_keepScreenOn
   5202      */
   5203     public boolean getKeepScreenOn() {
   5204         return (mViewFlags & KEEP_SCREEN_ON) != 0;
   5205     }
   5206 
   5207     /**
   5208      * Controls whether the screen should remain on, modifying the
   5209      * value of {@link #KEEP_SCREEN_ON}.
   5210      *
   5211      * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
   5212      *
   5213      * @see #getKeepScreenOn()
   5214      *
   5215      * @attr ref android.R.styleable#View_keepScreenOn
   5216      */
   5217     public void setKeepScreenOn(boolean keepScreenOn) {
   5218         setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
   5219     }
   5220 
   5221     /**
   5222      * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
   5223      * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
   5224      *
   5225      * @attr ref android.R.styleable#View_nextFocusLeft
   5226      */
   5227     public int getNextFocusLeftId() {
   5228         return mNextFocusLeftId;
   5229     }
   5230 
   5231     /**
   5232      * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
   5233      * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
   5234      * decide automatically.
   5235      *
   5236      * @attr ref android.R.styleable#View_nextFocusLeft
   5237      */
   5238     public void setNextFocusLeftId(int nextFocusLeftId) {
   5239         mNextFocusLeftId = nextFocusLeftId;
   5240     }
   5241 
   5242     /**
   5243      * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
   5244      * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
   5245      *
   5246      * @attr ref android.R.styleable#View_nextFocusRight
   5247      */
   5248     public int getNextFocusRightId() {
   5249         return mNextFocusRightId;
   5250     }
   5251 
   5252     /**
   5253      * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
   5254      * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
   5255      * decide automatically.
   5256      *
   5257      * @attr ref android.R.styleable#View_nextFocusRight
   5258      */
   5259     public void setNextFocusRightId(int nextFocusRightId) {
   5260         mNextFocusRightId = nextFocusRightId;
   5261     }
   5262 
   5263     /**
   5264      * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
   5265      * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
   5266      *
   5267      * @attr ref android.R.styleable#View_nextFocusUp
   5268      */
   5269     public int getNextFocusUpId() {
   5270         return mNextFocusUpId;
   5271     }
   5272 
   5273     /**
   5274      * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
   5275      * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
   5276      * decide automatically.
   5277      *
   5278      * @attr ref android.R.styleable#View_nextFocusUp
   5279      */
   5280     public void setNextFocusUpId(int nextFocusUpId) {
   5281         mNextFocusUpId = nextFocusUpId;
   5282     }
   5283 
   5284     /**
   5285      * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
   5286      * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
   5287      *
   5288      * @attr ref android.R.styleable#View_nextFocusDown
   5289      */
   5290     public int getNextFocusDownId() {
   5291         return mNextFocusDownId;
   5292     }
   5293 
   5294     /**
   5295      * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
   5296      * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
   5297      * decide automatically.
   5298      *
   5299      * @attr ref android.R.styleable#View_nextFocusDown
   5300      */
   5301     public void setNextFocusDownId(int nextFocusDownId) {
   5302         mNextFocusDownId = nextFocusDownId;
   5303     }
   5304 
   5305     /**
   5306      * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
   5307      * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
   5308      *
   5309      * @attr ref android.R.styleable#View_nextFocusForward
   5310      */
   5311     public int getNextFocusForwardId() {
   5312         return mNextFocusForwardId;
   5313     }
   5314 
   5315     /**
   5316      * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
   5317      * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
   5318      * decide automatically.
   5319      *
   5320      * @attr ref android.R.styleable#View_nextFocusForward
   5321      */
   5322     public void setNextFocusForwardId(int nextFocusForwardId) {
   5323         mNextFocusForwardId = nextFocusForwardId;
   5324     }
   5325 
   5326     /**
   5327      * Returns the visibility of this view and all of its ancestors
   5328      *
   5329      * @return True if this view and all of its ancestors are {@link #VISIBLE}
   5330      */
   5331     public boolean isShown() {
   5332         View current = this;
   5333         //noinspection ConstantConditions
   5334         do {
   5335             if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
   5336                 return false;
   5337             }
   5338             ViewParent parent = current.mParent;
   5339             if (parent == null) {
   5340                 return false; // We are not attached to the view root
   5341             }
   5342             if (!(parent instanceof View)) {
   5343                 return true;
   5344             }
   5345             current = (View) parent;
   5346         } while (current != null);
   5347 
   5348         return false;
   5349     }
   5350 
   5351     /**
   5352      * Called by the view hierarchy when the content insets for a window have
   5353      * changed, to allow it to adjust its content to fit within those windows.
   5354      * The content insets tell you the space that the status bar, input method,
   5355      * and other system windows infringe on the application's window.
   5356      *
   5357      * <p>You do not normally need to deal with this function, since the default
   5358      * window decoration given to applications takes care of applying it to the
   5359      * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
   5360      * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
   5361      * and your content can be placed under those system elements.  You can then
   5362      * use this method within your view hierarchy if you have parts of your UI
   5363      * which you would like to ensure are not being covered.
   5364      *
   5365      * <p>The default implementation of this method simply applies the content
   5366      * inset's to the view's padding, consuming that content (modifying the
   5367      * insets to be 0), and returning true.  This behavior is off by default, but can
   5368      * be enabled through {@link #setFitsSystemWindows(boolean)}.
   5369      *
   5370      * <p>This function's traversal down the hierarchy is depth-first.  The same content
   5371      * insets object is propagated down the hierarchy, so any changes made to it will
   5372      * be seen by all following views (including potentially ones above in
   5373      * the hierarchy since this is a depth-first traversal).  The first view
   5374      * that returns true will abort the entire traversal.
   5375      *
   5376      * <p>The default implementation works well for a situation where it is
   5377      * used with a container that covers the entire window, allowing it to
   5378      * apply the appropriate insets to its content on all edges.  If you need
   5379      * a more complicated layout (such as two different views fitting system
   5380      * windows, one on the top of the window, and one on the bottom),
   5381      * you can override the method and handle the insets however you would like.
   5382      * Note that the insets provided by the framework are always relative to the
   5383      * far edges of the window, not accounting for the location of the called view
   5384      * within that window.  (In fact when this method is called you do not yet know
   5385      * where the layout will place the view, as it is done before layout happens.)
   5386      *
   5387      * <p>Note: unlike many View methods, there is no dispatch phase to this
   5388      * call.  If you are overriding it in a ViewGroup and want to allow the
   5389      * call to continue to your children, you must be sure to call the super
   5390      * implementation.
   5391      *
   5392      * <p>Here is a sample layout that makes use of fitting system windows
   5393      * to have controls for a video view placed inside of the window decorations
   5394      * that it hides and shows.  This can be used with code like the second
   5395      * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
   5396      *
   5397      * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
   5398      *
   5399      * @param insets Current content insets of the window.  Prior to
   5400      * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
   5401      * the insets or else you and Android will be unhappy.
   5402      *
   5403      * @return Return true if this view applied the insets and it should not
   5404      * continue propagating further down the hierarchy, false otherwise.
   5405      * @see #getFitsSystemWindows()
   5406      * @see #setFitsSystemWindows()
   5407      * @see #setSystemUiVisibility(int)
   5408      */
   5409     protected boolean fitSystemWindows(Rect insets) {
   5410         if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
   5411             mUserPaddingStart = -1;
   5412             mUserPaddingEnd = -1;
   5413             mUserPaddingRelative = false;
   5414             if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
   5415                     || mAttachInfo == null
   5416                     || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
   5417                 internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
   5418                 return true;
   5419             } else {
   5420                 internalSetPadding(0, 0, 0, 0);
   5421                 return false;
   5422             }
   5423         }
   5424         return false;
   5425     }
   5426 
   5427     /**
   5428      * Sets whether or not this view should account for system screen decorations
   5429      * such as the status bar and inset its content; that is, controlling whether
   5430      * the default implementation of {@link #fitSystemWindows(Rect)} will be
   5431      * executed.  See that method for more details.
   5432      *
   5433      * <p>Note that if you are providing your own implementation of
   5434      * {@link #fitSystemWindows(Rect)}, then there is no need to set this
   5435      * flag to true -- your implementation will be overriding the default
   5436      * implementation that checks this flag.
   5437      *
   5438      * @param fitSystemWindows If true, then the default implementation of
   5439      * {@link #fitSystemWindows(Rect)} will be executed.
   5440      *
   5441      * @attr ref android.R.styleable#View_fitsSystemWindows
   5442      * @see #getFitsSystemWindows()
   5443      * @see #fitSystemWindows(Rect)
   5444      * @see #setSystemUiVisibility(int)
   5445      */
   5446     public void setFitsSystemWindows(boolean fitSystemWindows) {
   5447         setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
   5448     }
   5449 
   5450     /**
   5451      * Check for state of {@link #setFitsSystemWindows(boolean). If this method
   5452      * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
   5453      * will be executed.
   5454      *
   5455      * @return Returns true if the default implementation of
   5456      * {@link #fitSystemWindows(Rect)} will be executed.
   5457      *
   5458      * @attr ref android.R.styleable#View_fitsSystemWindows
   5459      * @see #setFitsSystemWindows()
   5460      * @see #fitSystemWindows(Rect)
   5461      * @see #setSystemUiVisibility(int)
   5462      */
   5463     public boolean getFitsSystemWindows() {
   5464         return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
   5465     }
   5466 
   5467     /** @hide */
   5468     public boolean fitsSystemWindows() {
   5469         return getFitsSystemWindows();
   5470     }
   5471 
   5472     /**
   5473      * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
   5474      */
   5475     public void requestFitSystemWindows() {
   5476         if (mParent != null) {
   5477             mParent.requestFitSystemWindows();
   5478         }
   5479     }
   5480 
   5481     /**
   5482      * For use by PhoneWindow to make its own system window fitting optional.
   5483      * @hide
   5484      */
   5485     public void makeOptionalFitsSystemWindows() {
   5486         setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
   5487     }
   5488 
   5489     /**
   5490      * Returns the visibility status for this view.
   5491      *
   5492      * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
   5493      * @attr ref android.R.styleable#View_visibility
   5494      */
   5495     @ViewDebug.ExportedProperty(mapping = {
   5496         @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
   5497         @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
   5498         @ViewDebug.IntToString(from = GONE,      to = "GONE")
   5499     })
   5500     public int getVisibility() {
   5501         return mViewFlags & VISIBILITY_MASK;
   5502     }
   5503 
   5504     /**
   5505      * Set the enabled state of this view.
   5506      *
   5507      * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
   5508      * @attr ref android.R.styleable#View_visibility
   5509      */
   5510     @RemotableViewMethod
   5511     public void setVisibility(int visibility) {
   5512         setFlags(visibility, VISIBILITY_MASK);
   5513         if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
   5514     }
   5515 
   5516     /**
   5517      * Returns the enabled status for this view. The interpretation of the
   5518      * enabled state varies by subclass.
   5519      *
   5520      * @return True if this view is enabled, false otherwise.
   5521      */
   5522     @ViewDebug.ExportedProperty
   5523     public boolean isEnabled() {
   5524         return (mViewFlags & ENABLED_MASK) == ENABLED;
   5525     }
   5526 
   5527     /**
   5528      * Set the enabled state of this view. The interpretation of the enabled
   5529      * state varies by subclass.
   5530      *
   5531      * @param enabled True if this view is enabled, false otherwise.
   5532      */
   5533     @RemotableViewMethod
   5534     public void setEnabled(boolean enabled) {
   5535         if (enabled == isEnabled()) return;
   5536 
   5537         setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
   5538 
   5539         /*
   5540          * The View most likely has to change its appearance, so refresh
   5541          * the drawable state.
   5542          */
   5543         refreshDrawableState();
   5544 
   5545         // Invalidate too, since the default behavior for views is to be
   5546         // be drawn at 50% alpha rather than to change the drawable.
   5547         invalidate(true);
   5548     }
   5549 
   5550     /**
   5551      * Set whether this view can receive the focus.
   5552      *
   5553      * Setting this to false will also ensure that this view is not focusable
   5554      * in touch mode.
   5555      *
   5556      * @param focusable If true, this view can receive the focus.
   5557      *
   5558      * @see #setFocusableInTouchMode(boolean)
   5559      * @attr ref android.R.styleable#View_focusable
   5560      */
   5561     public void setFocusable(boolean focusable) {
   5562         if (!focusable) {
   5563             setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
   5564         }
   5565         setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
   5566     }
   5567 
   5568     /**
   5569      * Set whether this view can receive focus while in touch mode.
   5570      *
   5571      * Setting this to true will also ensure that this view is focusable.
   5572      *
   5573      * @param focusableInTouchMode If true, this view can receive the focus while
   5574      *   in touch mode.
   5575      *
   5576      * @see #setFocusable(boolean)
   5577      * @attr ref android.R.styleable#View_focusableInTouchMode
   5578      */
   5579     public void setFocusableInTouchMode(boolean focusableInTouchMode) {
   5580         // Focusable in touch mode should always be set before the focusable flag
   5581         // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
   5582         // which, in touch mode, will not successfully request focus on this view
   5583         // because the focusable in touch mode flag is not set
   5584         setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
   5585         if (focusableInTouchMode) {
   5586             setFlags(FOCUSABLE, FOCUSABLE_MASK);
   5587         }
   5588     }
   5589 
   5590     /**
   5591      * Set whether this view should have sound effects enabled for events such as
   5592      * clicking and touching.
   5593      *
   5594      * <p>You may wish to disable sound effects for a view if you already play sounds,
   5595      * for instance, a dial key that plays dtmf tones.
   5596      *
   5597      * @param soundEffectsEnabled whether sound effects are enabled for this view.
   5598      * @see #isSoundEffectsEnabled()
   5599      * @see #playSoundEffect(int)
   5600      * @attr ref android.R.styleable#View_soundEffectsEnabled
   5601      */
   5602     public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
   5603         setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
   5604     }
   5605 
   5606     /**
   5607      * @return whether this view should have sound effects enabled for events such as
   5608      *     clicking and touching.
   5609      *
   5610      * @see #setSoundEffectsEnabled(boolean)
   5611      * @see #playSoundEffect(int)
   5612      * @attr ref android.R.styleable#View_soundEffectsEnabled
   5613      */
   5614     @ViewDebug.ExportedProperty
   5615     public boolean isSoundEffectsEnabled() {
   5616         return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
   5617     }
   5618 
   5619     /**
   5620      * Set whether this view should have haptic feedback for events such as
   5621      * long presses.
   5622      *
   5623      * <p>You may wish to disable haptic feedback if your view already controls
   5624      * its own haptic feedback.
   5625      *
   5626      * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
   5627      * @see #isHapticFeedbackEnabled()
   5628      * @see #performHapticFeedback(int)
   5629      * @attr ref android.R.styleable#View_hapticFeedbackEnabled
   5630      */
   5631     public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
   5632         setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
   5633     }
   5634 
   5635     /**
   5636      * @return whether this view should have haptic feedback enabled for events
   5637      * long presses.
   5638      *
   5639      * @see #setHapticFeedbackEnabled(boolean)
   5640      * @see #performHapticFeedback(int)
   5641      * @attr ref android.R.styleable#View_hapticFeedbackEnabled
   5642      */
   5643     @ViewDebug.ExportedProperty
   5644     public boolean isHapticFeedbackEnabled() {
   5645         return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
   5646     }
   5647 
   5648     /**
   5649      * Returns the layout direction for this view.
   5650      *
   5651      * @return One of {@link #LAYOUT_DIRECTION_LTR},
   5652      *   {@link #LAYOUT_DIRECTION_RTL},
   5653      *   {@link #LAYOUT_DIRECTION_INHERIT} or
   5654      *   {@link #LAYOUT_DIRECTION_LOCALE}.
   5655      *
   5656      * @attr ref android.R.styleable#View_layoutDirection
   5657      * @hide
   5658      */
   5659     @ViewDebug.ExportedProperty(category = "layout", mapping = {
   5660         @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
   5661         @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
   5662         @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
   5663         @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
   5664     })
   5665     public int getLayoutDirection() {
   5666         return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
   5667     }
   5668 
   5669     /**
   5670      * Set the layout direction for this view. This will propagate a reset of layout direction
   5671      * resolution to the view's children and resolve layout direction for this view.
   5672      *
   5673      * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
   5674      *   {@link #LAYOUT_DIRECTION_RTL},
   5675      *   {@link #LAYOUT_DIRECTION_INHERIT} or
   5676      *   {@link #LAYOUT_DIRECTION_LOCALE}.
   5677      *
   5678      * @attr ref android.R.styleable#View_layoutDirection
   5679      * @hide
   5680      */
   5681     @RemotableViewMethod
   5682     public void setLayoutDirection(int layoutDirection) {
   5683         if (getLayoutDirection() != layoutDirection) {
   5684             // Reset the current layout direction and the resolved one
   5685             mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
   5686             resetResolvedLayoutDirection();
   5687             // Set the new layout direction (filtered) and ask for a layout pass
   5688             mPrivateFlags2 |=
   5689                     ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
   5690             requestLayout();
   5691         }
   5692     }
   5693 
   5694     /**
   5695      * Returns the resolved layout direction for this view.
   5696      *
   5697      * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
   5698      * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
   5699      * @hide
   5700      */
   5701     @ViewDebug.ExportedProperty(category = "layout", mapping = {
   5702         @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
   5703         @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
   5704     })
   5705     public int getResolvedLayoutDirection() {
   5706         // The layout diretion will be resolved only if needed
   5707         if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
   5708             resolveLayoutDirection();
   5709         }
   5710         return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
   5711                 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
   5712     }
   5713 
   5714     /**
   5715      * Indicates whether or not this view's layout is right-to-left. This is resolved from
   5716      * layout attribute and/or the inherited value from the parent
   5717      *
   5718      * @return true if the layout is right-to-left.
   5719      * @hide
   5720      */
   5721     @ViewDebug.ExportedProperty(category = "layout")
   5722     public boolean isLayoutRtl() {
   5723         return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
   5724     }
   5725 
   5726     /**
   5727      * Indicates whether the view is currently tracking transient state that the
   5728      * app should not need to concern itself with saving and restoring, but that
   5729      * the framework should take special note to preserve when possible.
   5730      *
   5731      * <p>A view with transient state cannot be trivially rebound from an external
   5732      * data source, such as an adapter binding item views in a list. This may be
   5733      * because the view is performing an animation, tracking user selection
   5734      * of content, or similar.</p>
   5735      *
   5736      * @return true if the view has transient state
   5737      */
   5738     @ViewDebug.ExportedProperty(category = "layout")
   5739     public boolean hasTransientState() {
   5740         return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
   5741     }
   5742 
   5743     /**
   5744      * Set whether this view is currently tracking transient state that the
   5745      * framework should attempt to preserve when possible. This flag is reference counted,
   5746      * so every call to setHasTransientState(true) should be paired with a later call
   5747      * to setHasTransientState(false).
   5748      *
   5749      * <p>A view with transient state cannot be trivially rebound from an external
   5750      * data source, such as an adapter binding item views in a list. This may be
   5751      * because the view is performing an animation, tracking user selection
   5752      * of content, or similar.</p>
   5753      *
   5754      * @param hasTransientState true if this view has transient state
   5755      */
   5756     public void setHasTransientState(boolean hasTransientState) {
   5757         mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
   5758                 mTransientStateCount - 1;
   5759         if (mTransientStateCount < 0) {
   5760             mTransientStateCount = 0;
   5761             Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
   5762                     "unmatched pair of setHasTransientState calls");
   5763         }
   5764         if ((hasTransientState && mTransientStateCount == 1) ||
   5765                 (!hasTransientState && mTransientStateCount == 0)) {
   5766             // update flag if we've just incremented up from 0 or decremented down to 0
   5767             mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
   5768                     (hasTransientState ? HAS_TRANSIENT_STATE : 0);
   5769             if (mParent != null) {
   5770                 try {
   5771                     mParent.childHasTransientStateChanged(this, hasTransientState);
   5772                 } catch (AbstractMethodError e) {
   5773                     Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
   5774                             " does not fully implement ViewParent", e);
   5775                 }
   5776             }
   5777         }
   5778     }
   5779 
   5780     /**
   5781      * If this view doesn't do any drawing on its own, set this flag to
   5782      * allow further optimizations. By default, this flag is not set on
   5783      * View, but could be set on some View subclasses such as ViewGroup.
   5784      *
   5785      * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
   5786      * you should clear this flag.
   5787      *
   5788      * @param willNotDraw whether or not this View draw on its own
   5789      */
   5790     public void setWillNotDraw(boolean willNotDraw) {
   5791         setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
   5792     }
   5793 
   5794     /**
   5795      * Returns whether or not this View draws on its own.
   5796      *
   5797      * @return true if this view has nothing to draw, false otherwise
   5798      */
   5799     @ViewDebug.ExportedProperty(category = "drawing")
   5800     public boolean willNotDraw() {
   5801         return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
   5802     }
   5803 
   5804     /**
   5805      * When a View's drawing cache is enabled, drawing is redirected to an
   5806      * offscreen bitmap. Some views, like an ImageView, must be able to
   5807      * bypass this mechanism if they already draw a single bitmap, to avoid
   5808      * unnecessary usage of the memory.
   5809      *
   5810      * @param willNotCacheDrawing true if this view does not cache its
   5811      *        drawing, false otherwise
   5812      */
   5813     public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
   5814         setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
   5815     }
   5816 
   5817     /**
   5818      * Returns whether or not this View can cache its drawing or not.
   5819      *
   5820      * @return true if this view does not cache its drawing, false otherwise
   5821      */
   5822     @ViewDebug.ExportedProperty(category = "drawing")
   5823     public boolean willNotCacheDrawing() {
   5824         return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
   5825     }
   5826 
   5827     /**
   5828      * Indicates whether this view reacts to click events or not.
   5829      *
   5830      * @return true if the view is clickable, false otherwise
   5831      *
   5832      * @see #setClickable(boolean)
   5833      * @attr ref android.R.styleable#View_clickable
   5834      */
   5835     @ViewDebug.ExportedProperty
   5836     public boolean isClickable() {
   5837         return (mViewFlags & CLICKABLE) == CLICKABLE;
   5838     }
   5839 
   5840     /**
   5841      * Enables or disables click events for this view. When a view
   5842      * is clickable it will change its state to "pressed" on every click.
   5843      * Subclasses should set the view clickable to visually react to
   5844      * user's clicks.
   5845      *
   5846      * @param clickable true to make the view clickable, false otherwise
   5847      *
   5848      * @see #isClickable()
   5849      * @attr ref android.R.styleable#View_clickable
   5850      */
   5851     public void setClickable(boolean clickable) {
   5852         setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
   5853     }
   5854 
   5855     /**
   5856      * Indicates whether this view reacts to long click events or not.
   5857      *
   5858      * @return true if the view is long clickable, false otherwise
   5859      *
   5860      * @see #setLongClickable(boolean)
   5861      * @attr ref android.R.styleable#View_longClickable
   5862      */
   5863     public boolean isLongClickable() {
   5864         return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
   5865     }
   5866 
   5867     /**
   5868      * Enables or disables long click events for this view. When a view is long
   5869      * clickable it reacts to the user holding down the button for a longer
   5870      * duration than a tap. This event can either launch the listener or a
   5871      * context menu.
   5872      *
   5873      * @param longClickable true to make the view long clickable, false otherwise
   5874      * @see #isLongClickable()
   5875      * @attr ref android.R.styleable#View_longClickable
   5876      */
   5877     public void setLongClickable(boolean longClickable) {
   5878         setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
   5879     }
   5880 
   5881     /**
   5882      * Sets the pressed state for this view.
   5883      *
   5884      * @see #isClickable()
   5885      * @see #setClickable(boolean)
   5886      *
   5887      * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
   5888      *        the View's internal state from a previously set "pressed" state.
   5889      */
   5890     public void setPressed(boolean pressed) {
   5891         final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
   5892 
   5893         if (pressed) {
   5894             mPrivateFlags |= PRESSED;
   5895         } else {
   5896             mPrivateFlags &= ~PRESSED;
   5897         }
   5898 
   5899         if (needsRefresh) {
   5900             refreshDrawableState();
   5901         }
   5902         dispatchSetPressed(pressed);
   5903     }
   5904 
   5905     /**
   5906      * Dispatch setPressed to all of this View's children.
   5907      *
   5908      * @see #setPressed(boolean)
   5909      *
   5910      * @param pressed The new pressed state
   5911      */
   5912     protected void dispatchSetPressed(boolean pressed) {
   5913     }
   5914 
   5915     /**
   5916      * Indicates whether the view is currently in pressed state. Unless
   5917      * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
   5918      * the pressed state.
   5919      *
   5920      * @see #setPressed(boolean)
   5921      * @see #isClickable()
   5922      * @see #setClickable(boolean)
   5923      *
   5924      * @return true if the view is currently pressed, false otherwise
   5925      */
   5926     public boolean isPressed() {
   5927         return (mPrivateFlags & PRESSED) == PRESSED;
   5928     }
   5929 
   5930     /**
   5931      * Indicates whether this view will save its state (that is,
   5932      * whether its {@link #onSaveInstanceState} method will be called).
   5933      *
   5934      * @return Returns true if the view state saving is enabled, else false.
   5935      *
   5936      * @see #setSaveEnabled(boolean)
   5937      * @attr ref android.R.styleable#View_saveEnabled
   5938      */
   5939     public boolean isSaveEnabled() {
   5940         return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
   5941     }
   5942 
   5943     /**
   5944      * Controls whether the saving of this view's state is
   5945      * enabled (that is, whether its {@link #onSaveInstanceState} method
   5946      * will be called).  Note that even if freezing is enabled, the
   5947      * view still must have an id assigned to it (via {@link #setId(int)})
   5948      * for its state to be saved.  This flag can only disable the
   5949      * saving of this view; any child views may still have their state saved.
   5950      *
   5951      * @param enabled Set to false to <em>disable</em> state saving, or true
   5952      * (the default) to allow it.
   5953      *
   5954      * @see #isSaveEnabled()
   5955      * @see #setId(int)
   5956      * @see #onSaveInstanceState()
   5957      * @attr ref android.R.styleable#View_saveEnabled
   5958      */
   5959     public void setSaveEnabled(boolean enabled) {
   5960         setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
   5961     }
   5962 
   5963     /**
   5964      * Gets whether the framework should discard touches when the view's
   5965      * window is obscured by another visible window.
   5966      * Refer to the {@link View} security documentation for more details.
   5967      *
   5968      * @return True if touch filtering is enabled.
   5969      *
   5970      * @see #setFilterTouchesWhenObscured(boolean)
   5971      * @attr ref android.R.styleable#View_filterTouchesWhenObscured
   5972      */
   5973     @ViewDebug.ExportedProperty
   5974     public boolean getFilterTouchesWhenObscured() {
   5975         return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
   5976     }
   5977 
   5978     /**
   5979      * Sets whether the framework should discard touches when the view's
   5980      * window is obscured by another visible window.
   5981      * Refer to the {@link View} security documentation for more details.
   5982      *
   5983      * @param enabled True if touch filtering should be enabled.
   5984      *
   5985      * @see #getFilterTouchesWhenObscured
   5986      * @attr ref android.R.styleable#View_filterTouchesWhenObscured
   5987      */
   5988     public void setFilterTouchesWhenObscured(boolean enabled) {
   5989         setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
   5990                 FILTER_TOUCHES_WHEN_OBSCURED);
   5991     }
   5992 
   5993     /**
   5994      * Indicates whether the entire hierarchy under this view will save its
   5995      * state when a state saving traversal occurs from its parent.  The default
   5996      * is true; if false, these views will not be saved unless
   5997      * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
   5998      *
   5999      * @return Returns true if the view state saving from parent is enabled, else false.
   6000      *
   6001      * @see #setSaveFromParentEnabled(boolean)
   6002      */
   6003     public boolean isSaveFromParentEnabled() {
   6004         return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
   6005     }
   6006 
   6007     /**
   6008      * Controls whether the entire hierarchy under this view will save its
   6009      * state when a state saving traversal occurs from its parent.  The default
   6010      * is true; if false, these views will not be saved unless
   6011      * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
   6012      *
   6013      * @param enabled Set to false to <em>disable</em> state saving, or true
   6014      * (the default) to allow it.
   6015      *
   6016      * @see #isSaveFromParentEnabled()
   6017      * @see #setId(int)
   6018      * @see #onSaveInstanceState()
   6019      */
   6020     public void setSaveFromParentEnabled(boolean enabled) {
   6021         setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
   6022     }
   6023 
   6024 
   6025     /**
   6026      * Returns whether this View is able to take focus.
   6027      *
   6028      * @return True if this view can take focus, or false otherwise.
   6029      * @attr ref android.R.styleable#View_focusable
   6030      */
   6031     @ViewDebug.ExportedProperty(category = "focus")
   6032     public final boolean isFocusable() {
   6033         return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
   6034     }
   6035 
   6036     /**
   6037      * When a view is focusable, it may not want to take focus when in touch mode.
   6038      * For example, a button would like focus when the user is navigating via a D-pad
   6039      * so that the user can click on it, but once the user starts touching the screen,
   6040      * the button shouldn't take focus
   6041      * @return Whether the view is focusable in touch mode.
   6042      * @attr ref android.R.styleable#View_focusableInTouchMode
   6043      */
   6044     @ViewDebug.ExportedProperty
   6045     public final boolean isFocusableInTouchMode() {
   6046         return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
   6047     }
   6048 
   6049     /**
   6050      * Find the nearest view in the specified direction that can take focus.
   6051      * This does not actually give focus to that view.
   6052      *
   6053      * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
   6054      *
   6055      * @return The nearest focusable in the specified direction, or null if none
   6056      *         can be found.
   6057      */
   6058     public View focusSearch(int direction) {
   6059         if (mParent != null) {
   6060             return mParent.focusSearch(this, direction);
   6061         } else {
   6062             return null;
   6063         }
   6064     }
   6065 
   6066     /**
   6067      * This method is the last chance for the focused view and its ancestors to
   6068      * respond to an arrow key. This is called when the focused view did not
   6069      * consume the key internally, nor could the view system find a new view in
   6070      * the requested direction to give focus to.
   6071      *
   6072      * @param focused The currently focused view.
   6073      * @param direction The direction focus wants to move. One of FOCUS_UP,
   6074      *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
   6075      * @return True if the this view consumed this unhandled move.
   6076      */
   6077     public boolean dispatchUnhandledMove(View focused, int direction) {
   6078         return false;
   6079     }
   6080 
   6081     /**
   6082      * If a user manually specified the next view id for a particular direction,
   6083      * use the root to look up the view.
   6084      * @param root The root view of the hierarchy containing this view.
   6085      * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
   6086      * or FOCUS_BACKWARD.
   6087      * @return The user specified next view, or null if there is none.
   6088      */
   6089     View findUserSetNextFocus(View root, int direction) {
   6090         switch (direction) {
   6091             case FOCUS_LEFT:
   6092                 if (mNextFocusLeftId == View.NO_ID) return null;
   6093                 return findViewInsideOutShouldExist(root, mNextFocusLeftId);
   6094             case FOCUS_RIGHT:
   6095                 if (mNextFocusRightId == View.NO_ID) return null;
   6096                 return findViewInsideOutShouldExist(root, mNextFocusRightId);
   6097             case FOCUS_UP:
   6098                 if (mNextFocusUpId == View.NO_ID) return null;
   6099                 return findViewInsideOutShouldExist(root, mNextFocusUpId);
   6100             case FOCUS_DOWN:
   6101                 if (mNextFocusDownId == View.NO_ID) return null;
   6102                 return findViewInsideOutShouldExist(root, mNextFocusDownId);
   6103             case FOCUS_FORWARD:
   6104                 if (mNextFocusForwardId == View.NO_ID) return null;
   6105                 return findViewInsideOutShouldExist(root, mNextFocusForwardId);
   6106             case FOCUS_BACKWARD: {
   6107                 if (mID == View.NO_ID) return null;
   6108                 final int id = mID;
   6109                 return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
   6110                     @Override
   6111                     public boolean apply(View t) {
   6112                         return t.mNextFocusForwardId == id;
   6113                     }
   6114                 });
   6115             }
   6116         }
   6117         return null;
   6118     }
   6119 
   6120     private View findViewInsideOutShouldExist(View root, final int childViewId) {
   6121         View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
   6122             @Override
   6123             public boolean apply(View t) {
   6124                 return t.mID == childViewId;
   6125             }
   6126         });
   6127 
   6128         if (result == null) {
   6129             Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
   6130                     + "by user for id " + childViewId);
   6131         }
   6132         return result;
   6133     }
   6134 
   6135     /**
   6136      * Find and return all focusable views that are descendants of this view,
   6137      * possibly including this view if it is focusable itself.
   6138      *
   6139      * @param direction The direction of the focus
   6140      * @return A list of focusable views
   6141      */
   6142     public ArrayList<View> getFocusables(int direction) {
   6143         ArrayList<View> result = new ArrayList<View>(24);
   6144         addFocusables(result, direction);
   6145         return result;
   6146     }
   6147 
   6148     /**
   6149      * Add any focusable views that are descendants of this view (possibly
   6150      * including this view if it is focusable itself) to views.  If we are in touch mode,
   6151      * only add views that are also focusable in touch mode.
   6152      *
   6153      * @param views Focusable views found so far
   6154      * @param direction The direction of the focus
   6155      */
   6156     public void addFocusables(ArrayList<View> views, int direction) {
   6157         addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
   6158     }
   6159 
   6160     /**
   6161      * Adds any focusable views that are descendants of this view (possibly
   6162      * including this view if it is focusable itself) to views. This method
   6163      * adds all focusable views regardless if we are in touch mode or
   6164      * only views focusable in touch mode if we are in touch mode or
   6165      * only views that can take accessibility focus if accessibility is enabeld
   6166      * depending on the focusable mode paramater.
   6167      *
   6168      * @param views Focusable views found so far or null if all we are interested is
   6169      *        the number of focusables.
   6170      * @param direction The direction of the focus.
   6171      * @param focusableMode The type of focusables to be added.
   6172      *
   6173      * @see #FOCUSABLES_ALL
   6174      * @see #FOCUSABLES_TOUCH_MODE
   6175      */
   6176     public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
   6177         if (views == null) {
   6178             return;
   6179         }
   6180         if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
   6181             if (isAccessibilityFocusable()) {
   6182                 views.add(this);
   6183                 return;
   6184             }
   6185         }
   6186         if (!isFocusable()) {
   6187             return;
   6188         }
   6189         if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
   6190                 && isInTouchMode() && !isFocusableInTouchMode()) {
   6191             return;
   6192         }
   6193         views.add(this);
   6194     }
   6195 
   6196     /**
   6197      * Finds the Views that contain given text. The containment is case insensitive.
   6198      * The search is performed by either the text that the View renders or the content
   6199      * description that describes the view for accessibility purposes and the view does
   6200      * not render or both. Clients can specify how the search is to be performed via
   6201      * passing the {@link #FIND_VIEWS_WITH_TEXT} and
   6202      * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
   6203      *
   6204      * @param outViews The output list of matching Views.
   6205      * @param searched The text to match against.
   6206      *
   6207      * @see #FIND_VIEWS_WITH_TEXT
   6208      * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
   6209      * @see #setContentDescription(CharSequence)
   6210      */
   6211     public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
   6212         if (getAccessibilityNodeProvider() != null) {
   6213             if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
   6214                 outViews.add(this);
   6215             }
   6216         } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
   6217                 && (searched != null && searched.length() > 0)
   6218                 && (mContentDescription != null && mContentDescription.length() > 0)) {
   6219             String searchedLowerCase = searched.toString().toLowerCase();
   6220             String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
   6221             if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
   6222                 outViews.add(this);
   6223             }
   6224         }
   6225     }
   6226 
   6227     /**
   6228      * Find and return all touchable views that are descendants of this view,
   6229      * possibly including this view if it is touchable itself.
   6230      *
   6231      * @return A list of touchable views
   6232      */
   6233     public ArrayList<View> getTouchables() {
   6234         ArrayList<View> result = new ArrayList<View>();
   6235         addTouchables(result);
   6236         return result;
   6237     }
   6238 
   6239     /**
   6240      * Add any touchable views that are descendants of this view (possibly
   6241      * including this view if it is touchable itself) to views.
   6242      *
   6243      * @param views Touchable views found so far
   6244      */
   6245     public void addTouchables(ArrayList<View> views) {
   6246         final int viewFlags = mViewFlags;
   6247 
   6248         if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
   6249                 && (viewFlags & ENABLED_MASK) == ENABLED) {
   6250             views.add(this);
   6251         }
   6252     }
   6253 
   6254     /**
   6255      * Returns whether this View is accessibility focused.
   6256      *
   6257      * @return True if this View is accessibility focused.
   6258      */
   6259     boolean isAccessibilityFocused() {
   6260         return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
   6261     }
   6262 
   6263     /**
   6264      * Call this to try to give accessibility focus to this view.
   6265      *
   6266      * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
   6267      * returns false or the view is no visible or the view already has accessibility
   6268      * focus.
   6269      *
   6270      * See also {@link #focusSearch(int)}, which is what you call to say that you
   6271      * have focus, and you want your parent to look for the next one.
   6272      *
   6273      * @return Whether this view actually took accessibility focus.
   6274      *
   6275      * @hide
   6276      */
   6277     public boolean requestAccessibilityFocus() {
   6278         AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
   6279         if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
   6280             return false;
   6281         }
   6282         if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
   6283             return false;
   6284         }
   6285         if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
   6286             mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
   6287             ViewRootImpl viewRootImpl = getViewRootImpl();
   6288             if (viewRootImpl != null) {
   6289                 viewRootImpl.setAccessibilityFocus(this, null);
   6290             }
   6291             invalidate();
   6292             sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
   6293             notifyAccessibilityStateChanged();
   6294             return true;
   6295         }
   6296         return false;
   6297     }
   6298 
   6299     /**
   6300      * Call this to try to clear accessibility focus of this view.
   6301      *
   6302      * See also {@link #focusSearch(int)}, which is what you call to say that you
   6303      * have focus, and you want your parent to look for the next one.
   6304      *
   6305      * @hide
   6306      */
   6307     public void clearAccessibilityFocus() {
   6308         if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
   6309             mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
   6310             invalidate();
   6311             sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
   6312             notifyAccessibilityStateChanged();
   6313         }
   6314         // Clear the global reference of accessibility focus if this
   6315         // view or any of its descendants had accessibility focus.
   6316         ViewRootImpl viewRootImpl = getViewRootImpl();
   6317         if (viewRootImpl != null) {
   6318             View focusHost = viewRootImpl.getAccessibilityFocusedHost();
   6319             if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
   6320                 viewRootImpl.setAccessibilityFocus(null, null);
   6321             }
   6322         }
   6323     }
   6324 
   6325     private void sendAccessibilityHoverEvent(int eventType) {
   6326         // Since we are not delivering to a client accessibility events from not
   6327         // important views (unless the clinet request that) we need to fire the
   6328         // event from the deepest view exposed to the client. As a consequence if
   6329         // the user crosses a not exposed view the client will see enter and exit
   6330         // of the exposed predecessor followed by and enter and exit of that same
   6331         // predecessor when entering and exiting the not exposed descendant. This
   6332         // is fine since the client has a clear idea which view is hovered at the
   6333         // price of a couple more events being sent. This is a simple and
   6334         // working solution.
   6335         View source = this;
   6336         while (true) {
   6337             if (source.includeForAccessibility()) {
   6338                 source.sendAccessibilityEvent(eventType);
   6339                 return;
   6340             }
   6341             ViewParent parent = source.getParent();
   6342             if (parent instanceof View) {
   6343                 source = (View) parent;
   6344             } else {
   6345                 return;
   6346             }
   6347         }
   6348     }
   6349 
   6350     private void requestAccessibilityFocusFromHover() {
   6351         if (includeForAccessibility() && isActionableForAccessibility()) {
   6352             requestAccessibilityFocus();
   6353         } else {
   6354             if (mParent != null) {
   6355                 View nextFocus = mParent.findViewToTakeAccessibilityFocusFromHover(this, this);
   6356                 if (nextFocus != null) {
   6357                     nextFocus.requestAccessibilityFocus();
   6358                 }
   6359             }
   6360         }
   6361     }
   6362 
   6363     private boolean canTakeAccessibilityFocusFromHover() {
   6364         if (includeForAccessibility() && isActionableForAccessibility()) {
   6365             return true;
   6366         }
   6367         if (mParent != null) {
   6368             return (mParent.findViewToTakeAccessibilityFocusFromHover(this, this) == this);
   6369         }
   6370         return false;
   6371     }
   6372 
   6373     /**
   6374      * Clears accessibility focus without calling any callback methods
   6375      * normally invoked in {@link #clearAccessibilityFocus()}. This method
   6376      * is used for clearing accessibility focus when giving this focus to
   6377      * another view.
   6378      */
   6379     void clearAccessibilityFocusNoCallbacks() {
   6380         if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
   6381             mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
   6382             invalidate();
   6383         }
   6384     }
   6385 
   6386     /**
   6387      * Call this to try to give focus to a specific view or to one of its
   6388      * descendants.
   6389      *
   6390      * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
   6391      * false), or if it is focusable and it is not focusable in touch mode
   6392      * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
   6393      *
   6394      * See also {@link #focusSearch(int)}, which is what you call to say that you
   6395      * have focus, and you want your parent to look for the next one.
   6396      *
   6397      * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
   6398      * {@link #FOCUS_DOWN} and <code>null</code>.
   6399      *
   6400      * @return Whether this view or one of its descendants actually took focus.
   6401      */
   6402     public final boolean requestFocus() {
   6403         return requestFocus(View.FOCUS_DOWN);
   6404     }
   6405 
   6406     /**
   6407      * Call this to try to give focus to a specific view or to one of its
   6408      * descendants and give it a hint about what direction focus is heading.
   6409      *
   6410      * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
   6411      * false), or if it is focusable and it is not focusable in touch mode
   6412      * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
   6413      *
   6414      * See also {@link #focusSearch(int)}, which is what you call to say that you
   6415      * have focus, and you want your parent to look for the next one.
   6416      *
   6417      * This is equivalent to calling {@link #requestFocus(int, Rect)} with
   6418      * <code>null</code> set for the previously focused rectangle.
   6419      *
   6420      * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
   6421      * @return Whether this view or one of its descendants actually took focus.
   6422      */
   6423     public final boolean requestFocus(int direction) {
   6424         return requestFocus(direction, null);
   6425     }
   6426 
   6427     /**
   6428      * Call this to try to give focus to a specific view or to one of its descendants
   6429      * and give it hints about the direction and a specific rectangle that the focus
   6430      * is coming from.  The rectangle can help give larger views a finer grained hint
   6431      * about where focus is coming from, and therefore, where to show selection, or
   6432      * forward focus change internally.
   6433      *
   6434      * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
   6435      * false), or if it is focusable and it is not focusable in touch mode
   6436      * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
   6437      *
   6438      * A View will not take focus if it is not visible.
   6439      *
   6440      * A View will not take focus if one of its parents has
   6441      * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
   6442      * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
   6443      *
   6444      * See also {@link #focusSearch(int)}, which is what you call to say that you
   6445      * have focus, and you want your parent to look for the next one.
   6446      *
   6447      * You may wish to override this method if your custom {@link View} has an internal
   6448      * {@link View} that it wishes to forward the request to.
   6449      *
   6450      * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
   6451      * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
   6452      *        to give a finer grained hint about where focus is coming from.  May be null
   6453      *        if there is no hint.
   6454      * @return Whether this view or one of its descendants actually took focus.
   6455      */
   6456     public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
   6457         return requestFocusNoSearch(direction, previouslyFocusedRect);
   6458     }
   6459 
   6460     private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
   6461         // need to be focusable
   6462         if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
   6463                 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
   6464             return false;
   6465         }
   6466 
   6467         // need to be focusable in touch mode if in touch mode
   6468         if (isInTouchMode() &&
   6469             (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
   6470                return false;
   6471         }
   6472 
   6473         // need to not have any parents blocking us
   6474         if (hasAncestorThatBlocksDescendantFocus()) {
   6475             return false;
   6476         }
   6477 
   6478         handleFocusGainInternal(direction, previouslyFocusedRect);
   6479         return true;
   6480     }
   6481 
   6482     /**
   6483      * Call this to try to give focus to a specific view or to one of its descendants. This is a
   6484      * special variant of {@link #requestFocus() } that will allow views that are not focuable in
   6485      * touch mode to request focus when they are touched.
   6486      *
   6487      * @return Whether this view or one of its descendants actually took focus.
   6488      *
   6489      * @see #isInTouchMode()
   6490      *
   6491      */
   6492     public final boolean requestFocusFromTouch() {
   6493         // Leave touch mode if we need to
   6494         if (isInTouchMode()) {
   6495             ViewRootImpl viewRoot = getViewRootImpl();
   6496             if (viewRoot != null) {
   6497                 viewRoot.ensureTouchMode(false);
   6498             }
   6499         }
   6500         return requestFocus(View.FOCUS_DOWN);
   6501     }
   6502 
   6503     /**
   6504      * @return Whether any ancestor of this view blocks descendant focus.
   6505      */
   6506     private boolean hasAncestorThatBlocksDescendantFocus() {
   6507         ViewParent ancestor = mParent;
   6508         while (ancestor instanceof ViewGroup) {
   6509             final ViewGroup vgAncestor = (ViewGroup) ancestor;
   6510             if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
   6511                 return true;
   6512             } else {
   6513                 ancestor = vgAncestor.getParent();
   6514             }
   6515         }
   6516         return false;
   6517     }
   6518 
   6519     /**
   6520      * Gets the mode for determining whether this View is important for accessibility
   6521      * which is if it fires accessibility events and if it is reported to
   6522      * accessibility services that query the screen.
   6523      *
   6524      * @return The mode for determining whether a View is important for accessibility.
   6525      *
   6526      * @attr ref android.R.styleable#View_importantForAccessibility
   6527      *
   6528      * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
   6529      * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
   6530      * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
   6531      */
   6532     @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
   6533             @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
   6534             @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
   6535             @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
   6536         })
   6537     public int getImportantForAccessibility() {
   6538         return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
   6539                 >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
   6540     }
   6541 
   6542     /**
   6543      * Sets how to determine whether this view is important for accessibility
   6544      * which is if it fires accessibility events and if it is reported to
   6545      * accessibility services that query the screen.
   6546      *
   6547      * @param mode How to determine whether this view is important for accessibility.
   6548      *
   6549      * @attr ref android.R.styleable#View_importantForAccessibility
   6550      *
   6551      * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
   6552      * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
   6553      * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
   6554      */
   6555     public void setImportantForAccessibility(int mode) {
   6556         if (mode != getImportantForAccessibility()) {
   6557             mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
   6558             mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
   6559                     & IMPORTANT_FOR_ACCESSIBILITY_MASK;
   6560             notifyAccessibilityStateChanged();
   6561         }
   6562     }
   6563 
   6564     /**
   6565      * Gets whether this view should be exposed for accessibility.
   6566      *
   6567      * @return Whether the view is exposed for accessibility.
   6568      *
   6569      * @hide
   6570      */
   6571     public boolean isImportantForAccessibility() {
   6572         final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
   6573                 >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
   6574         switch (mode) {
   6575             case IMPORTANT_FOR_ACCESSIBILITY_YES:
   6576                 return true;
   6577             case IMPORTANT_FOR_ACCESSIBILITY_NO:
   6578                 return false;
   6579             case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
   6580                 return isActionableForAccessibility() || hasListenersForAccessibility();
   6581             default:
   6582                 throw new IllegalArgumentException("Unknow important for accessibility mode: "
   6583                         + mode);
   6584         }
   6585     }
   6586 
   6587     /**
   6588      * Gets the mode for determining whether this View can take accessibility focus.
   6589      *
   6590      * @return The mode for determining whether a View can take accessibility focus.
   6591      *
   6592      * @attr ref android.R.styleable#View_accessibilityFocusable
   6593      *
   6594      * @see #ACCESSIBILITY_FOCUSABLE_YES
   6595      * @see #ACCESSIBILITY_FOCUSABLE_NO
   6596      * @see #ACCESSIBILITY_FOCUSABLE_AUTO
   6597      *
   6598      * @hide
   6599      */
   6600     @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
   6601             @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_AUTO, to = "auto"),
   6602             @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_YES, to = "yes"),
   6603             @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_NO, to = "no")
   6604         })
   6605     public int getAccessibilityFocusable() {
   6606         return (mPrivateFlags2 & ACCESSIBILITY_FOCUSABLE_MASK) >>> ACCESSIBILITY_FOCUSABLE_SHIFT;
   6607     }
   6608 
   6609     /**
   6610      * Sets how to determine whether this view can take accessibility focus.
   6611      *
   6612      * @param mode How to determine whether this view can take accessibility focus.
   6613      *
   6614      * @attr ref android.R.styleable#View_accessibilityFocusable
   6615      *
   6616      * @see #ACCESSIBILITY_FOCUSABLE_YES
   6617      * @see #ACCESSIBILITY_FOCUSABLE_NO
   6618      * @see #ACCESSIBILITY_FOCUSABLE_AUTO
   6619      *
   6620      * @hide
   6621      */
   6622     public void setAccessibilityFocusable(int mode) {
   6623         if (mode != getAccessibilityFocusable()) {
   6624             mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSABLE_MASK;
   6625             mPrivateFlags2 |= (mode << ACCESSIBILITY_FOCUSABLE_SHIFT)
   6626                     & ACCESSIBILITY_FOCUSABLE_MASK;
   6627             notifyAccessibilityStateChanged();
   6628         }
   6629     }
   6630 
   6631     /**
   6632      * Gets whether this view can take accessibility focus.
   6633      *
   6634      * @return Whether the view can take accessibility focus.
   6635      *
   6636      * @hide
   6637      */
   6638     public boolean isAccessibilityFocusable() {
   6639         final int mode = (mPrivateFlags2 & ACCESSIBILITY_FOCUSABLE_MASK)
   6640                 >>> ACCESSIBILITY_FOCUSABLE_SHIFT;
   6641         switch (mode) {
   6642             case ACCESSIBILITY_FOCUSABLE_YES:
   6643                 return true;
   6644             case ACCESSIBILITY_FOCUSABLE_NO:
   6645                 return false;
   6646             case ACCESSIBILITY_FOCUSABLE_AUTO:
   6647                 return canTakeAccessibilityFocusFromHover()
   6648                         || getAccessibilityNodeProvider() != null;
   6649             default:
   6650                 throw new IllegalArgumentException("Unknow accessibility focusable mode: " + mode);
   6651         }
   6652     }
   6653 
   6654     /**
   6655      * Gets the parent for accessibility purposes. Note that the parent for
   6656      * accessibility is not necessary the immediate parent. It is the first
   6657      * predecessor that is important for accessibility.
   6658      *
   6659      * @return The parent for accessibility purposes.
   6660      */
   6661     public ViewParent getParentForAccessibility() {
   6662         if (mParent instanceof View) {
   6663             View parentView = (View) mParent;
   6664             if (parentView.includeForAccessibility()) {
   6665                 return mParent;
   6666             } else {
   6667                 return mParent.getParentForAccessibility();
   6668             }
   6669         }
   6670         return null;
   6671     }
   6672 
   6673     /**
   6674      * Adds the children of a given View for accessibility. Since some Views are
   6675      * not important for accessibility the children for accessibility are not
   6676      * necessarily direct children of the riew, rather they are the first level of
   6677      * descendants important for accessibility.
   6678      *
   6679      * @param children The list of children for accessibility.
   6680      */
   6681     public void addChildrenForAccessibility(ArrayList<View> children) {
   6682         if (includeForAccessibility()) {
   6683             children.add(this);
   6684         }
   6685     }
   6686 
   6687     /**
   6688      * Whether to regard this view for accessibility. A view is regarded for
   6689      * accessibility if it is important for accessibility or the querying
   6690      * accessibility service has explicitly requested that view not
   6691      * important for accessibility are regarded.
   6692      *
   6693      * @return Whether to regard the view for accessibility.
   6694      *
   6695      * @hide
   6696      */
   6697     public boolean includeForAccessibility() {
   6698         if (mAttachInfo != null) {
   6699             if (!mAttachInfo.mIncludeNotImportantViews) {
   6700                 return isImportantForAccessibility();
   6701             }
   6702             return true;
   6703         }
   6704         return false;
   6705     }
   6706 
   6707     /**
   6708      * Returns whether the View is considered actionable from
   6709      * accessibility perspective. Such view are important for
   6710      * accessiiblity.
   6711      *
   6712      * @return True if the view is actionable for accessibility.
   6713      *
   6714      * @hide
   6715      */
   6716     public boolean isActionableForAccessibility() {
   6717         return (isClickable() || isLongClickable() || isFocusable());
   6718     }
   6719 
   6720     /**
   6721      * Returns whether the View has registered callbacks wich makes it
   6722      * important for accessiiblity.
   6723      *
   6724      * @return True if the view is actionable for accessibility.
   6725      */
   6726     private boolean hasListenersForAccessibility() {
   6727         ListenerInfo info = getListenerInfo();
   6728         return mTouchDelegate != null || info.mOnKeyListener != null
   6729                 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
   6730                 || info.mOnHoverListener != null || info.mOnDragListener != null;
   6731     }
   6732 
   6733     /**
   6734      * Notifies accessibility services that some view's important for
   6735      * accessibility state has changed. Note that such notifications
   6736      * are made at most once every
   6737      * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
   6738      * to avoid unnecessary load to the system. Also once a view has
   6739      * made a notifucation this method is a NOP until the notification has
   6740      * been sent to clients.
   6741      *
   6742      * @hide
   6743      *
   6744      * TODO: Makse sure this method is called for any view state change
   6745      *       that is interesting for accessilility purposes.
   6746      */
   6747     public void notifyAccessibilityStateChanged() {
   6748         if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
   6749             return;
   6750         }
   6751         if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
   6752             mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
   6753             if (mParent != null) {
   6754                 mParent.childAccessibilityStateChanged(this);
   6755             }
   6756         }
   6757     }
   6758 
   6759     /**
   6760      * Reset the state indicating the this view has requested clients
   6761      * interested in its accessiblity state to be notified.
   6762      *
   6763      * @hide
   6764      */
   6765     public void resetAccessibilityStateChanged() {
   6766         mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
   6767     }
   6768 
   6769     /**
   6770      * Performs the specified accessibility action on the view. For
   6771      * possible accessibility actions look at {@link AccessibilityNodeInfo}.
   6772     * <p>
   6773     * If an {@link AccessibilityDelegate} has been specified via calling
   6774     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
   6775     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
   6776     * is responsible for handling this call.
   6777     * </p>
   6778      *
   6779      * @param action The action to perform.
   6780      * @param arguments Optional action arguments.
   6781      * @return Whether the action was performed.
   6782      */
   6783     public boolean performAccessibilityAction(int action, Bundle arguments) {
   6784       if (mAccessibilityDelegate != null) {
   6785           return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
   6786       } else {
   6787           return performAccessibilityActionInternal(action, arguments);
   6788       }
   6789     }
   6790 
   6791    /**
   6792     * @see #performAccessibilityAction(int, Bundle)
   6793     *
   6794     * Note: Called from the default {@link AccessibilityDelegate}.
   6795     */
   6796     boolean performAccessibilityActionInternal(int action, Bundle arguments) {
   6797         switch (action) {
   6798             case AccessibilityNodeInfo.ACTION_CLICK: {
   6799                 if (isClickable()) {
   6800                     return performClick();
   6801                 }
   6802             } break;
   6803             case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
   6804                 if (isLongClickable()) {
   6805                     return performLongClick();
   6806                 }
   6807             } break;
   6808             case AccessibilityNodeInfo.ACTION_FOCUS: {
   6809                 if (!hasFocus()) {
   6810                     // Get out of touch mode since accessibility
   6811                     // wants to move focus around.
   6812                     getViewRootImpl().ensureTouchMode(false);
   6813                     return requestFocus();
   6814                 }
   6815             } break;
   6816             case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
   6817                 if (hasFocus()) {
   6818                     clearFocus();
   6819                     return !isFocused();
   6820                 }
   6821             } break;
   6822             case AccessibilityNodeInfo.ACTION_SELECT: {
   6823                 if (!isSelected()) {
   6824                     setSelected(true);
   6825                     return isSelected();
   6826                 }
   6827             } break;
   6828             case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
   6829                 if (isSelected()) {
   6830                     setSelected(false);
   6831                     return !isSelected();
   6832                 }
   6833             } break;
   6834             case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
   6835                 final int mode = getAccessibilityFocusable();
   6836                 if (!isAccessibilityFocused()
   6837                         && (mode == ACCESSIBILITY_FOCUSABLE_YES
   6838                                 || mode == ACCESSIBILITY_FOCUSABLE_AUTO)) {
   6839                     return requestAccessibilityFocus();
   6840                 }
   6841             } break;
   6842             case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
   6843                 if (isAccessibilityFocused()) {
   6844                     clearAccessibilityFocus();
   6845                     return true;
   6846                 }
   6847             } break;
   6848             case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
   6849                 if (arguments != null) {
   6850                     final int granularity = arguments.getInt(
   6851                             AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
   6852                     return nextAtGranularity(granularity);
   6853                 }
   6854             } break;
   6855             case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
   6856                 if (arguments != null) {
   6857                     final int granularity = arguments.getInt(
   6858                             AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
   6859                     return previousAtGranularity(granularity);
   6860                 }
   6861             } break;
   6862         }
   6863         return false;
   6864     }
   6865 
   6866     private boolean nextAtGranularity(int granularity) {
   6867         CharSequence text = getIterableTextForAccessibility();
   6868         if (text == null || text.length() == 0) {
   6869             return false;
   6870         }
   6871         TextSegmentIterator iterator = getIteratorForGranularity(granularity);
   6872         if (iterator == null) {
   6873             return false;
   6874         }
   6875         final int current = getAccessibilityCursorPosition();
   6876         final int[] range = iterator.following(current);
   6877         if (range == null) {
   6878             return false;
   6879         }
   6880         final int start = range[0];
   6881         final int end = range[1];
   6882         setAccessibilityCursorPosition(end);
   6883         sendViewTextTraversedAtGranularityEvent(
   6884                 AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
   6885                 granularity, start, end);
   6886         return true;
   6887     }
   6888 
   6889     private boolean previousAtGranularity(int granularity) {
   6890         CharSequence text = getIterableTextForAccessibility();
   6891         if (text == null || text.length() == 0) {
   6892             return false;
   6893         }
   6894         TextSegmentIterator iterator = getIteratorForGranularity(granularity);
   6895         if (iterator == null) {
   6896             return false;
   6897         }
   6898         int current = getAccessibilityCursorPosition();
   6899         if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
   6900             current = text.length();
   6901         } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
   6902             // When traversing by character we always put the cursor after the character
   6903             // to ease edit and have to compensate before asking the for previous segment.
   6904             current--;
   6905         }
   6906         final int[] range = iterator.preceding(current);
   6907         if (range == null) {
   6908             return false;
   6909         }
   6910         final int start = range[0];
   6911         final int end = range[1];
   6912         // Always put the cursor after the character to ease edit.
   6913         if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
   6914             setAccessibilityCursorPosition(end);
   6915         } else {
   6916             setAccessibilityCursorPosition(start);
   6917         }
   6918         sendViewTextTraversedAtGranularityEvent(
   6919                 AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
   6920                 granularity, start, end);
   6921         return true;
   6922     }
   6923 
   6924     /**
   6925      * Gets the text reported for accessibility purposes.
   6926      *
   6927      * @return The accessibility text.
   6928      *
   6929      * @hide
   6930      */
   6931     public CharSequence getIterableTextForAccessibility() {
   6932         return mContentDescription;
   6933     }
   6934 
   6935     /**
   6936      * @hide
   6937      */
   6938     public int getAccessibilityCursorPosition() {
   6939         return mAccessibilityCursorPosition;
   6940     }
   6941 
   6942     /**
   6943      * @hide
   6944      */
   6945     public void setAccessibilityCursorPosition(int position) {
   6946         mAccessibilityCursorPosition = position;
   6947     }
   6948 
   6949     private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
   6950             int fromIndex, int toIndex) {
   6951         if (mParent == null) {
   6952             return;
   6953         }
   6954         AccessibilityEvent event = AccessibilityEvent.obtain(
   6955                 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
   6956         onInitializeAccessibilityEvent(event);
   6957         onPopulateAccessibilityEvent(event);
   6958         event.setFromIndex(fromIndex);
   6959         event.setToIndex(toIndex);
   6960         event.setAction(action);
   6961         event.setMovementGranularity(granularity);
   6962         mParent.requestSendAccessibilityEvent(this, event);
   6963     }
   6964 
   6965     /**
   6966      * @hide
   6967      */
   6968     public TextSegmentIterator getIteratorForGranularity(int granularity) {
   6969         switch (granularity) {
   6970             case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
   6971                 CharSequence text = getIterableTextForAccessibility();
   6972                 if (text != null && text.length() > 0) {
   6973                     CharacterTextSegmentIterator iterator =
   6974                         CharacterTextSegmentIterator.getInstance(
   6975                                 mContext.getResources().getConfiguration().locale);
   6976                     iterator.initialize(text.toString());
   6977                     return iterator;
   6978                 }
   6979             } break;
   6980             case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
   6981                 CharSequence text = getIterableTextForAccessibility();
   6982                 if (text != null && text.length() > 0) {
   6983                     WordTextSegmentIterator iterator =
   6984                         WordTextSegmentIterator.getInstance(
   6985                                 mContext.getResources().getConfiguration().locale);
   6986                     iterator.initialize(text.toString());
   6987                     return iterator;
   6988                 }
   6989             } break;
   6990             case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
   6991                 CharSequence text = getIterableTextForAccessibility();
   6992                 if (text != null && text.length() > 0) {
   6993                     ParagraphTextSegmentIterator iterator =
   6994                         ParagraphTextSegmentIterator.getInstance();
   6995                     iterator.initialize(text.toString());
   6996                     return iterator;
   6997                 }
   6998             } break;
   6999         }
   7000         return null;
   7001     }
   7002 
   7003     /**
   7004      * @hide
   7005      */
   7006     public void dispatchStartTemporaryDetach() {
   7007         clearAccessibilityFocus();
   7008         clearDisplayList();
   7009 
   7010         onStartTemporaryDetach();
   7011     }
   7012 
   7013     /**
   7014      * This is called when a container is going to temporarily detach a child, with
   7015      * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
   7016      * It will either be followed by {@link #onFinishTemporaryDetach()} or
   7017      * {@link #onDetachedFromWindow()} when the container is done.
   7018      */
   7019     public void onStartTemporaryDetach() {
   7020         removeUnsetPressCallback();
   7021         mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
   7022     }
   7023 
   7024     /**
   7025      * @hide
   7026      */
   7027     public void dispatchFinishTemporaryDetach() {
   7028         onFinishTemporaryDetach();
   7029     }
   7030 
   7031     /**
   7032      * Called after {@link #onStartTemporaryDetach} when the container is done
   7033      * changing the view.
   7034      */
   7035     public void onFinishTemporaryDetach() {
   7036     }
   7037 
   7038     /**
   7039      * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
   7040      * for this view's window.  Returns null if the view is not currently attached
   7041      * to the window.  Normally you will not need to use this directly, but
   7042      * just use the standard high-level event callbacks like
   7043      * {@link #onKeyDown(int, KeyEvent)}.
   7044      */
   7045     public KeyEvent.DispatcherState getKeyDispatcherState() {
   7046         return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
   7047     }
   7048 
   7049     /**
   7050      * Dispatch a key event before it is processed by any input method
   7051      * associated with the view hierarchy.  This can be used to intercept
   7052      * key events in special situations before the IME consumes them; a
   7053      * typical example would be handling the BACK key to update the application's
   7054      * UI instead of allowing the IME to see it and close itself.
   7055      *
   7056      * @param event The key event to be dispatched.
   7057      * @return True if the event was handled, false otherwise.
   7058      */
   7059     public boolean dispatchKeyEventPreIme(KeyEvent event) {
   7060         return onKeyPreIme(event.getKeyCode(), event);
   7061     }
   7062 
   7063     /**
   7064      * Dispatch a key event to the next view on the focus path. This path runs
   7065      * from the top of the view tree down to the currently focused view. If this
   7066      * view has focus, it will dispatch to itself. Otherwise it will dispatch
   7067      * the next node down the focus path. This method also fires any key
   7068      * listeners.
   7069      *
   7070      * @param event The key event to be dispatched.
   7071      * @return True if the event was handled, false otherwise.
   7072      */
   7073     public boolean dispatchKeyEvent(KeyEvent event) {
   7074         if (mInputEventConsistencyVerifier != null) {
   7075             mInputEventConsistencyVerifier.onKeyEvent(event, 0);
   7076         }
   7077 
   7078         // Give any attached key listener a first crack at the event.
   7079         //noinspection SimplifiableIfStatement
   7080         ListenerInfo li = mListenerInfo;
   7081         if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
   7082                 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
   7083             return true;
   7084         }
   7085 
   7086         if (event.dispatch(this, mAttachInfo != null
   7087                 ? mAttachInfo.mKeyDispatchState : null, this)) {
   7088             return true;
   7089         }
   7090 
   7091         if (mInputEventConsistencyVerifier != null) {
   7092             mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
   7093         }
   7094         return false;
   7095     }
   7096 
   7097     /**
   7098      * Dispatches a key shortcut event.
   7099      *
   7100      * @param event The key event to be dispatched.
   7101      * @return True if the event was handled by the view, false otherwise.
   7102      */
   7103     public boolean dispatchKeyShortcutEvent(KeyEvent event) {
   7104         return onKeyShortcut(event.getKeyCode(), event);
   7105     }
   7106 
   7107     /**
   7108      * Pass the touch screen motion event down to the target view, or this
   7109      * view if it is the target.
   7110      *
   7111      * @param event The motion event to be dispatched.
   7112      * @return True if the event was handled by the view, false otherwise.
   7113      */
   7114     public boolean dispatchTouchEvent(MotionEvent event) {
   7115         if (mInputEventConsistencyVerifier != null) {
   7116             mInputEventConsistencyVerifier.onTouchEvent(event, 0);
   7117         }
   7118 
   7119         if (onFilterTouchEventForSecurity(event)) {
   7120             //noinspection SimplifiableIfStatement
   7121             ListenerInfo li = mListenerInfo;
   7122             if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
   7123                     && li.mOnTouchListener.onTouch(this, event)) {
   7124                 return true;
   7125             }
   7126 
   7127             if (onTouchEvent(event)) {
   7128                 return true;
   7129             }
   7130         }
   7131 
   7132         if (mInputEventConsistencyVerifier != null) {
   7133             mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
   7134         }
   7135         return false;
   7136     }
   7137 
   7138     /**
   7139      * Filter the touch event to apply security policies.
   7140      *
   7141      * @param event The motion event to be filtered.
   7142      * @return True if the event should be dispatched, false if the event should be dropped.
   7143      *
   7144      * @see #getFilterTouchesWhenObscured
   7145      */
   7146     public boolean onFilterTouchEventForSecurity(MotionEvent event) {
   7147         //noinspection RedundantIfStatement
   7148         if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
   7149                 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
   7150             // Window is obscured, drop this touch.
   7151             return false;
   7152         }
   7153         return true;
   7154     }
   7155 
   7156     /**
   7157      * Pass a trackball motion event down to the focused view.
   7158      *
   7159      * @param event The motion event to be dispatched.
   7160      * @return True if the event was handled by the view, false otherwise.
   7161      */
   7162     public boolean dispatchTrackballEvent(MotionEvent event) {
   7163         if (mInputEventConsistencyVerifier != null) {
   7164             mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
   7165         }
   7166 
   7167         return onTrackballEvent(event);
   7168     }
   7169 
   7170     /**
   7171      * Dispatch a generic motion event.
   7172      * <p>
   7173      * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
   7174      * are delivered to the view under the pointer.  All other generic motion events are
   7175      * delivered to the focused view.  Hover events are handled specially and are delivered
   7176      * to {@link #onHoverEvent(MotionEvent)}.
   7177      * </p>
   7178      *
   7179      * @param event The motion event to be dispatched.
   7180      * @return True if the event was handled by the view, false otherwise.
   7181      */
   7182     public boolean dispatchGenericMotionEvent(MotionEvent event) {
   7183         if (mInputEventConsistencyVerifier != null) {
   7184             mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
   7185         }
   7186 
   7187         final int source = event.getSource();
   7188         if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
   7189             final int action = event.getAction();
   7190             if (action == MotionEvent.ACTION_HOVER_ENTER
   7191                     || action == MotionEvent.ACTION_HOVER_MOVE
   7192                     || action == MotionEvent.ACTION_HOVER_EXIT) {
   7193                 if (dispatchHoverEvent(event)) {
   7194                     return true;
   7195                 }
   7196             } else if (dispatchGenericPointerEvent(event)) {
   7197                 return true;
   7198             }
   7199         } else if (dispatchGenericFocusedEvent(event)) {
   7200             return true;
   7201         }
   7202 
   7203         if (dispatchGenericMotionEventInternal(event)) {
   7204             return true;
   7205         }
   7206 
   7207         if (mInputEventConsistencyVerifier != null) {
   7208             mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
   7209         }
   7210         return false;
   7211     }
   7212 
   7213     private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
   7214         //noinspection SimplifiableIfStatement
   7215         ListenerInfo li = mListenerInfo;
   7216         if (li != null && li.mOnGenericMotionListener != null
   7217                 && (mViewFlags & ENABLED_MASK) == ENABLED
   7218                 && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
   7219             return true;
   7220         }
   7221 
   7222         if (onGenericMotionEvent(event)) {
   7223             return true;
   7224         }
   7225 
   7226         if (mInputEventConsistencyVerifier != null) {
   7227             mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
   7228         }
   7229         return false;
   7230     }
   7231 
   7232     /**
   7233      * Dispatch a hover event.
   7234      * <p>
   7235      * Do not call this method directly.
   7236      * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
   7237      * </p>
   7238      *
   7239      * @param event The motion event to be dispatched.
   7240      * @return True if the event was handled by the view, false otherwise.
   7241      */
   7242     protected boolean dispatchHoverEvent(MotionEvent event) {
   7243         //noinspection SimplifiableIfStatement
   7244         ListenerInfo li = mListenerInfo;
   7245         if (li != null && li.mOnHoverListener != null
   7246                 && (mViewFlags & ENABLED_MASK) == ENABLED
   7247                 && li.mOnHoverListener.onHover(this, event)) {
   7248             return true;
   7249         }
   7250 
   7251         return onHoverEvent(event);
   7252     }
   7253 
   7254     /**
   7255      * Returns true if the view has a child to which it has recently sent
   7256      * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
   7257      * it does not have a hovered child, then it must be the innermost hovered view.
   7258      * @hide
   7259      */
   7260     protected boolean hasHoveredChild() {
   7261         return false;
   7262     }
   7263 
   7264     /**
   7265      * Dispatch a generic motion event to the view under the first pointer.
   7266      * <p>
   7267      * Do not call this method directly.
   7268      * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
   7269      * </p>
   7270      *
   7271      * @param event The motion event to be dispatched.
   7272      * @return True if the event was handled by the view, false otherwise.
   7273      */
   7274     protected boolean dispatchGenericPointerEvent(MotionEvent event) {
   7275         return false;
   7276     }
   7277 
   7278     /**
   7279      * Dispatch a generic motion event to the currently focused view.
   7280      * <p>
   7281      * Do not call this method directly.
   7282      * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
   7283      * </p>
   7284      *
   7285      * @param event The motion event to be dispatched.
   7286      * @return True if the event was handled by the view, false otherwise.
   7287      */
   7288     protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
   7289         return false;
   7290     }
   7291 
   7292     /**
   7293      * Dispatch a pointer event.
   7294      * <p>
   7295      * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
   7296      * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
   7297      * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
   7298      * and should not be expected to handle other pointing device features.
   7299      * </p>
   7300      *
   7301      * @param event The motion event to be dispatched.
   7302      * @return True if the event was handled by the view, false otherwise.
   7303      * @hide
   7304      */
   7305     public final boolean dispatchPointerEvent(MotionEvent event) {
   7306         if (event.isTouchEvent()) {
   7307             return dispatchTouchEvent(event);
   7308         } else {
   7309             return dispatchGenericMotionEvent(event);
   7310         }
   7311     }
   7312 
   7313     /**
   7314      * Called when the window containing this view gains or loses window focus.
   7315      * ViewGroups should override to route to their children.
   7316      *
   7317      * @param hasFocus True if the window containing this view now has focus,
   7318      *        false otherwise.
   7319      */
   7320     public void dispatchWindowFocusChanged(boolean hasFocus) {
   7321         onWindowFocusChanged(hasFocus);
   7322     }
   7323 
   7324     /**
   7325      * Called when the window containing this view gains or loses focus.  Note
   7326      * that this is separate from view focus: to receive key events, both
   7327      * your view and its window must have focus.  If a window is displayed
   7328      * on top of yours that takes input focus, then your own window will lose
   7329      * focus but the view focus will remain unchanged.
   7330      *
   7331      * @param hasWindowFocus True if the window containing this view now has
   7332      *        focus, false otherwise.
   7333      */
   7334     public void onWindowFocusChanged(boolean hasWindowFocus) {
   7335         InputMethodManager imm = InputMethodManager.peekInstance();
   7336         if (!hasWindowFocus) {
   7337             if (isPressed()) {
   7338                 setPressed(false);
   7339             }
   7340             if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
   7341                 imm.focusOut(this);
   7342             }
   7343             removeLongPressCallback();
   7344             removeTapCallback();
   7345             onFocusLost();
   7346         } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
   7347             imm.focusIn(this);
   7348         }
   7349         refreshDrawableState();
   7350     }
   7351 
   7352     /**
   7353      * Returns true if this view is in a window that currently has window focus.
   7354      * Note that this is not the same as the view itself having focus.
   7355      *
   7356      * @return True if this view is in a window that currently has window focus.
   7357      */
   7358     public boolean hasWindowFocus() {
   7359         return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
   7360     }
   7361 
   7362     /**
   7363      * Dispatch a view visibility change down the view hierarchy.
   7364      * ViewGroups should override to route to their children.
   7365      * @param changedView The view whose visibility changed. Could be 'this' or
   7366      * an ancestor view.
   7367      * @param visibility The new visibility of changedView: {@link #VISIBLE},
   7368      * {@link #INVISIBLE} or {@link #GONE}.
   7369      */
   7370     protected void dispatchVisibilityChanged(View changedView, int visibility) {
   7371         onVisibilityChanged(changedView, visibility);
   7372     }
   7373 
   7374     /**
   7375      * Called when the visibility of the view or an ancestor of the view is changed.
   7376      * @param changedView The view whose visibility changed. Could be 'this' or
   7377      * an ancestor view.
   7378      * @param visibility The new visibility of changedView: {@link #VISIBLE},
   7379      * {@link #INVISIBLE} or {@link #GONE}.
   7380      */
   7381     protected void onVisibilityChanged(View changedView, int visibility) {
   7382         if (visibility == VISIBLE) {
   7383             if (mAttachInfo != null) {
   7384                 initialAwakenScrollBars();
   7385             } else {
   7386                 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
   7387             }
   7388         }
   7389     }
   7390 
   7391     /**
   7392      * Dispatch a hint about whether this view is displayed. For instance, when
   7393      * a View moves out of the screen, it might receives a display hint indicating
   7394      * the view is not displayed. Applications should not <em>rely</em> on this hint
   7395      * as there is no guarantee that they will receive one.
   7396      *
   7397      * @param hint A hint about whether or not this view is displayed:
   7398      * {@link #VISIBLE} or {@link #INVISIBLE}.
   7399      */
   7400     public void dispatchDisplayHint(int hint) {
   7401         onDisplayHint(hint);
   7402     }
   7403 
   7404     /**
   7405      * Gives this view a hint about whether is displayed or not. For instance, when
   7406      * a View moves out of the screen, it might receives a display hint indicating
   7407      * the view is not displayed. Applications should not <em>rely</em> on this hint
   7408      * as there is no guarantee that they will receive one.
   7409      *
   7410      * @param hint A hint about whether or not this view is displayed:
   7411      * {@link #VISIBLE} or {@link #INVISIBLE}.
   7412      */
   7413     protected void onDisplayHint(int hint) {
   7414     }
   7415 
   7416     /**
   7417      * Dispatch a window visibility change down the view hierarchy.
   7418      * ViewGroups should override to route to their children.
   7419      *
   7420      * @param visibility The new visibility of the window.
   7421      *
   7422      * @see #onWindowVisibilityChanged(int)
   7423      */
   7424     public void dispatchWindowVisibilityChanged(int visibility) {
   7425         onWindowVisibilityChanged(visibility);
   7426     }
   7427 
   7428     /**
   7429      * Called when the window containing has change its visibility
   7430      * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
   7431      * that this tells you whether or not your window is being made visible
   7432      * to the window manager; this does <em>not</em> tell you whether or not
   7433      * your window is obscured by other windows on the screen, even if it
   7434      * is itself visible.
   7435      *
   7436      * @param visibility The new visibility of the window.
   7437      */
   7438     protected void onWindowVisibilityChanged(int visibility) {
   7439         if (visibility == VISIBLE) {
   7440             initialAwakenScrollBars();
   7441         }
   7442     }
   7443 
   7444     /**
   7445      * Returns the current visibility of the window this view is attached to
   7446      * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
   7447      *
   7448      * @return Returns the current visibility of the view's window.
   7449      */
   7450     public int getWindowVisibility() {
   7451         return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
   7452     }
   7453 
   7454     /**
   7455      * Retrieve the overall visible display size in which the window this view is
   7456      * attached to has been positioned in.  This takes into account screen
   7457      * decorations above the window, for both cases where the window itself
   7458      * is being position inside of them or the window is being placed under
   7459      * then and covered insets are used for the window to position its content
   7460      * inside.  In effect, this tells you the available area where content can
   7461      * be placed and remain visible to users.
   7462      *
   7463      * <p>This function requires an IPC back to the window manager to retrieve
   7464      * the requested information, so should not be used in performance critical
   7465      * code like drawing.
   7466      *
   7467      * @param outRect Filled in with the visible display frame.  If the view
   7468      * is not attached to a window, this is simply the raw display size.
   7469      */
   7470     public void getWindowVisibleDisplayFrame(Rect outRect) {
   7471         if (mAttachInfo != null) {
   7472             try {
   7473                 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
   7474             } catch (RemoteException e) {
   7475                 return;
   7476             }
   7477             // XXX This is really broken, and probably all needs to be done
   7478             // in the window manager, and we need to know more about whether
   7479             // we want the area behind or in front of the IME.
   7480             final Rect insets = mAttachInfo.mVisibleInsets;
   7481             outRect.left += insets.left;
   7482             outRect.top += insets.top;
   7483             outRect.right -= insets.right;
   7484             outRect.bottom -= insets.bottom;
   7485             return;
   7486         }
   7487         Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
   7488         d.getRectSize(outRect);
   7489     }
   7490 
   7491     /**
   7492      * Dispatch a notification about a resource configuration change down
   7493      * the view hierarchy.
   7494      * ViewGroups should override to route to their children.
   7495      *
   7496      * @param newConfig The new resource configuration.
   7497      *
   7498      * @see #onConfigurationChanged(android.content.res.Configuration)
   7499      */
   7500     public void dispatchConfigurationChanged(Configuration newConfig) {
   7501         onConfigurationChanged(newConfig);
   7502     }
   7503 
   7504     /**
   7505      * Called when the current configuration of the resources being used
   7506      * by the application have changed.  You can use this to decide when
   7507      * to reload resources that can changed based on orientation and other
   7508      * configuration characterstics.  You only need to use this if you are
   7509      * not relying on the normal {@link android.app.Activity} mechanism of
   7510      * recreating the activity instance upon a configuration change.
   7511      *
   7512      * @param newConfig The new resource configuration.
   7513      */
   7514     protected void onConfigurationChanged(Configuration newConfig) {
   7515     }
   7516 
   7517     /**
   7518      * Private function to aggregate all per-view attributes in to the view
   7519      * root.
   7520      */
   7521     void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
   7522         performCollectViewAttributes(attachInfo, visibility);
   7523     }
   7524 
   7525     void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
   7526         if ((visibility & VISIBILITY_MASK) == VISIBLE) {
   7527             if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
   7528                 attachInfo.mKeepScreenOn = true;
   7529             }
   7530             attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
   7531             ListenerInfo li = mListenerInfo;
   7532             if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
   7533                 attachInfo.mHasSystemUiListeners = true;
   7534             }
   7535         }
   7536     }
   7537 
   7538     void needGlobalAttributesUpdate(boolean force) {
   7539         final AttachInfo ai = mAttachInfo;
   7540         if (ai != null) {
   7541             if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
   7542                     || ai.mHasSystemUiListeners) {
   7543                 ai.mRecomputeGlobalAttributes = true;
   7544             }
   7545         }
   7546     }
   7547 
   7548     /**
   7549      * Returns whether the device is currently in touch mode.  Touch mode is entered
   7550      * once the user begins interacting with the device by touch, and affects various
   7551      * things like whether focus is always visible to the user.
   7552      *
   7553      * @return Whether the device is in touch mode.
   7554      */
   7555     @ViewDebug.ExportedProperty
   7556     public boolean isInTouchMode() {
   7557         if (mAttachInfo != null) {
   7558             return mAttachInfo.mInTouchMode;
   7559         } else {
   7560             return ViewRootImpl.isInTouchMode();
   7561         }
   7562     }
   7563 
   7564     /**
   7565      * Returns the context the view is running in, through which it can
   7566      * access the current theme, resources, etc.
   7567      *
   7568      * @return The view's Context.
   7569      */
   7570     @ViewDebug.CapturedViewProperty
   7571     public final Context getContext() {
   7572         return mContext;
   7573     }
   7574 
   7575     /**
   7576      * Handle a key event before it is processed by any input method
   7577      * associated with the view hierarchy.  This can be used to intercept
   7578      * key events in special situations before the IME consumes them; a
   7579      * typical example would be handling the BACK key to update the application's
   7580      * UI instead of allowing the IME to see it and close itself.
   7581      *
   7582      * @param keyCode The value in event.getKeyCode().
   7583      * @param event Description of the key event.
   7584      * @return If you handled the event, return true. If you want to allow the
   7585      *         event to be handled by the next receiver, return false.
   7586      */
   7587     public boolean onKeyPreIme(int keyCode, KeyEvent event) {
   7588         return false;
   7589     }
   7590 
   7591     /**
   7592      * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
   7593      * KeyEvent.Callback.onKeyDown()}: perform press of the view
   7594      * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
   7595      * is released, if the view is enabled and clickable.
   7596      *
   7597      * <p>Key presses in software keyboards will generally NOT trigger this listener,
   7598      * although some may elect to do so in some situations. Do not rely on this to
   7599      * catch software key presses.
   7600      *
   7601      * @param keyCode A key code that represents the button pressed, from
   7602      *                {@link android.view.KeyEvent}.
   7603      * @param event   The KeyEvent object that defines the button action.
   7604      */
   7605     public boolean onKeyDown(int keyCode, KeyEvent event) {
   7606         boolean result = false;
   7607 
   7608         switch (keyCode) {
   7609             case KeyEvent.KEYCODE_DPAD_CENTER:
   7610             case KeyEvent.KEYCODE_ENTER: {
   7611                 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
   7612                     return true;
   7613                 }
   7614                 // Long clickable items don't necessarily have to be clickable
   7615                 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
   7616                         (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
   7617                         (event.getRepeatCount() == 0)) {
   7618                     setPressed(true);
   7619                     checkForLongClick(0);
   7620                     return true;
   7621                 }
   7622                 break;
   7623             }
   7624         }
   7625         return result;
   7626     }
   7627 
   7628     /**
   7629      * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
   7630      * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
   7631      * the event).
   7632      * <p>Key presses in software keyboards will generally NOT trigger this listener,
   7633      * although some may elect to do so in some situations. Do not rely on this to
   7634      * catch software key presses.
   7635      */
   7636     public boolean onKeyLongPress(int keyCode, KeyEvent event) {
   7637         return false;
   7638     }
   7639 
   7640     /**
   7641      * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
   7642      * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
   7643      * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
   7644      * {@link KeyEvent#KEYCODE_ENTER} is released.
   7645      * <p>Key presses in software keyboards will generally NOT trigger this listener,
   7646      * although some may elect to do so in some situations. Do not rely on this to
   7647      * catch software key presses.
   7648      *
   7649      * @param keyCode A key code that represents the button pressed, from
   7650      *                {@link android.view.KeyEvent}.
   7651      * @param event   The KeyEvent object that defines the button action.
   7652      */
   7653     public boolean onKeyUp(int keyCode, KeyEvent event) {
   7654         boolean result = false;
   7655 
   7656         switch (keyCode) {
   7657             case KeyEvent.KEYCODE_DPAD_CENTER:
   7658             case KeyEvent.KEYCODE_ENTER: {
   7659                 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
   7660                     return true;
   7661                 }
   7662                 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
   7663                     setPressed(false);
   7664 
   7665                     if (!mHasPerformedLongPress) {
   7666                         // This is a tap, so remove the longpress check
   7667                         removeLongPressCallback();
   7668 
   7669                         result = performClick();
   7670                     }
   7671                 }
   7672                 break;
   7673             }
   7674         }
   7675         return result;
   7676     }
   7677 
   7678     /**
   7679      * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
   7680      * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
   7681      * the event).
   7682      * <p>Key presses in software keyboards will generally NOT trigger this listener,
   7683      * although some may elect to do so in some situations. Do not rely on this to
   7684      * catch software key presses.
   7685      *
   7686      * @param keyCode     A key code that represents the button pressed, from
   7687      *                    {@link android.view.KeyEvent}.
   7688      * @param repeatCount The number of times the action was made.
   7689      * @param event       The KeyEvent object that defines the button action.
   7690      */
   7691     public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
   7692         return false;
   7693     }
   7694 
   7695     /**
   7696      * Called on the focused view when a key shortcut event is not handled.
   7697      * Override this method to implement local key shortcuts for the View.
   7698      * Key shortcuts can also be implemented by setting the
   7699      * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
   7700      *
   7701      * @param keyCode The value in event.getKeyCode().
   7702      * @param event Description of the key event.
   7703      * @return If you handled the event, return true. If you want to allow the
   7704      *         event to be handled by the next receiver, return false.
   7705      */
   7706     public boolean onKeyShortcut(int keyCode, KeyEvent event) {
   7707         return false;
   7708     }
   7709 
   7710     /**
   7711      * Check whether the called view is a text editor, in which case it
   7712      * would make sense to automatically display a soft input window for
   7713      * it.  Subclasses should override this if they implement
   7714      * {@link #onCreateInputConnection(EditorInfo)} to return true if
   7715      * a call on that method would return a non-null InputConnection, and
   7716      * they are really a first-class editor that the user would normally
   7717      * start typing on when the go into a window containing your view.
   7718      *
   7719      * <p>The default implementation always returns false.  This does
   7720      * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
   7721      * will not be called or the user can not otherwise perform edits on your
   7722      * view; it is just a hint to the system that this is not the primary
   7723      * purpose of this view.
   7724      *
   7725      * @return Returns true if this view is a text editor, else false.
   7726      */
   7727     public boolean onCheckIsTextEditor() {
   7728         return false;
   7729     }
   7730 
   7731     /**
   7732      * Create a new InputConnection for an InputMethod to interact
   7733      * with the view.  The default implementation returns null, since it doesn't
   7734      * support input methods.  You can override this to implement such support.
   7735      * This is only needed for views that take focus and text input.
   7736      *
   7737      * <p>When implementing this, you probably also want to implement
   7738      * {@link #onCheckIsTextEditor()} to indicate you will return a
   7739      * non-null InputConnection.
   7740      *
   7741      * @param outAttrs Fill in with attribute information about the connection.
   7742      */
   7743     public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
   7744         return null;
   7745     }
   7746 
   7747     /**
   7748      * Called by the {@link android.view.inputmethod.InputMethodManager}
   7749      * when a view who is not the current
   7750      * input connection target is trying to make a call on the manager.  The
   7751      * default implementation returns false; you can override this to return
   7752      * true for certain views if you are performing InputConnection proxying
   7753      * to them.
   7754      * @param view The View that is making the InputMethodManager call.
   7755      * @return Return true to allow the call, false to reject.
   7756      */
   7757     public boolean checkInputConnectionProxy(View view) {
   7758         return false;
   7759     }
   7760 
   7761     /**
   7762      * Show the context menu for this view. It is not safe to hold on to the
   7763      * menu after returning from this method.
   7764      *
   7765      * You should normally not overload this method. Overload
   7766      * {@link #onCreateContextMenu(ContextMenu)} or define an
   7767      * {@link OnCreateContextMenuListener} to add items to the context menu.
   7768      *
   7769      * @param menu The context menu to populate
   7770      */
   7771     public void createContextMenu(ContextMenu menu) {
   7772         ContextMenuInfo menuInfo = getContextMenuInfo();
   7773 
   7774         // Sets the current menu info so all items added to menu will have
   7775         // my extra info set.
   7776         ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
   7777 
   7778         onCreateContextMenu(menu);
   7779         ListenerInfo li = mListenerInfo;
   7780         if (li != null && li.mOnCreateContextMenuListener != null) {
   7781             li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
   7782         }
   7783 
   7784         // Clear the extra information so subsequent items that aren't mine don't
   7785         // have my extra info.
   7786         ((MenuBuilder)menu).setCurrentMenuInfo(null);
   7787 
   7788         if (mParent != null) {
   7789             mParent.createContextMenu(menu);
   7790         }
   7791     }
   7792 
   7793     /**
   7794      * Views should implement this if they have extra information to associate
   7795      * with the context menu. The return result is supplied as a parameter to
   7796      * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
   7797      * callback.
   7798      *
   7799      * @return Extra information about the item for which the context menu
   7800      *         should be shown. This information will vary across different
   7801      *         subclasses of View.
   7802      */
   7803     protected ContextMenuInfo getContextMenuInfo() {
   7804         return null;
   7805     }
   7806 
   7807     /**
   7808      * Views should implement this if the view itself is going to add items to
   7809      * the context menu.
   7810      *
   7811      * @param menu the context menu to populate
   7812      */
   7813     protected void onCreateContextMenu(ContextMenu menu) {
   7814     }
   7815 
   7816     /**
   7817      * Implement this method to handle trackball motion events.  The
   7818      * <em>relative</em> movement of the trackball since the last event
   7819      * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
   7820      * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
   7821      * that a movement of 1 corresponds to the user pressing one DPAD key (so
   7822      * they will often be fractional values, representing the more fine-grained
   7823      * movement information available from a trackball).
   7824      *
   7825      * @param event The motion event.
   7826      * @return True if the event was handled, false otherwise.
   7827      */
   7828     public boolean onTrackballEvent(MotionEvent event) {
   7829         return false;
   7830     }
   7831 
   7832     /**
   7833      * Implement this method to handle generic motion events.
   7834      * <p>
   7835      * Generic motion events describe joystick movements, mouse hovers, track pad
   7836      * touches, scroll wheel movements and other input events.  The
   7837      * {@link MotionEvent#getSource() source} of the motion event specifies
   7838      * the class of input that was received.  Implementations of this method
   7839      * must examine the bits in the source before processing the event.
   7840      * The following code example shows how this is done.
   7841      * </p><p>
   7842      * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
   7843      * are delivered to the view under the pointer.  All other generic motion events are
   7844      * delivered to the focused view.
   7845      * </p>
   7846      * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
   7847      *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
   7848      *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
   7849      *             // process the joystick movement...
   7850      *             return true;
   7851      *         }
   7852      *     }
   7853      *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
   7854      *         switch (event.getAction()) {
   7855      *             case MotionEvent.ACTION_HOVER_MOVE:
   7856      *                 // process the mouse hover movement...
   7857      *                 return true;
   7858      *             case MotionEvent.ACTION_SCROLL:
   7859      *                 // process the scroll wheel movement...
   7860      *                 return true;
   7861      *         }
   7862      *     }
   7863      *     return super.onGenericMotionEvent(event);
   7864      * }</pre>
   7865      *
   7866      * @param event The generic motion event being processed.
   7867      * @return True if the event was handled, false otherwise.
   7868      */
   7869     public boolean onGenericMotionEvent(MotionEvent event) {
   7870         return false;
   7871     }
   7872 
   7873     /**
   7874      * Implement this method to handle hover events.
   7875      * <p>
   7876      * This method is called whenever a pointer is hovering into, over, or out of the
   7877      * bounds of a view and the view is not currently being touched.
   7878      * Hover events are represented as pointer events with action
   7879      * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
   7880      * or {@link MotionEvent#ACTION_HOVER_EXIT}.
   7881      * </p>
   7882      * <ul>
   7883      * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
   7884      * when the pointer enters the bounds of the view.</li>
   7885      * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
   7886      * when the pointer has already entered the bounds of the view and has moved.</li>
   7887      * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
   7888      * when the pointer has exited the bounds of the view or when the pointer is
   7889      * about to go down due to a button click, tap, or similar user action that
   7890      * causes the view to be touched.</li>
   7891      * </ul>
   7892      * <p>
   7893      * The view should implement this method to return true to indicate that it is
   7894      * handling the hover event, such as by changing its drawable state.
   7895      * </p><p>
   7896      * The default implementation calls {@link #setHovered} to update the hovered state
   7897      * of the view when a hover enter or hover exit event is received, if the view
   7898      * is enabled and is clickable.  The default implementation also sends hover
   7899      * accessibility events.
   7900      * </p>
   7901      *
   7902      * @param event The motion event that describes the hover.
   7903      * @return True if the view handled the hover event.
   7904      *
   7905      * @see #isHovered
   7906      * @see #setHovered
   7907      * @see #onHoverChanged
   7908      */
   7909     public boolean onHoverEvent(MotionEvent event) {
   7910         // The root view may receive hover (or touch) events that are outside the bounds of
   7911         // the window.  This code ensures that we only send accessibility events for
   7912         // hovers that are actually within the bounds of the root view.
   7913         final int action = event.getActionMasked();
   7914         if (!mSendingHoverAccessibilityEvents) {
   7915             if ((action == MotionEvent.ACTION_HOVER_ENTER
   7916                     || action == MotionEvent.ACTION_HOVER_MOVE)
   7917                     && !hasHoveredChild()
   7918                     && pointInView(event.getX(), event.getY())) {
   7919                 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
   7920                 mSendingHoverAccessibilityEvents = true;
   7921             }
   7922         } else {
   7923             if (action == MotionEvent.ACTION_HOVER_EXIT
   7924                     || (action == MotionEvent.ACTION_MOVE
   7925                             && !pointInView(event.getX(), event.getY()))) {
   7926                 mSendingHoverAccessibilityEvents = false;
   7927                 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
   7928                 // If the window does not have input focus we take away accessibility
   7929                 // focus as soon as the user stop hovering over the view.
   7930                 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
   7931                     getViewRootImpl().setAccessibilityFocus(null, null);
   7932                 }
   7933             }
   7934         }
   7935 
   7936         if (isHoverable()) {
   7937             switch (action) {
   7938                 case MotionEvent.ACTION_HOVER_ENTER:
   7939                     setHovered(true);
   7940                     break;
   7941                 case MotionEvent.ACTION_HOVER_EXIT:
   7942                     setHovered(false);
   7943                     break;
   7944             }
   7945 
   7946             // Dispatch the event to onGenericMotionEvent before returning true.
   7947             // This is to provide compatibility with existing applications that
   7948             // handled HOVER_MOVE events in onGenericMotionEvent and that would
   7949             // break because of the new default handling for hoverable views
   7950             // in onHoverEvent.
   7951             // Note that onGenericMotionEvent will be called by default when
   7952             // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
   7953             dispatchGenericMotionEventInternal(event);
   7954             return true;
   7955         }
   7956 
   7957         return false;
   7958     }
   7959 
   7960     /**
   7961      * Returns true if the view should handle {@link #onHoverEvent}
   7962      * by calling {@link #setHovered} to change its hovered state.
   7963      *
   7964      * @return True if the view is hoverable.
   7965      */
   7966     private boolean isHoverable() {
   7967         final int viewFlags = mViewFlags;
   7968         if ((viewFlags & ENABLED_MASK) == DISABLED) {
   7969             return false;
   7970         }
   7971 
   7972         return (viewFlags & CLICKABLE) == CLICKABLE
   7973                 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
   7974     }
   7975 
   7976     /**
   7977      * Returns true if the view is currently hovered.
   7978      *
   7979      * @return True if the view is currently hovered.
   7980      *
   7981      * @see #setHovered
   7982      * @see #onHoverChanged
   7983      */
   7984     @ViewDebug.ExportedProperty
   7985     public boolean isHovered() {
   7986         return (mPrivateFlags & HOVERED) != 0;
   7987     }
   7988 
   7989     /**
   7990      * Sets whether the view is currently hovered.
   7991      * <p>
   7992      * Calling this method also changes the drawable state of the view.  This
   7993      * enables the view to react to hover by using different drawable resources
   7994      * to change its appearance.
   7995      * </p><p>
   7996      * The {@link #onHoverChanged} method is called when the hovered state changes.
   7997      * </p>
   7998      *
   7999      * @param hovered True if the view is hovered.
   8000      *
   8001      * @see #isHovered
   8002      * @see #onHoverChanged
   8003      */
   8004     public void setHovered(boolean hovered) {
   8005         if (hovered) {
   8006             if ((mPrivateFlags & HOVERED) == 0) {
   8007                 mPrivateFlags |= HOVERED;
   8008                 refreshDrawableState();
   8009                 onHoverChanged(true);
   8010             }
   8011         } else {
   8012             if ((mPrivateFlags & HOVERED) != 0) {
   8013                 mPrivateFlags &= ~HOVERED;
   8014                 refreshDrawableState();
   8015                 onHoverChanged(false);
   8016             }
   8017         }
   8018     }
   8019 
   8020     /**
   8021      * Implement this method to handle hover state changes.
   8022      * <p>
   8023      * This method is called whenever the hover state changes as a result of a
   8024      * call to {@link #setHovered}.
   8025      * </p>
   8026      *
   8027      * @param hovered The current hover state, as returned by {@link #isHovered}.
   8028      *
   8029      * @see #isHovered
   8030      * @see #setHovered
   8031      */
   8032     public void onHoverChanged(boolean hovered) {
   8033     }
   8034 
   8035     /**
   8036      * Implement this method to handle touch screen motion events.
   8037      *
   8038      * @param event The motion event.
   8039      * @return True if the event was handled, false otherwise.
   8040      */
   8041     public boolean onTouchEvent(MotionEvent event) {
   8042         final int viewFlags = mViewFlags;
   8043 
   8044         if ((viewFlags & ENABLED_MASK) == DISABLED) {
   8045             if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
   8046                 setPressed(false);
   8047             }
   8048             // A disabled view that is clickable still consumes the touch
   8049             // events, it just doesn't respond to them.
   8050             return (((viewFlags & CLICKABLE) == CLICKABLE ||
   8051                     (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
   8052         }
   8053 
   8054         if (mTouchDelegate != null) {
   8055             if (mTouchDelegate.onTouchEvent(event)) {
   8056                 return true;
   8057             }
   8058         }
   8059 
   8060         if (((viewFlags & CLICKABLE) == CLICKABLE ||
   8061                 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
   8062             switch (event.getAction()) {
   8063                 case MotionEvent.ACTION_UP:
   8064                     boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
   8065                     if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
   8066                         // take focus if we don't have it already and we should in
   8067                         // touch mode.
   8068                         boolean focusTaken = false;
   8069                         if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
   8070                             focusTaken = requestFocus();
   8071                         }
   8072 
   8073                         if (prepressed) {
   8074                             // The button is being released before we actually
   8075                             // showed it as pressed.  Make it show the pressed
   8076                             // state now (before scheduling the click) to ensure
   8077                             // the user sees it.
   8078                             setPressed(true);
   8079                        }
   8080 
   8081                         if (!mHasPerformedLongPress) {
   8082                             // This is a tap, so remove the longpress check
   8083                             removeLongPressCallback();
   8084 
   8085                             // Only perform take click actions if we were in the pressed state
   8086                             if (!focusTaken) {
   8087                                 // Use a Runnable and post this rather than calling
   8088                                 // performClick directly. This lets other visual state
   8089                                 // of the view update before click actions start.
   8090                                 if (mPerformClick == null) {
   8091                                     mPerformClick = new PerformClick();
   8092                                 }
   8093                                 if (!post(mPerformClick)) {
   8094                                     performClick();
   8095                                 }
   8096                             }
   8097                         }
   8098 
   8099                         if (mUnsetPressedState == null) {
   8100                             mUnsetPressedState = new UnsetPressedState();
   8101                         }
   8102 
   8103                         if (prepressed) {
   8104                             postDelayed(mUnsetPressedState,
   8105                                     ViewConfiguration.getPressedStateDuration());
   8106                         } else if (!post(mUnsetPressedState)) {
   8107                             // If the post failed, unpress right now
   8108                             mUnsetPressedState.run();
   8109                         }
   8110                         removeTapCallback();
   8111                     }
   8112                     break;
   8113 
   8114                 case MotionEvent.ACTION_DOWN:
   8115                     mHasPerformedLongPress = false;
   8116 
   8117                     if (performButtonActionOnTouchDown(event)) {
   8118                         break;
   8119                     }
   8120 
   8121                     // Walk up the hierarchy to determine if we're inside a scrolling container.
   8122                     boolean isInScrollingContainer = isInScrollingContainer();
   8123 
   8124                     // For views inside a scrolling container, delay the pressed feedback for
   8125                     // a short period in case this is a scroll.
   8126                     if (isInScrollingContainer) {
   8127                         mPrivateFlags |= PREPRESSED;
   8128                         if (mPendingCheckForTap == null) {
   8129                             mPendingCheckForTap = new CheckForTap();
   8130                         }
   8131                         postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
   8132                     } else {
   8133                         // Not inside a scrolling container, so show the feedback right away
   8134                         setPressed(true);
   8135                         checkForLongClick(0);
   8136                     }
   8137                     break;
   8138 
   8139                 case MotionEvent.ACTION_CANCEL:
   8140                     setPressed(false);
   8141                     removeTapCallback();
   8142                     break;
   8143 
   8144                 case MotionEvent.ACTION_MOVE:
   8145                     final int x = (int) event.getX();
   8146                     final int y = (int) event.getY();
   8147 
   8148                     // Be lenient about moving outside of buttons
   8149                     if (!pointInView(x, y, mTouchSlop)) {
   8150                         // Outside button
   8151                         removeTapCallback();
   8152                         if ((mPrivateFlags & PRESSED) != 0) {
   8153                             // Remove any future long press/tap checks
   8154                             removeLongPressCallback();
   8155 
   8156                             setPressed(false);
   8157                         }
   8158                     }
   8159                     break;
   8160             }
   8161             return true;
   8162         }
   8163 
   8164         return false;
   8165     }
   8166 
   8167     /**
   8168      * @hide
   8169      */
   8170     public boolean isInScrollingContainer() {
   8171         ViewParent p = getParent();
   8172         while (p != null && p instanceof ViewGroup) {
   8173             if (((ViewGroup) p).shouldDelayChildPressedState()) {
   8174                 return true;
   8175             }
   8176             p = p.getParent();
   8177         }
   8178         return false;
   8179     }
   8180 
   8181     /**
   8182      * Remove the longpress detection timer.
   8183      */
   8184     private void removeLongPressCallback() {
   8185         if (mPendingCheckForLongPress != null) {
   8186           removeCallbacks(mPendingCheckForLongPress);
   8187         }
   8188     }
   8189 
   8190     /**
   8191      * Remove the pending click action
   8192      */
   8193     private void removePerformClickCallback() {
   8194         if (mPerformClick != null) {
   8195             removeCallbacks(mPerformClick);
   8196         }
   8197     }
   8198 
   8199     /**
   8200      * Remove the prepress detection timer.
   8201      */
   8202     private void removeUnsetPressCallback() {
   8203         if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
   8204             setPressed(false);
   8205             removeCallbacks(mUnsetPressedState);
   8206         }
   8207     }
   8208 
   8209     /**
   8210      * Remove the tap detection timer.
   8211      */
   8212     private void removeTapCallback() {
   8213         if (mPendingCheckForTap != null) {
   8214             mPrivateFlags &= ~PREPRESSED;
   8215             removeCallbacks(mPendingCheckForTap);
   8216         }
   8217     }
   8218 
   8219     /**
   8220      * Cancels a pending long press.  Your subclass can use this if you
   8221      * want the context menu to come up if the user presses and holds
   8222      * at the same place, but you don't want it to come up if they press
   8223      * and then move around enough to cause scrolling.
   8224      */
   8225     public void cancelLongPress() {
   8226         removeLongPressCallback();
   8227 
   8228         /*
   8229          * The prepressed state handled by the tap callback is a display
   8230          * construct, but the tap callback will post a long press callback
   8231          * less its own timeout. Remove it here.
   8232          */
   8233         removeTapCallback();
   8234     }
   8235 
   8236     /**
   8237      * Remove the pending callback for sending a
   8238      * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
   8239      */
   8240     private void removeSendViewScrolledAccessibilityEventCallback() {
   8241         if (mSendViewScrolledAccessibilityEvent != null) {
   8242             removeCallbacks(mSendViewScrolledAccessibilityEvent);
   8243             mSendViewScrolledAccessibilityEvent.mIsPending = false;
   8244         }
   8245     }
   8246 
   8247     /**
   8248      * Sets the TouchDelegate for this View.
   8249      */
   8250     public void setTouchDelegate(TouchDelegate delegate) {
   8251         mTouchDelegate = delegate;
   8252     }
   8253 
   8254     /**
   8255      * Gets the TouchDelegate for this View.
   8256      */
   8257     public TouchDelegate getTouchDelegate() {
   8258         return mTouchDelegate;
   8259     }
   8260 
   8261     /**
   8262      * Set flags controlling behavior of this view.
   8263      *
   8264      * @param flags Constant indicating the value which should be set
   8265      * @param mask Constant indicating the bit range that should be changed
   8266      */
   8267     void setFlags(int flags, int mask) {
   8268         int old = mViewFlags;
   8269         mViewFlags = (mViewFlags & ~mask) | (flags & mask);
   8270 
   8271         int changed = mViewFlags ^ old;
   8272         if (changed == 0) {
   8273             return;
   8274         }
   8275         int privateFlags = mPrivateFlags;
   8276 
   8277         /* Check if the FOCUSABLE bit has changed */
   8278         if (((changed & FOCUSABLE_MASK) != 0) &&
   8279                 ((privateFlags & HAS_BOUNDS) !=0)) {
   8280             if (((old & FOCUSABLE_MASK) == FOCUSABLE)
   8281                     && ((privateFlags & FOCUSED) != 0)) {
   8282                 /* Give up focus if we are no longer focusable */
   8283                 clearFocus();
   8284             } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
   8285                     && ((privateFlags & FOCUSED) == 0)) {
   8286                 /*
   8287                  * Tell the view system that we are now available to take focus
   8288                  * if no one else already has it.
   8289                  */
   8290                 if (mParent != null) mParent.focusableViewAvailable(this);
   8291             }
   8292             if (AccessibilityManager.getInstance(mContext).isEnabled()) {
   8293                 notifyAccessibilityStateChanged();
   8294             }
   8295         }
   8296 
   8297         if ((flags & VISIBILITY_MASK) == VISIBLE) {
   8298             if ((changed & VISIBILITY_MASK) != 0) {
   8299                 /*
   8300                  * If this view is becoming visible, invalidate it in case it changed while
   8301                  * it was not visible. Marking it drawn ensures that the invalidation will
   8302                  * go through.
   8303                  */
   8304                 mPrivateFlags |= DRAWN;
   8305                 invalidate(true);
   8306 
   8307                 needGlobalAttributesUpdate(true);
   8308 
   8309                 // a view becoming visible is worth notifying the parent
   8310                 // about in case nothing has focus.  even if this specific view
   8311                 // isn't focusable, it may contain something that is, so let
   8312                 // the root view try to give this focus if nothing else does.
   8313                 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
   8314                     mParent.focusableViewAvailable(this);
   8315                 }
   8316             }
   8317         }
   8318 
   8319         /* Check if the GONE bit has changed */
   8320         if ((changed & GONE) != 0) {
   8321             needGlobalAttributesUpdate(false);
   8322             requestLayout();
   8323 
   8324             if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
   8325                 if (hasFocus()) clearFocus();
   8326                 clearAccessibilityFocus();
   8327                 destroyDrawingCache();
   8328                 if (mParent instanceof View) {
   8329                     // GONE views noop invalidation, so invalidate the parent
   8330                     ((View) mParent).invalidate(true);
   8331                 }
   8332                 // Mark the view drawn to ensure that it gets invalidated properly the next
   8333                 // time it is visible and gets invalidated
   8334                 mPrivateFlags |= DRAWN;
   8335             }
   8336             if (mAttachInfo != null) {
   8337                 mAttachInfo.mViewVisibilityChanged = true;
   8338             }
   8339         }
   8340 
   8341         /* Check if the VISIBLE bit has changed */
   8342         if ((changed & INVISIBLE) != 0) {
   8343             needGlobalAttributesUpdate(false);
   8344             /*
   8345              * If this view is becoming invisible, set the DRAWN flag so that
   8346              * the next invalidate() will not be skipped.
   8347              */
   8348             mPrivateFlags |= DRAWN;
   8349 
   8350             if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
   8351                 // root view becoming invisible shouldn't clear focus and accessibility focus
   8352                 if (getRootView() != this) {
   8353                     clearFocus();
   8354                     clearAccessibilityFocus();
   8355                 }
   8356             }
   8357             if (mAttachInfo != null) {
   8358                 mAttachInfo.mViewVisibilityChanged = true;
   8359             }
   8360         }
   8361 
   8362         if ((changed & VISIBILITY_MASK) != 0) {
   8363             if (mParent instanceof ViewGroup) {
   8364                 ((ViewGroup) mParent).onChildVisibilityChanged(this,
   8365                         (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
   8366                 ((View) mParent).invalidate(true);
   8367             } else if (mParent != null) {
   8368                 mParent.invalidateChild(this, null);
   8369             }
   8370             dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
   8371         }
   8372 
   8373         if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
   8374             destroyDrawingCache();
   8375         }
   8376 
   8377         if ((changed & DRAWING_CACHE_ENABLED) != 0) {
   8378             destroyDrawingCache();
   8379             mPrivateFlags &= ~DRAWING_CACHE_VALID;
   8380             invalidateParentCaches();
   8381         }
   8382 
   8383         if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
   8384             destroyDrawingCache();
   8385             mPrivateFlags &= ~DRAWING_CACHE_VALID;
   8386         }
   8387 
   8388         if ((changed & DRAW_MASK) != 0) {
   8389             if ((mViewFlags & WILL_NOT_DRAW) != 0) {
   8390                 if (mBackground != null) {
   8391                     mPrivateFlags &= ~SKIP_DRAW;
   8392                     mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
   8393                 } else {
   8394                     mPrivateFlags |= SKIP_DRAW;
   8395                 }
   8396             } else {
   8397                 mPrivateFlags &= ~SKIP_DRAW;
   8398             }
   8399             requestLayout();
   8400             invalidate(true);
   8401         }
   8402 
   8403         if ((changed & KEEP_SCREEN_ON) != 0) {
   8404             if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
   8405                 mParent.recomputeViewAttributes(this);
   8406             }
   8407         }
   8408 
   8409         if (AccessibilityManager.getInstance(mContext).isEnabled()
   8410                 && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
   8411                         || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
   8412             notifyAccessibilityStateChanged();
   8413         }
   8414     }
   8415 
   8416     /**
   8417      * Change the view's z order in the tree, so it's on top of other sibling
   8418      * views
   8419      */
   8420     public void bringToFront() {
   8421         if (mParent != null) {
   8422             mParent.bringChildToFront(this);
   8423         }
   8424     }
   8425 
   8426     /**
   8427      * This is called in response to an internal scroll in this view (i.e., the
   8428      * view scrolled its own contents). This is typically as a result of
   8429      * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
   8430      * called.
   8431      *
   8432      * @param l Current horizontal scroll origin.
   8433      * @param t Current vertical scroll origin.
   8434      * @param oldl Previous horizontal scroll origin.
   8435      * @param oldt Previous vertical scroll origin.
   8436      */
   8437     protected void onScrollChanged(int l, int t, int oldl, int oldt) {
   8438         if (AccessibilityManager.getInstance(mContext).isEnabled()) {
   8439             postSendViewScrolledAccessibilityEventCallback();
   8440         }
   8441 
   8442         mBackgroundSizeChanged = true;
   8443 
   8444         final AttachInfo ai = mAttachInfo;
   8445         if (ai != null) {
   8446             ai.mViewScrollChanged = true;
   8447         }
   8448     }
   8449 
   8450     /**
   8451      * Interface definition for a callback to be invoked when the layout bounds of a view
   8452      * changes due to layout processing.
   8453      */
   8454     public interface OnLayoutChangeListener {
   8455         /**
   8456          * Called when the focus state of a view has changed.
   8457          *
   8458          * @param v The view whose state has changed.
   8459          * @param left The new value of the view's left property.
   8460          * @param top The new value of the view's top property.
   8461          * @param right The new value of the view's right property.
   8462          * @param bottom The new value of the view's bottom property.
   8463          * @param oldLeft The previous value of the view's left property.
   8464          * @param oldTop The previous value of the view's top property.
   8465          * @param oldRight The previous value of the view's right property.
   8466          * @param oldBottom The previous value of the view's bottom property.
   8467          */
   8468         void onLayoutChange(View v, int left, int top, int right, int bottom,
   8469             int oldLeft, int oldTop, int oldRight, int oldBottom);
   8470     }
   8471 
   8472     /**
   8473      * This is called during layout when the size of this view has changed. If
   8474      * you were just added to the view hierarchy, you're called with the old
   8475      * values of 0.
   8476      *
   8477      * @param w Current width of this view.
   8478      * @param h Current height of this view.
   8479      * @param oldw Old width of this view.
   8480      * @param oldh Old height of this view.
   8481      */
   8482     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
   8483     }
   8484 
   8485     /**
   8486      * Called by draw to draw the child views. This may be overridden
   8487      * by derived classes to gain control just before its children are drawn
   8488      * (but after its own view has been drawn).
   8489      * @param canvas the canvas on which to draw the view
   8490      */
   8491     protected void dispatchDraw(Canvas canvas) {
   8492 
   8493     }
   8494 
   8495     /**
   8496      * Gets the parent of this view. Note that the parent is a
   8497      * ViewParent and not necessarily a View.
   8498      *
   8499      * @return Parent of this view.
   8500      */
   8501     public final ViewParent getParent() {
   8502         return mParent;
   8503     }
   8504 
   8505     /**
   8506      * Set the horizontal scrolled position of your view. This will cause a call to
   8507      * {@link #onScrollChanged(int, int, int, int)} and the view will be
   8508      * invalidated.
   8509      * @param value the x position to scroll to
   8510      */
   8511     public void setScrollX(int value) {
   8512         scrollTo(value, mScrollY);
   8513     }
   8514 
   8515     /**
   8516      * Set the vertical scrolled position of your view. This will cause a call to
   8517      * {@link #onScrollChanged(int, int, int, int)} and the view will be
   8518      * invalidated.
   8519      * @param value the y position to scroll to
   8520      */
   8521     public void setScrollY(int value) {
   8522         scrollTo(mScrollX, value);
   8523     }
   8524 
   8525     /**
   8526      * Return the scrolled left position of this view. This is the left edge of
   8527      * the displayed part of your view. You do not need to draw any pixels
   8528      * farther left, since those are outside of the frame of your view on
   8529      * screen.
   8530      *
   8531      * @return The left edge of the displayed part of your view, in pixels.
   8532      */
   8533     public final int getScrollX() {
   8534         return mScrollX;
   8535     }
   8536 
   8537     /**
   8538      * Return the scrolled top position of this view. This is the top edge of
   8539      * the displayed part of your view. You do not need to draw any pixels above
   8540      * it, since those are outside of the frame of your view on screen.
   8541      *
   8542      * @return The top edge of the displayed part of your view, in pixels.
   8543      */
   8544     public final int getScrollY() {
   8545         return mScrollY;
   8546     }
   8547 
   8548     /**
   8549      * Return the width of the your view.
   8550      *
   8551      * @return The width of your view, in pixels.
   8552      */
   8553     @ViewDebug.ExportedProperty(category = "layout")
   8554     public final int getWidth() {
   8555         return mRight - mLeft;
   8556     }
   8557 
   8558     /**
   8559      * Return the height of your view.
   8560      *
   8561      * @return The height of your view, in pixels.
   8562      */
   8563     @ViewDebug.ExportedProperty(category = "layout")
   8564     public final int getHeight() {
   8565         return mBottom - mTop;
   8566     }
   8567 
   8568     /**
   8569      * Return the visible drawing bounds of your view. Fills in the output
   8570      * rectangle with the values from getScrollX(), getScrollY(),
   8571      * getWidth(), and getHeight().
   8572      *
   8573      * @param outRect The (scrolled) drawing bounds of the view.
   8574      */
   8575     public void getDrawingRect(Rect outRect) {
   8576         outRect.left = mScrollX;
   8577         outRect.top = mScrollY;
   8578         outRect.right = mScrollX + (mRight - mLeft);
   8579         outRect.bottom = mScrollY + (mBottom - mTop);
   8580     }
   8581 
   8582     /**
   8583      * Like {@link #getMeasuredWidthAndState()}, but only returns the
   8584      * raw width component (that is the result is masked by
   8585      * {@link #MEASURED_SIZE_MASK}).
   8586      *
   8587      * @return The raw measured width of this view.
   8588      */
   8589     public final int getMeasuredWidth() {
   8590         return mMeasuredWidth & MEASURED_SIZE_MASK;
   8591     }
   8592 
   8593     /**
   8594      * Return the full width measurement information for this view as computed
   8595      * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
   8596      * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
   8597      * This should be used during measurement and layout calculations only. Use
   8598      * {@link #getWidth()} to see how wide a view is after layout.
   8599      *
   8600      * @return The measured width of this view as a bit mask.
   8601      */
   8602     public final int getMeasuredWidthAndState() {
   8603         return mMeasuredWidth;
   8604     }
   8605 
   8606     /**
   8607      * Like {@link #getMeasuredHeightAndState()}, but only returns the
   8608      * raw width component (that is the result is masked by
   8609      * {@link #MEASURED_SIZE_MASK}).
   8610      *
   8611      * @return The raw measured height of this view.
   8612      */
   8613     public final int getMeasuredHeight() {
   8614         return mMeasuredHeight & MEASURED_SIZE_MASK;
   8615     }
   8616 
   8617     /**
   8618      * Return the full height measurement information for this view as computed
   8619      * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
   8620      * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
   8621      * This should be used during measurement and layout calculations only. Use
   8622      * {@link #getHeight()} to see how wide a view is after layout.
   8623      *
   8624      * @return The measured width of this view as a bit mask.
   8625      */
   8626     public final int getMeasuredHeightAndState() {
   8627         return mMeasuredHeight;
   8628     }
   8629 
   8630     /**
   8631      * Return only the state bits of {@link #getMeasuredWidthAndState()}
   8632      * and {@link #getMeasuredHeightAndState()}, combined into one integer.
   8633      * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
   8634      * and the height component is at the shifted bits
   8635      * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
   8636      */
   8637     public final int getMeasuredState() {
   8638         return (mMeasuredWidth&MEASURED_STATE_MASK)
   8639                 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
   8640                         & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
   8641     }
   8642 
   8643     /**
   8644      * The transform matrix of this view, which is calculated based on the current
   8645      * roation, scale, and pivot properties.
   8646      *
   8647      * @see #getRotation()
   8648      * @see #getScaleX()
   8649      * @see #getScaleY()
   8650      * @see #getPivotX()
   8651      * @see #getPivotY()
   8652      * @return The current transform matrix for the view
   8653      */
   8654     public Matrix getMatrix() {
   8655         if (mTransformationInfo != null) {
   8656             updateMatrix();
   8657             return mTransformationInfo.mMatrix;
   8658         }
   8659         return Matrix.IDENTITY_MATRIX;
   8660     }
   8661 
   8662     /**
   8663      * Utility function to determine if the value is far enough away from zero to be
   8664      * considered non-zero.
   8665      * @param value A floating point value to check for zero-ness
   8666      * @return whether the passed-in value is far enough away from zero to be considered non-zero
   8667      */
   8668     private static boolean nonzero(float value) {
   8669         return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
   8670     }
   8671 
   8672     /**
   8673      * Returns true if the transform matrix is the identity matrix.
   8674      * Recomputes the matrix if necessary.
   8675      *
   8676      * @return True if the transform matrix is the identity matrix, false otherwise.
   8677      */
   8678     final boolean hasIdentityMatrix() {
   8679         if (mTransformationInfo != null) {
   8680             updateMatrix();
   8681             return mTransformationInfo.mMatrixIsIdentity;
   8682         }
   8683         return true;
   8684     }
   8685 
   8686     void ensureTransformationInfo() {
   8687         if (mTransformationInfo == null) {
   8688             mTransformationInfo = new TransformationInfo();
   8689         }
   8690     }
   8691 
   8692     /**
   8693      * Recomputes the transform matrix if necessary.
   8694      */
   8695     private void updateMatrix() {
   8696         final TransformationInfo info = mTransformationInfo;
   8697         if (info == null) {
   8698             return;
   8699         }
   8700         if (info.mMatrixDirty) {
   8701             // transform-related properties have changed since the last time someone
   8702             // asked for the matrix; recalculate it with the current values
   8703 
   8704             // Figure out if we need to update the pivot point
   8705             if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
   8706                 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
   8707                     info.mPrevWidth = mRight - mLeft;
   8708                     info.mPrevHeight = mBottom - mTop;
   8709                     info.mPivotX = info.mPrevWidth / 2f;
   8710                     info.mPivotY = info.mPrevHeight / 2f;
   8711                 }
   8712             }
   8713             info.mMatrix.reset();
   8714             if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
   8715                 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
   8716                 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
   8717                 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
   8718             } else {
   8719                 if (info.mCamera == null) {
   8720                     info.mCamera = new Camera();
   8721                     info.matrix3D = new Matrix();
   8722                 }
   8723                 info.mCamera.save();
   8724                 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
   8725                 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
   8726                 info.mCamera.getMatrix(info.matrix3D);
   8727                 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
   8728                 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
   8729                         info.mPivotY + info.mTranslationY);
   8730                 info.mMatrix.postConcat(info.matrix3D);
   8731                 info.mCamera.restore();
   8732             }
   8733             info.mMatrixDirty = false;
   8734             info.mMatrixIsIdentity = info.mMatrix.isIdentity();
   8735             info.mInverseMatrixDirty = true;
   8736         }
   8737     }
   8738 
   8739     /**
   8740      * Utility method to retrieve the inverse of the current mMatrix property.
   8741      * We cache the matrix to avoid recalculating it when transform properties
   8742      * have not changed.
   8743      *
   8744      * @return The inverse of the current matrix of this view.
   8745      */
   8746     final Matrix getInverseMatrix() {
   8747         final TransformationInfo info = mTransformationInfo;
   8748         if (info != null) {
   8749             updateMatrix();
   8750             if (info.mInverseMatrixDirty) {
   8751                 if (info.mInverseMatrix == null) {
   8752                     info.mInverseMatrix = new Matrix();
   8753                 }
   8754                 info.mMatrix.invert(info.mInverseMatrix);
   8755                 info.mInverseMatrixDirty = false;
   8756             }
   8757             return info.mInverseMatrix;
   8758         }
   8759         return Matrix.IDENTITY_MATRIX;
   8760     }
   8761 
   8762     /**
   8763      * Gets the distance along the Z axis from the camera to this view.
   8764      *
   8765      * @see #setCameraDistance(float)
   8766      *
   8767      * @return The distance along the Z axis.
   8768      */
   8769     public float getCameraDistance() {
   8770         ensureTransformationInfo();
   8771         final float dpi = mResources.getDisplayMetrics().densityDpi;
   8772         final TransformationInfo info = mTransformationInfo;
   8773         if (info.mCamera == null) {
   8774             info.mCamera = new Camera();
   8775             info.matrix3D = new Matrix();
   8776         }
   8777         return -(info.mCamera.getLocationZ() * dpi);
   8778     }
   8779 
   8780     /**
   8781      * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
   8782      * views are drawn) from the camera to this view. The camera's distance
   8783      * affects 3D transformations, for instance rotations around the X and Y
   8784      * axis. If the rotationX or rotationY properties are changed and this view is
   8785      * large (more than half the size of the screen), it is recommended to always
   8786      * use a camera distance that's greater than the height (X axis rotation) or
   8787      * the width (Y axis rotation) of this view.</p>
   8788      *
   8789      * <p>The distance of the camera from the view plane can have an affect on the
   8790      * perspective distortion of the view when it is rotated around the x or y axis.
   8791      * For example, a large distance will result in a large viewing angle, and there
   8792      * will not be much perspective distortion of the view as it rotates. A short
   8793      * distance may cause much more perspective distortion upon rotation, and can
   8794      * also result in some drawing artifacts if the rotated view ends up partially
   8795      * behind the camera (which is why the recommendation is to use a distance at
   8796      * least as far as the size of the view, if the view is to be rotated.)</p>
   8797      *
   8798      * <p>The distance is expressed in "depth pixels." The default distance depends
   8799      * on the screen density. For instance, on a medium density display, the
   8800      * default distance is 1280. On a high density display, the default distance
   8801      * is 1920.</p>
   8802      *
   8803      * <p>If you want to specify a distance that leads to visually consistent
   8804      * results across various densities, use the following formula:</p>
   8805      * <pre>
   8806      * float scale = context.getResources().getDisplayMetrics().density;
   8807      * view.setCameraDistance(distance * scale);
   8808      * </pre>
   8809      *
   8810      * <p>The density scale factor of a high density display is 1.5,
   8811      * and 1920 = 1280 * 1.5.</p>
   8812      *
   8813      * @param distance The distance in "depth pixels", if negative the opposite
   8814      *        value is used
   8815      *
   8816      * @see #setRotationX(float)
   8817      * @see #setRotationY(float)
   8818      */
   8819     public void setCameraDistance(float distance) {
   8820         invalidateViewProperty(true, false);
   8821 
   8822         ensureTransformationInfo();
   8823         final float dpi = mResources.getDisplayMetrics().densityDpi;
   8824         final TransformationInfo info = mTransformationInfo;
   8825         if (info.mCamera == null) {
   8826             info.mCamera = new Camera();
   8827             info.matrix3D = new Matrix();
   8828         }
   8829 
   8830         info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
   8831         info.mMatrixDirty = true;
   8832 
   8833         invalidateViewProperty(false, false);
   8834         if (mDisplayList != null) {
   8835             mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
   8836         }
   8837         if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   8838             // View was rejected last time it was drawn by its parent; this may have changed
   8839             invalidateParentIfNeeded();
   8840         }
   8841     }
   8842 
   8843     /**
   8844      * The degrees that the view is rotated around the pivot point.
   8845      *
   8846      * @see #setRotation(float)
   8847      * @see #getPivotX()
   8848      * @see #getPivotY()
   8849      *
   8850      * @return The degrees of rotation.
   8851      */
   8852     @ViewDebug.ExportedProperty(category = "drawing")
   8853     public float getRotation() {
   8854         return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
   8855     }
   8856 
   8857     /**
   8858      * Sets the degrees that the view is rotated around the pivot point. Increasing values
   8859      * result in clockwise rotation.
   8860      *
   8861      * @param rotation The degrees of rotation.
   8862      *
   8863      * @see #getRotation()
   8864      * @see #getPivotX()
   8865      * @see #getPivotY()
   8866      * @see #setRotationX(float)
   8867      * @see #setRotationY(float)
   8868      *
   8869      * @attr ref android.R.styleable#View_rotation
   8870      */
   8871     public void setRotation(float rotation) {
   8872         ensureTransformationInfo();
   8873         final TransformationInfo info = mTransformationInfo;
   8874         if (info.mRotation != rotation) {
   8875             // Double-invalidation is necessary to capture view's old and new areas
   8876             invalidateViewProperty(true, false);
   8877             info.mRotation = rotation;
   8878             info.mMatrixDirty = true;
   8879             invalidateViewProperty(false, true);
   8880             if (mDisplayList != null) {
   8881                 mDisplayList.setRotation(rotation);
   8882             }
   8883             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   8884                 // View was rejected last time it was drawn by its parent; this may have changed
   8885                 invalidateParentIfNeeded();
   8886             }
   8887         }
   8888     }
   8889 
   8890     /**
   8891      * The degrees that the view is rotated around the vertical axis through the pivot point.
   8892      *
   8893      * @see #getPivotX()
   8894      * @see #getPivotY()
   8895      * @see #setRotationY(float)
   8896      *
   8897      * @return The degrees of Y rotation.
   8898      */
   8899     @ViewDebug.ExportedProperty(category = "drawing")
   8900     public float getRotationY() {
   8901         return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
   8902     }
   8903 
   8904     /**
   8905      * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
   8906      * Increasing values result in counter-clockwise rotation from the viewpoint of looking
   8907      * down the y axis.
   8908      *
   8909      * When rotating large views, it is recommended to adjust the camera distance
   8910      * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
   8911      *
   8912      * @param rotationY The degrees of Y rotation.
   8913      *
   8914      * @see #getRotationY()
   8915      * @see #getPivotX()
   8916      * @see #getPivotY()
   8917      * @see #setRotation(float)
   8918      * @see #setRotationX(float)
   8919      * @see #setCameraDistance(float)
   8920      *
   8921      * @attr ref android.R.styleable#View_rotationY
   8922      */
   8923     public void setRotationY(float rotationY) {
   8924         ensureTransformationInfo();
   8925         final TransformationInfo info = mTransformationInfo;
   8926         if (info.mRotationY != rotationY) {
   8927             invalidateViewProperty(true, false);
   8928             info.mRotationY = rotationY;
   8929             info.mMatrixDirty = true;
   8930             invalidateViewProperty(false, true);
   8931             if (mDisplayList != null) {
   8932                 mDisplayList.setRotationY(rotationY);
   8933             }
   8934             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   8935                 // View was rejected last time it was drawn by its parent; this may have changed
   8936                 invalidateParentIfNeeded();
   8937             }
   8938         }
   8939     }
   8940 
   8941     /**
   8942      * The degrees that the view is rotated around the horizontal axis through the pivot point.
   8943      *
   8944      * @see #getPivotX()
   8945      * @see #getPivotY()
   8946      * @see #setRotationX(float)
   8947      *
   8948      * @return The degrees of X rotation.
   8949      */
   8950     @ViewDebug.ExportedProperty(category = "drawing")
   8951     public float getRotationX() {
   8952         return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
   8953     }
   8954 
   8955     /**
   8956      * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
   8957      * Increasing values result in clockwise rotation from the viewpoint of looking down the
   8958      * x axis.
   8959      *
   8960      * When rotating large views, it is recommended to adjust the camera distance
   8961      * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
   8962      *
   8963      * @param rotationX The degrees of X rotation.
   8964      *
   8965      * @see #getRotationX()
   8966      * @see #getPivotX()
   8967      * @see #getPivotY()
   8968      * @see #setRotation(float)
   8969      * @see #setRotationY(float)
   8970      * @see #setCameraDistance(float)
   8971      *
   8972      * @attr ref android.R.styleable#View_rotationX
   8973      */
   8974     public void setRotationX(float rotationX) {
   8975         ensureTransformationInfo();
   8976         final TransformationInfo info = mTransformationInfo;
   8977         if (info.mRotationX != rotationX) {
   8978             invalidateViewProperty(true, false);
   8979             info.mRotationX = rotationX;
   8980             info.mMatrixDirty = true;
   8981             invalidateViewProperty(false, true);
   8982             if (mDisplayList != null) {
   8983                 mDisplayList.setRotationX(rotationX);
   8984             }
   8985             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   8986                 // View was rejected last time it was drawn by its parent; this may have changed
   8987                 invalidateParentIfNeeded();
   8988             }
   8989         }
   8990     }
   8991 
   8992     /**
   8993      * The amount that the view is scaled in x around the pivot point, as a proportion of
   8994      * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
   8995      *
   8996      * <p>By default, this is 1.0f.
   8997      *
   8998      * @see #getPivotX()
   8999      * @see #getPivotY()
   9000      * @return The scaling factor.
   9001      */
   9002     @ViewDebug.ExportedProperty(category = "drawing")
   9003     public float getScaleX() {
   9004         return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
   9005     }
   9006 
   9007     /**
   9008      * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
   9009      * the view's unscaled width. A value of 1 means that no scaling is applied.
   9010      *
   9011      * @param scaleX The scaling factor.
   9012      * @see #getPivotX()
   9013      * @see #getPivotY()
   9014      *
   9015      * @attr ref android.R.styleable#View_scaleX
   9016      */
   9017     public void setScaleX(float scaleX) {
   9018         ensureTransformationInfo();
   9019         final TransformationInfo info = mTransformationInfo;
   9020         if (info.mScaleX != scaleX) {
   9021             invalidateViewProperty(true, false);
   9022             info.mScaleX = scaleX;
   9023             info.mMatrixDirty = true;
   9024             invalidateViewProperty(false, true);
   9025             if (mDisplayList != null) {
   9026                 mDisplayList.setScaleX(scaleX);
   9027             }
   9028             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9029                 // View was rejected last time it was drawn by its parent; this may have changed
   9030                 invalidateParentIfNeeded();
   9031             }
   9032         }
   9033     }
   9034 
   9035     /**
   9036      * The amount that the view is scaled in y around the pivot point, as a proportion of
   9037      * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
   9038      *
   9039      * <p>By default, this is 1.0f.
   9040      *
   9041      * @see #getPivotX()
   9042      * @see #getPivotY()
   9043      * @return The scaling factor.
   9044      */
   9045     @ViewDebug.ExportedProperty(category = "drawing")
   9046     public float getScaleY() {
   9047         return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
   9048     }
   9049 
   9050     /**
   9051      * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
   9052      * the view's unscaled width. A value of 1 means that no scaling is applied.
   9053      *
   9054      * @param scaleY The scaling factor.
   9055      * @see #getPivotX()
   9056      * @see #getPivotY()
   9057      *
   9058      * @attr ref android.R.styleable#View_scaleY
   9059      */
   9060     public void setScaleY(float scaleY) {
   9061         ensureTransformationInfo();
   9062         final TransformationInfo info = mTransformationInfo;
   9063         if (info.mScaleY != scaleY) {
   9064             invalidateViewProperty(true, false);
   9065             info.mScaleY = scaleY;
   9066             info.mMatrixDirty = true;
   9067             invalidateViewProperty(false, true);
   9068             if (mDisplayList != null) {
   9069                 mDisplayList.setScaleY(scaleY);
   9070             }
   9071             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9072                 // View was rejected last time it was drawn by its parent; this may have changed
   9073                 invalidateParentIfNeeded();
   9074             }
   9075         }
   9076     }
   9077 
   9078     /**
   9079      * The x location of the point around which the view is {@link #setRotation(float) rotated}
   9080      * and {@link #setScaleX(float) scaled}.
   9081      *
   9082      * @see #getRotation()
   9083      * @see #getScaleX()
   9084      * @see #getScaleY()
   9085      * @see #getPivotY()
   9086      * @return The x location of the pivot point.
   9087      *
   9088      * @attr ref android.R.styleable#View_transformPivotX
   9089      */
   9090     @ViewDebug.ExportedProperty(category = "drawing")
   9091     public float getPivotX() {
   9092         return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
   9093     }
   9094 
   9095     /**
   9096      * Sets the x location of the point around which the view is
   9097      * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
   9098      * By default, the pivot point is centered on the object.
   9099      * Setting this property disables this behavior and causes the view to use only the
   9100      * explicitly set pivotX and pivotY values.
   9101      *
   9102      * @param pivotX The x location of the pivot point.
   9103      * @see #getRotation()
   9104      * @see #getScaleX()
   9105      * @see #getScaleY()
   9106      * @see #getPivotY()
   9107      *
   9108      * @attr ref android.R.styleable#View_transformPivotX
   9109      */
   9110     public void setPivotX(float pivotX) {
   9111         ensureTransformationInfo();
   9112         mPrivateFlags |= PIVOT_EXPLICITLY_SET;
   9113         final TransformationInfo info = mTransformationInfo;
   9114         if (info.mPivotX != pivotX) {
   9115             invalidateViewProperty(true, false);
   9116             info.mPivotX = pivotX;
   9117             info.mMatrixDirty = true;
   9118             invalidateViewProperty(false, true);
   9119             if (mDisplayList != null) {
   9120                 mDisplayList.setPivotX(pivotX);
   9121             }
   9122             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9123                 // View was rejected last time it was drawn by its parent; this may have changed
   9124                 invalidateParentIfNeeded();
   9125             }
   9126         }
   9127     }
   9128 
   9129     /**
   9130      * The y location of the point around which the view is {@link #setRotation(float) rotated}
   9131      * and {@link #setScaleY(float) scaled}.
   9132      *
   9133      * @see #getRotation()
   9134      * @see #getScaleX()
   9135      * @see #getScaleY()
   9136      * @see #getPivotY()
   9137      * @return The y location of the pivot point.
   9138      *
   9139      * @attr ref android.R.styleable#View_transformPivotY
   9140      */
   9141     @ViewDebug.ExportedProperty(category = "drawing")
   9142     public float getPivotY() {
   9143         return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
   9144     }
   9145 
   9146     /**
   9147      * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
   9148      * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
   9149      * Setting this property disables this behavior and causes the view to use only the
   9150      * explicitly set pivotX and pivotY values.
   9151      *
   9152      * @param pivotY The y location of the pivot point.
   9153      * @see #getRotation()
   9154      * @see #getScaleX()
   9155      * @see #getScaleY()
   9156      * @see #getPivotY()
   9157      *
   9158      * @attr ref android.R.styleable#View_transformPivotY
   9159      */
   9160     public void setPivotY(float pivotY) {
   9161         ensureTransformationInfo();
   9162         mPrivateFlags |= PIVOT_EXPLICITLY_SET;
   9163         final TransformationInfo info = mTransformationInfo;
   9164         if (info.mPivotY != pivotY) {
   9165             invalidateViewProperty(true, false);
   9166             info.mPivotY = pivotY;
   9167             info.mMatrixDirty = true;
   9168             invalidateViewProperty(false, true);
   9169             if (mDisplayList != null) {
   9170                 mDisplayList.setPivotY(pivotY);
   9171             }
   9172             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9173                 // View was rejected last time it was drawn by its parent; this may have changed
   9174                 invalidateParentIfNeeded();
   9175             }
   9176         }
   9177     }
   9178 
   9179     /**
   9180      * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
   9181      * completely transparent and 1 means the view is completely opaque.
   9182      *
   9183      * <p>By default this is 1.0f.
   9184      * @return The opacity of the view.
   9185      */
   9186     @ViewDebug.ExportedProperty(category = "drawing")
   9187     public float getAlpha() {
   9188         return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
   9189     }
   9190 
   9191     /**
   9192      * Returns whether this View has content which overlaps. This function, intended to be
   9193      * overridden by specific View types, is an optimization when alpha is set on a view. If
   9194      * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
   9195      * and then composited it into place, which can be expensive. If the view has no overlapping
   9196      * rendering, the view can draw each primitive with the appropriate alpha value directly.
   9197      * An example of overlapping rendering is a TextView with a background image, such as a
   9198      * Button. An example of non-overlapping rendering is a TextView with no background, or
   9199      * an ImageView with only the foreground image. The default implementation returns true;
   9200      * subclasses should override if they have cases which can be optimized.
   9201      *
   9202      * @return true if the content in this view might overlap, false otherwise.
   9203      */
   9204     public boolean hasOverlappingRendering() {
   9205         return true;
   9206     }
   9207 
   9208     /**
   9209      * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
   9210      * completely transparent and 1 means the view is completely opaque.</p>
   9211      *
   9212      * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
   9213      * responsible for applying the opacity itself. Otherwise, calling this method is
   9214      * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
   9215      * setting a hardware layer.</p>
   9216      *
   9217      * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
   9218      * performance implications. It is generally best to use the alpha property sparingly and
   9219      * transiently, as in the case of fading animations.</p>
   9220      *
   9221      * @param alpha The opacity of the view.
   9222      *
   9223      * @see #setLayerType(int, android.graphics.Paint)
   9224      *
   9225      * @attr ref android.R.styleable#View_alpha
   9226      */
   9227     public void setAlpha(float alpha) {
   9228         ensureTransformationInfo();
   9229         if (mTransformationInfo.mAlpha != alpha) {
   9230             mTransformationInfo.mAlpha = alpha;
   9231             if (onSetAlpha((int) (alpha * 255))) {
   9232                 mPrivateFlags |= ALPHA_SET;
   9233                 // subclass is handling alpha - don't optimize rendering cache invalidation
   9234                 invalidateParentCaches();
   9235                 invalidate(true);
   9236             } else {
   9237                 mPrivateFlags &= ~ALPHA_SET;
   9238                 invalidateViewProperty(true, false);
   9239                 if (mDisplayList != null) {
   9240                     mDisplayList.setAlpha(alpha);
   9241                 }
   9242             }
   9243         }
   9244     }
   9245 
   9246     /**
   9247      * Faster version of setAlpha() which performs the same steps except there are
   9248      * no calls to invalidate(). The caller of this function should perform proper invalidation
   9249      * on the parent and this object. The return value indicates whether the subclass handles
   9250      * alpha (the return value for onSetAlpha()).
   9251      *
   9252      * @param alpha The new value for the alpha property
   9253      * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
   9254      *         the new value for the alpha property is different from the old value
   9255      */
   9256     boolean setAlphaNoInvalidation(float alpha) {
   9257         ensureTransformationInfo();
   9258         if (mTransformationInfo.mAlpha != alpha) {
   9259             mTransformationInfo.mAlpha = alpha;
   9260             boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
   9261             if (subclassHandlesAlpha) {
   9262                 mPrivateFlags |= ALPHA_SET;
   9263                 return true;
   9264             } else {
   9265                 mPrivateFlags &= ~ALPHA_SET;
   9266                 if (mDisplayList != null) {
   9267                     mDisplayList.setAlpha(alpha);
   9268                 }
   9269             }
   9270         }
   9271         return false;
   9272     }
   9273 
   9274     /**
   9275      * Top position of this view relative to its parent.
   9276      *
   9277      * @return The top of this view, in pixels.
   9278      */
   9279     @ViewDebug.CapturedViewProperty
   9280     public final int getTop() {
   9281         return mTop;
   9282     }
   9283 
   9284     /**
   9285      * Sets the top position of this view relative to its parent. This method is meant to be called
   9286      * by the layout system and should not generally be called otherwise, because the property
   9287      * may be changed at any time by the layout.
   9288      *
   9289      * @param top The top of this view, in pixels.
   9290      */
   9291     public final void setTop(int top) {
   9292         if (top != mTop) {
   9293             updateMatrix();
   9294             final boolean matrixIsIdentity = mTransformationInfo == null
   9295                     || mTransformationInfo.mMatrixIsIdentity;
   9296             if (matrixIsIdentity) {
   9297                 if (mAttachInfo != null) {
   9298                     int minTop;
   9299                     int yLoc;
   9300                     if (top < mTop) {
   9301                         minTop = top;
   9302                         yLoc = top - mTop;
   9303                     } else {
   9304                         minTop = mTop;
   9305                         yLoc = 0;
   9306                     }
   9307                     invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
   9308                 }
   9309             } else {
   9310                 // Double-invalidation is necessary to capture view's old and new areas
   9311                 invalidate(true);
   9312             }
   9313 
   9314             int width = mRight - mLeft;
   9315             int oldHeight = mBottom - mTop;
   9316 
   9317             mTop = top;
   9318             if (mDisplayList != null) {
   9319                 mDisplayList.setTop(mTop);
   9320             }
   9321 
   9322             onSizeChanged(width, mBottom - mTop, width, oldHeight);
   9323 
   9324             if (!matrixIsIdentity) {
   9325                 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
   9326                     // A change in dimension means an auto-centered pivot point changes, too
   9327                     mTransformationInfo.mMatrixDirty = true;
   9328                 }
   9329                 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
   9330                 invalidate(true);
   9331             }
   9332             mBackgroundSizeChanged = true;
   9333             invalidateParentIfNeeded();
   9334             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9335                 // View was rejected last time it was drawn by its parent; this may have changed
   9336                 invalidateParentIfNeeded();
   9337             }
   9338         }
   9339     }
   9340 
   9341     /**
   9342      * Bottom position of this view relative to its parent.
   9343      *
   9344      * @return The bottom of this view, in pixels.
   9345      */
   9346     @ViewDebug.CapturedViewProperty
   9347     public final int getBottom() {
   9348         return mBottom;
   9349     }
   9350 
   9351     /**
   9352      * True if this view has changed since the last time being drawn.
   9353      *
   9354      * @return The dirty state of this view.
   9355      */
   9356     public boolean isDirty() {
   9357         return (mPrivateFlags & DIRTY_MASK) != 0;
   9358     }
   9359 
   9360     /**
   9361      * Sets the bottom position of this view relative to its parent. This method is meant to be
   9362      * called by the layout system and should not generally be called otherwise, because the
   9363      * property may be changed at any time by the layout.
   9364      *
   9365      * @param bottom The bottom of this view, in pixels.
   9366      */
   9367     public final void setBottom(int bottom) {
   9368         if (bottom != mBottom) {
   9369             updateMatrix();
   9370             final boolean matrixIsIdentity = mTransformationInfo == null
   9371                     || mTransformationInfo.mMatrixIsIdentity;
   9372             if (matrixIsIdentity) {
   9373                 if (mAttachInfo != null) {
   9374                     int maxBottom;
   9375                     if (bottom < mBottom) {
   9376                         maxBottom = mBottom;
   9377                     } else {
   9378                         maxBottom = bottom;
   9379                     }
   9380                     invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
   9381                 }
   9382             } else {
   9383                 // Double-invalidation is necessary to capture view's old and new areas
   9384                 invalidate(true);
   9385             }
   9386 
   9387             int width = mRight - mLeft;
   9388             int oldHeight = mBottom - mTop;
   9389 
   9390             mBottom = bottom;
   9391             if (mDisplayList != null) {
   9392                 mDisplayList.setBottom(mBottom);
   9393             }
   9394 
   9395             onSizeChanged(width, mBottom - mTop, width, oldHeight);
   9396 
   9397             if (!matrixIsIdentity) {
   9398                 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
   9399                     // A change in dimension means an auto-centered pivot point changes, too
   9400                     mTransformationInfo.mMatrixDirty = true;
   9401                 }
   9402                 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
   9403                 invalidate(true);
   9404             }
   9405             mBackgroundSizeChanged = true;
   9406             invalidateParentIfNeeded();
   9407             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9408                 // View was rejected last time it was drawn by its parent; this may have changed
   9409                 invalidateParentIfNeeded();
   9410             }
   9411         }
   9412     }
   9413 
   9414     /**
   9415      * Left position of this view relative to its parent.
   9416      *
   9417      * @return The left edge of this view, in pixels.
   9418      */
   9419     @ViewDebug.CapturedViewProperty
   9420     public final int getLeft() {
   9421         return mLeft;
   9422     }
   9423 
   9424     /**
   9425      * Sets the left position of this view relative to its parent. This method is meant to be called
   9426      * by the layout system and should not generally be called otherwise, because the property
   9427      * may be changed at any time by the layout.
   9428      *
   9429      * @param left The bottom of this view, in pixels.
   9430      */
   9431     public final void setLeft(int left) {
   9432         if (left != mLeft) {
   9433             updateMatrix();
   9434             final boolean matrixIsIdentity = mTransformationInfo == null
   9435                     || mTransformationInfo.mMatrixIsIdentity;
   9436             if (matrixIsIdentity) {
   9437                 if (mAttachInfo != null) {
   9438                     int minLeft;
   9439                     int xLoc;
   9440                     if (left < mLeft) {
   9441                         minLeft = left;
   9442                         xLoc = left - mLeft;
   9443                     } else {
   9444                         minLeft = mLeft;
   9445                         xLoc = 0;
   9446                     }
   9447                     invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
   9448                 }
   9449             } else {
   9450                 // Double-invalidation is necessary to capture view's old and new areas
   9451                 invalidate(true);
   9452             }
   9453 
   9454             int oldWidth = mRight - mLeft;
   9455             int height = mBottom - mTop;
   9456 
   9457             mLeft = left;
   9458             if (mDisplayList != null) {
   9459                 mDisplayList.setLeft(left);
   9460             }
   9461 
   9462             onSizeChanged(mRight - mLeft, height, oldWidth, height);
   9463 
   9464             if (!matrixIsIdentity) {
   9465                 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
   9466                     // A change in dimension means an auto-centered pivot point changes, too
   9467                     mTransformationInfo.mMatrixDirty = true;
   9468                 }
   9469                 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
   9470                 invalidate(true);
   9471             }
   9472             mBackgroundSizeChanged = true;
   9473             invalidateParentIfNeeded();
   9474             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9475                 // View was rejected last time it was drawn by its parent; this may have changed
   9476                 invalidateParentIfNeeded();
   9477             }
   9478         }
   9479     }
   9480 
   9481     /**
   9482      * Right position of this view relative to its parent.
   9483      *
   9484      * @return The right edge of this view, in pixels.
   9485      */
   9486     @ViewDebug.CapturedViewProperty
   9487     public final int getRight() {
   9488         return mRight;
   9489     }
   9490 
   9491     /**
   9492      * Sets the right position of this view relative to its parent. This method is meant to be called
   9493      * by the layout system and should not generally be called otherwise, because the property
   9494      * may be changed at any time by the layout.
   9495      *
   9496      * @param right The bottom of this view, in pixels.
   9497      */
   9498     public final void setRight(int right) {
   9499         if (right != mRight) {
   9500             updateMatrix();
   9501             final boolean matrixIsIdentity = mTransformationInfo == null
   9502                     || mTransformationInfo.mMatrixIsIdentity;
   9503             if (matrixIsIdentity) {
   9504                 if (mAttachInfo != null) {
   9505                     int maxRight;
   9506                     if (right < mRight) {
   9507                         maxRight = mRight;
   9508                     } else {
   9509                         maxRight = right;
   9510                     }
   9511                     invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
   9512                 }
   9513             } else {
   9514                 // Double-invalidation is necessary to capture view's old and new areas
   9515                 invalidate(true);
   9516             }
   9517 
   9518             int oldWidth = mRight - mLeft;
   9519             int height = mBottom - mTop;
   9520 
   9521             mRight = right;
   9522             if (mDisplayList != null) {
   9523                 mDisplayList.setRight(mRight);
   9524             }
   9525 
   9526             onSizeChanged(mRight - mLeft, height, oldWidth, height);
   9527 
   9528             if (!matrixIsIdentity) {
   9529                 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
   9530                     // A change in dimension means an auto-centered pivot point changes, too
   9531                     mTransformationInfo.mMatrixDirty = true;
   9532                 }
   9533                 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
   9534                 invalidate(true);
   9535             }
   9536             mBackgroundSizeChanged = true;
   9537             invalidateParentIfNeeded();
   9538             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9539                 // View was rejected last time it was drawn by its parent; this may have changed
   9540                 invalidateParentIfNeeded();
   9541             }
   9542         }
   9543     }
   9544 
   9545     /**
   9546      * The visual x position of this view, in pixels. This is equivalent to the
   9547      * {@link #setTranslationX(float) translationX} property plus the current
   9548      * {@link #getLeft() left} property.
   9549      *
   9550      * @return The visual x position of this view, in pixels.
   9551      */
   9552     @ViewDebug.ExportedProperty(category = "drawing")
   9553     public float getX() {
   9554         return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
   9555     }
   9556 
   9557     /**
   9558      * Sets the visual x position of this view, in pixels. This is equivalent to setting the
   9559      * {@link #setTranslationX(float) translationX} property to be the difference between
   9560      * the x value passed in and the current {@link #getLeft() left} property.
   9561      *
   9562      * @param x The visual x position of this view, in pixels.
   9563      */
   9564     public void setX(float x) {
   9565         setTranslationX(x - mLeft);
   9566     }
   9567 
   9568     /**
   9569      * The visual y position of this view, in pixels. This is equivalent to the
   9570      * {@link #setTranslationY(float) translationY} property plus the current
   9571      * {@link #getTop() top} property.
   9572      *
   9573      * @return The visual y position of this view, in pixels.
   9574      */
   9575     @ViewDebug.ExportedProperty(category = "drawing")
   9576     public float getY() {
   9577         return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
   9578     }
   9579 
   9580     /**
   9581      * Sets the visual y position of this view, in pixels. This is equivalent to setting the
   9582      * {@link #setTranslationY(float) translationY} property to be the difference between
   9583      * the y value passed in and the current {@link #getTop() top} property.
   9584      *
   9585      * @param y The visual y position of this view, in pixels.
   9586      */
   9587     public void setY(float y) {
   9588         setTranslationY(y - mTop);
   9589     }
   9590 
   9591 
   9592     /**
   9593      * The horizontal location of this view relative to its {@link #getLeft() left} position.
   9594      * This position is post-layout, in addition to wherever the object's
   9595      * layout placed it.
   9596      *
   9597      * @return The horizontal position of this view relative to its left position, in pixels.
   9598      */
   9599     @ViewDebug.ExportedProperty(category = "drawing")
   9600     public float getTranslationX() {
   9601         return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
   9602     }
   9603 
   9604     /**
   9605      * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
   9606      * This effectively positions the object post-layout, in addition to wherever the object's
   9607      * layout placed it.
   9608      *
   9609      * @param translationX The horizontal position of this view relative to its left position,
   9610      * in pixels.
   9611      *
   9612      * @attr ref android.R.styleable#View_translationX
   9613      */
   9614     public void setTranslationX(float translationX) {
   9615         ensureTransformationInfo();
   9616         final TransformationInfo info = mTransformationInfo;
   9617         if (info.mTranslationX != translationX) {
   9618             // Double-invalidation is necessary to capture view's old and new areas
   9619             invalidateViewProperty(true, false);
   9620             info.mTranslationX = translationX;
   9621             info.mMatrixDirty = true;
   9622             invalidateViewProperty(false, true);
   9623             if (mDisplayList != null) {
   9624                 mDisplayList.setTranslationX(translationX);
   9625             }
   9626             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9627                 // View was rejected last time it was drawn by its parent; this may have changed
   9628                 invalidateParentIfNeeded();
   9629             }
   9630         }
   9631     }
   9632 
   9633     /**
   9634      * The horizontal location of this view relative to its {@link #getTop() top} position.
   9635      * This position is post-layout, in addition to wherever the object's
   9636      * layout placed it.
   9637      *
   9638      * @return The vertical position of this view relative to its top position,
   9639      * in pixels.
   9640      */
   9641     @ViewDebug.ExportedProperty(category = "drawing")
   9642     public float getTranslationY() {
   9643         return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
   9644     }
   9645 
   9646     /**
   9647      * Sets the vertical location of this view relative to its {@link #getTop() top} position.
   9648      * This effectively positions the object post-layout, in addition to wherever the object's
   9649      * layout placed it.
   9650      *
   9651      * @param translationY The vertical position of this view relative to its top position,
   9652      * in pixels.
   9653      *
   9654      * @attr ref android.R.styleable#View_translationY
   9655      */
   9656     public void setTranslationY(float translationY) {
   9657         ensureTransformationInfo();
   9658         final TransformationInfo info = mTransformationInfo;
   9659         if (info.mTranslationY != translationY) {
   9660             invalidateViewProperty(true, false);
   9661             info.mTranslationY = translationY;
   9662             info.mMatrixDirty = true;
   9663             invalidateViewProperty(false, true);
   9664             if (mDisplayList != null) {
   9665                 mDisplayList.setTranslationY(translationY);
   9666             }
   9667             if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
   9668                 // View was rejected last time it was drawn by its parent; this may have changed
   9669                 invalidateParentIfNeeded();
   9670             }
   9671         }
   9672     }
   9673 
   9674     /**
   9675      * Hit rectangle in parent's coordinates
   9676      *
   9677      * @param outRect The hit rectangle of the view.
   9678      */
   9679     public void getHitRect(Rect outRect) {
   9680         updateMatrix();
   9681         final TransformationInfo info = mTransformationInfo;
   9682         if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
   9683             outRect.set(mLeft, mTop, mRight, mBottom);
   9684         } else {
   9685             final RectF tmpRect = mAttachInfo.mTmpTransformRect;
   9686             tmpRect.set(-info.mPivotX, -info.mPivotY,
   9687                     getWidth() - info.mPivotX, getHeight() - info.mPivotY);
   9688             info.mMatrix.mapRect(tmpRect);
   9689             outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
   9690                     (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
   9691         }
   9692     }
   9693 
   9694     /**
   9695      * Determines whether the given point, in local coordinates is inside the view.
   9696      */
   9697     /*package*/ final boolean pointInView(float localX, float localY) {
   9698         return localX >= 0 && localX < (mRight - mLeft)
   9699                 && localY >= 0 && localY < (mBottom - mTop);
   9700     }
   9701 
   9702     /**
   9703      * Utility method to determine whether the given point, in local coordinates,
   9704      * is inside the view, where the area of the view is expanded by the slop factor.
   9705      * This method is called while processing touch-move events to determine if the event
   9706      * is still within the view.
   9707      */
   9708     private boolean pointInView(float localX, float localY, float slop) {
   9709         return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
   9710                 localY < ((mBottom - mTop) + slop);
   9711     }
   9712 
   9713     /**
   9714      * When a view has focus and the user navigates away from it, the next view is searched for
   9715      * starting from the rectangle filled in by this method.
   9716      *
   9717      * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
   9718      * of the view.  However, if your view maintains some idea of internal selection,
   9719      * such as a cursor, or a selected row or column, you should override this method and
   9720      * fill in a more specific rectangle.
   9721      *
   9722      * @param r The rectangle to fill in, in this view's coordinates.
   9723      */
   9724     public void getFocusedRect(Rect r) {
   9725         getDrawingRect(r);
   9726     }
   9727 
   9728     /**
   9729      * If some part of this view is not clipped by any of its parents, then
   9730      * return that area in r in global (root) coordinates. To convert r to local
   9731      * coordinates (without taking possible View rotations into account), offset
   9732      * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
   9733      * If the view is completely clipped or translated out, return false.
   9734      *
   9735      * @param r If true is returned, r holds the global coordinates of the
   9736      *        visible portion of this view.
   9737      * @param globalOffset If true is returned, globalOffset holds the dx,dy
   9738      *        between this view and its root. globalOffet may be null.
   9739      * @return true if r is non-empty (i.e. part of the view is visible at the
   9740      *         root level.
   9741      */
   9742     public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
   9743         int width = mRight - mLeft;
   9744         int height = mBottom - mTop;
   9745         if (width > 0 && height > 0) {
   9746             r.set(0, 0, width, height);
   9747             if (globalOffset != null) {
   9748                 globalOffset.set(-mScrollX, -mScrollY);
   9749             }
   9750             return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
   9751         }
   9752         return false;
   9753     }
   9754 
   9755     public final boolean getGlobalVisibleRect(Rect r) {
   9756         return getGlobalVisibleRect(r, null);
   9757     }
   9758 
   9759     public final boolean getLocalVisibleRect(Rect r) {
   9760         final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
   9761         if (getGlobalVisibleRect(r, offset)) {
   9762             r.offset(-offset.x, -offset.y); // make r local
   9763             return true;
   9764         }
   9765         return false;
   9766     }
   9767 
   9768     /**
   9769      * Offset this view's vertical location by the specified number of pixels.
   9770      *
   9771      * @param offset the number of pixels to offset the view by
   9772      */
   9773     public void offsetTopAndBottom(int offset) {
   9774         if (offset != 0) {
   9775             updateMatrix();
   9776             final boolean matrixIsIdentity = mTransformationInfo == null
   9777                     || mTransformationInfo.mMatrixIsIdentity;
   9778             if (matrixIsIdentity) {
   9779                 if (mDisplayList != null) {
   9780                     invalidateViewProperty(false, false);
   9781                 } else {
   9782                     final ViewParent p = mParent;
   9783                     if (p != null && mAttachInfo != null) {
   9784                         final Rect r = mAttachInfo.mTmpInvalRect;
   9785                         int minTop;
   9786                         int maxBottom;
   9787                         int yLoc;
   9788                         if (offset < 0) {
   9789                             minTop = mTop + offset;
   9790                             maxBottom = mBottom;
   9791                             yLoc = offset;
   9792                         } else {
   9793                             minTop = mTop;
   9794                             maxBottom = mBottom + offset;
   9795                             yLoc = 0;
   9796                         }
   9797                         r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
   9798                         p.invalidateChild(this, r);
   9799                     }
   9800                 }
   9801             } else {
   9802                 invalidateViewProperty(false, false);
   9803             }
   9804 
   9805             mTop += offset;
   9806             mBottom += offset;
   9807             if (mDisplayList != null) {
   9808                 mDisplayList.offsetTopBottom(offset);
   9809                 invalidateViewProperty(false, false);
   9810             } else {
   9811                 if (!matrixIsIdentity) {
   9812                     invalidateViewProperty(false, true);
   9813                 }
   9814                 invalidateParentIfNeeded();
   9815             }
   9816         }
   9817     }
   9818 
   9819     /**
   9820      * Offset this view's horizontal location by the specified amount of pixels.
   9821      *
   9822      * @param offset the numer of pixels to offset the view by
   9823      */
   9824     public void offsetLeftAndRight(int offset) {
   9825         if (offset != 0) {
   9826             updateMatrix();
   9827             final boolean matrixIsIdentity = mTransformationInfo == null
   9828                     || mTransformationInfo.mMatrixIsIdentity;
   9829             if (matrixIsIdentity) {
   9830                 if (mDisplayList != null) {
   9831                     invalidateViewProperty(false, false);
   9832                 } else {
   9833                     final ViewParent p = mParent;
   9834                     if (p != null && mAttachInfo != null) {
   9835                         final Rect r = mAttachInfo.mTmpInvalRect;
   9836                         int minLeft;
   9837                         int maxRight;
   9838                         if (offset < 0) {
   9839                             minLeft = mLeft + offset;
   9840                             maxRight = mRight;
   9841                         } else {
   9842                             minLeft = mLeft;
   9843                             maxRight = mRight + offset;
   9844                         }
   9845                         r.set(0, 0, maxRight - minLeft, mBottom - mTop);
   9846                         p.invalidateChild(this, r);
   9847                     }
   9848                 }
   9849             } else {
   9850                 invalidateViewProperty(false, false);
   9851             }
   9852 
   9853             mLeft += offset;
   9854             mRight += offset;
   9855             if (mDisplayList != null) {
   9856                 mDisplayList.offsetLeftRight(offset);
   9857                 invalidateViewProperty(false, false);
   9858             } else {
   9859                 if (!matrixIsIdentity) {
   9860                     invalidateViewProperty(false, true);
   9861                 }
   9862                 invalidateParentIfNeeded();
   9863             }
   9864         }
   9865     }
   9866 
   9867     /**
   9868      * Get the LayoutParams associated with this view. All views should have
   9869      * layout parameters. These supply parameters to the <i>parent</i> of this
   9870      * view specifying how it should be arranged. There are many subclasses of
   9871      * ViewGroup.LayoutParams, and these correspond to the different subclasses
   9872      * of ViewGroup that are responsible for arranging their children.
   9873      *
   9874      * This method may return null if this View is not attached to a parent
   9875      * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
   9876      * was not invoked successfully. When a View is attached to a parent
   9877      * ViewGroup, this method must not return null.
   9878      *
   9879      * @return The LayoutParams associated with this view, or null if no
   9880      *         parameters have been set yet
   9881      */
   9882     @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
   9883     public ViewGroup.LayoutParams getLayoutParams() {
   9884         return mLayoutParams;
   9885     }
   9886 
   9887     /**
   9888      * Set the layout parameters associated with this view. These supply
   9889      * parameters to the <i>parent</i> of this view specifying how it should be
   9890      * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
   9891      * correspond to the different subclasses of ViewGroup that are responsible
   9892      * for arranging their children.
   9893      *
   9894      * @param params The layout parameters for this view, cannot be null
   9895      */
   9896     public void setLayoutParams(ViewGroup.LayoutParams params) {
   9897         if (params == null) {
   9898             throw new NullPointerException("Layout parameters cannot be null");
   9899         }
   9900         mLayoutParams = params;
   9901         if (mParent instanceof ViewGroup) {
   9902             ((ViewGroup) mParent).onSetLayoutParams(this, params);
   9903         }
   9904         requestLayout();
   9905     }
   9906 
   9907     /**
   9908      * Set the scrolled position of your view. This will cause a call to
   9909      * {@link #onScrollChanged(int, int, int, int)} and the view will be
   9910      * invalidated.
   9911      * @param x the x position to scroll to
   9912      * @param y the y position to scroll to
   9913      */
   9914     public void scrollTo(int x, int y) {
   9915         if (mScrollX != x || mScrollY != y) {
   9916             int oldX = mScrollX;
   9917             int oldY = mScrollY;
   9918             mScrollX = x;
   9919             mScrollY = y;
   9920             invalidateParentCaches();
   9921             onScrollChanged(mScrollX, mScrollY, oldX, oldY);
   9922             if (!awakenScrollBars()) {
   9923                 postInvalidateOnAnimation();
   9924             }
   9925         }
   9926     }
   9927 
   9928     /**
   9929      * Move the scrolled position of your view. This will cause a call to
   9930      * {@link #onScrollChanged(int, int, int, int)} and the view will be
   9931      * invalidated.
   9932      * @param x the amount of pixels to scroll by horizontally
   9933      * @param y the amount of pixels to scroll by vertically
   9934      */
   9935     public void scrollBy(int x, int y) {
   9936         scrollTo(mScrollX + x, mScrollY + y);
   9937     }
   9938 
   9939     /**
   9940      * <p>Trigger the scrollbars to draw. When invoked this method starts an
   9941      * animation to fade the scrollbars out after a default delay. If a subclass
   9942      * provides animated scrolling, the start delay should equal the duration
   9943      * of the scrolling animation.</p>
   9944      *
   9945      * <p>The animation starts only if at least one of the scrollbars is
   9946      * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
   9947      * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
   9948      * this method returns true, and false otherwise. If the animation is
   9949      * started, this method calls {@link #invalidate()}; in that case the
   9950      * caller should not call {@link #invalidate()}.</p>
   9951      *
   9952      * <p>This method should be invoked every time a subclass directly updates
   9953      * the scroll parameters.</p>
   9954      *
   9955      * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
   9956      * and {@link #scrollTo(int, int)}.</p>
   9957      *
   9958      * @return true if the animation is played, false otherwise
   9959      *
   9960      * @see #awakenScrollBars(int)
   9961      * @see #scrollBy(int, int)
   9962      * @see #scrollTo(int, int)
   9963      * @see #isHorizontalScrollBarEnabled()
   9964      * @see #isVerticalScrollBarEnabled()
   9965      * @see #setHorizontalScrollBarEnabled(boolean)
   9966      * @see #setVerticalScrollBarEnabled(boolean)
   9967      */
   9968     protected boolean awakenScrollBars() {
   9969         return mScrollCache != null &&
   9970                 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
   9971     }
   9972 
   9973     /**
   9974      * Trigger the scrollbars to draw.
   9975      * This method differs from awakenScrollBars() only in its default duration.
   9976      * initialAwakenScrollBars() will show the scroll bars for longer than
   9977      * usual to give the user more of a chance to notice them.
   9978      *
   9979      * @return true if the animation is played, false otherwise.
   9980      */
   9981     private boolean initialAwakenScrollBars() {
   9982         return mScrollCache != null &&
   9983                 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
   9984     }
   9985 
   9986     /**
   9987      * <p>
   9988      * Trigger the scrollbars to draw. When invoked this method starts an
   9989      * animation to fade the scrollbars out after a fixed delay. If a subclass
   9990      * provides animated scrolling, the start delay should equal the duration of
   9991      * the scrolling animation.
   9992      * </p>
   9993      *
   9994      * <p>
   9995      * The animation starts only if at least one of the scrollbars is enabled,
   9996      * as specified by {@link #isHorizontalScrollBarEnabled()} and
   9997      * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
   9998      * this method returns true, and false otherwise. If the animation is
   9999      * started, this method calls {@link #invalidate()}; in that case the caller
   10000      * should not call {@link #invalidate()}.
   10001      * </p>
   10002      *
   10003      * <p>
   10004      * This method should be invoked everytime a subclass directly updates the
   10005      * scroll parameters.
   10006      * </p>
   10007      *
   10008      * @param startDelay the delay, in milliseconds, after which the animation
   10009      *        should start; when the delay is 0, the animation starts
   10010      *        immediately
   10011      * @return true if the animation is played, false otherwise
   10012      *
   10013      * @see #scrollBy(int, int)
   10014      * @see #scrollTo(int, int)
   10015      * @see #isHorizontalScrollBarEnabled()
   10016      * @see #isVerticalScrollBarEnabled()
   10017      * @see #setHorizontalScrollBarEnabled(boolean)
   10018      * @see #setVerticalScrollBarEnabled(boolean)
   10019      */
   10020     protected boolean awakenScrollBars(int startDelay) {
   10021         return awakenScrollBars(startDelay, true);
   10022     }
   10023 
   10024     /**
   10025      * <p>
   10026      * Trigger the scrollbars to draw. When invoked this method starts an
   10027      * animation to fade the scrollbars out after a fixed delay. If a subclass
   10028      * provides animated scrolling, the start delay should equal the duration of
   10029      * the scrolling animation.
   10030      * </p>
   10031      *
   10032      * <p>
   10033      * The animation starts only if at least one of the scrollbars is enabled,
   10034      * as specified by {@link #isHorizontalScrollBarEnabled()} and
   10035      * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
   10036      * this method returns true, and false otherwise. If the animation is
   10037      * started, this method calls {@link #invalidate()} if the invalidate parameter
   10038      * is set to true; in that case the caller
   10039      * should not call {@link #invalidate()}.
   10040      * </p>
   10041      *
   10042      * <p>
   10043      * This method should be invoked everytime a subclass directly updates the
   10044      * scroll parameters.
   10045      * </p>
   10046      *
   10047      * @param startDelay the delay, in milliseconds, after which the animation
   10048      *        should start; when the delay is 0, the animation starts
   10049      *        immediately
   10050      *
   10051      * @param invalidate Wheter this method should call invalidate
   10052      *
   10053      * @return true if the animation is played, false otherwise
   10054      *
   10055      * @see #scrollBy(int, int)
   10056      * @see #scrollTo(int, int)
   10057      * @see #isHorizontalScrollBarEnabled()
   10058      * @see #isVerticalScrollBarEnabled()
   10059      * @see #setHorizontalScrollBarEnabled(boolean)
   10060      * @see #setVerticalScrollBarEnabled(boolean)
   10061      */
   10062     protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
   10063         final ScrollabilityCache scrollCache = mScrollCache;
   10064 
   10065         if (scrollCache == null || !scrollCache.fadeScrollBars) {
   10066             return false;
   10067         }
   10068 
   10069         if (scrollCache.scrollBar == null) {
   10070             scrollCache.scrollBar = new ScrollBarDrawable();
   10071         }
   10072 
   10073         if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
   10074 
   10075             if (invalidate) {
   10076                 // Invalidate to show the scrollbars
   10077                 postInvalidateOnAnimation();
   10078             }
   10079 
   10080             if (scrollCache.state == ScrollabilityCache.OFF) {
   10081                 // FIXME: this is copied from WindowManagerService.
   10082                 // We should get this value from the system when it
   10083                 // is possible to do so.
   10084                 final int KEY_REPEAT_FIRST_DELAY = 750;
   10085                 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
   10086             }
   10087 
   10088             // Tell mScrollCache when we should start fading. This may
   10089             // extend the fade start time if one was already scheduled
   10090             long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
   10091             scrollCache.fadeStartTime = fadeStartTime;
   10092             scrollCache.state = ScrollabilityCache.ON;
   10093 
   10094             // Schedule our fader to run, unscheduling any old ones first
   10095             if (mAttachInfo != null) {
   10096                 mAttachInfo.mHandler.removeCallbacks(scrollCache);
   10097                 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
   10098             }
   10099 
   10100             return true;
   10101         }
   10102 
   10103         return false;
   10104     }
   10105 
   10106     /**
   10107      * Do not invalidate views which are not visible and which are not running an animation. They
   10108      * will not get drawn and they should not set dirty flags as if they will be drawn
   10109      */
   10110     private boolean skipInvalidate() {
   10111         return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
   10112                 (!(mParent instanceof ViewGroup) ||
   10113                         !((ViewGroup) mParent).isViewTransitioning(this));
   10114     }
   10115     /**
   10116      * Mark the area defined by dirty as needing to be drawn. If the view is
   10117      * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
   10118      * in the future. This must be called from a UI thread. To call from a non-UI
   10119      * thread, call {@link #postInvalidate()}.
   10120      *
   10121      * WARNING: This method is destructive to dirty.
   10122      * @param dirty the rectangle representing the bounds of the dirty region
   10123      */
   10124     public void invalidate(Rect dirty) {
   10125         if (skipInvalidate()) {
   10126             return;
   10127         }
   10128         if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
   10129                 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
   10130                 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
   10131             mPrivateFlags &= ~DRAWING_CACHE_VALID;
   10132             mPrivateFlags |= INVALIDATED;
   10133             mPrivateFlags |= DIRTY;
   10134             final ViewParent p = mParent;
   10135             final AttachInfo ai = mAttachInfo;
   10136             //noinspection PointlessBooleanExpression,ConstantConditions
   10137             if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
   10138                 if (p != null && ai != null && ai.mHardwareAccelerated) {
   10139                     // fast-track for GL-enabled applications; just invalidate the whole hierarchy
   10140                     // with a null dirty rect, which tells the ViewAncestor to redraw everything
   10141                     p.invalidateChild(this, null);
   10142                     return;
   10143                 }
   10144             }
   10145             if (p != null && ai != null) {
   10146                 final int scrollX = mScrollX;
   10147                 final int scrollY = mScrollY;
   10148                 final Rect r = ai.mTmpInvalRect;
   10149                 r.set(dirty.left - scrollX, dirty.top - scrollY,
   10150                         dirty.right - scrollX, dirty.bottom - scrollY);
   10151                 mParent.invalidateChild(this, r);
   10152             }
   10153         }
   10154     }
   10155 
   10156     /**
   10157      * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
   10158      * The coordinates of the dirty rect are relative to the view.
   10159      * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
   10160      * will be called at some point in the future. This must be called from
   10161      * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
   10162      * @param l the left position of the dirty region
   10163      * @param t the top position of the dirty region
   10164      * @param r the right position of the dirty region
   10165      * @param b the bottom position of the dirty region
   10166      */
   10167     public void invalidate(int l, int t, int r, int b) {
   10168         if (skipInvalidate()) {
   10169             return;
   10170         }
   10171         if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
   10172                 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
   10173                 (mPrivateFlags & INVALIDATED) != INVALIDATED) {
   10174             mPrivateFlags &= ~DRAWING_CACHE_VALID;
   10175             mPrivateFlags |= INVALIDATED;
   10176             mPrivateFlags |= DIRTY;
   10177             final ViewParent p = mParent;
   10178             final AttachInfo ai = mAttachInfo;
   10179             //noinspection PointlessBooleanExpression,ConstantConditions
   10180             if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
   10181                 if (p != null && ai != null && ai.mHardwareAccelerated) {
   10182                     // fast-track for GL-enabled applications; just invalidate the whole hierarchy
   10183                     // with a null dirty rect, which tells the ViewAncestor to redraw everything
   10184                     p.invalidateChild(this, null);
   10185                     return;
   10186                 }
   10187             }
   10188             if (p != null && ai != null && l < r && t < b) {
   10189                 final int scrollX = mScrollX;
   10190                 final int scrollY = mScrollY;
   10191                 final Rect tmpr = ai.mTmpInvalRect;
   10192                 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
   10193                 p.invalidateChild(this, tmpr);
   10194             }
   10195         }
   10196     }
   10197 
   10198     /**
   10199      * Invalidate the whole view. If the view is visible,
   10200      * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
   10201      * the future. This must be called from a UI thread. To call from a non-UI thread,
   10202      * call {@link #postInvalidate()}.
   10203      */
   10204     public void invalidate() {
   10205         invalidate(true);
   10206     }
   10207 
   10208     /**
   10209      * This is where the invalidate() work actually happens. A full invalidate()
   10210      * causes the drawing cache to be invalidated, but this function can be called with
   10211      * invalidateCache set to false to skip that invalidation step for cases that do not
   10212      * need it (for example, a component that remains at the same dimensions with the same
   10213      * content).
   10214      *
   10215      * @param invalidateCache Whether the drawing cache for this view should be invalidated as
   10216      * well. This is usually true for a full invalidate, but may be set to false if the
   10217      * View's contents or dimensions have not changed.
   10218      */
   10219     void invalidate(boolean invalidateCache) {
   10220         if (skipInvalidate()) {
   10221             return;
   10222         }
   10223         if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
   10224                 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
   10225                 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
   10226             mLastIsOpaque = isOpaque();
   10227             mPrivateFlags &= ~DRAWN;
   10228             mPrivateFlags |= DIRTY;
   10229             if (invalidateCache) {
   10230                 mPrivateFlags |= INVALIDATED;
   10231                 mPrivateFlags &= ~DRAWING_CACHE_VALID;
   10232             }
   10233             final AttachInfo ai = mAttachInfo;
   10234             final ViewParent p = mParent;
   10235             //noinspection PointlessBooleanExpression,ConstantConditions
   10236             if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
   10237                 if (p != null && ai != null && ai.mHardwareAccelerated) {
   10238                     // fast-track for GL-enabled applications; just invalidate the whole hierarchy
   10239                     // with a null dirty rect, which tells the ViewAncestor to redraw everything
   10240                     p.invalidateChild(this, null);
   10241                     return;
   10242                 }
   10243             }
   10244 
   10245             if (p != null && ai != null) {
   10246                 final Rect r = ai.mTmpInvalRect;
   10247                 r.set(0, 0, mRight - mLeft, mBottom - mTop);
   10248                 // Don't call invalidate -- we don't want to internally scroll
   10249                 // our own bounds
   10250                 p.invalidateChild(this, r);
   10251             }
   10252         }
   10253     }
   10254 
   10255     /**
   10256      * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
   10257      * set any flags or handle all of the cases handled by the default invalidation methods.
   10258      * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
   10259      * dirty rect. This method calls into fast invalidation methods in ViewGroup that
   10260      * walk up the hierarchy, transforming the dirty rect as necessary.
   10261      *
   10262      * The method also handles normal invalidation logic if display list properties are not
   10263      * being used in this view. The invalidateParent and forceRedraw flags are used by that
   10264      * backup approach, to handle these cases used in the various property-setting methods.
   10265      *
   10266      * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
   10267      * are not being used in this view
   10268      * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
   10269      * list properties are not being used in this view
   10270      */
   10271     void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
   10272         if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
   10273             if (invalidateParent) {
   10274                 invalidateParentCaches();
   10275             }
   10276             if (forceRedraw) {
   10277                 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
   10278             }
   10279             invalidate(false);
   10280         } else {
   10281             final AttachInfo ai = mAttachInfo;
   10282             final ViewParent p = mParent;
   10283             if (p != null && ai != null) {
   10284                 final Rect r = ai.mTmpInvalRect;
   10285                 r.set(0, 0, mRight - mLeft, mBottom - mTop);
   10286                 if (mParent instanceof ViewGroup) {
   10287                     ((ViewGroup) mParent).invalidateChildFast(this, r);
   10288                 } else {
   10289                     mParent.invalidateChild(this, r);
   10290                 }
   10291             }
   10292         }
   10293     }
   10294 
   10295     /**
   10296      * Utility method to transform a given Rect by the current matrix of this view.
   10297      */
   10298     void transformRect(final Rect rect) {
   10299         if (!getMatrix().isIdentity()) {
   10300             RectF boundingRect = mAttachInfo.mTmpTransformRect;
   10301             boundingRect.set(rect);
   10302             getMatrix().mapRect(boundingRect);
   10303             rect.set((int) (boundingRect.left - 0.5f),
   10304                     (int) (boundingRect.top - 0.5f),
   10305                     (int) (boundingRect.right + 0.5f),
   10306                     (int) (boundingRect.bottom + 0.5f));
   10307         }
   10308     }
   10309 
   10310     /**
   10311      * Used to indicate that the parent of this view should clear its caches. This functionality
   10312      * is used to force the parent to rebuild its display list (when hardware-accelerated),
   10313      * which is necessary when various parent-managed properties of the view change, such as
   10314      * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
   10315      * clears the parent caches and does not causes an invalidate event.
   10316      *
   10317      * @hide
   10318      */
   10319     protected void invalidateParentCaches() {
   10320         if (mParent instanceof View) {
   10321             ((View) mParent).mPrivateFlags |= INVALIDATED;
   10322         }
   10323     }
   10324 
   10325     /**
   10326      * Used to indicate that the parent of this view should be invalidated. This functionality
   10327      * is used to force the parent to rebuild its display list (when hardware-accelerated),
   10328      * which is necessary when various parent-managed properties of the view change, such as
   10329      * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
   10330      * an invalidation event to the parent.
   10331      *
   10332      * @hide
   10333      */
   10334     protected void invalidateParentIfNeeded() {
   10335         if (isHardwareAccelerated() && mParent instanceof View) {
   10336             ((View) mParent).invalidate(true);
   10337         }
   10338     }
   10339 
   10340     /**
   10341      * Indicates whether this View is opaque. An opaque View guarantees that it will
   10342      * draw all the pixels overlapping its bounds using a fully opaque color.
   10343      *
   10344      * Subclasses of View should override this method whenever possible to indicate
   10345      * whether an instance is opaque. Opaque Views are treated in a special way by
   10346      * the View hierarchy, possibly allowing it to perform optimizations during
   10347      * invalidate/draw passes.
   10348      *
   10349      * @return True if this View is guaranteed to be fully opaque, false otherwise.
   10350      */
   10351     @ViewDebug.ExportedProperty(category = "drawing")
   10352     public boolean isOpaque() {
   10353         return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
   10354                 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
   10355                         >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
   10356     }
   10357 
   10358     /**
   10359      * @hide
   10360      */
   10361     protected void computeOpaqueFlags() {
   10362         // Opaque if:
   10363         //   - Has a background
   10364         //   - Background is opaque
   10365         //   - Doesn't have scrollbars or scrollbars are inside overlay
   10366 
   10367         if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
   10368             mPrivateFlags |= OPAQUE_BACKGROUND;
   10369         } else {
   10370             mPrivateFlags &= ~OPAQUE_BACKGROUND;
   10371         }
   10372 
   10373         final int flags = mViewFlags;
   10374         if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
   10375                 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
   10376             mPrivateFlags |= OPAQUE_SCROLLBARS;
   10377         } else {
   10378             mPrivateFlags &= ~OPAQUE_SCROLLBARS;
   10379         }
   10380     }
   10381 
   10382     /**
   10383      * @hide
   10384      */
   10385     protected boolean hasOpaqueScrollbars() {
   10386         return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
   10387     }
   10388 
   10389     /**
   10390      * @return A handler associated with the thread running the View. This
   10391      * handler can be used to pump events in the UI events queue.
   10392      */
   10393     public Handler getHandler() {
   10394         if (mAttachInfo != null) {
   10395             return mAttachInfo.mHandler;
   10396         }
   10397         return null;
   10398     }
   10399 
   10400     /**
   10401      * Gets the view root associated with the View.
   10402      * @return The view root, or null if none.
   10403      * @hide
   10404      */
   10405     public ViewRootImpl getViewRootImpl() {
   10406         if (mAttachInfo != null) {
   10407             return mAttachInfo.mViewRootImpl;
   10408         }
   10409         return null;
   10410     }
   10411 
   10412     /**
   10413      * <p>Causes the Runnable to be added to the message queue.
   10414      * The runnable will be run on the user interface thread.</p>
   10415      *
   10416      * <p>This method can be invoked from outside of the UI thread
   10417      * only when this View is attached to a window.</p>
   10418      *
   10419      * @param action The Runnable that will be executed.
   10420      *
   10421      * @return Returns true if the Runnable was successfully placed in to the
   10422      *         message queue.  Returns false on failure, usually because the
   10423      *         looper processing the message queue is exiting.
   10424      *
   10425      * @see #postDelayed
   10426      * @see #removeCallbacks
   10427      */
   10428     public boolean post(Runnable action) {
   10429         final AttachInfo attachInfo = mAttachInfo;
   10430         if (attachInfo != null) {
   10431             return attachInfo.mHandler.post(action);
   10432         }
   10433         // Assume that post will succeed later
   10434         ViewRootImpl.getRunQueue().post(action);
   10435         return true;
   10436     }
   10437 
   10438     /**
   10439      * <p>Causes the Runnable to be added to the message queue, to be run
   10440      * after the specified amount of time elapses.
   10441      * The runnable will be run on the user interface thread.</p>
   10442      *
   10443      * <p>This method can be invoked from outside of the UI thread
   10444      * only when this View is attached to a window.</p>
   10445      *
   10446      * @param action The Runnable that will be executed.
   10447      * @param delayMillis The delay (in milliseconds) until the Runnable
   10448      *        will be executed.
   10449      *
   10450      * @return true if the Runnable was successfully placed in to the
   10451      *         message queue.  Returns false on failure, usually because the
   10452      *         looper processing the message queue is exiting.  Note that a
   10453      *         result of true does not mean the Runnable will be processed --
   10454      *         if the looper is quit before the delivery time of the message
   10455      *         occurs then the message will be dropped.
   10456      *
   10457      * @see #post
   10458      * @see #removeCallbacks
   10459      */
   10460     public boolean postDelayed(Runnable action, long delayMillis) {
   10461         final AttachInfo attachInfo = mAttachInfo;
   10462         if (attachInfo != null) {
   10463             return attachInfo.mHandler.postDelayed(action, delayMillis);
   10464         }
   10465         // Assume that post will succeed later
   10466         ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
   10467         return true;
   10468     }
   10469 
   10470     /**
   10471      * <p>Causes the Runnable to execute on the next animation time step.
   10472      * The runnable will be run on the user interface thread.</p>
   10473      *
   10474      * <p>This method can be invoked from outside of the UI thread
   10475      * only when this View is attached to a window.</p>
   10476      *
   10477      * @param action The Runnable that will be executed.
   10478      *
   10479      * @see #postOnAnimationDelayed
   10480      * @see #removeCallbacks
   10481      */
   10482     public void postOnAnimation(Runnable action) {
   10483         final AttachInfo attachInfo = mAttachInfo;
   10484         if (attachInfo != null) {
   10485             attachInfo.mViewRootImpl.mChoreographer.postCallback(
   10486                     Choreographer.CALLBACK_ANIMATION, action, null);
   10487         } else {
   10488             // Assume that post will succeed later
   10489             ViewRootImpl.getRunQueue().post(action);
   10490         }
   10491     }
   10492 
   10493     /**
   10494      * <p>Causes the Runnable to execute on the next animation time step,
   10495      * after the specified amount of time elapses.
   10496      * The runnable will be run on the user interface thread.</p>
   10497      *
   10498      * <p>This method can be invoked from outside of the UI thread
   10499      * only when this View is attached to a window.</p>
   10500      *
   10501      * @param action The Runnable that will be executed.
   10502      * @param delayMillis The delay (in milliseconds) until the Runnable
   10503      *        will be executed.
   10504      *
   10505      * @see #postOnAnimation
   10506      * @see #removeCallbacks
   10507      */
   10508     public void postOnAnimationDelayed(Runnable action, long delayMillis) {
   10509         final AttachInfo attachInfo = mAttachInfo;
   10510         if (attachInfo != null) {
   10511             attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
   10512                     Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
   10513         } else {
   10514             // Assume that post will succeed later
   10515             ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
   10516         }
   10517     }
   10518 
   10519     /**
   10520      * <p>Removes the specified Runnable from the message queue.</p>
   10521      *
   10522      * <p>This method can be invoked from outside of the UI thread
   10523      * only when this View is attached to a window.</p>
   10524      *
   10525      * @param action The Runnable to remove from the message handling queue
   10526      *
   10527      * @return true if this view could ask the Handler to remove the Runnable,
   10528      *         false otherwise. When the returned value is true, the Runnable
   10529      *         may or may not have been actually removed from the message queue
   10530      *         (for instance, if the Runnable was not in the queue already.)
   10531      *
   10532      * @see #post
   10533      * @see #postDelayed
   10534      * @see #postOnAnimation
   10535      * @see #postOnAnimationDelayed
   10536      */
   10537     public boolean removeCallbacks(Runnable action) {
   10538         if (action != null) {
   10539             final AttachInfo attachInfo = mAttachInfo;
   10540             if (attachInfo != null) {
   10541                 attachInfo.mHandler.removeCallbacks(action);
   10542                 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
   10543                         Choreographer.CALLBACK_ANIMATION, action, null);
   10544             } else {
   10545                 // Assume that post will succeed later
   10546                 ViewRootImpl.getRunQueue().removeCallbacks(action);
   10547             }
   10548         }
   10549         return true;
   10550     }
   10551 
   10552     /**
   10553      * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
   10554      * Use this to invalidate the View from a non-UI thread.</p>
   10555      *
   10556      * <p>This method can be invoked from outside of the UI thread
   10557      * only when this View is attached to a window.</p>
   10558      *
   10559      * @see #invalidate()
   10560      * @see #postInvalidateDelayed(long)
   10561      */
   10562     public void postInvalidate() {
   10563         postInvalidateDelayed(0);
   10564     }
   10565 
   10566     /**
   10567      * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
   10568      * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
   10569      *
   10570      * <p>This method can be invoked from outside of the UI thread
   10571      * only when this View is attached to a window.</p>
   10572      *
   10573      * @param left The left coordinate of the rectangle to invalidate.
   10574      * @param top The top coordinate of the rectangle to invalidate.
   10575      * @param right The right coordinate of the rectangle to invalidate.
   10576      * @param bottom The bottom coordinate of the rectangle to invalidate.
   10577      *
   10578      * @see #invalidate(int, int, int, int)
   10579      * @see #invalidate(Rect)
   10580      * @see #postInvalidateDelayed(long, int, int, int, int)
   10581      */
   10582     public void postInvalidate(int left, int top, int right, int bottom) {
   10583         postInvalidateDelayed(0, left, top, right, bottom);
   10584     }
   10585 
   10586     /**
   10587      * <p>Cause an invalidate to happen on a subsequent cycle through the event
   10588      * loop. Waits for the specified amount of time.</p>
   10589      *
   10590      * <p>This method can be invoked from outside of the UI thread
   10591      * only when this View is attached to a window.</p>
   10592      *
   10593      * @param delayMilliseconds the duration in milliseconds to delay the
   10594      *         invalidation by
   10595      *
   10596      * @see #invalidate()
   10597      * @see #postInvalidate()
   10598      */
   10599     public void postInvalidateDelayed(long delayMilliseconds) {
   10600         // We try only with the AttachInfo because there's no point in invalidating
   10601         // if we are not attached to our window
   10602         final AttachInfo attachInfo = mAttachInfo;
   10603         if (attachInfo != null) {
   10604             attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
   10605         }
   10606     }
   10607 
   10608     /**
   10609      * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
   10610      * through the event loop. Waits for the specified amount of time.</p>
   10611      *
   10612      * <p>This method can be invoked from outside of the UI thread
   10613      * only when this View is attached to a window.</p>
   10614      *
   10615      * @param delayMilliseconds the duration in milliseconds to delay the
   10616      *         invalidation by
   10617      * @param left The left coordinate of the rectangle to invalidate.
   10618      * @param top The top coordinate of the rectangle to invalidate.
   10619      * @param right The right coordinate of the rectangle to invalidate.
   10620      * @param bottom The bottom coordinate of the rectangle to invalidate.
   10621      *
   10622      * @see #invalidate(int, int, int, int)
   10623      * @see #invalidate(Rect)
   10624      * @see #postInvalidate(int, int, int, int)
   10625      */
   10626     public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
   10627             int right, int bottom) {
   10628 
   10629         // We try only with the AttachInfo because there's no point in invalidating
   10630         // if we are not attached to our window
   10631         final AttachInfo attachInfo = mAttachInfo;
   10632         if (attachInfo != null) {
   10633             final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
   10634             info.target = this;
   10635             info.left = left;
   10636             info.top = top;
   10637             info.right = right;
   10638             info.bottom = bottom;
   10639 
   10640             attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
   10641         }
   10642     }
   10643 
   10644     /**
   10645      * <p>Cause an invalidate to happen on the next animation time step, typically the
   10646      * next display frame.</p>
   10647      *
   10648      * <p>This method can be invoked from outside of the UI thread
   10649      * only when this View is attached to a window.</p>
   10650      *
   10651      * @see #invalidate()
   10652      */
   10653     public void postInvalidateOnAnimation() {
   10654         // We try only with the AttachInfo because there's no point in invalidating
   10655         // if we are not attached to our window
   10656         final AttachInfo attachInfo = mAttachInfo;
   10657         if (attachInfo != null) {
   10658             attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
   10659         }
   10660     }
   10661 
   10662     /**
   10663      * <p>Cause an invalidate of the specified area to happen on the next animation
   10664      * time step, typically the next display frame.</p>
   10665      *
   10666      * <p>This method can be invoked from outside of the UI thread
   10667      * only when this View is attached to a window.</p>
   10668      *
   10669      * @param left The left coordinate of the rectangle to invalidate.
   10670      * @param top The top coordinate of the rectangle to invalidate.
   10671      * @param right The right coordinate of the rectangle to invalidate.
   10672      * @param bottom The bottom coordinate of the rectangle to invalidate.
   10673      *
   10674      * @see #invalidate(int, int, int, int)
   10675      * @see #invalidate(Rect)
   10676      */
   10677     public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
   10678         // We try only with the AttachInfo because there's no point in invalidating
   10679         // if we are not attached to our window
   10680         final AttachInfo attachInfo = mAttachInfo;
   10681         if (attachInfo != null) {
   10682             final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
   10683             info.target = this;
   10684             info.left = left;
   10685             info.top = top;
   10686             info.right = right;
   10687             info.bottom = bottom;
   10688 
   10689             attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
   10690         }
   10691     }
   10692 
   10693     /**
   10694      * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
   10695      * This event is sent at most once every
   10696      * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
   10697      */
   10698     private void postSendViewScrolledAccessibilityEventCallback() {
   10699         if (mSendViewScrolledAccessibilityEvent == null) {
   10700             mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
   10701         }
   10702         if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
   10703             mSendViewScrolledAccessibilityEvent.mIsPending = true;
   10704             postDelayed(mSendViewScrolledAccessibilityEvent,
   10705                     ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
   10706         }
   10707     }
   10708 
   10709     /**
   10710      * Called by a parent to request that a child update its values for mScrollX
   10711      * and mScrollY if necessary. This will typically be done if the child is
   10712      * animating a scroll using a {@link android.widget.Scroller Scroller}
   10713      * object.
   10714      */
   10715     public void computeScroll() {
   10716     }
   10717 
   10718     /**
   10719      * <p>Indicate whether the horizontal edges are faded when the view is
   10720      * scrolled horizontally.</p>
   10721      *
   10722      * @return true if the horizontal edges should are faded on scroll, false
   10723      *         otherwise
   10724      *
   10725      * @see #setHorizontalFadingEdgeEnabled(boolean)
   10726      *
   10727      * @attr ref android.R.styleable#View_requiresFadingEdge
   10728      */
   10729     public boolean isHorizontalFadingEdgeEnabled() {
   10730         return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
   10731     }
   10732 
   10733     /**
   10734      * <p>Define whether the horizontal edges should be faded when this view
   10735      * is scrolled horizontally.</p>
   10736      *
   10737      * @param horizontalFadingEdgeEnabled true if the horizontal edges should
   10738      *                                    be faded when the view is scrolled
   10739      *                                    horizontally
   10740      *
   10741      * @see #isHorizontalFadingEdgeEnabled()
   10742      *
   10743      * @attr ref android.R.styleable#View_requiresFadingEdge
   10744      */
   10745     public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
   10746         if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
   10747             if (horizontalFadingEdgeEnabled) {
   10748                 initScrollCache();
   10749             }
   10750 
   10751             mViewFlags ^= FADING_EDGE_HORIZONTAL;
   10752         }
   10753     }
   10754 
   10755     /**
   10756      * <p>Indicate whether the vertical edges are faded when the view is
   10757      * scrolled horizontally.</p>
   10758      *
   10759      * @return true if the vertical edges should are faded on scroll, false
   10760      *         otherwise
   10761      *
   10762      * @see #setVerticalFadingEdgeEnabled(boolean)
   10763      *
   10764      * @attr ref android.R.styleable#View_requiresFadingEdge
   10765      */
   10766     public boolean isVerticalFadingEdgeEnabled() {
   10767         return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
   10768     }
   10769 
   10770     /**
   10771      * <p>Define whether the vertical edges should be faded when this view
   10772      * is scrolled vertically.</p>
   10773      *
   10774      * @param verticalFadingEdgeEnabled true if the vertical edges should
   10775      *                                  be faded when the view is scrolled
   10776      *                                  vertically
   10777      *
   10778      * @see #isVerticalFadingEdgeEnabled()
   10779      *
   10780      * @attr ref android.R.styleable#View_requiresFadingEdge
   10781      */
   10782     public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
   10783         if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
   10784             if (verticalFadingEdgeEnabled) {
   10785                 initScrollCache();
   10786             }
   10787 
   10788             mViewFlags ^= FADING_EDGE_VERTICAL;
   10789         }
   10790     }
   10791 
   10792     /**
   10793      * Returns the strength, or intensity, of the top faded edge. The strength is
   10794      * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
   10795      * returns 0.0 or 1.0 but no value in between.
   10796      *
   10797      * Subclasses should override this method to provide a smoother fade transition
   10798      * when scrolling occurs.
   10799      *
   10800      * @return the intensity of the top fade as a float between 0.0f and 1.0f
   10801      */
   10802     protected float getTopFadingEdgeStrength() {
   10803         return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
   10804     }
   10805 
   10806     /**
   10807      * Returns the strength, or intensity, of the bottom faded edge. The strength is
   10808      * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
   10809      * returns 0.0 or 1.0 but no value in between.
   10810      *
   10811      * Subclasses should override this method to provide a smoother fade transition
   10812      * when scrolling occurs.
   10813      *
   10814      * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
   10815      */
   10816     protected float getBottomFadingEdgeStrength() {
   10817         return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
   10818                 computeVerticalScrollRange() ? 1.0f : 0.0f;
   10819     }
   10820 
   10821     /**
   10822      * Returns the strength, or intensity, of the left faded edge. The strength is
   10823      * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
   10824      * returns 0.0 or 1.0 but no value in between.
   10825      *
   10826      * Subclasses should override this method to provide a smoother fade transition
   10827      * when scrolling occurs.
   10828      *
   10829      * @return the intensity of the left fade as a float between 0.0f and 1.0f
   10830      */
   10831     protected float getLeftFadingEdgeStrength() {
   10832         return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
   10833     }
   10834 
   10835     /**
   10836      * Returns the strength, or intensity, of the right faded edge. The strength is
   10837      * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
   10838      * returns 0.0 or 1.0 but no value in between.
   10839      *
   10840      * Subclasses should override this method to provide a smoother fade transition
   10841      * when scrolling occurs.
   10842      *
   10843      * @return the intensity of the right fade as a float between 0.0f and 1.0f
   10844      */
   10845     protected float getRightFadingEdgeStrength() {
   10846         return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
   10847                 computeHorizontalScrollRange() ? 1.0f : 0.0f;
   10848     }
   10849 
   10850     /**
   10851      * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
   10852      * scrollbar is not drawn by default.</p>
   10853      *
   10854      * @return true if the horizontal scrollbar should be painted, false
   10855      *         otherwise
   10856      *
   10857      * @see #setHorizontalScrollBarEnabled(boolean)
   10858      */
   10859     public boolean isHorizontalScrollBarEnabled() {
   10860         return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
   10861     }
   10862 
   10863     /**
   10864      * <p>Define whether the horizontal scrollbar should be drawn or not. The
   10865      * scrollbar is not drawn by default.</p>
   10866      *
   10867      * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
   10868      *                                   be painted
   10869      *
   10870      * @see #isHorizontalScrollBarEnabled()
   10871      */
   10872     public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
   10873         if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
   10874             mViewFlags ^= SCROLLBARS_HORIZONTAL;
   10875             computeOpaqueFlags();
   10876             resolvePadding();
   10877         }
   10878     }
   10879 
   10880     /**
   10881      * <p>Indicate whether the vertical scrollbar should be drawn or not. The
   10882      * scrollbar is not drawn by default.</p>
   10883      *
   10884      * @return true if the vertical scrollbar should be painted, false
   10885      *         otherwise
   10886      *
   10887      * @see #setVerticalScrollBarEnabled(boolean)
   10888      */
   10889     public boolean isVerticalScrollBarEnabled() {
   10890         return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
   10891     }
   10892 
   10893     /**
   10894      * <p>Define whether the vertical scrollbar should be drawn or not. The
   10895      * scrollbar is not drawn by default.</p>
   10896      *
   10897      * @param verticalScrollBarEnabled true if the vertical scrollbar should
   10898      *                                 be painted
   10899      *
   10900      * @see #isVerticalScrollBarEnabled()
   10901      */
   10902     public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
   10903         if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
   10904             mViewFlags ^= SCROLLBARS_VERTICAL;
   10905             computeOpaqueFlags();
   10906             resolvePadding();
   10907         }
   10908     }
   10909 
   10910     /**
   10911      * @hide
   10912      */
   10913     protected void recomputePadding() {
   10914         setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
   10915     }
   10916 
   10917     /**
   10918      * Define whether scrollbars will fade when the view is not scrolling.
   10919      *
   10920      * @param fadeScrollbars wheter to enable fading
   10921      *
   10922      * @attr ref android.R.styleable#View_fadeScrollbars
   10923      */
   10924     public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
   10925         initScrollCache();
   10926         final ScrollabilityCache scrollabilityCache = mScrollCache;
   10927         scrollabilityCache.fadeScrollBars = fadeScrollbars;
   10928         if (fadeScrollbars) {
   10929             scrollabilityCache.state = ScrollabilityCache.OFF;
   10930         } else {
   10931             scrollabilityCache.state = ScrollabilityCache.ON;
   10932         }
   10933     }
   10934 
   10935     /**
   10936      *
   10937      * Returns true if scrollbars will fade when this view is not scrolling
   10938      *
   10939      * @return true if scrollbar fading is enabled
   10940      *
   10941      * @attr ref android.R.styleable#View_fadeScrollbars
   10942      */
   10943     public boolean isScrollbarFadingEnabled() {
   10944         return mScrollCache != null && mScrollCache.fadeScrollBars;
   10945     }
   10946 
   10947     /**
   10948      *
   10949      * Returns the delay before scrollbars fade.
   10950      *
   10951      * @return the delay before scrollbars fade
   10952      *
   10953      * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
   10954      */
   10955     public int getScrollBarDefaultDelayBeforeFade() {
   10956         return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
   10957                 mScrollCache.scrollBarDefaultDelayBeforeFade;
   10958     }
   10959 
   10960     /**
   10961      * Define the delay before scrollbars fade.
   10962      *
   10963      * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
   10964      *
   10965      * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
   10966      */
   10967     public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
   10968         getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
   10969     }
   10970 
   10971     /**
   10972      *
   10973      * Returns the scrollbar fade duration.
   10974      *
   10975      * @return the scrollbar fade duration
   10976      *
   10977      * @attr ref android.R.styleable#View_scrollbarFadeDuration
   10978      */
   10979     public int getScrollBarFadeDuration() {
   10980         return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
   10981                 mScrollCache.scrollBarFadeDuration;
   10982     }
   10983 
   10984     /**
   10985      * Define the scrollbar fade duration.
   10986      *
   10987      * @param scrollBarFadeDuration - the scrollbar fade duration
   10988      *
   10989      * @attr ref android.R.styleable#View_scrollbarFadeDuration
   10990      */
   10991     public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
   10992         getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
   10993     }
   10994 
   10995     /**
   10996      *
   10997      * Returns the scrollbar size.
   10998      *
   10999      * @return the scrollbar size
   11000      *
   11001      * @attr ref android.R.styleable#View_scrollbarSize
   11002      */
   11003     public int getScrollBarSize() {
   11004         return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
   11005                 mScrollCache.scrollBarSize;
   11006     }
   11007 
   11008     /**
   11009      * Define the scrollbar size.
   11010      *
   11011      * @param scrollBarSize - the scrollbar size
   11012      *
   11013      * @attr ref android.R.styleable#View_scrollbarSize
   11014      */
   11015     public void setScrollBarSize(int scrollBarSize) {
   11016         getScrollCache().scrollBarSize = scrollBarSize;
   11017     }
   11018 
   11019     /**
   11020      * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
   11021      * inset. When inset, they add to the padding of the view. And the scrollbars
   11022      * can be drawn inside the padding area or on the edge of the view. For example,
   11023      * if a view has a background drawable and you want to draw the scrollbars
   11024      * inside the padding specified by the drawable, you can use
   11025      * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
   11026      * appear at the edge of the view, ignoring the padding, then you can use
   11027      * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
   11028      * @param style the style of the scrollbars. Should be one of
   11029      * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
   11030      * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
   11031      * @see #SCROLLBARS_INSIDE_OVERLAY
   11032      * @see #SCROLLBARS_INSIDE_INSET
   11033      * @see #SCROLLBARS_OUTSIDE_OVERLAY
   11034      * @see #SCROLLBARS_OUTSIDE_INSET
   11035      *
   11036      * @attr ref android.R.styleable#View_scrollbarStyle
   11037      */
   11038     public void setScrollBarStyle(int style) {
   11039         if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
   11040             mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
   11041             computeOpaqueFlags();
   11042             resolvePadding();
   11043         }
   11044     }
   11045 
   11046     /**
   11047      * <p>Returns the current scrollbar style.</p>
   11048      * @return the current scrollbar style
   11049      * @see #SCROLLBARS_INSIDE_OVERLAY
   11050      * @see #SCROLLBARS_INSIDE_INSET
   11051      * @see #SCROLLBARS_OUTSIDE_OVERLAY
   11052      * @see #SCROLLBARS_OUTSIDE_INSET
   11053      *
   11054      * @attr ref android.R.styleable#View_scrollbarStyle
   11055      */
   11056     @ViewDebug.ExportedProperty(mapping = {
   11057             @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
   11058             @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
   11059             @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
   11060             @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
   11061     })
   11062     public int getScrollBarStyle() {
   11063         return mViewFlags & SCROLLBARS_STYLE_MASK;
   11064     }
   11065 
   11066     /**
   11067      * <p>Compute the horizontal range that the horizontal scrollbar
   11068      * represents.</p>
   11069      *
   11070      * <p>The range is expressed in arbitrary units that must be the same as the
   11071      * units used by {@link #computeHorizontalScrollExtent()} and
   11072      * {@link #computeHorizontalScrollOffset()}.</p>
   11073      *
   11074      * <p>The default range is the drawing width of this view.</p>
   11075      *
   11076      * @return the total horizontal range represented by the horizontal
   11077      *         scrollbar
   11078      *
   11079      * @see #computeHorizontalScrollExtent()
   11080      * @see #computeHorizontalScrollOffset()
   11081      * @see android.widget.ScrollBarDrawable
   11082      */
   11083     protected int computeHorizontalScrollRange() {
   11084         return getWidth();
   11085     }
   11086 
   11087     /**
   11088      * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
   11089      * within the horizontal range. This value is used to compute the position
   11090      * of the thumb within the scrollbar's track.</p>
   11091      *
   11092      * <p>The range is expressed in arbitrary units that must be the same as the
   11093      * units used by {@link #computeHorizontalScrollRange()} and
   11094      * {@link #computeHorizontalScrollExtent()}.</p>
   11095      *
   11096      * <p>The default offset is the scroll offset of this view.</p>
   11097      *
   11098      * @return the horizontal offset of the scrollbar's thumb
   11099      *
   11100      * @see #computeHorizontalScrollRange()
   11101      * @see #computeHorizontalScrollExtent()
   11102      * @see android.widget.ScrollBarDrawable
   11103      */
   11104     protected int computeHorizontalScrollOffset() {
   11105         return mScrollX;
   11106     }
   11107 
   11108     /**
   11109      * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
   11110      * within the horizontal range. This value is used to compute the length
   11111      * of the thumb within the scrollbar's track.</p>
   11112      *
   11113      * <p>The range is expressed in arbitrary units that must be the same as the
   11114      * units used by {@link #computeHorizontalScrollRange()} and
   11115      * {@link #computeHorizontalScrollOffset()}.</p>
   11116      *
   11117      * <p>The default extent is the drawing width of this view.</p>
   11118      *
   11119      * @return the horizontal extent of the scrollbar's thumb
   11120      *
   11121      * @see #computeHorizontalScrollRange()
   11122      * @see #computeHorizontalScrollOffset()
   11123      * @see android.widget.ScrollBarDrawable
   11124      */
   11125     protected int computeHorizontalScrollExtent() {
   11126         return getWidth();
   11127     }
   11128 
   11129     /**
   11130      * <p>Compute the vertical range that the vertical scrollbar represents.</p>
   11131      *
   11132      * <p>The range is expressed in arbitrary units that must be the same as the
   11133      * units used by {@link #computeVerticalScrollExtent()} and
   11134      * {@link #computeVerticalScrollOffset()}.</p>
   11135      *
   11136      * @return the total vertical range represented by the vertical scrollbar
   11137      *
   11138      * <p>The default range is the drawing height of this view.</p>
   11139      *
   11140      * @see #computeVerticalScrollExtent()
   11141      * @see #computeVerticalScrollOffset()
   11142      * @see android.widget.ScrollBarDrawable
   11143      */
   11144     protected int computeVerticalScrollRange() {
   11145         return getHeight();
   11146     }
   11147 
   11148     /**
   11149      * <p>Compute the vertical offset of the vertical scrollbar's thumb
   11150      * within the horizontal range. This value is used to compute the position
   11151      * of the thumb within the scrollbar's track.</p>
   11152      *
   11153      * <p>The range is expressed in arbitrary units that must be the same as the
   11154      * units used by {@link #computeVerticalScrollRange()} and
   11155      * {@link #computeVerticalScrollExtent()}.</p>
   11156      *
   11157      * <p>The default offset is the scroll offset of this view.</p>
   11158      *
   11159      * @return the vertical offset of the scrollbar's thumb
   11160      *
   11161      * @see #computeVerticalScrollRange()
   11162      * @see #computeVerticalScrollExtent()
   11163      * @see android.widget.ScrollBarDrawable
   11164      */
   11165     protected int computeVerticalScrollOffset() {
   11166         return mScrollY;
   11167     }
   11168 
   11169     /**
   11170      * <p>Compute the vertical extent of the horizontal scrollbar's thumb
   11171      * within the vertical range. This value is used to compute the length
   11172      * of the thumb within the scrollbar's track.</p>
   11173      *
   11174      * <p>The range is expressed in arbitrary units that must be the same as the
   11175      * units used by {@link #computeVerticalScrollRange()} and
   11176      * {@link #computeVerticalScrollOffset()}.</p>
   11177      *
   11178      * <p>The default extent is the drawing height of this view.</p>
   11179      *
   11180      * @return the vertical extent of the scrollbar's thumb
   11181      *
   11182      * @see #computeVerticalScrollRange()
   11183      * @see #computeVerticalScrollOffset()
   11184      * @see android.widget.ScrollBarDrawable
   11185      */
   11186     protected int computeVerticalScrollExtent() {
   11187         return getHeight();
   11188     }
   11189 
   11190     /**
   11191      * Check if this view can be scrolled horizontally in a certain direction.
   11192      *
   11193      * @param direction Negative to check scrolling left, positive to check scrolling right.
   11194      * @return true if this view can be scrolled in the specified direction, false otherwise.
   11195      */
   11196     public boolean canScrollHorizontally(int direction) {
   11197         final int offset = computeHorizontalScrollOffset();
   11198         final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
   11199         if (range == 0) return false;
   11200         if (direction < 0) {
   11201             return offset > 0;
   11202         } else {
   11203             return offset < range - 1;
   11204         }
   11205     }
   11206 
   11207     /**
   11208      * Check if this view can be scrolled vertically in a certain direction.
   11209      *
   11210      * @param direction Negative to check scrolling up, positive to check scrolling down.
   11211      * @return true if this view can be scrolled in the specified direction, false otherwise.
   11212      */
   11213     public boolean canScrollVertically(int direction) {
   11214         final int offset = computeVerticalScrollOffset();
   11215         final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
   11216         if (range == 0) return false;
   11217         if (direction < 0) {
   11218             return offset > 0;
   11219         } else {
   11220             return offset < range - 1;
   11221         }
   11222     }
   11223 
   11224     /**
   11225      * <p>Request the drawing of the horizontal and the vertical scrollbar. The
   11226      * scrollbars are painted only if they have been awakened first.</p>
   11227      *
   11228      * @param canvas the canvas on which to draw the scrollbars
   11229      *
   11230      * @see #awakenScrollBars(int)
   11231      */
   11232     protected final void onDrawScrollBars(Canvas canvas) {
   11233         // scrollbars are drawn only when the animation is running
   11234         final ScrollabilityCache cache = mScrollCache;
   11235         if (cache != null) {
   11236 
   11237             int state = cache.state;
   11238 
   11239             if (state == ScrollabilityCache.OFF) {
   11240                 return;
   11241             }
   11242 
   11243             boolean invalidate = false;
   11244 
   11245             if (state == ScrollabilityCache.FADING) {
   11246                 // We're fading -- get our fade interpolation
   11247                 if (cache.interpolatorValues == null) {
   11248                     cache.interpolatorValues = new float[1];
   11249                 }
   11250 
   11251                 float[] values = cache.interpolatorValues;
   11252 
   11253                 // Stops the animation if we're done
   11254                 if (cache.scrollBarInterpolator.timeToValues(values) ==
   11255                         Interpolator.Result.FREEZE_END) {
   11256                     cache.state = ScrollabilityCache.OFF;
   11257                 } else {
   11258                     cache.scrollBar.setAlpha(Math.round(values[0]));
   11259                 }
   11260 
   11261                 // This will make the scroll bars inval themselves after
   11262                 // drawing. We only want this when we're fading so that
   11263                 // we prevent excessive redraws
   11264                 invalidate = true;
   11265             } else {
   11266                 // We're just on -- but we may have been fading before so
   11267                 // reset alpha
   11268                 cache.scrollBar.setAlpha(255);
   11269             }
   11270 
   11271 
   11272             final int viewFlags = mViewFlags;
   11273 
   11274             final boolean drawHorizontalScrollBar =
   11275                 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
   11276             final boolean drawVerticalScrollBar =
   11277                 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
   11278                 && !isVerticalScrollBarHidden();
   11279 
   11280             if (drawVerticalScrollBar || drawHorizontalScrollBar) {
   11281                 final int width = mRight - mLeft;
   11282                 final int height = mBottom - mTop;
   11283 
   11284                 final ScrollBarDrawable scrollBar = cache.scrollBar;
   11285 
   11286                 final int scrollX = mScrollX;
   11287                 final int scrollY = mScrollY;
   11288                 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
   11289 
   11290                 int left, top, right, bottom;
   11291 
   11292                 if (drawHorizontalScrollBar) {
   11293                     int size = scrollBar.getSize(false);
   11294                     if (size <= 0) {
   11295                         size = cache.scrollBarSize;
   11296                     }
   11297 
   11298                     scrollBar.setParameters(computeHorizontalScrollRange(),
   11299                                             computeHorizontalScrollOffset(),
   11300                                             computeHorizontalScrollExtent(), false);
   11301                     final int verticalScrollBarGap = drawVerticalScrollBar ?
   11302                             getVerticalScrollbarWidth() : 0;
   11303                     top = scrollY + height - size - (mUserPaddingBottom & inside);
   11304                     left = scrollX + (mPaddingLeft & inside);
   11305                     right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
   11306                     bottom = top + size;
   11307                     onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
   11308                     if (invalidate) {
   11309                         invalidate(left, top, right, bottom);
   11310                     }
   11311                 }
   11312 
   11313                 if (drawVerticalScrollBar) {
   11314                     int size = scrollBar.getSize(true);
   11315                     if (size <= 0) {
   11316                         size = cache.scrollBarSize;
   11317                     }
   11318 
   11319                     scrollBar.setParameters(computeVerticalScrollRange(),
   11320                                             computeVerticalScrollOffset(),
   11321                                             computeVerticalScrollExtent(), true);
   11322                     switch (mVerticalScrollbarPosition) {
   11323                         default:
   11324                         case SCROLLBAR_POSITION_DEFAULT:
   11325                         case SCROLLBAR_POSITION_RIGHT:
   11326                             left = scrollX + width - size - (mUserPaddingRight & inside);
   11327                             break;
   11328                         case SCROLLBAR_POSITION_LEFT:
   11329                             left = scrollX + (mUserPaddingLeft & inside);
   11330                             break;
   11331                     }
   11332                     top = scrollY + (mPaddingTop & inside);
   11333                     right = left + size;
   11334                     bottom = scrollY + height - (mUserPaddingBottom & inside);
   11335                     onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
   11336                     if (invalidate) {
   11337                         invalidate(left, top, right, bottom);
   11338                     }
   11339                 }
   11340             }
   11341         }
   11342     }
   11343 
   11344     /**
   11345      * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
   11346      * FastScroller is visible.
   11347      * @return whether to temporarily hide the vertical scrollbar
   11348      * @hide
   11349      */
   11350     protected boolean isVerticalScrollBarHidden() {
   11351         return false;
   11352     }
   11353 
   11354     /**
   11355      * <p>Draw the horizontal scrollbar if
   11356      * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
   11357      *
   11358      * @param canvas the canvas on which to draw the scrollbar
   11359      * @param scrollBar the scrollbar's drawable
   11360      *
   11361      * @see #isHorizontalScrollBarEnabled()
   11362      * @see #computeHorizontalScrollRange()
   11363      * @see #computeHorizontalScrollExtent()
   11364      * @see #computeHorizontalScrollOffset()
   11365      * @see android.widget.ScrollBarDrawable
   11366      * @hide
   11367      */
   11368     protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
   11369             int l, int t, int r, int b) {
   11370         scrollBar.setBounds(l, t, r, b);
   11371         scrollBar.draw(canvas);
   11372     }
   11373 
   11374     /**
   11375      * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
   11376      * returns true.</p>
   11377      *
   11378      * @param canvas the canvas on which to draw the scrollbar
   11379      * @param scrollBar the scrollbar's drawable
   11380      *
   11381      * @see #isVerticalScrollBarEnabled()
   11382      * @see #computeVerticalScrollRange()
   11383      * @see #computeVerticalScrollExtent()
   11384      * @see #computeVerticalScrollOffset()
   11385      * @see android.widget.ScrollBarDrawable
   11386      * @hide
   11387      */
   11388     protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
   11389             int l, int t, int r, int b) {
   11390         scrollBar.setBounds(l, t, r, b);
   11391         scrollBar.draw(canvas);
   11392     }
   11393 
   11394     /**
   11395      * Implement this to do your drawing.
   11396      *
   11397      * @param canvas the canvas on which the background will be drawn
   11398      */
   11399     protected void onDraw(Canvas canvas) {
   11400     }
   11401 
   11402     /*
   11403      * Caller is responsible for calling requestLayout if necessary.
   11404      * (This allows addViewInLayout to not request a new layout.)
   11405      */
   11406     void assignParent(ViewParent parent) {
   11407         if (mParent == null) {
   11408             mParent = parent;
   11409         } else if (parent == null) {
   11410             mParent = null;
   11411         } else {
   11412             throw new RuntimeException("view " + this + " being added, but"
   11413                     + " it already has a parent");
   11414         }
   11415     }
   11416 
   11417     /**
   11418      * This is called when the view is attached to a window.  At this point it
   11419      * has a Surface and will start drawing.  Note that this function is
   11420      * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
   11421      * however it may be called any time before the first onDraw -- including
   11422      * before or after {@link #onMeasure(int, int)}.
   11423      *
   11424      * @see #onDetachedFromWindow()
   11425      */
   11426     protected void onAttachedToWindow() {
   11427         if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
   11428             mParent.requestTransparentRegion(this);
   11429         }
   11430 
   11431         if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
   11432             initialAwakenScrollBars();
   11433             mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
   11434         }
   11435 
   11436         jumpDrawablesToCurrentState();
   11437 
   11438         // Order is important here: LayoutDirection MUST be resolved before Padding
   11439         // and TextDirection
   11440         resolveLayoutDirection();
   11441         resolvePadding();
   11442         resolveTextDirection();
   11443         resolveTextAlignment();
   11444 
   11445         clearAccessibilityFocus();
   11446         if (isFocused()) {
   11447             InputMethodManager imm = InputMethodManager.peekInstance();
   11448             imm.focusIn(this);
   11449         }
   11450 
   11451         if (mAttachInfo != null && mDisplayList != null) {
   11452             mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
   11453         }
   11454     }
   11455 
   11456     /**
   11457      * @see #onScreenStateChanged(int)
   11458      */
   11459     void dispatchScreenStateChanged(int screenState) {
   11460         onScreenStateChanged(screenState);
   11461     }
   11462 
   11463     /**
   11464      * This method is called whenever the state of the screen this view is
   11465      * attached to changes. A state change will usually occurs when the screen
   11466      * turns on or off (whether it happens automatically or the user does it
   11467      * manually.)
   11468      *
   11469      * @param screenState The new state of the screen. Can be either
   11470      *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
   11471      */
   11472     public void onScreenStateChanged(int screenState) {
   11473     }
   11474 
   11475     /**
   11476      * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
   11477      */
   11478     private boolean hasRtlSupport() {
   11479         return mContext.getApplicationInfo().hasRtlSupport();
   11480     }
   11481 
   11482     /**
   11483      * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
   11484      * that the parent directionality can and will be resolved before its children.
   11485      * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
   11486      * @hide
   11487      */
   11488     public void resolveLayoutDirection() {
   11489         // Clear any previous layout direction resolution
   11490         mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
   11491 
   11492         if (hasRtlSupport()) {
   11493             // Set resolved depending on layout direction
   11494             switch (getLayoutDirection()) {
   11495                 case LAYOUT_DIRECTION_INHERIT:
   11496                     // If this is root view, no need to look at parent's layout dir.
   11497                     if (canResolveLayoutDirection()) {
   11498                         ViewGroup viewGroup = ((ViewGroup) mParent);
   11499 
   11500                         if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
   11501                             mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
   11502                         }
   11503                     } else {
   11504                         // Nothing to do, LTR by default
   11505                     }
   11506                     break;
   11507                 case LAYOUT_DIRECTION_RTL:
   11508                     mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
   11509                     break;
   11510                 case LAYOUT_DIRECTION_LOCALE:
   11511                     if(isLayoutDirectionRtl(Locale.getDefault())) {
   11512                         mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
   11513                     }
   11514                     break;
   11515                 default:
   11516                     // Nothing to do, LTR by default
   11517             }
   11518         }
   11519 
   11520         // Set to resolved
   11521         mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
   11522         onResolvedLayoutDirectionChanged();
   11523         // Resolve padding
   11524         resolvePadding();
   11525     }
   11526 
   11527     /**
   11528      * Called when layout direction has been resolved.
   11529      *
   11530      * The default implementation does nothing.
   11531      * @hide
   11532      */
   11533     public void onResolvedLayoutDirectionChanged() {
   11534     }
   11535 
   11536     /**
   11537      * Resolve padding depending on layout direction.
   11538      * @hide
   11539      */
   11540     public void resolvePadding() {
   11541         // If the user specified the absolute padding (either with android:padding or
   11542         // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
   11543         // use the default padding or the padding from the background drawable
   11544         // (stored at this point in mPadding*)
   11545         int resolvedLayoutDirection = getResolvedLayoutDirection();
   11546         switch (resolvedLayoutDirection) {
   11547             case LAYOUT_DIRECTION_RTL:
   11548                 // Start user padding override Right user padding. Otherwise, if Right user
   11549                 // padding is not defined, use the default Right padding. If Right user padding
   11550                 // is defined, just use it.
   11551                 if (mUserPaddingStart >= 0) {
   11552                     mUserPaddingRight = mUserPaddingStart;
   11553                 } else if (mUserPaddingRight < 0) {
   11554                     mUserPaddingRight = mPaddingRight;
   11555                 }
   11556                 if (mUserPaddingEnd >= 0) {
   11557                     mUserPaddingLeft = mUserPaddingEnd;
   11558                 } else if (mUserPaddingLeft < 0) {
   11559                     mUserPaddingLeft = mPaddingLeft;
   11560                 }
   11561                 break;
   11562             case LAYOUT_DIRECTION_LTR:
   11563             default:
   11564                 // Start user padding override Left user padding. Otherwise, if Left user
   11565                 // padding is not defined, use the default left padding. If Left user padding
   11566                 // is defined, just use it.
   11567                 if (mUserPaddingStart >= 0) {
   11568                     mUserPaddingLeft = mUserPaddingStart;
   11569                 } else if (mUserPaddingLeft < 0) {
   11570                     mUserPaddingLeft = mPaddingLeft;
   11571                 }
   11572                 if (mUserPaddingEnd >= 0) {
   11573                     mUserPaddingRight = mUserPaddingEnd;
   11574                 } else if (mUserPaddingRight < 0) {
   11575                     mUserPaddingRight = mPaddingRight;
   11576                 }
   11577         }
   11578 
   11579         mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
   11580 
   11581         if(isPaddingRelative()) {
   11582             setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
   11583         } else {
   11584             recomputePadding();
   11585         }
   11586         onPaddingChanged(resolvedLayoutDirection);
   11587     }
   11588 
   11589     /**
   11590      * Resolve padding depending on the layout direction. Subclasses that care about
   11591      * padding resolution should override this method. The default implementation does
   11592      * nothing.
   11593      *
   11594      * @param layoutDirection the direction of the layout
   11595      *
   11596      * @see {@link #LAYOUT_DIRECTION_LTR}
   11597      * @see {@link #LAYOUT_DIRECTION_RTL}
   11598      * @hide
   11599      */
   11600     public void onPaddingChanged(int layoutDirection) {
   11601     }
   11602 
   11603     /**
   11604      * Check if layout direction resolution can be done.
   11605      *
   11606      * @return true if layout direction resolution can be done otherwise return false.
   11607      * @hide
   11608      */
   11609     public boolean canResolveLayoutDirection() {
   11610         switch (getLayoutDirection()) {
   11611             case LAYOUT_DIRECTION_INHERIT:
   11612                 return (mParent != null) && (mParent instanceof ViewGroup);
   11613             default:
   11614                 return true;
   11615         }
   11616     }
   11617 
   11618     /**
   11619      * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
   11620      * when reset is done.
   11621      * @hide
   11622      */
   11623     public void resetResolvedLayoutDirection() {
   11624         // Reset the current resolved bits
   11625         mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
   11626         onResolvedLayoutDirectionReset();
   11627         // Reset also the text direction
   11628         resetResolvedTextDirection();
   11629     }
   11630 
   11631     /**
   11632      * Called during reset of resolved layout direction.
   11633      *
   11634      * Subclasses need to override this method to clear cached information that depends on the
   11635      * resolved layout direction, or to inform child views that inherit their layout direction.
   11636      *
   11637      * The default implementation does nothing.
   11638      * @hide
   11639      */
   11640     public void onResolvedLayoutDirectionReset() {
   11641     }
   11642 
   11643     /**
   11644      * Check if a Locale uses an RTL script.
   11645      *
   11646      * @param locale Locale to check
   11647      * @return true if the Locale uses an RTL script.
   11648      * @hide
   11649      */
   11650     protected static boolean isLayoutDirectionRtl(Locale locale) {
   11651         return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
   11652     }
   11653 
   11654     /**
   11655      * This is called when the view is detached from a window.  At this point it
   11656      * no longer has a surface for drawing.
   11657      *
   11658      * @see #onAttachedToWindow()
   11659      */
   11660     protected void onDetachedFromWindow() {
   11661         mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
   11662 
   11663         removeUnsetPressCallback();
   11664         removeLongPressCallback();
   11665         removePerformClickCallback();
   11666         removeSendViewScrolledAccessibilityEventCallback();
   11667 
   11668         destroyDrawingCache();
   11669 
   11670         destroyLayer(false);
   11671 
   11672         if (mAttachInfo != null) {
   11673             if (mDisplayList != null) {
   11674                 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
   11675             }
   11676             mAttachInfo.mViewRootImpl.cancelInvalidate(this);
   11677         } else {
   11678             // Should never happen
   11679             clearDisplayList();
   11680         }
   11681 
   11682         mCurrentAnimation = null;
   11683 
   11684         resetResolvedLayoutDirection();
   11685         resetResolvedTextAlignment();
   11686         resetAccessibilityStateChanged();
   11687     }
   11688 
   11689     /**
   11690      * @return The number of times this view has been attached to a window
   11691      */
   11692     protected int getWindowAttachCount() {
   11693         return mWindowAttachCount;
   11694     }
   11695 
   11696     /**
   11697      * Retrieve a unique token identifying the window this view is attached to.
   11698      * @return Return the window's token for use in
   11699      * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
   11700      */
   11701     public IBinder getWindowToken() {
   11702         return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
   11703     }
   11704 
   11705     /**
   11706      * Retrieve a unique token identifying the top-level "real" window of
   11707      * the window that this view is attached to.  That is, this is like
   11708      * {@link #getWindowToken}, except if the window this view in is a panel
   11709      * window (attached to another containing window), then the token of
   11710      * the containing window is returned instead.
   11711      *
   11712      * @return Returns the associated window token, either
   11713      * {@link #getWindowToken()} or the containing window's token.
   11714      */
   11715     public IBinder getApplicationWindowToken() {
   11716         AttachInfo ai = mAttachInfo;
   11717         if (ai != null) {
   11718             IBinder appWindowToken = ai.mPanelParentWindowToken;
   11719             if (appWindowToken == null) {
   11720                 appWindowToken = ai.mWindowToken;
   11721             }
   11722             return appWindowToken;
   11723         }
   11724         return null;
   11725     }
   11726 
   11727     /**
   11728      * Retrieve private session object this view hierarchy is using to
   11729      * communicate with the window manager.
   11730      * @return the session object to communicate with the window manager
   11731      */
   11732     /*package*/ IWindowSession getWindowSession() {
   11733         return mAttachInfo != null ? mAttachInfo.mSession : null;
   11734     }
   11735 
   11736     /**
   11737      * @param info the {@link android.view.View.AttachInfo} to associated with
   11738      *        this view
   11739      */
   11740     void dispatchAttachedToWindow(AttachInfo info, int visibility) {
   11741         //System.out.println("Attached! " + this);
   11742         mAttachInfo = info;
   11743         mWindowAttachCount++;
   11744         // We will need to evaluate the drawable state at least once.
   11745         mPrivateFlags |= DRAWABLE_STATE_DIRTY;
   11746         if (mFloatingTreeObserver != null) {
   11747             info.mTreeObserver.merge(mFloatingTreeObserver);
   11748             mFloatingTreeObserver = null;
   11749         }
   11750         if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
   11751             mAttachInfo.mScrollContainers.add(this);
   11752             mPrivateFlags |= SCROLL_CONTAINER_ADDED;
   11753         }
   11754         performCollectViewAttributes(mAttachInfo, visibility);
   11755         onAttachedToWindow();
   11756 
   11757         ListenerInfo li = mListenerInfo;
   11758         final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
   11759                 li != null ? li.mOnAttachStateChangeListeners : null;
   11760         if (listeners != null && listeners.size() > 0) {
   11761             // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
   11762             // perform the dispatching. The iterator is a safe guard against listeners that
   11763             // could mutate the list by calling the various add/remove methods. This prevents
   11764             // the array from being modified while we iterate it.
   11765             for (OnAttachStateChangeListener listener : listeners) {
   11766                 listener.onViewAttachedToWindow(this);
   11767             }
   11768         }
   11769 
   11770         int vis = info.mWindowVisibility;
   11771         if (vis != GONE) {
   11772             onWindowVisibilityChanged(vis);
   11773         }
   11774         if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
   11775             // If nobody has evaluated the drawable state yet, then do it now.
   11776             refreshDrawableState();
   11777         }
   11778     }
   11779 
   11780     void dispatchDetachedFromWindow() {
   11781         AttachInfo info = mAttachInfo;
   11782         if (info != null) {
   11783             int vis = info.mWindowVisibility;
   11784             if (vis != GONE) {
   11785                 onWindowVisibilityChanged(GONE);
   11786             }
   11787         }
   11788 
   11789         onDetachedFromWindow();
   11790 
   11791         ListenerInfo li = mListenerInfo;
   11792         final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
   11793                 li != null ? li.mOnAttachStateChangeListeners : null;
   11794         if (listeners != null && listeners.size() > 0) {
   11795             // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
   11796             // perform the dispatching. The iterator is a safe guard against listeners that
   11797             // could mutate the list by calling the various add/remove methods. This prevents
   11798             // the array from being modified while we iterate it.
   11799             for (OnAttachStateChangeListener listener : listeners) {
   11800                 listener.onViewDetachedFromWindow(this);
   11801             }
   11802         }
   11803 
   11804         if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
   11805             mAttachInfo.mScrollContainers.remove(this);
   11806             mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
   11807         }
   11808 
   11809         mAttachInfo = null;
   11810     }
   11811 
   11812     /**
   11813      * Store this view hierarchy's frozen state into the given container.
   11814      *
   11815      * @param container The SparseArray in which to save the view's state.
   11816      *
   11817      * @see #restoreHierarchyState(android.util.SparseArray)
   11818      * @see #dispatchSaveInstanceState(android.util.SparseArray)
   11819      * @see #onSaveInstanceState()
   11820      */
   11821     public void saveHierarchyState(SparseArray<Parcelable> container) {
   11822         dispatchSaveInstanceState(container);
   11823     }
   11824 
   11825     /**
   11826      * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
   11827      * this view and its children. May be overridden to modify how freezing happens to a
   11828      * view's children; for example, some views may want to not store state for their children.
   11829      *
   11830      * @param container The SparseArray in which to save the view's state.
   11831      *
   11832      * @see #dispatchRestoreInstanceState(android.util.SparseArray)
   11833      * @see #saveHierarchyState(android.util.SparseArray)
   11834      * @see #onSaveInstanceState()
   11835      */
   11836     protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
   11837         if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
   11838             mPrivateFlags &= ~SAVE_STATE_CALLED;
   11839             Parcelable state = onSaveInstanceState();
   11840             if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
   11841                 throw new IllegalStateException(
   11842                         "Derived class did not call super.onSaveInstanceState()");
   11843             }
   11844             if (state != null) {
   11845                 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
   11846                 // + ": " + state);
   11847                 container.put(mID, state);
   11848             }
   11849         }
   11850     }
   11851 
   11852     /**
   11853      * Hook allowing a view to generate a representation of its internal state
   11854      * that can later be used to create a new instance with that same state.
   11855      * This state should only contain information that is not persistent or can
   11856      * not be reconstructed later. For example, you will never store your
   11857      * current position on screen because that will be computed again when a
   11858      * new instance of the view is placed in its view hierarchy.
   11859      * <p>
   11860      * Some examples of things you may store here: the current cursor position
   11861      * in a text view (but usually not the text itself since that is stored in a
   11862      * content provider or other persistent storage), the currently selected
   11863      * item in a list view.
   11864      *
   11865      * @return Returns a Parcelable object containing the view's current dynamic
   11866      *         state, or null if there is nothing interesting to save. The
   11867      *         default implementation returns null.
   11868      * @see #onRestoreInstanceState(android.os.Parcelable)
   11869      * @see #saveHierarchyState(android.util.SparseArray)
   11870      * @see #dispatchSaveInstanceState(android.util.SparseArray)
   11871      * @see #setSaveEnabled(boolean)
   11872      */
   11873     protected Parcelable onSaveInstanceState() {
   11874         mPrivateFlags |= SAVE_STATE_CALLED;
   11875         return BaseSavedState.EMPTY_STATE;
   11876     }
   11877 
   11878     /**
   11879      * Restore this view hierarchy's frozen state from the given container.
   11880      *
   11881      * @param container The SparseArray which holds previously frozen states.
   11882      *
   11883      * @see #saveHierarchyState(android.util.SparseArray)
   11884      * @see #dispatchRestoreInstanceState(android.util.SparseArray)
   11885      * @see #onRestoreInstanceState(android.os.Parcelable)
   11886      */
   11887     public void restoreHierarchyState(SparseArray<Parcelable> container) {
   11888         dispatchRestoreInstanceState(container);
   11889     }
   11890 
   11891     /**
   11892      * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
   11893      * state for this view and its children. May be overridden to modify how restoring
   11894      * happens to a view's children; for example, some views may want to not store state
   11895      * for their children.
   11896      *
   11897      * @param container The SparseArray which holds previously saved state.
   11898      *
   11899      * @see #dispatchSaveInstanceState(android.util.SparseArray)
   11900      * @see #restoreHierarchyState(android.util.SparseArray)
   11901      * @see #onRestoreInstanceState(android.os.Parcelable)
   11902      */
   11903     protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
   11904         if (mID != NO_ID) {
   11905             Parcelable state = container.get(mID);
   11906             if (state != null) {
   11907                 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
   11908                 // + ": " + state);
   11909                 mPrivateFlags &= ~SAVE_STATE_CALLED;
   11910                 onRestoreInstanceState(state);
   11911                 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
   11912                     throw new IllegalStateException(
   11913                             "Derived class did not call super.onRestoreInstanceState()");
   11914                 }
   11915             }
   11916         }
   11917     }
   11918 
   11919     /**
   11920      * Hook allowing a view to re-apply a representation of its internal state that had previously
   11921      * been generated by {@link #onSaveInstanceState}. This function will never be called with a
   11922      * null state.
   11923      *
   11924      * @param state The frozen state that had previously been returned by
   11925      *        {@link #onSaveInstanceState}.
   11926      *
   11927      * @see #onSaveInstanceState()
   11928      * @see #restoreHierarchyState(android.util.SparseArray)
   11929      * @see #dispatchRestoreInstanceState(android.util.SparseArray)
   11930      */
   11931     protected void onRestoreInstanceState(Parcelable state) {
   11932         mPrivateFlags |= SAVE_STATE_CALLED;
   11933         if (state != BaseSavedState.EMPTY_STATE && state != null) {
   11934             throw new IllegalArgumentException("Wrong state class, expecting View State but "
   11935                     + "received " + state.getClass().toString() + " instead. This usually happens "
   11936                     + "when two views of different type have the same id in the same hierarchy. "
   11937                     + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
   11938                     + "other views do not use the same id.");
   11939         }
   11940     }
   11941 
   11942     /**
   11943      * <p>Return the time at which the drawing of the view hierarchy started.</p>
   11944      *
   11945      * @return the drawing start time in milliseconds
   11946      */
   11947     public long getDrawingTime() {
   11948         return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
   11949     }
   11950 
   11951     /**
   11952      * <p>Enables or disables the duplication of the parent's state into this view. When
   11953      * duplication is enabled, this view gets its drawable state from its parent rather
   11954      * than from its own internal properties.</p>
   11955      *
   11956      * <p>Note: in the current implementation, setting this property to true after the
   11957      * view was added to a ViewGroup might have no effect at all. This property should
   11958      * always be used from XML or set to true before adding this view to a ViewGroup.</p>
   11959      *
   11960      * <p>Note: if this view's parent addStateFromChildren property is enabled and this
   11961      * property is enabled, an exception will be thrown.</p>
   11962      *
   11963      * <p>Note: if the child view uses and updates additionnal states which are unknown to the
   11964      * parent, these states should not be affected by this method.</p>
   11965      *
   11966      * @param enabled True to enable duplication of the parent's drawable state, false
   11967      *                to disable it.
   11968      *
   11969      * @see #getDrawableState()
   11970      * @see #isDuplicateParentStateEnabled()
   11971      */
   11972     public void setDuplicateParentStateEnabled(boolean enabled) {
   11973         setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
   11974     }
   11975 
   11976     /**
   11977      * <p>Indicates whether this duplicates its drawable state from its parent.</p>
   11978      *
   11979      * @return True if this view's drawable state is duplicated from the parent,
   11980      *         false otherwise
   11981      *
   11982      * @see #getDrawableState()
   11983      * @see #setDuplicateParentStateEnabled(boolean)
   11984      */
   11985     public boolean isDuplicateParentStateEnabled() {
   11986         return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
   11987     }
   11988 
   11989     /**
   11990      * <p>Specifies the type of layer backing this view. The layer can be
   11991      * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
   11992      * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
   11993      *
   11994      * <p>A layer is associated with an optional {@link android.graphics.Paint}
   11995      * instance that controls how the layer is composed on screen. The following
   11996      * properties of the paint are taken into account when composing the layer:</p>
   11997      * <ul>
   11998      * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
   11999      * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
   12000      * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
   12001      * </ul>
   12002      *
   12003      * <p>If this view has an alpha value set to < 1.0 by calling
   12004      * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
   12005      * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
   12006      * equivalent to setting a hardware layer on this view and providing a paint with
   12007      * the desired alpha value.<p>
   12008      *
   12009      * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
   12010      * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
   12011      * for more information on when and how to use layers.</p>
   12012      *
   12013      * @param layerType The ype of layer to use with this view, must be one of
   12014      *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
   12015      *        {@link #LAYER_TYPE_HARDWARE}
   12016      * @param paint The paint used to compose the layer. This argument is optional
   12017      *        and can be null. It is ignored when the layer type is
   12018      *        {@link #LAYER_TYPE_NONE}
   12019      *
   12020      * @see #getLayerType()
   12021      * @see #LAYER_TYPE_NONE
   12022      * @see #LAYER_TYPE_SOFTWARE
   12023      * @see #LAYER_TYPE_HARDWARE
   12024      * @see #setAlpha(float)
   12025      *
   12026      * @attr ref android.R.styleable#View_layerType
   12027      */
   12028     public void setLayerType(int layerType, Paint paint) {
   12029         if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
   12030             throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
   12031                     + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
   12032         }
   12033 
   12034         if (layerType == mLayerType) {
   12035             if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
   12036                 mLayerPaint = paint == null ? new Paint() : paint;
   12037                 invalidateParentCaches();
   12038                 invalidate(true);
   12039             }
   12040             return;
   12041         }
   12042 
   12043         // Destroy any previous software drawing cache if needed
   12044         switch (mLayerType) {
   12045             case LAYER_TYPE_HARDWARE:
   12046                 destroyLayer(false);
   12047                 // fall through - non-accelerated views may use software layer mechanism instead
   12048             case LAYER_TYPE_SOFTWARE:
   12049                 destroyDrawingCache();
   12050                 break;
   12051             default:
   12052                 break;
   12053         }
   12054 
   12055         mLayerType = layerType;
   12056         final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
   12057         mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
   12058         mLocalDirtyRect = layerDisabled ? null : new Rect();
   12059 
   12060         invalidateParentCaches();
   12061         invalidate(true);
   12062     }
   12063 
   12064     /**
   12065      * Indicates whether this view has a static layer. A view with layer type
   12066      * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
   12067      * dynamic.
   12068      */
   12069     boolean hasStaticLayer() {
   12070         return true;
   12071     }
   12072 
   12073     /**
   12074      * Indicates what type of layer is currently associated with this view. By default
   12075      * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
   12076      * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
   12077      * for more information on the different types of layers.
   12078      *
   12079      * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
   12080      *         {@link #LAYER_TYPE_HARDWARE}
   12081      *
   12082      * @see #setLayerType(int, android.graphics.Paint)
   12083      * @see #buildLayer()
   12084      * @see #LAYER_TYPE_NONE
   12085      * @see #LAYER_TYPE_SOFTWARE
   12086      * @see #LAYER_TYPE_HARDWARE
   12087      */
   12088     public int getLayerType() {
   12089         return mLayerType;
   12090     }
   12091 
   12092     /**
   12093      * Forces this view's layer to be created and this view to be rendered
   12094      * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
   12095      * invoking this method will have no effect.
   12096      *
   12097      * This method can for instance be used to render a view into its layer before
   12098      * starting an animation. If this view is complex, rendering into the layer
   12099      * before starting the animation will avoid skipping frames.
   12100      *
   12101      * @throws IllegalStateException If this view is not attached to a window
   12102      *
   12103      * @see #setLayerType(int, android.graphics.Paint)
   12104      */
   12105     public void buildLayer() {
   12106         if (mLayerType == LAYER_TYPE_NONE) return;
   12107 
   12108         if (mAttachInfo == null) {
   12109             throw new IllegalStateException("This view must be attached to a window first");
   12110         }
   12111 
   12112         switch (mLayerType) {
   12113             case LAYER_TYPE_HARDWARE:
   12114                 if (mAttachInfo.mHardwareRenderer != null &&
   12115                         mAttachInfo.mHardwareRenderer.isEnabled() &&
   12116                         mAttachInfo.mHardwareRenderer.validate()) {
   12117                     getHardwareLayer();
   12118                 }
   12119                 break;
   12120             case LAYER_TYPE_SOFTWARE:
   12121                 buildDrawingCache(true);
   12122                 break;
   12123         }
   12124     }
   12125 
   12126     // Make sure the HardwareRenderer.validate() was invoked before calling this method
   12127     void flushLayer() {
   12128         if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
   12129             mHardwareLayer.flush();
   12130         }
   12131     }
   12132 
   12133     /**
   12134      * <p>Returns a hardware layer that can be used to draw this view again
   12135      * without executing its draw method.</p>
   12136      *
   12137      * @return A HardwareLayer ready to render, or null if an error occurred.
   12138      */
   12139     HardwareLayer getHardwareLayer() {
   12140         if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
   12141                 !mAttachInfo.mHardwareRenderer.isEnabled()) {
   12142             return null;
   12143         }
   12144 
   12145         if (!mAttachInfo.mHardwareRenderer.validate()) return null;
   12146 
   12147         final int width = mRight - mLeft;
   12148         final int height = mBottom - mTop;
   12149 
   12150         if (width == 0 || height == 0) {
   12151             return null;
   12152         }
   12153 
   12154         if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
   12155             if (mHardwareLayer == null) {
   12156                 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
   12157                         width, height, isOpaque());
   12158                 mLocalDirtyRect.set(0, 0, width, height);
   12159             } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
   12160                 mHardwareLayer.resize(width, height);
   12161                 mLocalDirtyRect.set(0, 0, width, height);
   12162             }
   12163 
   12164             // The layer is not valid if the underlying GPU resources cannot be allocated
   12165             if (!mHardwareLayer.isValid()) {
   12166                 return null;
   12167             }
   12168 
   12169             mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
   12170             mLocalDirtyRect.setEmpty();
   12171         }
   12172 
   12173         return mHardwareLayer;
   12174     }
   12175 
   12176     /**
   12177      * Destroys this View's hardware layer if possible.
   12178      *
   12179      * @return True if the layer was destroyed, false otherwise.
   12180      *
   12181      * @see #setLayerType(int, android.graphics.Paint)
   12182      * @see #LAYER_TYPE_HARDWARE
   12183      */
   12184     boolean destroyLayer(boolean valid) {
   12185         if (mHardwareLayer != null) {
   12186             AttachInfo info = mAttachInfo;
   12187             if (info != null && info.mHardwareRenderer != null &&
   12188                     info.mHardwareRenderer.isEnabled() &&
   12189                     (valid || info.mHardwareRenderer.validate())) {
   12190                 mHardwareLayer.destroy();
   12191                 mHardwareLayer = null;
   12192 
   12193                 invalidate(true);
   12194                 invalidateParentCaches();
   12195             }
   12196             return true;
   12197         }
   12198         return false;
   12199     }
   12200 
   12201     /**
   12202      * Destroys all hardware rendering resources. This method is invoked
   12203      * when the system needs to reclaim resources. Upon execution of this
   12204      * method, you should free any OpenGL resources created by the view.
   12205      *
   12206      * Note: you <strong>must</strong> call
   12207      * <code>super.destroyHardwareResources()</code> when overriding
   12208      * this method.
   12209      *
   12210      * @hide
   12211      */
   12212     protected void destroyHardwareResources() {
   12213         destroyLayer(true);
   12214     }
   12215 
   12216     /**
   12217      * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
   12218      * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
   12219      * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
   12220      * the cache is enabled. To benefit from the cache, you must request the drawing cache by
   12221      * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
   12222      * null.</p>
   12223      *
   12224      * <p>Enabling the drawing cache is similar to
   12225      * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
   12226      * acceleration is turned off. When hardware acceleration is turned on, enabling the
   12227      * drawing cache has no effect on rendering because the system uses a different mechanism
   12228      * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
   12229      * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
   12230      * for information on how to enable software and hardware layers.</p>
   12231      *
   12232      * <p>This API can be used to manually generate
   12233      * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
   12234      * {@link #getDrawingCache()}.</p>
   12235      *
   12236      * @param enabled true to enable the drawing cache, false otherwise
   12237      *
   12238      * @see #isDrawingCacheEnabled()
   12239      * @see #getDrawingCache()
   12240      * @see #buildDrawingCache()
   12241      * @see #setLayerType(int, android.graphics.Paint)
   12242      */
   12243     public void setDrawingCacheEnabled(boolean enabled) {
   12244         mCachingFailed = false;
   12245         setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
   12246     }
   12247 
   12248     /**
   12249      * <p>Indicates whether the drawing cache is enabled for this view.</p>
   12250      *
   12251      * @return true if the drawing cache is enabled
   12252      *
   12253      * @see #setDrawingCacheEnabled(boolean)
   12254      * @see #getDrawingCache()
   12255      */
   12256     @ViewDebug.ExportedProperty(category = "drawing")
   12257     public boolean isDrawingCacheEnabled() {
   12258         return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
   12259     }
   12260 
   12261     /**
   12262      * Debugging utility which recursively outputs the dirty state of a view and its
   12263      * descendants.
   12264      *
   12265      * @hide
   12266      */
   12267     @SuppressWarnings({"UnusedDeclaration"})
   12268     public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
   12269         Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
   12270                 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
   12271                 (mPrivateFlags & View.DRAWING_CACHE_VALID) +
   12272                 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
   12273         if (clear) {
   12274             mPrivateFlags &= clearMask;
   12275         }
   12276         if (this instanceof ViewGroup) {
   12277             ViewGroup parent = (ViewGroup) this;
   12278             final int count = parent.getChildCount();
   12279             for (int i = 0; i < count; i++) {
   12280                 final View child = parent.getChildAt(i);
   12281                 child.outputDirtyFlags(indent + "  ", clear, clearMask);
   12282             }
   12283         }
   12284     }
   12285 
   12286     /**
   12287      * This method is used by ViewGroup to cause its children to restore or recreate their
   12288      * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
   12289      * to recreate its own display list, which would happen if it went through the normal
   12290      * draw/dispatchDraw mechanisms.
   12291      *
   12292      * @hide
   12293      */
   12294     protected void dispatchGetDisplayList() {}
   12295 
   12296     /**
   12297      * A view that is not attached or hardware accelerated cannot create a display list.
   12298      * This method checks these conditions and returns the appropriate result.
   12299      *
   12300      * @return true if view has the ability to create a display list, false otherwise.
   12301      *
   12302      * @hide
   12303      */
   12304     public boolean canHaveDisplayList() {
   12305         return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
   12306     }
   12307 
   12308     /**
   12309      * @return The HardwareRenderer associated with that view or null if hardware rendering
   12310      * is not supported or this this has not been attached to a window.
   12311      *
   12312      * @hide
   12313      */
   12314     public HardwareRenderer getHardwareRenderer() {
   12315         if (mAttachInfo != null) {
   12316             return mAttachInfo.mHardwareRenderer;
   12317         }
   12318         return null;
   12319     }
   12320 
   12321     /**
   12322      * Returns a DisplayList. If the incoming displayList is null, one will be created.
   12323      * Otherwise, the same display list will be returned (after having been rendered into
   12324      * along the way, depending on the invalidation state of the view).
   12325      *
   12326      * @param displayList The previous version of this displayList, could be null.
   12327      * @param isLayer Whether the requester of the display list is a layer. If so,
   12328      * the view will avoid creating a layer inside the resulting display list.
   12329      * @return A new or reused DisplayList object.
   12330      */
   12331     private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
   12332         if (!canHaveDisplayList()) {
   12333             return null;
   12334         }
   12335 
   12336         if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
   12337                 displayList == null || !displayList.isValid() ||
   12338                 (!isLayer && mRecreateDisplayList))) {
   12339             // Don't need to recreate the display list, just need to tell our
   12340             // children to restore/recreate theirs
   12341             if (displayList != null && displayList.isValid() &&
   12342                     !isLayer && !mRecreateDisplayList) {
   12343                 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
   12344                 mPrivateFlags &= ~DIRTY_MASK;
   12345                 dispatchGetDisplayList();
   12346 
   12347                 return displayList;
   12348             }
   12349 
   12350             if (!isLayer) {
   12351                 // If we got here, we're recreating it. Mark it as such to ensure that
   12352                 // we copy in child display lists into ours in drawChild()
   12353                 mRecreateDisplayList = true;
   12354             }
   12355             if (displayList == null) {
   12356                 final String name = getClass().getSimpleName();
   12357                 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
   12358                 // If we're creating a new display list, make sure our parent gets invalidated
   12359                 // since they will need to recreate their display list to account for this
   12360                 // new child display list.
   12361                 invalidateParentCaches();
   12362             }
   12363 
   12364             boolean caching = false;
   12365             final HardwareCanvas canvas = displayList.start();
   12366             int width = mRight - mLeft;
   12367             int height = mBottom - mTop;
   12368 
   12369             try {
   12370                 canvas.setViewport(width, height);
   12371                 // The dirty rect should always be null for a display list
   12372                 canvas.onPreDraw(null);
   12373                 int layerType = (
   12374                         !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
   12375                         getLayerType() : LAYER_TYPE_NONE;
   12376                 if (!isLayer && layerType != LAYER_TYPE_NONE) {
   12377                     if (layerType == LAYER_TYPE_HARDWARE) {
   12378                         final HardwareLayer layer = getHardwareLayer();
   12379                         if (layer != null && layer.isValid()) {
   12380                             canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
   12381                         } else {
   12382                             canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
   12383                                     Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
   12384                                             Canvas.CLIP_TO_LAYER_SAVE_FLAG);
   12385                         }
   12386                         caching = true;
   12387                     } else {
   12388                         buildDrawingCache(true);
   12389                         Bitmap cache = getDrawingCache(true);
   12390                         if (cache != null) {
   12391                             canvas.drawBitmap(cache, 0, 0, mLayerPaint);
   12392                             caching = true;
   12393                         }
   12394                     }
   12395                 } else {
   12396 
   12397                     computeScroll();
   12398 
   12399                     canvas.translate(-mScrollX, -mScrollY);
   12400                     if (!isLayer) {
   12401                         mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
   12402                         mPrivateFlags &= ~DIRTY_MASK;
   12403                     }
   12404 
   12405                     // Fast path for layouts with no backgrounds
   12406                     if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
   12407                         dispatchDraw(canvas);
   12408                     } else {
   12409                         draw(canvas);
   12410                     }
   12411                 }
   12412             } finally {
   12413                 canvas.onPostDraw();
   12414 
   12415                 displayList.end();
   12416                 displayList.setCaching(caching);
   12417                 if (isLayer) {
   12418                     displayList.setLeftTopRightBottom(0, 0, width, height);
   12419                 } else {
   12420                     setDisplayListProperties(displayList);
   12421                 }
   12422             }
   12423         } else if (!isLayer) {
   12424             mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
   12425             mPrivateFlags &= ~DIRTY_MASK;
   12426         }
   12427 
   12428         return displayList;
   12429     }
   12430 
   12431     /**
   12432      * Get the DisplayList for the HardwareLayer
   12433      *
   12434      * @param layer The HardwareLayer whose DisplayList we want
   12435      * @return A DisplayList fopr the specified HardwareLayer
   12436      */
   12437     private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
   12438         DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
   12439         layer.setDisplayList(displayList);
   12440         return displayList;
   12441     }
   12442 
   12443 
   12444     /**
   12445      * <p>Returns a display list that can be used to draw this view again
   12446      * without executing its draw method.</p>
   12447      *
   12448      * @return A DisplayList ready to replay, or null if caching is not enabled.
   12449      *
   12450      * @hide
   12451      */
   12452     public DisplayList getDisplayList() {
   12453         mDisplayList = getDisplayList(mDisplayList, false);
   12454         return mDisplayList;
   12455     }
   12456 
   12457     private void clearDisplayList() {
   12458         if (mDisplayList != null) {
   12459             mDisplayList.invalidate();
   12460             mDisplayList.clear();
   12461         }
   12462     }
   12463 
   12464     /**
   12465      * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
   12466      *
   12467      * @return A non-scaled bitmap representing this view or null if cache is disabled.
   12468      *
   12469      * @see #getDrawingCache(boolean)
   12470      */
   12471     public Bitmap getDrawingCache() {
   12472         return getDrawingCache(false);
   12473     }
   12474 
   12475     /**
   12476      * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
   12477      * is null when caching is disabled. If caching is enabled and the cache is not ready,
   12478      * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
   12479      * draw from the cache when the cache is enabled. To benefit from the cache, you must
   12480      * request the drawing cache by calling this method and draw it on screen if the
   12481      * returned bitmap is not null.</p>
   12482      *
   12483      * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
   12484      * this method will create a bitmap of the same size as this view. Because this bitmap
   12485      * will be drawn scaled by the parent ViewGroup, the result on screen might show
   12486      * scaling artifacts. To avoid such artifacts, you should call this method by setting
   12487      * the auto scaling to true. Doing so, however, will generate a bitmap of a different
   12488      * size than the view. This implies that your application must be able to handle this
   12489      * size.</p>
   12490      *
   12491      * @param autoScale Indicates whether the generated bitmap should be scaled based on
   12492      *        the current density of the screen when the application is in compatibility
   12493      *        mode.
   12494      *
   12495      * @return A bitmap representing this view or null if cache is disabled.
   12496      *
   12497      * @see #setDrawingCacheEnabled(boolean)
   12498      * @see #isDrawingCacheEnabled()
   12499      * @see #buildDrawingCache(boolean)
   12500      * @see #destroyDrawingCache()
   12501      */
   12502     public Bitmap getDrawingCache(boolean autoScale) {
   12503         if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
   12504             return null;
   12505         }
   12506         if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
   12507             buildDrawingCache(autoScale);
   12508         }
   12509         return autoScale ? mDrawingCache : mUnscaledDrawingCache;
   12510     }
   12511 
   12512     /**
   12513      * <p>Frees the resources used by the drawing cache. If you call
   12514      * {@link #buildDrawingCache()} manually without calling
   12515      * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
   12516      * should cleanup the cache with this method afterwards.</p>
   12517      *
   12518      * @see #setDrawingCacheEnabled(boolean)
   12519      * @see #buildDrawingCache()
   12520      * @see #getDrawingCache()
   12521      */
   12522     public void destroyDrawingCache() {
   12523         if (mDrawingCache != null) {
   12524             mDrawingCache.recycle();
   12525             mDrawingCache = null;
   12526         }
   12527         if (mUnscaledDrawingCache != null) {
   12528             mUnscaledDrawingCache.recycle();
   12529             mUnscaledDrawingCache = null;
   12530         }
   12531     }
   12532 
   12533     /**
   12534      * Setting a solid background color for the drawing cache's bitmaps will improve
   12535      * performance and memory usage. Note, though that this should only be used if this
   12536      * view will always be drawn on top of a solid color.
   12537      *
   12538      * @param color The background color to use for the drawing cache's bitmap
   12539      *
   12540      * @see #setDrawingCacheEnabled(boolean)
   12541      * @see #buildDrawingCache()
   12542      * @see #getDrawingCache()
   12543      */
   12544     public void setDrawingCacheBackgroundColor(int color) {
   12545         if (color != mDrawingCacheBackgroundColor) {
   12546             mDrawingCacheBackgroundColor = color;
   12547             mPrivateFlags &= ~DRAWING_CACHE_VALID;
   12548         }
   12549     }
   12550 
   12551     /**
   12552      * @see #setDrawingCacheBackgroundColor(int)
   12553      *
   12554      * @return The background color to used for the drawing cache's bitmap
   12555      */
   12556     public int getDrawingCacheBackgroundColor() {
   12557         return mDrawingCacheBackgroundColor;
   12558     }
   12559 
   12560     /**
   12561      * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
   12562      *
   12563      * @see #buildDrawingCache(boolean)
   12564      */
   12565     public void buildDrawingCache() {
   12566         buildDrawingCache(false);
   12567     }
   12568 
   12569     /**
   12570      * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
   12571      *
   12572      * <p>If you call {@link #buildDrawingCache()} manually without calling
   12573      * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
   12574      * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
   12575      *
   12576      * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
   12577      * this method will create a bitmap of the same size as this view. Because this bitmap
   12578      * will be drawn scaled by the parent ViewGroup, the result on screen might show
   12579      * scaling artifacts. To avoid such artifacts, you should call this method by setting
   12580      * the auto scaling to true. Doing so, however, will generate a bitmap of a different
   12581      * size than the view. This implies that your application must be able to handle this
   12582      * size.</p>
   12583      *
   12584      * <p>You should avoid calling this method when hardware acceleration is enabled. If
   12585      * you do not need the drawing cache bitmap, calling this method will increase memory
   12586      * usage and cause the view to be rendered in software once, thus negatively impacting
   12587      * performance.</p>
   12588      *
   12589      * @see #getDrawingCache()
   12590      * @see #destroyDrawingCache()
   12591      */
   12592     public void buildDrawingCache(boolean autoScale) {
   12593         if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
   12594                 mDrawingCache == null : mUnscaledDrawingCache == null)) {
   12595             mCachingFailed = false;
   12596 
   12597             int width = mRight - mLeft;
   12598             int height = mBottom - mTop;
   12599 
   12600             final AttachInfo attachInfo = mAttachInfo;
   12601             final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
   12602 
   12603             if (autoScale && scalingRequired) {
   12604                 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
   12605                 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
   12606             }
   12607 
   12608             final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
   12609             final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
   12610             final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
   12611 
   12612             if (width <= 0 || height <= 0 ||
   12613                      // Projected bitmap size in bytes
   12614                     (width * height * (opaque && !use32BitCache ? 2 : 4) >
   12615                             ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
   12616                 destroyDrawingCache();
   12617                 mCachingFailed = true;
   12618                 return;
   12619             }
   12620 
   12621             boolean clear = true;
   12622             Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
   12623 
   12624             if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
   12625                 Bitmap.Config quality;
   12626                 if (!opaque) {
   12627                     // Never pick ARGB_4444 because it looks awful
   12628                     // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
   12629                     switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
   12630                         case DRAWING_CACHE_QUALITY_AUTO:
   12631                             quality = Bitmap.Config.ARGB_8888;
   12632                             break;
   12633                         case DRAWING_CACHE_QUALITY_LOW:
   12634                             quality = Bitmap.Config.ARGB_8888;
   12635                             break;
   12636                         case DRAWING_CACHE_QUALITY_HIGH:
   12637                             quality = Bitmap.Config.ARGB_8888;
   12638                             break;
   12639                         default:
   12640                             quality = Bitmap.Config.ARGB_8888;
   12641                             break;
   12642                     }
   12643                 } else {
   12644                     // Optimization for translucent windows
   12645                     // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
   12646                     quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
   12647                 }
   12648 
   12649                 // Try to cleanup memory
   12650                 if (bitmap != null) bitmap.recycle();
   12651 
   12652                 try {
   12653                     bitmap = Bitmap.createBitmap(width, height, quality);
   12654                     bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
   12655                     if (autoScale) {
   12656                         mDrawingCache = bitmap;
   12657                     } else {
   12658                         mUnscaledDrawingCache = bitmap;
   12659                     }
   12660                     if (opaque && use32BitCache) bitmap.setHasAlpha(false);
   12661                 } catch (OutOfMemoryError e) {
   12662                     // If there is not enough memory to create the bitmap cache, just
   12663                     // ignore the issue as bitmap caches are not required to draw the
   12664                     // view hierarchy
   12665                     if (autoScale) {
   12666                         mDrawingCache = null;
   12667                     } else {
   12668                         mUnscaledDrawingCache = null;
   12669                     }
   12670                     mCachingFailed = true;
   12671                     return;
   12672                 }
   12673 
   12674                 clear = drawingCacheBackgroundColor != 0;
   12675             }
   12676 
   12677             Canvas canvas;
   12678             if (attachInfo != null) {
   12679                 canvas = attachInfo.mCanvas;
   12680                 if (canvas == null) {
   12681                     canvas = new Canvas();
   12682                 }
   12683                 canvas.setBitmap(bitmap);
   12684                 // Temporarily clobber the cached Canvas in case one of our children
   12685                 // is also using a drawing cache. Without this, the children would
   12686                 // steal the canvas by attaching their own bitmap to it and bad, bad
   12687                 // thing would happen (invisible views, corrupted drawings, etc.)
   12688                 attachInfo.mCanvas = null;
   12689             } else {
   12690                 // This case should hopefully never or seldom happen
   12691                 canvas = new Canvas(bitmap);
   12692             }
   12693 
   12694             if (clear) {
   12695                 bitmap.eraseColor(drawingCacheBackgroundColor);
   12696             }
   12697 
   12698             computeScroll();
   12699             final int restoreCount = canvas.save();
   12700 
   12701             if (autoScale && scalingRequired) {
   12702                 final float scale = attachInfo.mApplicationScale;
   12703                 canvas.scale(scale, scale);
   12704             }
   12705 
   12706             canvas.translate(-mScrollX, -mScrollY);
   12707 
   12708             mPrivateFlags |= DRAWN;
   12709             if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
   12710                     mLayerType != LAYER_TYPE_NONE) {
   12711                 mPrivateFlags |= DRAWING_CACHE_VALID;
   12712             }
   12713 
   12714             // Fast path for layouts with no backgrounds
   12715             if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
   12716                 mPrivateFlags &= ~DIRTY_MASK;
   12717                 dispatchDraw(canvas);
   12718             } else {
   12719                 draw(canvas);
   12720             }
   12721 
   12722             canvas.restoreToCount(restoreCount);
   12723             canvas.setBitmap(null);
   12724 
   12725             if (attachInfo != null) {
   12726                 // Restore the cached Canvas for our siblings
   12727                 attachInfo.mCanvas = canvas;
   12728             }
   12729         }
   12730     }
   12731 
   12732     /**
   12733      * Create a snapshot of the view into a bitmap.  We should probably make
   12734      * some form of this public, but should think about the API.
   12735      */
   12736     Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
   12737         int width = mRight - mLeft;
   12738         int height = mBottom - mTop;
   12739 
   12740         final AttachInfo attachInfo = mAttachInfo;
   12741         final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
   12742         width = (int) ((width * scale) + 0.5f);
   12743         height = (int) ((height * scale) + 0.5f);
   12744 
   12745         Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
   12746         if (bitmap == null) {
   12747             throw new OutOfMemoryError();
   12748         }
   12749 
   12750         Resources resources = getResources();
   12751         if (resources != null) {
   12752             bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
   12753         }
   12754 
   12755         Canvas canvas;
   12756         if (attachInfo != null) {
   12757             canvas = attachInfo.mCanvas;
   12758             if (canvas == null) {
   12759                 canvas = new Canvas();
   12760             }
   12761             canvas.setBitmap(bitmap);
   12762             // Temporarily clobber the cached Canvas in case one of our children
   12763             // is also using a drawing cache. Without this, the children would
   12764             // steal the canvas by attaching their own bitmap to it and bad, bad
   12765             // things would happen (invisible views, corrupted drawings, etc.)
   12766             attachInfo.mCanvas = null;
   12767         } else {
   12768             // This case should hopefully never or seldom happen
   12769             canvas = new Canvas(bitmap);
   12770         }
   12771 
   12772         if ((backgroundColor & 0xff000000) != 0) {
   12773             bitmap.eraseColor(backgroundColor);
   12774         }
   12775 
   12776         computeScroll();
   12777         final int restoreCount = canvas.save();
   12778         canvas.scale(scale, scale);
   12779         canvas.translate(-mScrollX, -mScrollY);
   12780 
   12781         // Temporarily remove the dirty mask
   12782         int flags = mPrivateFlags;
   12783         mPrivateFlags &= ~DIRTY_MASK;
   12784 
   12785         // Fast path for layouts with no backgrounds
   12786         if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
   12787             dispatchDraw(canvas);
   12788         } else {
   12789             draw(canvas);
   12790         }
   12791 
   12792         mPrivateFlags = flags;
   12793 
   12794         canvas.restoreToCount(restoreCount);
   12795         canvas.setBitmap(null);
   12796 
   12797         if (attachInfo != null) {
   12798             // Restore the cached Canvas for our siblings
   12799             attachInfo.mCanvas = canvas;
   12800         }
   12801 
   12802         return bitmap;
   12803     }
   12804 
   12805     /**
   12806      * Indicates whether this View is currently in edit mode. A View is usually
   12807      * in edit mode when displayed within a developer tool. For instance, if
   12808      * this View is being drawn by a visual user interface builder, this method
   12809      * should return true.
   12810      *
   12811      * Subclasses should check the return value of this method to provide
   12812      * different behaviors if their normal behavior might interfere with the
   12813      * host environment. For instance: the class spawns a thread in its
   12814      * constructor, the drawing code relies on device-specific features, etc.
   12815      *
   12816      * This method is usually checked in the drawing code of custom widgets.
   12817      *
   12818      * @return True if this View is in edit mode, false otherwise.
   12819      */
   12820     public boolean isInEditMode() {
   12821         return false;
   12822     }
   12823 
   12824     /**
   12825      * If the View draws content inside its padding and enables fading edges,
   12826      * it needs to support padding offsets. Padding offsets are added to the
   12827      * fading edges to extend the length of the fade so that it covers pixels
   12828      * drawn inside the padding.
   12829      *
   12830      * Subclasses of this class should override this method if they need
   12831      * to draw content inside the padding.
   12832      *
   12833      * @return True if padding offset must be applied, false otherwise.
   12834      *
   12835      * @see #getLeftPaddingOffset()
   12836      * @see #getRightPaddingOffset()
   12837      * @see #getTopPaddingOffset()
   12838      * @see #getBottomPaddingOffset()
   12839      *
   12840      * @since CURRENT
   12841      */
   12842     protected boolean isPaddingOffsetRequired() {
   12843         return false;
   12844     }
   12845 
   12846     /**
   12847      * Amount by which to extend the left fading region. Called only when
   12848      * {@link #isPaddingOffsetRequired()} returns true.
   12849      *
   12850      * @return The left padding offset in pixels.
   12851      *
   12852      * @see #isPaddingOffsetRequired()
   12853      *
   12854      * @since CURRENT
   12855      */
   12856     protected int getLeftPaddingOffset() {
   12857         return 0;
   12858     }
   12859 
   12860     /**
   12861      * Amount by which to extend the right fading region. Called only when
   12862      * {@link #isPaddingOffsetRequired()} returns true.
   12863      *
   12864      * @return The right padding offset in pixels.
   12865      *
   12866      * @see #isPaddingOffsetRequired()
   12867      *
   12868      * @since CURRENT
   12869      */
   12870     protected int getRightPaddingOffset() {
   12871         return 0;
   12872     }
   12873 
   12874     /**
   12875      * Amount by which to extend the top fading region. Called only when
   12876      * {@link #isPaddingOffsetRequired()} returns true.
   12877      *
   12878      * @return The top padding offset in pixels.
   12879      *
   12880      * @see #isPaddingOffsetRequired()
   12881      *
   12882      * @since CURRENT
   12883      */
   12884     protected int getTopPaddingOffset() {
   12885         return 0;
   12886     }
   12887 
   12888     /**
   12889      * Amount by which to extend the bottom fading region. Called only when
   12890      * {@link #isPaddingOffsetRequired()} returns true.
   12891      *
   12892      * @return The bottom padding offset in pixels.
   12893      *
   12894      * @see #isPaddingOffsetRequired()
   12895      *
   12896      * @since CURRENT
   12897      */
   12898     protected int getBottomPaddingOffset() {
   12899         return 0;
   12900     }
   12901 
   12902     /**
   12903      * @hide
   12904      * @param offsetRequired
   12905      */
   12906     protected int getFadeTop(boolean offsetRequired) {
   12907         int top = mPaddingTop;
   12908         if (offsetRequired) top += getTopPaddingOffset();
   12909         return top;
   12910     }
   12911 
   12912     /**
   12913      * @hide
   12914      * @param offsetRequired
   12915      */
   12916     protected int getFadeHeight(boolean offsetRequired) {
   12917         int padding = mPaddingTop;
   12918         if (offsetRequired) padding += getTopPaddingOffset();
   12919         return mBottom - mTop - mPaddingBottom - padding;
   12920     }
   12921 
   12922     /**
   12923      * <p>Indicates whether this view is attached to a hardware accelerated
   12924      * window or not.</p>
   12925      *
   12926      * <p>Even if this method returns true, it does not mean that every call
   12927      * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
   12928      * accelerated {@link android.graphics.Canvas}. For instance, if this view
   12929      * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
   12930      * window is hardware accelerated,
   12931      * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
   12932      * return false, and this method will return true.</p>
   12933      *
   12934      * @return True if the view is attached to a window and the window is
   12935      *         hardware accelerated; false in any other case.
   12936      */
   12937     public boolean isHardwareAccelerated() {
   12938         return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
   12939     }
   12940 
   12941     /**
   12942      * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
   12943      * case of an active Animation being run on the view.
   12944      */
   12945     private boolean drawAnimation(ViewGroup parent, long drawingTime,
   12946             Animation a, boolean scalingRequired) {
   12947         Transformation invalidationTransform;
   12948         final int flags = parent.mGroupFlags;
   12949         final boolean initialized = a.isInitialized();
   12950         if (!initialized) {
   12951             a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
   12952             a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
   12953             if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
   12954             onAnimationStart();
   12955         }
   12956 
   12957         boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
   12958         if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
   12959             if (parent.mInvalidationTransformation == null) {
   12960                 parent.mInvalidationTransformation = new Transformation();
   12961             }
   12962             invalidationTransform = parent.mInvalidationTransformation;
   12963             a.getTransformation(drawingTime, invalidationTransform, 1f);
   12964         } else {
   12965             invalidationTransform = parent.mChildTransformation;
   12966         }
   12967 
   12968         if (more) {
   12969             if (!a.willChangeBounds()) {
   12970                 if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
   12971                         parent.FLAG_OPTIMIZE_INVALIDATE) {
   12972                     parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
   12973                 } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
   12974                     // The child need to draw an animation, potentially offscreen, so
   12975                     // make sure we do not cancel invalidate requests
   12976                     parent.mPrivateFlags |= DRAW_ANIMATION;
   12977                     parent.invalidate(mLeft, mTop, mRight, mBottom);
   12978                 }
   12979             } else {
   12980                 if (parent.mInvalidateRegion == null) {
   12981                     parent.mInvalidateRegion = new RectF();
   12982                 }
   12983                 final RectF region = parent.mInvalidateRegion;
   12984                 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
   12985                         invalidationTransform);
   12986 
   12987                 // The child need to draw an animation, potentially offscreen, so
   12988                 // make sure we do not cancel invalidate requests
   12989                 parent.mPrivateFlags |= DRAW_ANIMATION;
   12990 
   12991                 final int left = mLeft + (int) region.left;
   12992                 final int top = mTop + (int) region.top;
   12993                 parent.invalidate(left, top, left + (int) (region.width() + .5f),
   12994                         top + (int) (region.height() + .5f));
   12995             }
   12996         }
   12997         return more;
   12998     }
   12999 
   13000     /**
   13001      * This method is called by getDisplayList() when a display list is created or re-rendered.
   13002      * It sets or resets the current value of all properties on that display list (resetting is
   13003      * necessary when a display list is being re-created, because we need to make sure that
   13004      * previously-set transform values
   13005      */
   13006     void setDisplayListProperties(DisplayList displayList) {
   13007         if (displayList != null) {
   13008             displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
   13009             displayList.setHasOverlappingRendering(hasOverlappingRendering());
   13010             if (mParent instanceof ViewGroup) {
   13011                 displayList.setClipChildren(
   13012                         (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
   13013             }
   13014             float alpha = 1;
   13015             if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
   13016                     ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
   13017                 ViewGroup parentVG = (ViewGroup) mParent;
   13018                 final boolean hasTransform =
   13019                         parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
   13020                 if (hasTransform) {
   13021                     Transformation transform = parentVG.mChildTransformation;
   13022                     final int transformType = parentVG.mChildTransformation.getTransformationType();
   13023                     if (transformType != Transformation.TYPE_IDENTITY) {
   13024                         if ((transformType & Transformation.TYPE_ALPHA) != 0) {
   13025                             alpha = transform.getAlpha();
   13026                         }
   13027                         if ((transformType & Transformation.TYPE_MATRIX) != 0) {
   13028                             displayList.setStaticMatrix(transform.getMatrix());
   13029                         }
   13030                     }
   13031                 }
   13032             }
   13033             if (mTransformationInfo != null) {
   13034                 alpha *= mTransformationInfo.mAlpha;
   13035                 if (alpha < 1) {
   13036                     final int multipliedAlpha = (int) (255 * alpha);
   13037                     if (onSetAlpha(multipliedAlpha)) {
   13038                         alpha = 1;
   13039                     }
   13040                 }
   13041                 displayList.setTransformationInfo(alpha,
   13042                         mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
   13043                         mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
   13044                         mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
   13045                         mTransformationInfo.mScaleY);
   13046                 if (mTransformationInfo.mCamera == null) {
   13047                     mTransformationInfo.mCamera = new Camera();
   13048                     mTransformationInfo.matrix3D = new Matrix();
   13049                 }
   13050                 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
   13051                 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
   13052                     displayList.setPivotX(getPivotX());
   13053                     displayList.setPivotY(getPivotY());
   13054                 }
   13055             } else if (alpha < 1) {
   13056                 displayList.setAlpha(alpha);
   13057             }
   13058         }
   13059     }
   13060 
   13061     /**
   13062      * This method is called by ViewGroup.drawChild() to have each child view draw itself.
   13063      * This draw() method is an implementation detail and is not intended to be overridden or
   13064      * to be called from anywhere else other than ViewGroup.drawChild().
   13065      */
   13066     boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
   13067         boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
   13068         boolean more = false;
   13069         final boolean childHasIdentityMatrix = hasIdentityMatrix();
   13070         final int flags = parent.mGroupFlags;
   13071 
   13072         if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
   13073             parent.mChildTransformation.clear();
   13074             parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
   13075         }
   13076 
   13077         Transformation transformToApply = null;
   13078         boolean concatMatrix = false;
   13079 
   13080         boolean scalingRequired = false;
   13081         boolean caching;
   13082         int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
   13083 
   13084         final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
   13085         if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
   13086                 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
   13087             caching = true;
   13088             // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
   13089             if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
   13090         } else {
   13091             caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
   13092         }
   13093 
   13094         final Animation a = getAnimation();
   13095         if (a != null) {
   13096             more = drawAnimation(parent, drawingTime, a, scalingRequired);
   13097             concatMatrix = a.willChangeTransformationMatrix();
   13098             if (concatMatrix) {
   13099                 mPrivateFlags3 |= VIEW_IS_ANIMATING_TRANSFORM;
   13100             }
   13101             transformToApply = parent.mChildTransformation;
   13102         } else {
   13103             if ((mPrivateFlags3 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
   13104                     mDisplayList != null) {
   13105                 // No longer animating: clear out old animation matrix
   13106                 mDisplayList.setAnimationMatrix(null);
   13107                 mPrivateFlags3 &= ~VIEW_IS_ANIMATING_TRANSFORM;
   13108             }
   13109             if (!useDisplayListProperties &&
   13110                     (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
   13111                 final boolean hasTransform =
   13112                         parent.getChildStaticTransformation(this, parent.mChildTransformation);
   13113                 if (hasTransform) {
   13114                     final int transformType = parent.mChildTransformation.getTransformationType();
   13115                     transformToApply = transformType != Transformation.TYPE_IDENTITY ?
   13116                             parent.mChildTransformation : null;
   13117                     concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
   13118                 }
   13119             }
   13120         }
   13121 
   13122         concatMatrix |= !childHasIdentityMatrix;
   13123 
   13124         // Sets the flag as early as possible to allow draw() implementations
   13125         // to call invalidate() successfully when doing animations
   13126         mPrivateFlags |= DRAWN;
   13127 
   13128         if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
   13129                 (mPrivateFlags & DRAW_ANIMATION) == 0) {
   13130             mPrivateFlags2 |= VIEW_QUICK_REJECTED;
   13131             return more;
   13132         }
   13133         mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
   13134 
   13135         if (hardwareAccelerated) {
   13136             // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
   13137             // retain the flag's value temporarily in the mRecreateDisplayList flag
   13138             mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
   13139             mPrivateFlags &= ~INVALIDATED;
   13140         }
   13141 
   13142         computeScroll();
   13143 
   13144         final int sx = mScrollX;
   13145         final int sy = mScrollY;
   13146 
   13147         DisplayList displayList = null;
   13148         Bitmap cache = null;
   13149         boolean hasDisplayList = false;
   13150         if (caching) {
   13151             if (!hardwareAccelerated) {
   13152                 if (layerType != LAYER_TYPE_NONE) {
   13153                     layerType = LAYER_TYPE_SOFTWARE;
   13154                     buildDrawingCache(true);
   13155                 }
   13156                 cache = getDrawingCache(true);
   13157             } else {
   13158                 switch (layerType) {
   13159                     case LAYER_TYPE_SOFTWARE:
   13160                         if (useDisplayListProperties) {
   13161                             hasDisplayList = canHaveDisplayList();
   13162                         } else {
   13163                             buildDrawingCache(true);
   13164                             cache = getDrawingCache(true);
   13165                         }
   13166                         break;
   13167                     case LAYER_TYPE_HARDWARE:
   13168                         if (useDisplayListProperties) {
   13169                             hasDisplayList = canHaveDisplayList();
   13170                         }
   13171                         break;
   13172                     case LAYER_TYPE_NONE:
   13173                         // Delay getting the display list until animation-driven alpha values are
   13174                         // set up and possibly passed on to the view
   13175                         hasDisplayList = canHaveDisplayList();
   13176                         break;
   13177                 }
   13178             }
   13179         }
   13180         useDisplayListProperties &= hasDisplayList;
   13181         if (useDisplayListProperties) {
   13182             displayList = getDisplayList();
   13183             if (!displayList.isValid()) {
   13184                 // Uncommon, but possible. If a view is removed from the hierarchy during the call
   13185                 // to getDisplayList(), the display list will be marked invalid and we should not
   13186                 // try to use it again.
   13187                 displayList = null;
   13188                 hasDisplayList = false;
   13189                 useDisplayListProperties = false;
   13190             }
   13191         }
   13192 
   13193         final boolean hasNoCache = cache == null || hasDisplayList;
   13194         final boolean offsetForScroll = cache == null && !hasDisplayList &&
   13195                 layerType != LAYER_TYPE_HARDWARE;
   13196 
   13197         int restoreTo = -1;
   13198         if (!useDisplayListProperties || transformToApply != null) {
   13199             restoreTo = canvas.save();
   13200         }
   13201         if (offsetForScroll) {
   13202             canvas.translate(mLeft - sx, mTop - sy);
   13203         } else {
   13204             if (!useDisplayListProperties) {
   13205                 canvas.translate(mLeft, mTop);
   13206             }
   13207             if (scalingRequired) {
   13208                 if (useDisplayListProperties) {
   13209                     // TODO: Might not need this if we put everything inside the DL
   13210                     restoreTo = canvas.save();
   13211                 }
   13212                 // mAttachInfo cannot be null, otherwise scalingRequired == false
   13213                 final float scale = 1.0f / mAttachInfo.mApplicationScale;
   13214                 canvas.scale(scale, scale);
   13215             }
   13216         }
   13217 
   13218         float alpha = useDisplayListProperties ? 1 : getAlpha();
   13219         if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
   13220                 (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
   13221             if (transformToApply != null || !childHasIdentityMatrix) {
   13222                 int transX = 0;
   13223                 int transY = 0;
   13224 
   13225                 if (offsetForScroll) {
   13226                     transX = -sx;
   13227                     transY = -sy;
   13228                 }
   13229 
   13230                 if (transformToApply != null) {
   13231                     if (concatMatrix) {
   13232                         if (useDisplayListProperties) {
   13233                             displayList.setAnimationMatrix(transformToApply.getMatrix());
   13234                         } else {
   13235                             // Undo the scroll translation, apply the transformation matrix,
   13236                             // then redo the scroll translate to get the correct result.
   13237                             canvas.translate(-transX, -transY);
   13238                             canvas.concat(transformToApply.getMatrix());
   13239                             canvas.translate(transX, transY);
   13240                         }
   13241                         parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
   13242                     }
   13243 
   13244                     float transformAlpha = transformToApply.getAlpha();
   13245                     if (transformAlpha < 1) {
   13246                         alpha *= transformAlpha;
   13247                         parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
   13248                     }
   13249                 }
   13250 
   13251                 if (!childHasIdentityMatrix && !useDisplayListProperties) {
   13252                     canvas.translate(-transX, -transY);
   13253                     canvas.concat(getMatrix());
   13254                     canvas.translate(transX, transY);
   13255                 }
   13256             }
   13257 
   13258             // Deal with alpha if it is or used to be <1
   13259             if (alpha < 1 ||
   13260                     (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
   13261                 if (alpha < 1) {
   13262                     mPrivateFlags3 |= VIEW_IS_ANIMATING_ALPHA;
   13263                 } else {
   13264                     mPrivateFlags3 &= ~VIEW_IS_ANIMATING_ALPHA;
   13265                 }
   13266                 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
   13267                 if (hasNoCache) {
   13268                     final int multipliedAlpha = (int) (255 * alpha);
   13269                     if (!onSetAlpha(multipliedAlpha)) {
   13270                         int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
   13271                         if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
   13272                                 layerType != LAYER_TYPE_NONE) {
   13273                             layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
   13274                         }
   13275                         if (useDisplayListProperties) {
   13276                             displayList.setAlpha(alpha * getAlpha());
   13277                         } else  if (layerType == LAYER_TYPE_NONE) {
   13278                             final int scrollX = hasDisplayList ? 0 : sx;
   13279                             final int scrollY = hasDisplayList ? 0 : sy;
   13280                             canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
   13281                                     scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
   13282                         }
   13283                     } else {
   13284                         // Alpha is handled by the child directly, clobber the layer's alpha
   13285                         mPrivateFlags |= ALPHA_SET;
   13286                     }
   13287                 }
   13288             }
   13289         } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
   13290             onSetAlpha(255);
   13291             mPrivateFlags &= ~ALPHA_SET;
   13292         }
   13293 
   13294         if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
   13295                 !useDisplayListProperties) {
   13296             if (offsetForScroll) {
   13297                 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
   13298             } else {
   13299                 if (!scalingRequired || cache == null) {
   13300                     canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
   13301                 } else {
   13302                     canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
   13303                 }
   13304             }
   13305         }
   13306 
   13307         if (!useDisplayListProperties && hasDisplayList) {
   13308             displayList = getDisplayList();
   13309             if (!displayList.isValid()) {
   13310                 // Uncommon, but possible. If a view is removed from the hierarchy during the call
   13311                 // to getDisplayList(), the display list will be marked invalid and we should not
   13312                 // try to use it again.
   13313                 displayList = null;
   13314                 hasDisplayList = false;
   13315             }
   13316         }
   13317 
   13318         if (hasNoCache) {
   13319             boolean layerRendered = false;
   13320             if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
   13321                 final HardwareLayer layer = getHardwareLayer();
   13322                 if (layer != null && layer.isValid()) {
   13323                     mLayerPaint.setAlpha((int) (alpha * 255));
   13324                     ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
   13325                     layerRendered = true;
   13326                 } else {
   13327                     final int scrollX = hasDisplayList ? 0 : sx;
   13328                     final int scrollY = hasDisplayList ? 0 : sy;
   13329                     canvas.saveLayer(scrollX, scrollY,
   13330                             scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
   13331                             Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
   13332                 }
   13333             }
   13334 
   13335             if (!layerRendered) {
   13336                 if (!hasDisplayList) {
   13337                     // Fast path for layouts with no backgrounds
   13338                     if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
   13339                         mPrivateFlags &= ~DIRTY_MASK;
   13340                         dispatchDraw(canvas);
   13341                     } else {
   13342                         draw(canvas);
   13343                     }
   13344                 } else {
   13345                     mPrivateFlags &= ~DIRTY_MASK;
   13346                     ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
   13347                 }
   13348             }
   13349         } else if (cache != null) {
   13350             mPrivateFlags &= ~DIRTY_MASK;
   13351             Paint cachePaint;
   13352 
   13353             if (layerType == LAYER_TYPE_NONE) {
   13354                 cachePaint = parent.mCachePaint;
   13355                 if (cachePaint == null) {
   13356                     cachePaint = new Paint();
   13357                     cachePaint.setDither(false);
   13358                     parent.mCachePaint = cachePaint;
   13359                 }
   13360                 if (alpha < 1) {
   13361                     cachePaint.setAlpha((int) (alpha * 255));
   13362                     parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
   13363                 } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
   13364                     cachePaint.setAlpha(255);
   13365                     parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
   13366                 }
   13367             } else {
   13368                 cachePaint = mLayerPaint;
   13369                 cachePaint.setAlpha((int) (alpha * 255));
   13370             }
   13371             canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
   13372         }
   13373 
   13374         if (restoreTo >= 0) {
   13375             canvas.restoreToCount(restoreTo);
   13376         }
   13377 
   13378         if (a != null && !more) {
   13379             if (!hardwareAccelerated && !a.getFillAfter()) {
   13380                 onSetAlpha(255);
   13381             }
   13382             parent.finishAnimatingView(this, a);
   13383         }
   13384 
   13385         if (more && hardwareAccelerated) {
   13386             // invalidation is the trigger to recreate display lists, so if we're using
   13387             // display lists to render, force an invalidate to allow the animation to
   13388             // continue drawing another frame
   13389             parent.invalidate(true);
   13390             if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
   13391                 // alpha animations should cause the child to recreate its display list
   13392                 invalidate(true);
   13393             }
   13394         }
   13395 
   13396         mRecreateDisplayList = false;
   13397 
   13398         return more;
   13399     }
   13400 
   13401     /**
   13402      * Manually render this view (and all of its children) to the given Canvas.
   13403      * The view must have already done a full layout before this function is
   13404      * called.  When implementing a view, implement
   13405      * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
   13406      * If you do need to override this method, call the superclass version.
   13407      *
   13408      * @param canvas The Canvas to which the View is rendered.
   13409      */
   13410     public void draw(Canvas canvas) {
   13411         final int privateFlags = mPrivateFlags;
   13412         final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
   13413                 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
   13414         mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
   13415 
   13416         /*
   13417          * Draw traversal performs several drawing steps which must be executed
   13418          * in the appropriate order:
   13419          *
   13420          *      1. Draw the background
   13421          *      2. If necessary, save the canvas' layers to prepare for fading
   13422          *      3. Draw view's content
   13423          *      4. Draw children
   13424          *      5. If necessary, draw the fading edges and restore layers
   13425          *      6. Draw decorations (scrollbars for instance)
   13426          */
   13427 
   13428         // Step 1, draw the background, if needed
   13429         int saveCount;
   13430 
   13431         if (!dirtyOpaque) {
   13432             final Drawable background = mBackground;
   13433             if (background != null) {
   13434                 final int scrollX = mScrollX;
   13435                 final int scrollY = mScrollY;
   13436 
   13437                 if (mBackgroundSizeChanged) {
   13438                     background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
   13439                     mBackgroundSizeChanged = false;
   13440                 }
   13441 
   13442                 if ((scrollX | scrollY) == 0) {
   13443                     background.draw(canvas);
   13444                 } else {
   13445                     canvas.translate(scrollX, scrollY);
   13446                     background.draw(canvas);
   13447                     canvas.translate(-scrollX, -scrollY);
   13448                 }
   13449             }
   13450         }
   13451 
   13452         // skip step 2 & 5 if possible (common case)
   13453         final int viewFlags = mViewFlags;
   13454         boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
   13455         boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
   13456         if (!verticalEdges && !horizontalEdges) {
   13457             // Step 3, draw the content
   13458             if (!dirtyOpaque) onDraw(canvas);
   13459 
   13460             // Step 4, draw the children
   13461             dispatchDraw(canvas);
   13462 
   13463             // Step 6, draw decorations (scrollbars)
   13464             onDrawScrollBars(canvas);
   13465 
   13466             // we're done...
   13467             return;
   13468         }
   13469 
   13470         /*
   13471          * Here we do the full fledged routine...
   13472          * (this is an uncommon case where speed matters less,
   13473          * this is why we repeat some of the tests that have been
   13474          * done above)
   13475          */
   13476 
   13477         boolean drawTop = false;
   13478         boolean drawBottom = false;
   13479         boolean drawLeft = false;
   13480         boolean drawRight = false;
   13481 
   13482         float topFadeStrength = 0.0f;
   13483         float bottomFadeStrength = 0.0f;
   13484         float leftFadeStrength = 0.0f;
   13485         float rightFadeStrength = 0.0f;
   13486 
   13487         // Step 2, save the canvas' layers
   13488         int paddingLeft = mPaddingLeft;
   13489 
   13490         final boolean offsetRequired = isPaddingOffsetRequired();
   13491         if (offsetRequired) {
   13492             paddingLeft += getLeftPaddingOffset();
   13493         }
   13494 
   13495         int left = mScrollX + paddingLeft;
   13496         int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
   13497         int top = mScrollY + getFadeTop(offsetRequired);
   13498         int bottom = top + getFadeHeight(offsetRequired);
   13499 
   13500         if (offsetRequired) {
   13501             right += getRightPaddingOffset();
   13502             bottom += getBottomPaddingOffset();
   13503         }
   13504 
   13505         final ScrollabilityCache scrollabilityCache = mScrollCache;
   13506         final float fadeHeight = scrollabilityCache.fadingEdgeLength;
   13507         int length = (int) fadeHeight;
   13508 
   13509         // clip the fade length if top and bottom fades overlap
   13510         // overlapping fades produce odd-looking artifacts
   13511         if (verticalEdges && (top + length > bottom - length)) {
   13512             length = (bottom - top) / 2;
   13513         }
   13514 
   13515         // also clip horizontal fades if necessary
   13516         if (horizontalEdges && (left + length > right - length)) {
   13517             length = (right - left) / 2;
   13518         }
   13519 
   13520         if (verticalEdges) {
   13521             topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
   13522             drawTop = topFadeStrength * fadeHeight > 1.0f;
   13523             bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
   13524             drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
   13525         }
   13526 
   13527         if (horizontalEdges) {
   13528             leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
   13529             drawLeft = leftFadeStrength * fadeHeight > 1.0f;
   13530             rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
   13531             drawRight = rightFadeStrength * fadeHeight > 1.0f;
   13532         }
   13533 
   13534         saveCount = canvas.getSaveCount();
   13535 
   13536         int solidColor = getSolidColor();
   13537         if (solidColor == 0) {
   13538             final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
   13539 
   13540             if (drawTop) {
   13541                 canvas.saveLayer(left, top, right, top + length, null, flags);
   13542             }
   13543 
   13544             if (drawBottom) {
   13545                 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
   13546             }
   13547 
   13548             if (drawLeft) {
   13549                 canvas.saveLayer(left, top, left + length, bottom, null, flags);
   13550             }
   13551 
   13552             if (drawRight) {
   13553                 canvas.saveLayer(right - length, top, right, bottom, null, flags);
   13554             }
   13555         } else {
   13556             scrollabilityCache.setFadeColor(solidColor);
   13557         }
   13558 
   13559         // Step 3, draw the content
   13560         if (!dirtyOpaque) onDraw(canvas);
   13561 
   13562         // Step 4, draw the children
   13563         dispatchDraw(canvas);
   13564 
   13565         // Step 5, draw the fade effect and restore layers
   13566         final Paint p = scrollabilityCache.paint;
   13567         final Matrix matrix = scrollabilityCache.matrix;
   13568         final Shader fade = scrollabilityCache.shader;
   13569 
   13570         if (drawTop) {
   13571             matrix.setScale(1, fadeHeight * topFadeStrength);
   13572             matrix.postTranslate(left, top);
   13573             fade.setLocalMatrix(matrix);
   13574             canvas.drawRect(left, top, right, top + length, p);
   13575         }
   13576 
   13577         if (drawBottom) {
   13578             matrix.setScale(1, fadeHeight * bottomFadeStrength);
   13579             matrix.postRotate(180);
   13580             matrix.postTranslate(left, bottom);
   13581             fade.setLocalMatrix(matrix);
   13582             canvas.drawRect(left, bottom - length, right, bottom, p);
   13583         }
   13584 
   13585         if (drawLeft) {
   13586             matrix.setScale(1, fadeHeight * leftFadeStrength);
   13587             matrix.postRotate(-90);
   13588             matrix.postTranslate(left, top);
   13589             fade.setLocalMatrix(matrix);
   13590             canvas.drawRect(left, top, left + length, bottom, p);
   13591         }
   13592 
   13593         if (drawRight) {
   13594             matrix.setScale(1, fadeHeight * rightFadeStrength);
   13595             matrix.postRotate(90);
   13596             matrix.postTranslate(right, top);
   13597             fade.setLocalMatrix(matrix);
   13598             canvas.drawRect(right - length, top, right, bottom, p);
   13599         }
   13600 
   13601         canvas.restoreToCount(saveCount);
   13602 
   13603         // Step 6, draw decorations (scrollbars)
   13604         onDrawScrollBars(canvas);
   13605     }
   13606 
   13607     /**
   13608      * Override this if your view is known to always be drawn on top of a solid color background,
   13609      * and needs to draw fading edges. Returning a non-zero color enables the view system to
   13610      * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
   13611      * should be set to 0xFF.
   13612      *
   13613      * @see #setVerticalFadingEdgeEnabled(boolean)
   13614      * @see #setHorizontalFadingEdgeEnabled(boolean)
   13615      *
   13616      * @return The known solid color background for this view, or 0 if the color may vary
   13617      */
   13618     @ViewDebug.ExportedProperty(category = "drawing")
   13619     public int getSolidColor() {
   13620         return 0;
   13621     }
   13622 
   13623     /**
   13624      * Build a human readable string representation of the specified view flags.
   13625      *
   13626      * @param flags the view flags to convert to a string
   13627      * @return a String representing the supplied flags
   13628      */
   13629     private static String printFlags(int flags) {
   13630         String output = "";
   13631         int numFlags = 0;
   13632         if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
   13633             output += "TAKES_FOCUS";
   13634             numFlags++;
   13635         }
   13636 
   13637         switch (flags & VISIBILITY_MASK) {
   13638         case INVISIBLE:
   13639             if (numFlags > 0) {
   13640                 output += " ";
   13641             }
   13642             output += "INVISIBLE";
   13643             // USELESS HERE numFlags++;
   13644             break;
   13645         case GONE:
   13646             if (numFlags > 0) {
   13647                 output += " ";
   13648             }
   13649             output += "GONE";
   13650             // USELESS HERE numFlags++;
   13651             break;
   13652         default:
   13653             break;
   13654         }
   13655         return output;
   13656     }
   13657 
   13658     /**
   13659      * Build a human readable string representation of the specified private
   13660      * view flags.
   13661      *
   13662      * @param privateFlags the private view flags to convert to a string
   13663      * @return a String representing the supplied flags
   13664      */
   13665     private static String printPrivateFlags(int privateFlags) {
   13666         String output = "";
   13667         int numFlags = 0;
   13668 
   13669         if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
   13670             output += "WANTS_FOCUS";
   13671             numFlags++;
   13672         }
   13673 
   13674         if ((privateFlags & FOCUSED) == FOCUSED) {
   13675             if (numFlags > 0) {
   13676                 output += " ";
   13677             }
   13678             output += "FOCUSED";
   13679             numFlags++;
   13680         }
   13681 
   13682         if ((privateFlags & SELECTED) == SELECTED) {
   13683             if (numFlags > 0) {
   13684                 output += " ";
   13685             }
   13686             output += "SELECTED";
   13687             numFlags++;
   13688         }
   13689 
   13690         if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
   13691             if (numFlags > 0) {
   13692                 output += " ";
   13693             }
   13694             output += "IS_ROOT_NAMESPACE";
   13695             numFlags++;
   13696         }
   13697 
   13698         if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
   13699             if (numFlags > 0) {
   13700                 output += " ";
   13701             }
   13702             output += "HAS_BOUNDS";
   13703             numFlags++;
   13704         }
   13705 
   13706         if ((privateFlags & DRAWN) == DRAWN) {
   13707             if (numFlags > 0) {
   13708                 output += " ";
   13709             }
   13710             output += "DRAWN";
   13711             // USELESS HERE numFlags++;
   13712         }
   13713         return output;
   13714     }
   13715 
   13716     /**
   13717      * <p>Indicates whether or not this view's layout will be requested during
   13718      * the next hierarchy layout pass.</p>
   13719      *
   13720      * @return true if the layout will be forced during next layout pass
   13721      */
   13722     public boolean isLayoutRequested() {
   13723         return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
   13724     }
   13725 
   13726     /**
   13727      * Assign a size and position to a view and all of its
   13728      * descendants
   13729      *
   13730      * <p>This is the second phase of the layout mechanism.
   13731      * (The first is measuring). In this phase, each parent calls
   13732      * layout on all of its children to position them.
   13733      * This is typically done using the child measurements
   13734      * that were stored in the measure pass().</p>
   13735      *
   13736      * <p>Derived classes should not override this method.
   13737      * Derived classes with children should override
   13738      * onLayout. In that method, they should
   13739      * call layout on each of their children.</p>
   13740      *
   13741      * @param l Left position, relative to parent
   13742      * @param t Top position, relative to parent
   13743      * @param r Right position, relative to parent
   13744      * @param b Bottom position, relative to parent
   13745      */
   13746     @SuppressWarnings({"unchecked"})
   13747     public void layout(int l, int t, int r, int b) {
   13748         int oldL = mLeft;
   13749         int oldT = mTop;
   13750         int oldB = mBottom;
   13751         int oldR = mRight;
   13752         boolean changed = setFrame(l, t, r, b);
   13753         if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
   13754             onLayout(changed, l, t, r, b);
   13755             mPrivateFlags &= ~LAYOUT_REQUIRED;
   13756 
   13757             ListenerInfo li = mListenerInfo;
   13758             if (li != null && li.mOnLayoutChangeListeners != null) {
   13759                 ArrayList<OnLayoutChangeListener> listenersCopy =
   13760                         (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
   13761                 int numListeners = listenersCopy.size();
   13762                 for (int i = 0; i < numListeners; ++i) {
   13763                     listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
   13764                 }
   13765             }
   13766         }
   13767         mPrivateFlags &= ~FORCE_LAYOUT;
   13768     }
   13769 
   13770     /**
   13771      * Called from layout when this view should
   13772      * assign a size and position to each of its children.
   13773      *
   13774      * Derived classes with children should override
   13775      * this method and call layout on each of
   13776      * their children.
   13777      * @param changed This is a new size or position for this view
   13778      * @param left Left position, relative to parent
   13779      * @param top Top position, relative to parent
   13780      * @param right Right position, relative to parent
   13781      * @param bottom Bottom position, relative to parent
   13782      */
   13783     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
   13784     }
   13785 
   13786     /**
   13787      * Assign a size and position to this view.
   13788      *
   13789      * This is called from layout.
   13790      *
   13791      * @param left Left position, relative to parent
   13792      * @param top Top position, relative to parent
   13793      * @param right Right position, relative to parent
   13794      * @param bottom Bottom position, relative to parent
   13795      * @return true if the new size and position are different than the
   13796      *         previous ones
   13797      * {@hide}
   13798      */
   13799     protected boolean setFrame(int left, int top, int right, int bottom) {
   13800         boolean changed = false;
   13801 
   13802         if (DBG) {
   13803             Log.d("View", this + " View.setFrame(" + left + "," + top + ","
   13804                     + right + "," + bottom + ")");
   13805         }
   13806 
   13807         if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
   13808             changed = true;
   13809 
   13810             // Remember our drawn bit
   13811             int drawn = mPrivateFlags & DRAWN;
   13812 
   13813             int oldWidth = mRight - mLeft;
   13814             int oldHeight = mBottom - mTop;
   13815             int newWidth = right - left;
   13816             int newHeight = bottom - top;
   13817             boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
   13818 
   13819             // Invalidate our old position
   13820             invalidate(sizeChanged);
   13821 
   13822             mLeft = left;
   13823             mTop = top;
   13824             mRight = right;
   13825             mBottom = bottom;
   13826             if (mDisplayList != null) {
   13827                 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
   13828             }
   13829 
   13830             mPrivateFlags |= HAS_BOUNDS;
   13831 
   13832 
   13833             if (sizeChanged) {
   13834                 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
   13835                     // A change in dimension means an auto-centered pivot point changes, too
   13836                     if (mTransformationInfo != null) {
   13837                         mTransformationInfo.mMatrixDirty = true;
   13838                     }
   13839                 }
   13840                 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
   13841             }
   13842 
   13843             if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
   13844                 // If we are visible, force the DRAWN bit to on so that
   13845                 // this invalidate will go through (at least to our parent).
   13846                 // This is because someone may have invalidated this view
   13847                 // before this call to setFrame came in, thereby clearing
   13848                 // the DRAWN bit.
   13849                 mPrivateFlags |= DRAWN;
   13850                 invalidate(sizeChanged);
   13851                 // parent display list may need to be recreated based on a change in the bounds
   13852                 // of any child
   13853                 invalidateParentCaches();
   13854             }
   13855 
   13856             // Reset drawn bit to original value (invalidate turns it off)
   13857             mPrivateFlags |= drawn;
   13858 
   13859             mBackgroundSizeChanged = true;
   13860         }
   13861         return changed;
   13862     }
   13863 
   13864     /**
   13865      * Finalize inflating a view from XML.  This is called as the last phase
   13866      * of inflation, after all child views have been added.
   13867      *
   13868      * <p>Even if the subclass overrides onFinishInflate, they should always be
   13869      * sure to call the super method, so that we get called.
   13870      */
   13871     protected void onFinishInflate() {
   13872     }
   13873 
   13874     /**
   13875      * Returns the resources associated with this view.
   13876      *
   13877      * @return Resources object.
   13878      */
   13879     public Resources getResources() {
   13880         return mResources;
   13881     }
   13882 
   13883     /**
   13884      * Invalidates the specified Drawable.
   13885      *
   13886      * @param drawable the drawable to invalidate
   13887      */
   13888     public void invalidateDrawable(Drawable drawable) {
   13889         if (verifyDrawable(drawable)) {
   13890             final Rect dirty = drawable.getBounds();
   13891             final int scrollX = mScrollX;
   13892             final int scrollY = mScrollY;
   13893 
   13894             invalidate(dirty.left + scrollX, dirty.top + scrollY,
   13895                     dirty.right + scrollX, dirty.bottom + scrollY);
   13896         }
   13897     }
   13898 
   13899     /**
   13900      * Schedules an action on a drawable to occur at a specified time.
   13901      *
   13902      * @param who the recipient of the action
   13903      * @param what the action to run on the drawable
   13904      * @param when the time at which the action must occur. Uses the
   13905      *        {@link SystemClock#uptimeMillis} timebase.
   13906      */
   13907     public void scheduleDrawable(Drawable who, Runnable what, long when) {
   13908         if (verifyDrawable(who) && what != null) {
   13909             final long delay = when - SystemClock.uptimeMillis();
   13910             if (mAttachInfo != null) {
   13911                 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
   13912                         Choreographer.CALLBACK_ANIMATION, what, who,
   13913                         Choreographer.subtractFrameDelay(delay));
   13914             } else {
   13915                 ViewRootImpl.getRunQueue().postDelayed(what, delay);
   13916             }
   13917         }
   13918     }
   13919 
   13920     /**
   13921      * Cancels a scheduled action on a drawable.
   13922      *
   13923      * @param who the recipient of the action
   13924      * @param what the action to cancel
   13925      */
   13926     public void unscheduleDrawable(Drawable who, Runnable what) {
   13927         if (verifyDrawable(who) && what != null) {
   13928             if (mAttachInfo != null) {
   13929                 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
   13930                         Choreographer.CALLBACK_ANIMATION, what, who);
   13931             } else {
   13932                 ViewRootImpl.getRunQueue().removeCallbacks(what);
   13933             }
   13934         }
   13935     }
   13936 
   13937     /**
   13938      * Unschedule any events associated with the given Drawable.  This can be
   13939      * used when selecting a new Drawable into a view, so that the previous
   13940      * one is completely unscheduled.
   13941      *
   13942      * @param who The Drawable to unschedule.
   13943      *
   13944      * @see #drawableStateChanged
   13945      */
   13946     public void unscheduleDrawable(Drawable who) {
   13947         if (mAttachInfo != null && who != null) {
   13948             mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
   13949                     Choreographer.CALLBACK_ANIMATION, null, who);
   13950         }
   13951     }
   13952 
   13953     /**
   13954     * Return the layout direction of a given Drawable.
   13955     *
   13956     * @param who the Drawable to query
   13957     * @hide
   13958     */
   13959     public int getResolvedLayoutDirection(Drawable who) {
   13960         return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
   13961     }
   13962 
   13963     /**
   13964      * If your view subclass is displaying its own Drawable objects, it should
   13965      * override this function and return true for any Drawable it is
   13966      * displaying.  This allows animations for those drawables to be
   13967      * scheduled.
   13968      *
   13969      * <p>Be sure to call through to the super class when overriding this
   13970      * function.
   13971      *
   13972      * @param who The Drawable to verify.  Return true if it is one you are
   13973      *            displaying, else return the result of calling through to the
   13974      *            super class.
   13975      *
   13976      * @return boolean If true than the Drawable is being displayed in the
   13977      *         view; else false and it is not allowed to animate.
   13978      *
   13979      * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
   13980      * @see #drawableStateChanged()
   13981      */
   13982     protected boolean verifyDrawable(Drawable who) {
   13983         return who == mBackground;
   13984     }
   13985 
   13986     /**
   13987      * This function is called whenever the state of the view changes in such
   13988      * a way that it impacts the state of drawables being shown.
   13989      *
   13990      * <p>Be sure to call through to the superclass when overriding this
   13991      * function.
   13992      *
   13993      * @see Drawable#setState(int[])
   13994      */
   13995     protected void drawableStateChanged() {
   13996         Drawable d = mBackground;
   13997         if (d != null && d.isStateful()) {
   13998             d.setState(getDrawableState());
   13999         }
   14000     }
   14001 
   14002     /**
   14003      * Call this to force a view to update its drawable state. This will cause
   14004      * drawableStateChanged to be called on this view. Views that are interested
   14005      * in the new state should call getDrawableState.
   14006      *
   14007      * @see #drawableStateChanged
   14008      * @see #getDrawableState
   14009      */
   14010     public void refreshDrawableState() {
   14011         mPrivateFlags |= DRAWABLE_STATE_DIRTY;
   14012         drawableStateChanged();
   14013 
   14014         ViewParent parent = mParent;
   14015         if (parent != null) {
   14016             parent.childDrawableStateChanged(this);
   14017         }
   14018     }
   14019 
   14020     /**
   14021      * Return an array of resource IDs of the drawable states representing the
   14022      * current state of the view.
   14023      *
   14024      * @return The current drawable state
   14025      *
   14026      * @see Drawable#setState(int[])
   14027      * @see #drawableStateChanged()
   14028      * @see #onCreateDrawableState(int)
   14029      */
   14030     public final int[] getDrawableState() {
   14031         if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
   14032             return mDrawableState;
   14033         } else {
   14034             mDrawableState = onCreateDrawableState(0);
   14035             mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
   14036             return mDrawableState;
   14037         }
   14038     }
   14039 
   14040     /**
   14041      * Generate the new {@link android.graphics.drawable.Drawable} state for
   14042      * this view. This is called by the view
   14043      * system when the cached Drawable state is determined to be invalid.  To
   14044      * retrieve the current state, you should use {@link #getDrawableState}.
   14045      *
   14046      * @param extraSpace if non-zero, this is the number of extra entries you
   14047      * would like in the returned array in which you can place your own
   14048      * states.
   14049      *
   14050      * @return Returns an array holding the current {@link Drawable} state of
   14051      * the view.
   14052      *
   14053      * @see #mergeDrawableStates(int[], int[])
   14054      */
   14055     protected int[] onCreateDrawableState(int extraSpace) {
   14056         if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
   14057                 mParent instanceof View) {
   14058             return ((View) mParent).onCreateDrawableState(extraSpace);
   14059         }
   14060 
   14061         int[] drawableState;
   14062 
   14063         int privateFlags = mPrivateFlags;
   14064 
   14065         int viewStateIndex = 0;
   14066         if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
   14067         if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
   14068         if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
   14069         if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
   14070         if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
   14071         if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
   14072         if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
   14073                 HardwareRenderer.isAvailable()) {
   14074             // This is set if HW acceleration is requested, even if the current
   14075             // process doesn't allow it.  This is just to allow app preview
   14076             // windows to better match their app.
   14077             viewStateIndex |= VIEW_STATE_ACCELERATED;
   14078         }
   14079         if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
   14080 
   14081         final int privateFlags2 = mPrivateFlags2;
   14082         if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
   14083         if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
   14084 
   14085         drawableState = VIEW_STATE_SETS[viewStateIndex];
   14086 
   14087         //noinspection ConstantIfStatement
   14088         if (false) {
   14089             Log.i("View", "drawableStateIndex=" + viewStateIndex);
   14090             Log.i("View", toString()
   14091                     + " pressed=" + ((privateFlags & PRESSED) != 0)
   14092                     + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
   14093                     + " fo=" + hasFocus()
   14094                     + " sl=" + ((privateFlags & SELECTED) != 0)
   14095                     + " wf=" + hasWindowFocus()
   14096                     + ": " + Arrays.toString(drawableState));
   14097         }
   14098 
   14099         if (extraSpace == 0) {
   14100             return drawableState;
   14101         }
   14102 
   14103         final int[] fullState;
   14104         if (drawableState != null) {
   14105             fullState = new int[drawableState.length + extraSpace];
   14106             System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
   14107         } else {
   14108             fullState = new int[extraSpace];
   14109         }
   14110 
   14111         return fullState;
   14112     }
   14113 
   14114     /**
   14115      * Merge your own state values in <var>additionalState</var> into the base
   14116      * state values <var>baseState</var> that were returned by
   14117      * {@link #onCreateDrawableState(int)}.
   14118      *
   14119      * @param baseState The base state values returned by
   14120      * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
   14121      * own additional state values.
   14122      *
   14123      * @param additionalState The additional state values you would like
   14124      * added to <var>baseState</var>; this array is not modified.
   14125      *
   14126      * @return As a convenience, the <var>baseState</var> array you originally
   14127      * passed into the function is returned.
   14128      *
   14129      * @see #onCreateDrawableState(int)
   14130      */
   14131     protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
   14132         final int N = baseState.length;
   14133         int i = N - 1;
   14134         while (i >= 0 && baseState[i] == 0) {
   14135             i--;
   14136         }
   14137         System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
   14138         return baseState;
   14139     }
   14140 
   14141     /**
   14142      * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
   14143      * on all Drawable objects associated with this view.
   14144      */
   14145     public void jumpDrawablesToCurrentState() {
   14146         if (mBackground != null) {
   14147             mBackground.jumpToCurrentState();
   14148         }
   14149     }
   14150 
   14151     /**
   14152      * Sets the background color for this view.
   14153      * @param color the color of the background
   14154      */
   14155     @RemotableViewMethod
   14156     public void setBackgroundColor(int color) {
   14157         if (mBackground instanceof ColorDrawable) {
   14158             ((ColorDrawable) mBackground).setColor(color);
   14159         } else {
   14160             setBackground(new ColorDrawable(color));
   14161         }
   14162     }
   14163 
   14164     /**
   14165      * Set the background to a given resource. The resource should refer to
   14166      * a Drawable object or 0 to remove the background.
   14167      * @param resid The identifier of the resource.
   14168      *
   14169      * @attr ref android.R.styleable#View_background
   14170      */
   14171     @RemotableViewMethod
   14172     public void setBackgroundResource(int resid) {
   14173         if (resid != 0 && resid == mBackgroundResource) {
   14174             return;
   14175         }
   14176 
   14177         Drawable d= null;
   14178         if (resid != 0) {
   14179             d = mResources.getDrawable(resid);
   14180         }
   14181         setBackground(d);
   14182 
   14183         mBackgroundResource = resid;
   14184     }
   14185 
   14186     /**
   14187      * Set the background to a given Drawable, or remove the background. If the
   14188      * background has padding, this View's padding is set to the background's
   14189      * padding. However, when a background is removed, this View's padding isn't
   14190      * touched. If setting the padding is desired, please use
   14191      * {@link #setPadding(int, int, int, int)}.
   14192      *
   14193      * @param background The Drawable to use as the background, or null to remove the
   14194      *        background
   14195      */
   14196     public void setBackground(Drawable background) {
   14197         //noinspection deprecation
   14198         setBackgroundDrawable(background);
   14199     }
   14200 
   14201     /**
   14202      * @deprecated use {@link #setBackground(Drawable)} instead
   14203      */
   14204     @Deprecated
   14205     public void setBackgroundDrawable(Drawable background) {
   14206         if (background == mBackground) {
   14207             return;
   14208         }
   14209 
   14210         boolean requestLayout = false;
   14211 
   14212         mBackgroundResource = 0;
   14213 
   14214         /*
   14215          * Regardless of whether we're setting a new background or not, we want
   14216          * to clear the previous drawable.
   14217          */
   14218         if (mBackground != null) {
   14219             mBackground.setCallback(null);
   14220             unscheduleDrawable(mBackground);
   14221         }
   14222 
   14223         if (background != null) {
   14224             Rect padding = sThreadLocal.get();
   14225             if (padding == null) {
   14226                 padding = new Rect();
   14227                 sThreadLocal.set(padding);
   14228             }
   14229             if (background.getPadding(padding)) {
   14230                 switch (background.getResolvedLayoutDirectionSelf()) {
   14231                     case LAYOUT_DIRECTION_RTL:
   14232                         setPadding(padding.right, padding.top, padding.left, padding.bottom);
   14233                         break;
   14234                     case LAYOUT_DIRECTION_LTR:
   14235                     default:
   14236                         setPadding(padding.left, padding.top, padding.right, padding.bottom);
   14237                 }
   14238             }
   14239 
   14240             // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
   14241             // if it has a different minimum size, we should layout again
   14242             if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
   14243                     mBackground.getMinimumWidth() != background.getMinimumWidth()) {
   14244                 requestLayout = true;
   14245             }
   14246 
   14247             background.setCallback(this);
   14248             if (background.isStateful()) {
   14249                 background.setState(getDrawableState());
   14250             }
   14251             background.setVisible(getVisibility() == VISIBLE, false);
   14252             mBackground = background;
   14253 
   14254             if ((mPrivateFlags & SKIP_DRAW) != 0) {
   14255                 mPrivateFlags &= ~SKIP_DRAW;
   14256                 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
   14257                 requestLayout = true;
   14258             }
   14259         } else {
   14260             /* Remove the background */
   14261             mBackground = null;
   14262 
   14263             if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
   14264                 /*
   14265                  * This view ONLY drew the background before and we're removing
   14266                  * the background, so now it won't draw anything
   14267                  * (hence we SKIP_DRAW)
   14268                  */
   14269                 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
   14270                 mPrivateFlags |= SKIP_DRAW;
   14271             }
   14272 
   14273             /*
   14274              * When the background is set, we try to apply its padding to this
   14275              * View. When the background is removed, we don't touch this View's
   14276              * padding. This is noted in the Javadocs. Hence, we don't need to
   14277              * requestLayout(), the invalidate() below is sufficient.
   14278              */
   14279 
   14280             // The old background's minimum size could have affected this
   14281             // View's layout, so let's requestLayout
   14282             requestLayout = true;
   14283         }
   14284 
   14285         computeOpaqueFlags();
   14286 
   14287         if (requestLayout) {
   14288             requestLayout();
   14289         }
   14290 
   14291         mBackgroundSizeChanged = true;
   14292         invalidate(true);
   14293     }
   14294 
   14295     /**
   14296      * Gets the background drawable
   14297      *
   14298      * @return The drawable used as the background for this view, if any.
   14299      *
   14300      * @see #setBackground(Drawable)
   14301      *
   14302      * @attr ref android.R.styleable#View_background
   14303      */
   14304     public Drawable getBackground() {
   14305         return mBackground;
   14306     }
   14307 
   14308     /**
   14309      * Sets the padding. The view may add on the space required to display
   14310      * the scrollbars, depending on the style and visibility of the scrollbars.
   14311      * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
   14312      * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
   14313      * from the values set in this call.
   14314      *
   14315      * @attr ref android.R.styleable#View_padding
   14316      * @attr ref android.R.styleable#View_paddingBottom
   14317      * @attr ref android.R.styleable#View_paddingLeft
   14318      * @attr ref android.R.styleable#View_paddingRight
   14319      * @attr ref android.R.styleable#View_paddingTop
   14320      * @param left the left padding in pixels
   14321      * @param top the top padding in pixels
   14322      * @param right the right padding in pixels
   14323      * @param bottom the bottom padding in pixels
   14324      */
   14325     public void setPadding(int left, int top, int right, int bottom) {
   14326         mUserPaddingStart = -1;
   14327         mUserPaddingEnd = -1;
   14328         mUserPaddingRelative = false;
   14329 
   14330         internalSetPadding(left, top, right, bottom);
   14331     }
   14332 
   14333     private void internalSetPadding(int left, int top, int right, int bottom) {
   14334         mUserPaddingLeft = left;
   14335         mUserPaddingRight = right;
   14336         mUserPaddingBottom = bottom;
   14337 
   14338         final int viewFlags = mViewFlags;
   14339         boolean changed = false;
   14340 
   14341         // Common case is there are no scroll bars.
   14342         if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
   14343             if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
   14344                 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
   14345                         ? 0 : getVerticalScrollbarWidth();
   14346                 switch (mVerticalScrollbarPosition) {
   14347                     case SCROLLBAR_POSITION_DEFAULT:
   14348                         if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
   14349                             left += offset;
   14350                         } else {
   14351                             right += offset;
   14352                         }
   14353                         break;
   14354                     case SCROLLBAR_POSITION_RIGHT:
   14355                         right += offset;
   14356                         break;
   14357                     case SCROLLBAR_POSITION_LEFT:
   14358                         left += offset;
   14359                         break;
   14360                 }
   14361             }
   14362             if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
   14363                 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
   14364                         ? 0 : getHorizontalScrollbarHeight();
   14365             }
   14366         }
   14367 
   14368         if (mPaddingLeft != left) {
   14369             changed = true;
   14370             mPaddingLeft = left;
   14371         }
   14372         if (mPaddingTop != top) {
   14373             changed = true;
   14374             mPaddingTop = top;
   14375         }
   14376         if (mPaddingRight != right) {
   14377             changed = true;
   14378             mPaddingRight = right;
   14379         }
   14380         if (mPaddingBottom != bottom) {
   14381             changed = true;
   14382             mPaddingBottom = bottom;
   14383         }
   14384 
   14385         if (changed) {
   14386             requestLayout();
   14387         }
   14388     }
   14389 
   14390     /**
   14391      * Sets the relative padding. The view may add on the space required to display
   14392      * the scrollbars, depending on the style and visibility of the scrollbars.
   14393      * from the values set in this call.
   14394      *
   14395      * @param start the start padding in pixels
   14396      * @param top the top padding in pixels
   14397      * @param end the end padding in pixels
   14398      * @param bottom the bottom padding in pixels
   14399      * @hide
   14400      */
   14401     public void setPaddingRelative(int start, int top, int end, int bottom) {
   14402         mUserPaddingStart = start;
   14403         mUserPaddingEnd = end;
   14404         mUserPaddingRelative = true;
   14405 
   14406         switch(getResolvedLayoutDirection()) {
   14407             case LAYOUT_DIRECTION_RTL:
   14408                 internalSetPadding(end, top, start, bottom);
   14409                 break;
   14410             case LAYOUT_DIRECTION_LTR:
   14411             default:
   14412                 internalSetPadding(start, top, end, bottom);
   14413         }
   14414     }
   14415 
   14416     /**
   14417      * Returns the top padding of this view.
   14418      *
   14419      * @return the top padding in pixels
   14420      */
   14421     public int getPaddingTop() {
   14422         return mPaddingTop;
   14423     }
   14424 
   14425     /**
   14426      * Returns the bottom padding of this view. If there are inset and enabled
   14427      * scrollbars, this value may include the space required to display the
   14428      * scrollbars as well.
   14429      *
   14430      * @return the bottom padding in pixels
   14431      */
   14432     public int getPaddingBottom() {
   14433         return mPaddingBottom;
   14434     }
   14435 
   14436     /**
   14437      * Returns the left padding of this view. If there are inset and enabled
   14438      * scrollbars, this value may include the space required to display the
   14439      * scrollbars as well.
   14440      *
   14441      * @return the left padding in pixels
   14442      */
   14443     public int getPaddingLeft() {
   14444         return mPaddingLeft;
   14445     }
   14446 
   14447     /**
   14448      * Returns the start padding of this view depending on its resolved layout direction.
   14449      * If there are inset and enabled scrollbars, this value may include the space
   14450      * required to display the scrollbars as well.
   14451      *
   14452      * @return the start padding in pixels
   14453      * @hide
   14454      */
   14455     public int getPaddingStart() {
   14456         return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
   14457                 mPaddingRight : mPaddingLeft;
   14458     }
   14459 
   14460     /**
   14461      * Returns the right padding of this view. If there are inset and enabled
   14462      * scrollbars, this value may include the space required to display the
   14463      * scrollbars as well.
   14464      *
   14465      * @return the right padding in pixels
   14466      */
   14467     public int getPaddingRight() {
   14468         return mPaddingRight;
   14469     }
   14470 
   14471     /**
   14472      * Returns the end padding of this view depending on its resolved layout direction.
   14473      * If there are inset and enabled scrollbars, this value may include the space
   14474      * required to display the scrollbars as well.
   14475      *
   14476      * @return the end padding in pixels
   14477      * @hide
   14478      */
   14479     public int getPaddingEnd() {
   14480         return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
   14481                 mPaddingLeft : mPaddingRight;
   14482     }
   14483 
   14484     /**
   14485      * Return if the padding as been set thru relative values
   14486      * {@link #setPaddingRelative(int, int, int, int)}
   14487      *
   14488      * @return true if the padding is relative or false if it is not.
   14489      * @hide
   14490      */
   14491     public boolean isPaddingRelative() {
   14492         return mUserPaddingRelative;
   14493     }
   14494 
   14495     /**
   14496      * @hide
   14497      */
   14498     public Insets getOpticalInsets() {
   14499         if (mLayoutInsets == null) {
   14500             mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
   14501         }
   14502         return mLayoutInsets;
   14503     }
   14504 
   14505     /**
   14506      * @hide
   14507      */
   14508     public void setLayoutInsets(Insets layoutInsets) {
   14509         mLayoutInsets = layoutInsets;
   14510     }
   14511 
   14512     /**
   14513      * Changes the selection state of this view. A view can be selected or not.
   14514      * Note that selection is not the same as focus. Views are typically
   14515      * selected in the context of an AdapterView like ListView or GridView;
   14516      * the selected view is the view that is highlighted.
   14517      *
   14518      * @param selected true if the view must be selected, false otherwise
   14519      */
   14520     public void setSelected(boolean selected) {
   14521         if (((mPrivateFlags & SELECTED) != 0) != selected) {
   14522             mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
   14523             if (!selected) resetPressedState();
   14524             invalidate(true);
   14525             refreshDrawableState();
   14526             dispatchSetSelected(selected);
   14527             if (AccessibilityManager.getInstance(mContext).isEnabled()) {
   14528                 notifyAccessibilityStateChanged();
   14529             }
   14530         }
   14531     }
   14532 
   14533     /**
   14534      * Dispatch setSelected to all of this View's children.
   14535      *
   14536      * @see #setSelected(boolean)
   14537      *
   14538      * @param selected The new selected state
   14539      */
   14540     protected void dispatchSetSelected(boolean selected) {
   14541     }
   14542 
   14543     /**
   14544      * Indicates the selection state of this view.
   14545      *
   14546      * @return true if the view is selected, false otherwise
   14547      */
   14548     @ViewDebug.ExportedProperty
   14549     public boolean isSelected() {
   14550         return (mPrivateFlags & SELECTED) != 0;
   14551     }
   14552 
   14553     /**
   14554      * Changes the activated state of this view. A view can be activated or not.
   14555      * Note that activation is not the same as selection.  Selection is
   14556      * a transient property, representing the view (hierarchy) the user is
   14557      * currently interacting with.  Activation is a longer-term state that the
   14558      * user can move views in and out of.  For example, in a list view with
   14559      * single or multiple selection enabled, the views in the current selection
   14560      * set are activated.  (Um, yeah, we are deeply sorry about the terminology
   14561      * here.)  The activated state is propagated down to children of the view it
   14562      * is set on.
   14563      *
   14564      * @param activated true if the view must be activated, false otherwise
   14565      */
   14566     public void setActivated(boolean activated) {
   14567         if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
   14568             mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
   14569             invalidate(true);
   14570             refreshDrawableState();
   14571             dispatchSetActivated(activated);
   14572         }
   14573     }
   14574 
   14575     /**
   14576      * Dispatch setActivated to all of this View's children.
   14577      *
   14578      * @see #setActivated(boolean)
   14579      *
   14580      * @param activated The new activated state
   14581      */
   14582     protected void dispatchSetActivated(boolean activated) {
   14583     }
   14584 
   14585     /**
   14586      * Indicates the activation state of this view.
   14587      *
   14588      * @return true if the view is activated, false otherwise
   14589      */
   14590     @ViewDebug.ExportedProperty
   14591     public boolean isActivated() {
   14592         return (mPrivateFlags & ACTIVATED) != 0;
   14593     }
   14594 
   14595     /**
   14596      * Returns the ViewTreeObserver for this view's hierarchy. The view tree
   14597      * observer can be used to get notifications when global events, like
   14598      * layout, happen.
   14599      *
   14600      * The returned ViewTreeObserver observer is not guaranteed to remain
   14601      * valid for the lifetime of this View. If the caller of this method keeps
   14602      * a long-lived reference to ViewTreeObserver, it should always check for
   14603      * the return value of {@link ViewTreeObserver#isAlive()}.
   14604      *
   14605      * @return The ViewTreeObserver for this view's hierarchy.
   14606      */
   14607     public ViewTreeObserver getViewTreeObserver() {
   14608         if (mAttachInfo != null) {
   14609             return mAttachInfo.mTreeObserver;
   14610         }
   14611         if (mFloatingTreeObserver == null) {
   14612             mFloatingTreeObserver = new ViewTreeObserver();
   14613         }
   14614         return mFloatingTreeObserver;
   14615     }
   14616 
   14617     /**
   14618      * <p>Finds the topmost view in the current view hierarchy.</p>
   14619      *
   14620      * @return the topmost view containing this view
   14621      */
   14622     public View getRootView() {
   14623         if (mAttachInfo != null) {
   14624             final View v = mAttachInfo.mRootView;
   14625             if (v != null) {
   14626                 return v;
   14627             }
   14628         }
   14629 
   14630         View parent = this;
   14631 
   14632         while (parent.mParent != null && parent.mParent instanceof View) {
   14633             parent = (View) parent.mParent;
   14634         }
   14635 
   14636         return parent;
   14637     }
   14638 
   14639     /**
   14640      * <p>Computes the coordinates of this view on the screen. The argument
   14641      * must be an array of two integers. After the method returns, the array
   14642      * contains the x and y location in that order.</p>
   14643      *
   14644      * @param location an array of two integers in which to hold the coordinates
   14645      */
   14646     public void getLocationOnScreen(int[] location) {
   14647         getLocationInWindow(location);
   14648 
   14649         final AttachInfo info = mAttachInfo;
   14650         if (info != null) {
   14651             location[0] += info.mWindowLeft;
   14652             location[1] += info.mWindowTop;
   14653         }
   14654     }
   14655 
   14656     /**
   14657      * <p>Computes the coordinates of this view in its window. The argument
   14658      * must be an array of two integers. After the method returns, the array
   14659      * contains the x and y location in that order.</p>
   14660      *
   14661      * @param location an array of two integers in which to hold the coordinates
   14662      */
   14663     public void getLocationInWindow(int[] location) {
   14664         if (location == null || location.length < 2) {
   14665             throw new IllegalArgumentException("location must be an array of two integers");
   14666         }
   14667 
   14668         if (mAttachInfo == null) {
   14669             // When the view is not attached to a window, this method does not make sense
   14670             location[0] = location[1] = 0;
   14671             return;
   14672         }
   14673 
   14674         float[] position = mAttachInfo.mTmpTransformLocation;
   14675         position[0] = position[1] = 0.0f;
   14676 
   14677         if (!hasIdentityMatrix()) {
   14678             getMatrix().mapPoints(position);
   14679         }
   14680 
   14681         position[0] += mLeft;
   14682         position[1] += mTop;
   14683 
   14684         ViewParent viewParent = mParent;
   14685         while (viewParent instanceof View) {
   14686             final View view = (View) viewParent;
   14687 
   14688             position[0] -= view.mScrollX;
   14689             position[1] -= view.mScrollY;
   14690 
   14691             if (!view.hasIdentityMatrix()) {
   14692                 view.getMatrix().mapPoints(position);
   14693             }
   14694 
   14695             position[0] += view.mLeft;
   14696             position[1] += view.mTop;
   14697 
   14698             viewParent = view.mParent;
   14699          }
   14700 
   14701         if (viewParent instanceof ViewRootImpl) {
   14702             // *cough*
   14703             final ViewRootImpl vr = (ViewRootImpl) viewParent;
   14704             position[1] -= vr.mCurScrollY;
   14705         }
   14706 
   14707         location[0] = (int) (position[0] + 0.5f);
   14708         location[1] = (int) (position[1] + 0.5f);
   14709     }
   14710 
   14711     /**
   14712      * {@hide}
   14713      * @param id the id of the view to be found
   14714      * @return the view of the specified id, null if cannot be found
   14715      */
   14716     protected View findViewTraversal(int id) {
   14717         if (id == mID) {
   14718             return this;
   14719         }
   14720         return null;
   14721     }
   14722 
   14723     /**
   14724      * {@hide}
   14725      * @param tag the tag of the view to be found
   14726      * @return the view of specified tag, null if cannot be found
   14727      */
   14728     protected View findViewWithTagTraversal(Object tag) {
   14729         if (tag != null && tag.equals(mTag)) {
   14730             return this;
   14731         }
   14732         return null;
   14733     }
   14734 
   14735     /**
   14736      * {@hide}
   14737      * @param predicate The predicate to evaluate.
   14738      * @param childToSkip If not null, ignores this child during the recursive traversal.
   14739      * @return The first view that matches the predicate or null.
   14740      */
   14741     protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
   14742         if (predicate.apply(this)) {
   14743             return this;
   14744         }
   14745         return null;
   14746     }
   14747 
   14748     /**
   14749      * Look for a child view with the given id.  If this view has the given
   14750      * id, return this view.
   14751      *
   14752      * @param id The id to search for.
   14753      * @return The view that has the given id in the hierarchy or null
   14754      */
   14755     public final View findViewById(int id) {
   14756         if (id < 0) {
   14757             return null;
   14758         }
   14759         return findViewTraversal(id);
   14760     }
   14761 
   14762     /**
   14763      * Finds a view by its unuque and stable accessibility id.
   14764      *
   14765      * @param accessibilityId The searched accessibility id.
   14766      * @return The found view.
   14767      */
   14768     final View findViewByAccessibilityId(int accessibilityId) {
   14769         if (accessibilityId < 0) {
   14770             return null;
   14771         }
   14772         return findViewByAccessibilityIdTraversal(accessibilityId);
   14773     }
   14774 
   14775     /**
   14776      * Performs the traversal to find a view by its unuque and stable accessibility id.
   14777      *
   14778      * <strong>Note:</strong>This method does not stop at the root namespace
   14779      * boundary since the user can touch the screen at an arbitrary location
   14780      * potentially crossing the root namespace bounday which will send an
   14781      * accessibility event to accessibility services and they should be able
   14782      * to obtain the event source. Also accessibility ids are guaranteed to be
   14783      * unique in the window.
   14784      *
   14785      * @param accessibilityId The accessibility id.
   14786      * @return The found view.
   14787      */
   14788     View findViewByAccessibilityIdTraversal(int accessibilityId) {
   14789         if (getAccessibilityViewId() == accessibilityId) {
   14790             return this;
   14791         }
   14792         return null;
   14793     }
   14794 
   14795     /**
   14796      * Look for a child view with the given tag.  If this view has the given
   14797      * tag, return this view.
   14798      *
   14799      * @param tag The tag to search for, using "tag.equals(getTag())".
   14800      * @return The View that has the given tag in the hierarchy or null
   14801      */
   14802     public final View findViewWithTag(Object tag) {
   14803         if (tag == null) {
   14804             return null;
   14805         }
   14806         return findViewWithTagTraversal(tag);
   14807     }
   14808 
   14809     /**
   14810      * {@hide}
   14811      * Look for a child view that matches the specified predicate.
   14812      * If this view matches the predicate, return this view.
   14813      *
   14814      * @param predicate The predicate to evaluate.
   14815      * @return The first view that matches the predicate or null.
   14816      */
   14817     public final View findViewByPredicate(Predicate<View> predicate) {
   14818         return findViewByPredicateTraversal(predicate, null);
   14819     }
   14820 
   14821     /**
   14822      * {@hide}
   14823      * Look for a child view that matches the specified predicate,
   14824      * starting with the specified view and its descendents and then
   14825      * recusively searching the ancestors and siblings of that view
   14826      * until this view is reached.
   14827      *
   14828      * This method is useful in cases where the predicate does not match
   14829      * a single unique view (perhaps multiple views use the same id)
   14830      * and we are trying to find the view that is "closest" in scope to the
   14831      * starting view.
   14832      *
   14833      * @param start The view to start from.
   14834      * @param predicate The predicate to evaluate.
   14835      * @return The first view that matches the predicate or null.
   14836      */
   14837     public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
   14838         View childToSkip = null;
   14839         for (;;) {
   14840             View view = start.findViewByPredicateTraversal(predicate, childToSkip);
   14841             if (view != null || start == this) {
   14842                 return view;
   14843             }
   14844 
   14845             ViewParent parent = start.getParent();
   14846             if (parent == null || !(parent instanceof View)) {
   14847                 return null;
   14848             }
   14849 
   14850             childToSkip = start;
   14851             start = (View) parent;
   14852         }
   14853     }
   14854 
   14855     /**
   14856      * Sets the identifier for this view. The identifier does not have to be
   14857      * unique in this view's hierarchy. The identifier should be a positive
   14858      * number.
   14859      *
   14860      * @see #NO_ID
   14861      * @see #getId()
   14862      * @see #findViewById(int)
   14863      *
   14864      * @param id a number used to identify the view
   14865      *
   14866      * @attr ref android.R.styleable#View_id
   14867      */
   14868     public void setId(int id) {
   14869         mID = id;
   14870     }
   14871 
   14872     /**
   14873      * {@hide}
   14874      *
   14875      * @param isRoot true if the view belongs to the root namespace, false
   14876      *        otherwise
   14877      */
   14878     public void setIsRootNamespace(boolean isRoot) {
   14879         if (isRoot) {
   14880             mPrivateFlags |= IS_ROOT_NAMESPACE;
   14881         } else {
   14882             mPrivateFlags &= ~IS_ROOT_NAMESPACE;
   14883         }
   14884     }
   14885 
   14886     /**
   14887      * {@hide}
   14888      *
   14889      * @return true if the view belongs to the root namespace, false otherwise
   14890      */
   14891     public boolean isRootNamespace() {
   14892         return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
   14893     }
   14894 
   14895     /**
   14896      * Returns this view's identifier.
   14897      *
   14898      * @return a positive integer used to identify the view or {@link #NO_ID}
   14899      *         if the view has no ID
   14900      *
   14901      * @see #setId(int)
   14902      * @see #findViewById(int)
   14903      * @attr ref android.R.styleable#View_id
   14904      */
   14905     @ViewDebug.CapturedViewProperty
   14906     public int getId() {
   14907         return mID;
   14908     }
   14909 
   14910     /**
   14911      * Returns this view's tag.
   14912      *
   14913      * @return the Object stored in this view as a tag
   14914      *
   14915      * @see #setTag(Object)
   14916      * @see #getTag(int)
   14917      */
   14918     @ViewDebug.ExportedProperty
   14919     public Object getTag() {
   14920         return mTag;
   14921     }
   14922 
   14923     /**
   14924      * Sets the tag associated with this view. A tag can be used to mark
   14925      * a view in its hierarchy and does not have to be unique within the
   14926      * hierarchy. Tags can also be used to store data within a view without
   14927      * resorting to another data structure.
   14928      *
   14929      * @param tag an Object to tag the view with
   14930      *
   14931      * @see #getTag()
   14932      * @see #setTag(int, Object)
   14933      */
   14934     public void setTag(final Object tag) {
   14935         mTag = tag;
   14936     }
   14937 
   14938     /**
   14939      * Returns the tag associated with this view and the specified key.
   14940      *
   14941      * @param key The key identifying the tag
   14942      *
   14943      * @return the Object stored in this view as a tag
   14944      *
   14945      * @see #setTag(int, Object)
   14946      * @see #getTag()
   14947      */
   14948     public Object getTag(int key) {
   14949         if (mKeyedTags != null) return mKeyedTags.get(key);
   14950         return null;
   14951     }
   14952 
   14953     /**
   14954      * Sets a tag associated with this view and a key. A tag can be used
   14955      * to mark a view in its hierarchy and does not have to be unique within
   14956      * the hierarchy. Tags can also be used to store data within a view
   14957      * without resorting to another data structure.
   14958      *
   14959      * The specified key should be an id declared in the resources of the
   14960      * application to ensure it is unique (see the <a
   14961      * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
   14962      * Keys identified as belonging to
   14963      * the Android framework or not associated with any package will cause
   14964      * an {@link IllegalArgumentException} to be thrown.
   14965      *
   14966      * @param key The key identifying the tag
   14967      * @param tag An Object to tag the view with
   14968      *
   14969      * @throws IllegalArgumentException If they specified key is not valid
   14970      *
   14971      * @see #setTag(Object)
   14972      * @see #getTag(int)
   14973      */
   14974     public void setTag(int key, final Object tag) {
   14975         // If the package id is 0x00 or 0x01, it's either an undefined package
   14976         // or a framework id
   14977         if ((key >>> 24) < 2) {
   14978             throw new IllegalArgumentException("The key must be an application-specific "
   14979                     + "resource id.");
   14980         }
   14981 
   14982         setKeyedTag(key, tag);
   14983     }
   14984 
   14985     /**
   14986      * Variation of {@link #setTag(int, Object)} that enforces the key to be a
   14987      * framework id.
   14988      *
   14989      * @hide
   14990      */
   14991     public void setTagInternal(int key, Object tag) {
   14992         if ((key >>> 24) != 0x1) {
   14993             throw new IllegalArgumentException("The key must be a framework-specific "
   14994                     + "resource id.");
   14995         }
   14996 
   14997         setKeyedTag(key, tag);
   14998     }
   14999 
   15000     private void setKeyedTag(int key, Object tag) {
   15001         if (mKeyedTags == null) {
   15002             mKeyedTags = new SparseArray<Object>();
   15003         }
   15004 
   15005         mKeyedTags.put(key, tag);
   15006     }
   15007 
   15008     /**
   15009      * Prints information about this view in the log output, with the tag
   15010      * {@link #VIEW_LOG_TAG}.
   15011      *
   15012      * @hide
   15013      */
   15014     public void debug() {
   15015         debug(0);
   15016     }
   15017 
   15018     /**
   15019      * Prints information about this view in the log output, with the tag
   15020      * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
   15021      * indentation defined by the <code>depth</code>.
   15022      *
   15023      * @param depth the indentation level
   15024      *
   15025      * @hide
   15026      */
   15027     protected void debug(int depth) {
   15028         String output = debugIndent(depth - 1);
   15029 
   15030         output += "+ " + this;
   15031         int id = getId();
   15032         if (id != -1) {
   15033             output += " (id=" + id + ")";
   15034         }
   15035         Object tag = getTag();
   15036         if (tag != null) {
   15037             output += " (tag=" + tag + ")";
   15038         }
   15039         Log.d(VIEW_LOG_TAG, output);
   15040 
   15041         if ((mPrivateFlags & FOCUSED) != 0) {
   15042             output = debugIndent(depth) + " FOCUSED";
   15043             Log.d(VIEW_LOG_TAG, output);
   15044         }
   15045 
   15046         output = debugIndent(depth);
   15047         output += "frame={" + mLeft + ", " + mTop + ", " + mRight
   15048                 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
   15049                 + "} ";
   15050         Log.d(VIEW_LOG_TAG, output);
   15051 
   15052         if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
   15053                 || mPaddingBottom != 0) {
   15054             output = debugIndent(depth);
   15055             output += "padding={" + mPaddingLeft + ", " + mPaddingTop
   15056                     + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
   15057             Log.d(VIEW_LOG_TAG, output);
   15058         }
   15059 
   15060         output = debugIndent(depth);
   15061         output += "mMeasureWidth=" + mMeasuredWidth +
   15062                 " mMeasureHeight=" + mMeasuredHeight;
   15063         Log.d(VIEW_LOG_TAG, output);
   15064 
   15065         output = debugIndent(depth);
   15066         if (mLayoutParams == null) {
   15067             output += "BAD! no layout params";
   15068         } else {
   15069             output = mLayoutParams.debug(output);
   15070         }
   15071         Log.d(VIEW_LOG_TAG, output);
   15072 
   15073         output = debugIndent(depth);
   15074         output += "flags={";
   15075         output += View.printFlags(mViewFlags);
   15076         output += "}";
   15077         Log.d(VIEW_LOG_TAG, output);
   15078 
   15079         output = debugIndent(depth);
   15080         output += "privateFlags={";
   15081         output += View.printPrivateFlags(mPrivateFlags);
   15082         output += "}";
   15083         Log.d(VIEW_LOG_TAG, output);
   15084     }
   15085 
   15086     /**
   15087      * Creates a string of whitespaces used for indentation.
   15088      *
   15089      * @param depth the indentation level
   15090      * @return a String containing (depth * 2 + 3) * 2 white spaces
   15091      *
   15092      * @hide
   15093      */
   15094     protected static String debugIndent(int depth) {
   15095         StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
   15096         for (int i = 0; i < (depth * 2) + 3; i++) {
   15097             spaces.append(' ').append(' ');
   15098         }
   15099         return spaces.toString();
   15100     }
   15101 
   15102     /**
   15103      * <p>Return the offset of the widget's text baseline from the widget's top
   15104      * boundary. If this widget does not support baseline alignment, this
   15105      * method returns -1. </p>
   15106      *
   15107      * @return the offset of the baseline within the widget's bounds or -1
   15108      *         if baseline alignment is not supported
   15109      */
   15110     @ViewDebug.ExportedProperty(category = "layout")
   15111     public int getBaseline() {
   15112         return -1;
   15113     }
   15114 
   15115     /**
   15116      * Call this when something has changed which has invalidated the
   15117      * layout of this view. This will schedule a layout pass of the view
   15118      * tree.
   15119      */
   15120     public void requestLayout() {
   15121         mPrivateFlags |= FORCE_LAYOUT;
   15122         mPrivateFlags |= INVALIDATED;
   15123 
   15124         if (mLayoutParams != null) {
   15125             mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
   15126         }
   15127 
   15128         if (mParent != null && !mParent.isLayoutRequested()) {
   15129             mParent.requestLayout();
   15130         }
   15131     }
   15132 
   15133     /**
   15134      * Forces this view to be laid out during the next layout pass.
   15135      * This method does not call requestLayout() or forceLayout()
   15136      * on the parent.
   15137      */
   15138     public void forceLayout() {
   15139         mPrivateFlags |= FORCE_LAYOUT;
   15140         mPrivateFlags |= INVALIDATED;
   15141     }
   15142 
   15143     /**
   15144      * <p>
   15145      * This is called to find out how big a view should be. The parent
   15146      * supplies constraint information in the width and height parameters.
   15147      * </p>
   15148      *
   15149      * <p>
   15150      * The actual measurement work of a view is performed in
   15151      * {@link #onMeasure(int, int)}, called by this method. Therefore, only
   15152      * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
   15153      * </p>
   15154      *
   15155      *
   15156      * @param widthMeasureSpec Horizontal space requirements as imposed by the
   15157      *        parent
   15158      * @param heightMeasureSpec Vertical space requirements as imposed by the
   15159      *        parent
   15160      *
   15161      * @see #onMeasure(int, int)
   15162      */
   15163     public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
   15164         if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
   15165                 widthMeasureSpec != mOldWidthMeasureSpec ||
   15166                 heightMeasureSpec != mOldHeightMeasureSpec) {
   15167 
   15168             // first clears the measured dimension flag
   15169             mPrivateFlags &= ~MEASURED_DIMENSION_SET;
   15170 
   15171             // measure ourselves, this should set the measured dimension flag back
   15172             onMeasure(widthMeasureSpec, heightMeasureSpec);
   15173 
   15174             // flag not set, setMeasuredDimension() was not invoked, we raise
   15175             // an exception to warn the developer
   15176             if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
   15177                 throw new IllegalStateException("onMeasure() did not set the"
   15178                         + " measured dimension by calling"
   15179                         + " setMeasuredDimension()");
   15180             }
   15181 
   15182             mPrivateFlags |= LAYOUT_REQUIRED;
   15183         }
   15184 
   15185         mOldWidthMeasureSpec = widthMeasureSpec;
   15186         mOldHeightMeasureSpec = heightMeasureSpec;
   15187     }
   15188 
   15189     /**
   15190      * <p>
   15191      * Measure the view and its content to determine the measured width and the
   15192      * measured height. This method is invoked by {@link #measure(int, int)} and
   15193      * should be overriden by subclasses to provide accurate and efficient
   15194      * measurement of their contents.
   15195      * </p>
   15196      *
   15197      * <p>
   15198      * <strong>CONTRACT:</strong> When overriding this method, you
   15199      * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
   15200      * measured width and height of this view. Failure to do so will trigger an
   15201      * <code>IllegalStateException</code>, thrown by
   15202      * {@link #measure(int, int)}. Calling the superclass'
   15203      * {@link #onMeasure(int, int)} is a valid use.
   15204      * </p>
   15205      *
   15206      * <p>
   15207      * The base class implementation of measure defaults to the background size,
   15208      * unless a larger size is allowed by the MeasureSpec. Subclasses should
   15209      * override {@link #onMeasure(int, int)} to provide better measurements of
   15210      * their content.
   15211      * </p>
   15212      *
   15213      * <p>
   15214      * If this method is overridden, it is the subclass's responsibility to make
   15215      * sure the measured height and width are at least the view's minimum height
   15216      * and width ({@link #getSuggestedMinimumHeight()} and
   15217      * {@link #getSuggestedMinimumWidth()}).
   15218      * </p>
   15219      *
   15220      * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
   15221      *                         The requirements are encoded with
   15222      *                         {@link android.view.View.MeasureSpec}.
   15223      * @param heightMeasureSpec vertical space requirements as imposed by the parent.
   15224      *                         The requirements are encoded with
   15225      *                         {@link android.view.View.MeasureSpec}.
   15226      *
   15227      * @see #getMeasuredWidth()
   15228      * @see #getMeasuredHeight()
   15229      * @see #setMeasuredDimension(int, int)
   15230      * @see #getSuggestedMinimumHeight()
   15231      * @see #getSuggestedMinimumWidth()
   15232      * @see android.view.View.MeasureSpec#getMode(int)
   15233      * @see android.view.View.MeasureSpec#getSize(int)
   15234      */
   15235     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   15236         setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
   15237                 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
   15238     }
   15239 
   15240     /**
   15241      * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
   15242      * measured width and measured height. Failing to do so will trigger an
   15243      * exception at measurement time.</p>
   15244      *
   15245      * @param measuredWidth The measured width of this view.  May be a complex
   15246      * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
   15247      * {@link #MEASURED_STATE_TOO_SMALL}.
   15248      * @param measuredHeight The measured height of this view.  May be a complex
   15249      * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
   15250      * {@link #MEASURED_STATE_TOO_SMALL}.
   15251      */
   15252     protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
   15253         mMeasuredWidth = measuredWidth;
   15254         mMeasuredHeight = measuredHeight;
   15255 
   15256         mPrivateFlags |= MEASURED_DIMENSION_SET;
   15257     }
   15258 
   15259     /**
   15260      * Merge two states as returned by {@link #getMeasuredState()}.
   15261      * @param curState The current state as returned from a view or the result
   15262      * of combining multiple views.
   15263      * @param newState The new view state to combine.
   15264      * @return Returns a new integer reflecting the combination of the two
   15265      * states.
   15266      */
   15267     public static int combineMeasuredStates(int curState, int newState) {
   15268         return curState | newState;
   15269     }
   15270 
   15271     /**
   15272      * Version of {@link #resolveSizeAndState(int, int, int)}
   15273      * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
   15274      */
   15275     public static int resolveSize(int size, int measureSpec) {
   15276         return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
   15277     }
   15278 
   15279     /**
   15280      * Utility to reconcile a desired size and state, with constraints imposed
   15281      * by a MeasureSpec.  Will take the desired size, unless a different size
   15282      * is imposed by the constraints.  The returned value is a compound integer,
   15283      * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
   15284      * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
   15285      * size is smaller than the size the view wants to be.
   15286      *
   15287      * @param size How big the view wants to be
   15288      * @param measureSpec Constraints imposed by the parent
   15289      * @return Size information bit mask as defined by
   15290      * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
   15291      */
   15292     public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
   15293         int result = size;
   15294         int specMode = MeasureSpec.getMode(measureSpec);
   15295         int specSize =  MeasureSpec.getSize(measureSpec);
   15296         switch (specMode) {
   15297         case MeasureSpec.UNSPECIFIED:
   15298             result = size;
   15299             break;
   15300         case MeasureSpec.AT_MOST:
   15301             if (specSize < size) {
   15302                 result = specSize | MEASURED_STATE_TOO_SMALL;
   15303             } else {
   15304                 result = size;
   15305             }
   15306             break;
   15307         case MeasureSpec.EXACTLY:
   15308             result = specSize;
   15309             break;
   15310         }
   15311         return result | (childMeasuredState&MEASURED_STATE_MASK);
   15312     }
   15313 
   15314     /**
   15315      * Utility to return a default size. Uses the supplied size if the
   15316      * MeasureSpec imposed no constraints. Will get larger if allowed
   15317      * by the MeasureSpec.
   15318      *
   15319      * @param size Default size for this view
   15320      * @param measureSpec Constraints imposed by the parent
   15321      * @return The size this view should be.
   15322      */
   15323     public static int getDefaultSize(int size, int measureSpec) {
   15324         int result = size;
   15325         int specMode = MeasureSpec.getMode(measureSpec);
   15326         int specSize = MeasureSpec.getSize(measureSpec);
   15327 
   15328         switch (specMode) {
   15329         case MeasureSpec.UNSPECIFIED:
   15330             result = size;
   15331             break;
   15332         case MeasureSpec.AT_MOST:
   15333         case MeasureSpec.EXACTLY:
   15334             result = specSize;
   15335             break;
   15336         }
   15337         return result;
   15338     }
   15339 
   15340     /**
   15341      * Returns the suggested minimum height that the view should use. This
   15342      * returns the maximum of the view's minimum height
   15343      * and the background's minimum height
   15344      * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
   15345      * <p>
   15346      * When being used in {@link #onMeasure(int, int)}, the caller should still
   15347      * ensure the returned height is within the requirements of the parent.
   15348      *
   15349      * @return The suggested minimum height of the view.
   15350      */
   15351     protected int getSuggestedMinimumHeight() {
   15352         return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
   15353 
   15354     }
   15355 
   15356     /**
   15357      * Returns the suggested minimum width that the view should use. This
   15358      * returns the maximum of the view's minimum width)
   15359      * and the background's minimum width
   15360      *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
   15361      * <p>
   15362      * When being used in {@link #onMeasure(int, int)}, the caller should still
   15363      * ensure the returned width is within the requirements of the parent.
   15364      *
   15365      * @return The suggested minimum width of the view.
   15366      */
   15367     protected int getSuggestedMinimumWidth() {
   15368         return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
   15369     }
   15370 
   15371     /**
   15372      * Returns the minimum height of the view.
   15373      *
   15374      * @return the minimum height the view will try to be.
   15375      *
   15376      * @see #setMinimumHeight(int)
   15377      *
   15378      * @attr ref android.R.styleable#View_minHeight
   15379      */
   15380     public int getMinimumHeight() {
   15381         return mMinHeight;
   15382     }
   15383 
   15384     /**
   15385      * Sets the minimum height of the view. It is not guaranteed the view will
   15386      * be able to achieve this minimum height (for example, if its parent layout
   15387      * constrains it with less available height).
   15388      *
   15389      * @param minHeight The minimum height the view will try to be.
   15390      *
   15391      * @see #getMinimumHeight()
   15392      *
   15393      * @attr ref android.R.styleable#View_minHeight
   15394      */
   15395     public void setMinimumHeight(int minHeight) {
   15396         mMinHeight = minHeight;
   15397         requestLayout();
   15398     }
   15399 
   15400     /**
   15401      * Returns the minimum width of the view.
   15402      *
   15403      * @return the minimum width the view will try to be.
   15404      *
   15405      * @see #setMinimumWidth(int)
   15406      *
   15407      * @attr ref android.R.styleable#View_minWidth
   15408      */
   15409     public int getMinimumWidth() {
   15410         return mMinWidth;
   15411     }
   15412 
   15413     /**
   15414      * Sets the minimum width of the view. It is not guaranteed the view will
   15415      * be able to achieve this minimum width (for example, if its parent layout
   15416      * constrains it with less available width).
   15417      *
   15418      * @param minWidth The minimum width the view will try to be.
   15419      *
   15420      * @see #getMinimumWidth()
   15421      *
   15422      * @attr ref android.R.styleable#View_minWidth
   15423      */
   15424     public void setMinimumWidth(int minWidth) {
   15425         mMinWidth = minWidth;
   15426         requestLayout();
   15427 
   15428     }
   15429 
   15430     /**
   15431      * Get the animation currently associated with this view.
   15432      *
   15433      * @return The animation that is currently playing or
   15434      *         scheduled to play for this view.
   15435      */
   15436     public Animation getAnimation() {
   15437         return mCurrentAnimation;
   15438     }
   15439 
   15440     /**
   15441      * Start the specified animation now.
   15442      *
   15443      * @param animation the animation to start now
   15444      */
   15445     public void startAnimation(Animation animation) {
   15446         animation.setStartTime(Animation.START_ON_FIRST_FRAME);
   15447         setAnimation(animation);
   15448         invalidateParentCaches();
   15449         invalidate(true);
   15450     }
   15451 
   15452     /**
   15453      * Cancels any animations for this view.
   15454      */
   15455     public void clearAnimation() {
   15456         if (mCurrentAnimation != null) {
   15457             mCurrentAnimation.detach();
   15458         }
   15459         mCurrentAnimation = null;
   15460         invalidateParentIfNeeded();
   15461     }
   15462 
   15463     /**
   15464      * Sets the next animation to play for this view.
   15465      * If you want the animation to play immediately, use
   15466      * {@link #startAnimation(android.view.animation.Animation)} instead.
   15467      * This method provides allows fine-grained
   15468      * control over the start time and invalidation, but you
   15469      * must make sure that 1) the animation has a start time set, and
   15470      * 2) the view's parent (which controls animations on its children)
   15471      * will be invalidated when the animation is supposed to
   15472      * start.
   15473      *
   15474      * @param animation The next animation, or null.
   15475      */
   15476     public void setAnimation(Animation animation) {
   15477         mCurrentAnimation = animation;
   15478 
   15479         if (animation != null) {
   15480             // If the screen is off assume the animation start time is now instead of
   15481             // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
   15482             // would cause the animation to start when the screen turns back on
   15483             if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
   15484                     animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
   15485                 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
   15486             }
   15487             animation.reset();
   15488         }
   15489     }
   15490 
   15491     /**
   15492      * Invoked by a parent ViewGroup to notify the start of the animation
   15493      * currently associated with this view. If you override this method,
   15494      * always call super.onAnimationStart();
   15495      *
   15496      * @see #setAnimation(android.view.animation.Animation)
   15497      * @see #getAnimation()
   15498      */
   15499     protected void onAnimationStart() {
   15500         mPrivateFlags |= ANIMATION_STARTED;
   15501     }
   15502 
   15503     /**
   15504      * Invoked by a parent ViewGroup to notify the end of the animation
   15505      * currently associated with this view. If you override this method,
   15506      * always call super.onAnimationEnd();
   15507      *
   15508      * @see #setAnimation(android.view.animation.Animation)
   15509      * @see #getAnimation()
   15510      */
   15511     protected void onAnimationEnd() {
   15512         mPrivateFlags &= ~ANIMATION_STARTED;
   15513     }
   15514 
   15515     /**
   15516      * Invoked if there is a Transform that involves alpha. Subclass that can
   15517      * draw themselves with the specified alpha should return true, and then
   15518      * respect that alpha when their onDraw() is called. If this returns false
   15519      * then the view may be redirected to draw into an offscreen buffer to
   15520      * fulfill the request, which will look fine, but may be slower than if the
   15521      * subclass handles it internally. The default implementation returns false.
   15522      *
   15523      * @param alpha The alpha (0..255) to apply to the view's drawing
   15524      * @return true if the view can draw with the specified alpha.
   15525      */
   15526     protected boolean onSetAlpha(int alpha) {
   15527         return false;
   15528     }
   15529 
   15530     /**
   15531      * This is used by the RootView to perform an optimization when
   15532      * the view hierarchy contains one or several SurfaceView.
   15533      * SurfaceView is always considered transparent, but its children are not,
   15534      * therefore all View objects remove themselves from the global transparent
   15535      * region (passed as a parameter to this function).
   15536      *
   15537      * @param region The transparent region for this ViewAncestor (window).
   15538      *
   15539      * @return Returns true if the effective visibility of the view at this
   15540      * point is opaque, regardless of the transparent region; returns false
   15541      * if it is possible for underlying windows to be seen behind the view.
   15542      *
   15543      * {@hide}
   15544      */
   15545     public boolean gatherTransparentRegion(Region region) {
   15546         final AttachInfo attachInfo = mAttachInfo;
   15547         if (region != null && attachInfo != null) {
   15548             final int pflags = mPrivateFlags;
   15549             if ((pflags & SKIP_DRAW) == 0) {
   15550                 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
   15551                 // remove it from the transparent region.
   15552                 final int[] location = attachInfo.mTransparentLocation;
   15553                 getLocationInWindow(location);
   15554                 region.op(location[0], location[1], location[0] + mRight - mLeft,
   15555                         location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
   15556             } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
   15557                 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
   15558                 // exists, so we remove the background drawable's non-transparent
   15559                 // parts from this transparent region.
   15560                 applyDrawableToTransparentRegion(mBackground, region);
   15561             }
   15562         }
   15563         return true;
   15564     }
   15565 
   15566     /**
   15567      * Play a sound effect for this view.
   15568      *
   15569      * <p>The framework will play sound effects for some built in actions, such as
   15570      * clicking, but you may wish to play these effects in your widget,
   15571      * for instance, for internal navigation.
   15572      *
   15573      * <p>The sound effect will only be played if sound effects are enabled by the user, and
   15574      * {@link #isSoundEffectsEnabled()} is true.
   15575      *
   15576      * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
   15577      */
   15578     public void playSoundEffect(int soundConstant) {
   15579         if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
   15580             return;
   15581         }
   15582         mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
   15583     }
   15584 
   15585     /**
   15586      * BZZZTT!!1!
   15587      *
   15588      * <p>Provide haptic feedback to the user for this view.
   15589      *
   15590      * <p>The framework will provide haptic feedback for some built in actions,
   15591      * such as long presses, but you may wish to provide feedback for your
   15592      * own widget.
   15593      *
   15594      * <p>The feedback will only be performed if
   15595      * {@link #isHapticFeedbackEnabled()} is true.
   15596      *
   15597      * @param feedbackConstant One of the constants defined in
   15598      * {@link HapticFeedbackConstants}
   15599      */
   15600     public boolean performHapticFeedback(int feedbackConstant) {
   15601         return performHapticFeedback(feedbackConstant, 0);
   15602     }
   15603 
   15604     /**
   15605      * BZZZTT!!1!
   15606      *
   15607      * <p>Like {@link #performHapticFeedback(int)}, with additional options.
   15608      *
   15609      * @param feedbackConstant One of the constants defined in
   15610      * {@link HapticFeedbackConstants}
   15611      * @param flags Additional flags as per {@link HapticFeedbackConstants}.
   15612      */
   15613     public boolean performHapticFeedback(int feedbackConstant, int flags) {
   15614         if (mAttachInfo == null) {
   15615             return false;
   15616         }
   15617         //noinspection SimplifiableIfStatement
   15618         if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
   15619                 && !isHapticFeedbackEnabled()) {
   15620             return false;
   15621         }
   15622         return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
   15623                 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
   15624     }
   15625 
   15626     /**
   15627      * Request that the visibility of the status bar or other screen/window
   15628      * decorations be changed.
   15629      *
   15630      * <p>This method is used to put the over device UI into temporary modes
   15631      * where the user's attention is focused more on the application content,
   15632      * by dimming or hiding surrounding system affordances.  This is typically
   15633      * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
   15634      * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
   15635      * to be placed behind the action bar (and with these flags other system
   15636      * affordances) so that smooth transitions between hiding and showing them
   15637      * can be done.
   15638      *
   15639      * <p>Two representative examples of the use of system UI visibility is
   15640      * implementing a content browsing application (like a magazine reader)
   15641      * and a video playing application.
   15642      *
   15643      * <p>The first code shows a typical implementation of a View in a content
   15644      * browsing application.  In this implementation, the application goes
   15645      * into a content-oriented mode by hiding the status bar and action bar,
   15646      * and putting the navigation elements into lights out mode.  The user can
   15647      * then interact with content while in this mode.  Such an application should
   15648      * provide an easy way for the user to toggle out of the mode (such as to
   15649      * check information in the status bar or access notifications).  In the
   15650      * implementation here, this is done simply by tapping on the content.
   15651      *
   15652      * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
   15653      *      content}
   15654      *
   15655      * <p>This second code sample shows a typical implementation of a View
   15656      * in a video playing application.  In this situation, while the video is
   15657      * playing the application would like to go into a complete full-screen mode,
   15658      * to use as much of the display as possible for the video.  When in this state
   15659      * the user can not interact with the application; the system intercepts
   15660      * touching on the screen to pop the UI out of full screen mode.  See
   15661      * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
   15662      *
   15663      * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
   15664      *      content}
   15665      *
   15666      * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
   15667      * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
   15668      * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
   15669      * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
   15670      */
   15671     public void setSystemUiVisibility(int visibility) {
   15672         if (visibility != mSystemUiVisibility) {
   15673             mSystemUiVisibility = visibility;
   15674             if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
   15675                 mParent.recomputeViewAttributes(this);
   15676             }
   15677         }
   15678     }
   15679 
   15680     /**
   15681      * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
   15682      * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
   15683      * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
   15684      * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
   15685      * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
   15686      */
   15687     public int getSystemUiVisibility() {
   15688         return mSystemUiVisibility;
   15689     }
   15690 
   15691     /**
   15692      * Returns the current system UI visibility that is currently set for
   15693      * the entire window.  This is the combination of the
   15694      * {@link #setSystemUiVisibility(int)} values supplied by all of the
   15695      * views in the window.
   15696      */
   15697     public int getWindowSystemUiVisibility() {
   15698         return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
   15699     }
   15700 
   15701     /**
   15702      * Override to find out when the window's requested system UI visibility
   15703      * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
   15704      * This is different from the callbacks recieved through
   15705      * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
   15706      * in that this is only telling you about the local request of the window,
   15707      * not the actual values applied by the system.
   15708      */
   15709     public void onWindowSystemUiVisibilityChanged(int visible) {
   15710     }
   15711 
   15712     /**
   15713      * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
   15714      * the view hierarchy.
   15715      */
   15716     public void dispatchWindowSystemUiVisiblityChanged(int visible) {
   15717         onWindowSystemUiVisibilityChanged(visible);
   15718     }
   15719 
   15720     /**
   15721      * Set a listener to receive callbacks when the visibility of the system bar changes.
   15722      * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
   15723      */
   15724     public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
   15725         getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
   15726         if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
   15727             mParent.recomputeViewAttributes(this);
   15728         }
   15729     }
   15730 
   15731     /**
   15732      * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
   15733      * the view hierarchy.
   15734      */
   15735     public void dispatchSystemUiVisibilityChanged(int visibility) {
   15736         ListenerInfo li = mListenerInfo;
   15737         if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
   15738             li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
   15739                     visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
   15740         }
   15741     }
   15742 
   15743     boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
   15744         int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
   15745         if (val != mSystemUiVisibility) {
   15746             setSystemUiVisibility(val);
   15747             return true;
   15748         }
   15749         return false;
   15750     }
   15751 
   15752     /** @hide */
   15753     public void setDisabledSystemUiVisibility(int flags) {
   15754         if (mAttachInfo != null) {
   15755             if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
   15756                 mAttachInfo.mDisabledSystemUiVisibility = flags;
   15757                 if (mParent != null) {
   15758                     mParent.recomputeViewAttributes(this);
   15759                 }
   15760             }
   15761         }
   15762     }
   15763 
   15764     /**
   15765      * Creates an image that the system displays during the drag and drop
   15766      * operation. This is called a &quot;drag shadow&quot;. The default implementation
   15767      * for a DragShadowBuilder based on a View returns an image that has exactly the same
   15768      * appearance as the given View. The default also positions the center of the drag shadow
   15769      * directly under the touch point. If no View is provided (the constructor with no parameters
   15770      * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
   15771      * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
   15772      * default is an invisible drag shadow.
   15773      * <p>
   15774      * You are not required to use the View you provide to the constructor as the basis of the
   15775      * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
   15776      * anything you want as the drag shadow.
   15777      * </p>
   15778      * <p>
   15779      *  You pass a DragShadowBuilder object to the system when you start the drag. The system
   15780      *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
   15781      *  size and position of the drag shadow. It uses this data to construct a
   15782      *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
   15783      *  so that your application can draw the shadow image in the Canvas.
   15784      * </p>
   15785      *
   15786      * <div class="special reference">
   15787      * <h3>Developer Guides</h3>
   15788      * <p>For a guide to implementing drag and drop features, read the
   15789      * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
   15790      * </div>
   15791      */
   15792     public static class DragShadowBuilder {
   15793         private final WeakReference<View> mView;
   15794 
   15795         /**
   15796          * Constructs a shadow image builder based on a View. By default, the resulting drag
   15797          * shadow will have the same appearance and dimensions as the View, with the touch point
   15798          * over the center of the View.
   15799          * @param view A View. Any View in scope can be used.
   15800          */
   15801         public DragShadowBuilder(View view) {
   15802             mView = new WeakReference<View>(view);
   15803         }
   15804 
   15805         /**
   15806          * Construct a shadow builder object with no associated View.  This
   15807          * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
   15808          * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
   15809          * to supply the drag shadow's dimensions and appearance without
   15810          * reference to any View object. If they are not overridden, then the result is an
   15811          * invisible drag shadow.
   15812          */
   15813         public DragShadowBuilder() {
   15814             mView = new WeakReference<View>(null);
   15815         }
   15816 
   15817         /**
   15818          * Returns the View object that had been passed to the
   15819          * {@link #View.DragShadowBuilder(View)}
   15820          * constructor.  If that View parameter was {@code null} or if the
   15821          * {@link #View.DragShadowBuilder()}
   15822          * constructor was used to instantiate the builder object, this method will return
   15823          * null.
   15824          *
   15825          * @return The View object associate with this builder object.
   15826          */
   15827         @SuppressWarnings({"JavadocReference"})
   15828         final public View getView() {
   15829             return mView.get();
   15830         }
   15831 
   15832         /**
   15833          * Provides the metrics for the shadow image. These include the dimensions of
   15834          * the shadow image, and the point within that shadow that should
   15835          * be centered under the touch location while dragging.
   15836          * <p>
   15837          * The default implementation sets the dimensions of the shadow to be the
   15838          * same as the dimensions of the View itself and centers the shadow under
   15839          * the touch point.
   15840          * </p>
   15841          *
   15842          * @param shadowSize A {@link android.graphics.Point} containing the width and height
   15843          * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
   15844          * desired width and must set {@link android.graphics.Point#y} to the desired height of the
   15845          * image.
   15846          *
   15847          * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
   15848          * shadow image that should be underneath the touch point during the drag and drop
   15849          * operation. Your application must set {@link android.graphics.Point#x} to the
   15850          * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
   15851          */
   15852         public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
   15853             final View view = mView.get();
   15854             if (view != null) {
   15855                 shadowSize.set(view.getWidth(), view.getHeight());
   15856                 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
   15857             } else {
   15858                 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
   15859             }
   15860         }
   15861 
   15862         /**
   15863          * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
   15864          * based on the dimensions it received from the
   15865          * {@link #onProvideShadowMetrics(Point, Point)} callback.
   15866          *
   15867          * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
   15868          */
   15869         public void onDrawShadow(Canvas canvas) {
   15870             final View view = mView.get();
   15871             if (view != null) {
   15872                 view.draw(canvas);
   15873             } else {
   15874                 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
   15875             }
   15876         }
   15877     }
   15878 
   15879     /**
   15880      * Starts a drag and drop operation. When your application calls this method, it passes a
   15881      * {@link android.view.View.DragShadowBuilder} object to the system. The
   15882      * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
   15883      * to get metrics for the drag shadow, and then calls the object's
   15884      * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
   15885      * <p>
   15886      *  Once the system has the drag shadow, it begins the drag and drop operation by sending
   15887      *  drag events to all the View objects in your application that are currently visible. It does
   15888      *  this either by calling the View object's drag listener (an implementation of
   15889      *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
   15890      *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
   15891      *  Both are passed a {@link android.view.DragEvent} object that has a
   15892      *  {@link android.view.DragEvent#getAction()} value of
   15893      *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
   15894      * </p>
   15895      * <p>
   15896      * Your application can invoke startDrag() on any attached View object. The View object does not
   15897      * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
   15898      * be related to the View the user selected for dragging.
   15899      * </p>
   15900      * @param data A {@link android.content.ClipData} object pointing to the data to be
   15901      * transferred by the drag and drop operation.
   15902      * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
   15903      * drag shadow.
   15904      * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
   15905      * drop operation. This Object is put into every DragEvent object sent by the system during the
   15906      * current drag.
   15907      * <p>
   15908      * myLocalState is a lightweight mechanism for the sending information from the dragged View
   15909      * to the target Views. For example, it can contain flags that differentiate between a
   15910      * a copy operation and a move operation.
   15911      * </p>
   15912      * @param flags Flags that control the drag and drop operation. No flags are currently defined,
   15913      * so the parameter should be set to 0.
   15914      * @return {@code true} if the method completes successfully, or
   15915      * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
   15916      * do a drag, and so no drag operation is in progress.
   15917      */
   15918     public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
   15919             Object myLocalState, int flags) {
   15920         if (ViewDebug.DEBUG_DRAG) {
   15921             Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
   15922         }
   15923         boolean okay = false;
   15924 
   15925         Point shadowSize = new Point();
   15926         Point shadowTouchPoint = new Point();
   15927         shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
   15928 
   15929         if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
   15930                 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
   15931             throw new IllegalStateException("Drag shadow dimensions must not be negative");
   15932         }
   15933 
   15934         if (ViewDebug.DEBUG_DRAG) {
   15935             Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
   15936                     + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
   15937         }
   15938         Surface surface = new Surface();
   15939         try {
   15940             IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
   15941                     flags, shadowSize.x, shadowSize.y, surface);
   15942             if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
   15943                     + " surface=" + surface);
   15944             if (token != null) {
   15945                 Canvas canvas = surface.lockCanvas(null);
   15946                 try {
   15947                     canvas.drawColor(0, PorterDuff.Mode.CLEAR);
   15948                     shadowBuilder.onDrawShadow(canvas);
   15949                 } finally {
   15950                     surface.unlockCanvasAndPost(canvas);
   15951                 }
   15952 
   15953                 final ViewRootImpl root = getViewRootImpl();
   15954 
   15955                 // Cache the local state object for delivery with DragEvents
   15956                 root.setLocalDragState(myLocalState);
   15957 
   15958                 // repurpose 'shadowSize' for the last touch point
   15959                 root.getLastTouchPoint(shadowSize);
   15960 
   15961                 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
   15962                         shadowSize.x, shadowSize.y,
   15963                         shadowTouchPoint.x, shadowTouchPoint.y, data);
   15964                 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
   15965 
   15966                 // Off and running!  Release our local surface instance; the drag
   15967                 // shadow surface is now managed by the system process.
   15968                 surface.release();
   15969             }
   15970         } catch (Exception e) {
   15971             Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
   15972             surface.destroy();
   15973         }
   15974 
   15975         return okay;
   15976     }
   15977 
   15978     /**
   15979      * Handles drag events sent by the system following a call to
   15980      * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
   15981      *<p>
   15982      * When the system calls this method, it passes a
   15983      * {@link android.view.DragEvent} object. A call to
   15984      * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
   15985      * in DragEvent. The method uses these to determine what is happening in the drag and drop
   15986      * operation.
   15987      * @param event The {@link android.view.DragEvent} sent by the system.
   15988      * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
   15989      * in DragEvent, indicating the type of drag event represented by this object.
   15990      * @return {@code true} if the method was successful, otherwise {@code false}.
   15991      * <p>
   15992      *  The method should return {@code true} in response to an action type of
   15993      *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
   15994      *  operation.
   15995      * </p>
   15996      * <p>
   15997      *  The method should also return {@code true} in response to an action type of
   15998      *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
   15999      *  {@code false} if it didn't.
   16000      * </p>
   16001      */
   16002     public boolean onDragEvent(DragEvent event) {
   16003         return false;
   16004     }
   16005 
   16006     /**
   16007      * Detects if this View is enabled and has a drag event listener.
   16008      * If both are true, then it calls the drag event listener with the
   16009      * {@link android.view.DragEvent} it received. If the drag event listener returns
   16010      * {@code true}, then dispatchDragEvent() returns {@code true}.
   16011      * <p>
   16012      * For all other cases, the method calls the
   16013      * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
   16014      * method and returns its result.
   16015      * </p>
   16016      * <p>
   16017      * This ensures that a drag event is always consumed, even if the View does not have a drag
   16018      * event listener. However, if the View has a listener and the listener returns true, then
   16019      * onDragEvent() is not called.
   16020      * </p>
   16021      */
   16022     public boolean dispatchDragEvent(DragEvent event) {
   16023         //noinspection SimplifiableIfStatement
   16024         ListenerInfo li = mListenerInfo;
   16025         if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
   16026                 && li.mOnDragListener.onDrag(this, event)) {
   16027             return true;
   16028         }
   16029         return onDragEvent(event);
   16030     }
   16031 
   16032     boolean canAcceptDrag() {
   16033         return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
   16034     }
   16035 
   16036     /**
   16037      * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
   16038      * it is ever exposed at all.
   16039      * @hide
   16040      */
   16041     public void onCloseSystemDialogs(String reason) {
   16042     }
   16043 
   16044     /**
   16045      * Given a Drawable whose bounds have been set to draw into this view,
   16046      * update a Region being computed for
   16047      * {@link #gatherTransparentRegion(android.graphics.Region)} so
   16048      * that any non-transparent parts of the Drawable are removed from the
   16049      * given transparent region.
   16050      *
   16051      * @param dr The Drawable whose transparency is to be applied to the region.
   16052      * @param region A Region holding the current transparency information,
   16053      * where any parts of the region that are set are considered to be
   16054      * transparent.  On return, this region will be modified to have the
   16055      * transparency information reduced by the corresponding parts of the
   16056      * Drawable that are not transparent.
   16057      * {@hide}
   16058      */
   16059     public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
   16060         if (DBG) {
   16061             Log.i("View", "Getting transparent region for: " + this);
   16062         }
   16063         final Region r = dr.getTransparentRegion();
   16064         final Rect db = dr.getBounds();
   16065         final AttachInfo attachInfo = mAttachInfo;
   16066         if (r != null && attachInfo != null) {
   16067             final int w = getRight()-getLeft();
   16068             final int h = getBottom()-getTop();
   16069             if (db.left > 0) {
   16070                 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
   16071                 r.op(0, 0, db.left, h, Region.Op.UNION);
   16072             }
   16073             if (db.right < w) {
   16074                 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
   16075                 r.op(db.right, 0, w, h, Region.Op.UNION);
   16076             }
   16077             if (db.top > 0) {
   16078                 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
   16079                 r.op(0, 0, w, db.top, Region.Op.UNION);
   16080             }
   16081             if (db.bottom < h) {
   16082                 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
   16083                 r.op(0, db.bottom, w, h, Region.Op.UNION);
   16084             }
   16085             final int[] location = attachInfo.mTransparentLocation;
   16086             getLocationInWindow(location);
   16087             r.translate(location[0], location[1]);
   16088             region.op(r, Region.Op.INTERSECT);
   16089         } else {
   16090             region.op(db, Region.Op.DIFFERENCE);
   16091         }
   16092     }
   16093 
   16094     private void checkForLongClick(int delayOffset) {
   16095         if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
   16096             mHasPerformedLongPress = false;
   16097 
   16098             if (mPendingCheckForLongPress == null) {
   16099                 mPendingCheckForLongPress = new CheckForLongPress();
   16100             }
   16101             mPendingCheckForLongPress.rememberWindowAttachCount();
   16102             postDelayed(mPendingCheckForLongPress,
   16103                     ViewConfiguration.getLongPressTimeout() - delayOffset);
   16104         }
   16105     }
   16106 
   16107     /**
   16108      * Inflate a view from an XML resource.  This convenience method wraps the {@link
   16109      * LayoutInflater} class, which provides a full range of options for view inflation.
   16110      *
   16111      * @param context The Context object for your activity or application.
   16112      * @param resource The resource ID to inflate
   16113      * @param root A view group that will be the parent.  Used to properly inflate the
   16114      * layout_* parameters.
   16115      * @see LayoutInflater
   16116      */
   16117     public static View inflate(Context context, int resource, ViewGroup root) {
   16118         LayoutInflater factory = LayoutInflater.from(context);
   16119         return factory.inflate(resource, root);
   16120     }
   16121 
   16122     /**
   16123      * Scroll the view with standard behavior for scrolling beyond the normal
   16124      * content boundaries. Views that call this method should override
   16125      * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
   16126      * results of an over-scroll operation.
   16127      *
   16128      * Views can use this method to handle any touch or fling-based scrolling.
   16129      *
   16130      * @param deltaX Change in X in pixels
   16131      * @param deltaY Change in Y in pixels
   16132      * @param scrollX Current X scroll value in pixels before applying deltaX
   16133      * @param scrollY Current Y scroll value in pixels before applying deltaY
   16134      * @param scrollRangeX Maximum content scroll range along the X axis
   16135      * @param scrollRangeY Maximum content scroll range along the Y axis
   16136      * @param maxOverScrollX Number of pixels to overscroll by in either direction
   16137      *          along the X axis.
   16138      * @param maxOverScrollY Number of pixels to overscroll by in either direction
   16139      *          along the Y axis.
   16140      * @param isTouchEvent true if this scroll operation is the result of a touch event.
   16141      * @return true if scrolling was clamped to an over-scroll boundary along either
   16142      *          axis, false otherwise.
   16143      */
   16144     @SuppressWarnings({"UnusedParameters"})
   16145     protected boolean overScrollBy(int deltaX, int deltaY,
   16146             int scrollX, int scrollY,
   16147             int scrollRangeX, int scrollRangeY,
   16148             int maxOverScrollX, int maxOverScrollY,
   16149             boolean isTouchEvent) {
   16150         final int overScrollMode = mOverScrollMode;
   16151         final boolean canScrollHorizontal =
   16152                 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
   16153         final boolean canScrollVertical =
   16154                 computeVerticalScrollRange() > computeVerticalScrollExtent();
   16155         final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
   16156                 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
   16157         final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
   16158                 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
   16159 
   16160         int newScrollX = scrollX + deltaX;
   16161         if (!overScrollHorizontal) {
   16162             maxOverScrollX = 0;
   16163         }
   16164 
   16165         int newScrollY = scrollY + deltaY;
   16166         if (!overScrollVertical) {
   16167             maxOverScrollY = 0;
   16168         }
   16169 
   16170         // Clamp values if at the limits and record
   16171         final int left = -maxOverScrollX;
   16172         final int right = maxOverScrollX + scrollRangeX;
   16173         final int top = -maxOverScrollY;
   16174         final int bottom = maxOverScrollY + scrollRangeY;
   16175 
   16176         boolean clampedX = false;
   16177         if (newScrollX > right) {
   16178             newScrollX = right;
   16179             clampedX = true;
   16180         } else if (newScrollX < left) {
   16181             newScrollX = left;
   16182             clampedX = true;
   16183         }
   16184 
   16185         boolean clampedY = false;
   16186         if (newScrollY > bottom) {
   16187             newScrollY = bottom;
   16188             clampedY = true;
   16189         } else if (newScrollY < top) {
   16190             newScrollY = top;
   16191             clampedY = true;
   16192         }
   16193 
   16194         onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
   16195 
   16196         return clampedX || clampedY;
   16197     }
   16198 
   16199     /**
   16200      * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
   16201      * respond to the results of an over-scroll operation.
   16202      *
   16203      * @param scrollX New X scroll value in pixels
   16204      * @param scrollY New Y scroll value in pixels
   16205      * @param clampedX True if scrollX was clamped to an over-scroll boundary
   16206      * @param clampedY True if scrollY was clamped to an over-scroll boundary
   16207      */
   16208     protected void onOverScrolled(int scrollX, int scrollY,
   16209             boolean clampedX, boolean clampedY) {
   16210         // Intentionally empty.
   16211     }
   16212 
   16213     /**
   16214      * Returns the over-scroll mode for this view. The result will be
   16215      * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
   16216      * (allow over-scrolling only if the view content is larger than the container),
   16217      * or {@link #OVER_SCROLL_NEVER}.
   16218      *
   16219      * @return This view's over-scroll mode.
   16220      */
   16221     public int getOverScrollMode() {
   16222         return mOverScrollMode;
   16223     }
   16224 
   16225     /**
   16226      * Set the over-scroll mode for this view. Valid over-scroll modes are
   16227      * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
   16228      * (allow over-scrolling only if the view content is larger than the container),
   16229      * or {@link #OVER_SCROLL_NEVER}.
   16230      *
   16231      * Setting the over-scroll mode of a view will have an effect only if the
   16232      * view is capable of scrolling.
   16233      *
   16234      * @param overScrollMode The new over-scroll mode for this view.
   16235      */
   16236     public void setOverScrollMode(int overScrollMode) {
   16237         if (overScrollMode != OVER_SCROLL_ALWAYS &&
   16238                 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
   16239                 overScrollMode != OVER_SCROLL_NEVER) {
   16240             throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
   16241         }
   16242         mOverScrollMode = overScrollMode;
   16243     }
   16244 
   16245     /**
   16246      * Gets a scale factor that determines the distance the view should scroll
   16247      * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
   16248      * @return The vertical scroll scale factor.
   16249      * @hide
   16250      */
   16251     protected float getVerticalScrollFactor() {
   16252         if (mVerticalScrollFactor == 0) {
   16253             TypedValue outValue = new TypedValue();
   16254             if (!mContext.getTheme().resolveAttribute(
   16255                     com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
   16256                 throw new IllegalStateException(
   16257                         "Expected theme to define listPreferredItemHeight.");
   16258             }
   16259             mVerticalScrollFactor = outValue.getDimension(
   16260                     mContext.getResources().getDisplayMetrics());
   16261         }
   16262         return mVerticalScrollFactor;
   16263     }
   16264 
   16265     /**
   16266      * Gets a scale factor that determines the distance the view should scroll
   16267      * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
   16268      * @return The horizontal scroll scale factor.
   16269      * @hide
   16270      */
   16271     protected float getHorizontalScrollFactor() {
   16272         // TODO: Should use something else.
   16273         return getVerticalScrollFactor();
   16274     }
   16275 
   16276     /**
   16277      * Return the value specifying the text direction or policy that was set with
   16278      * {@link #setTextDirection(int)}.
   16279      *
   16280      * @return the defined text direction. It can be one of:
   16281      *
   16282      * {@link #TEXT_DIRECTION_INHERIT},
   16283      * {@link #TEXT_DIRECTION_FIRST_STRONG}
   16284      * {@link #TEXT_DIRECTION_ANY_RTL},
   16285      * {@link #TEXT_DIRECTION_LTR},
   16286      * {@link #TEXT_DIRECTION_RTL},
   16287      * {@link #TEXT_DIRECTION_LOCALE}
   16288      * @hide
   16289      */
   16290     @ViewDebug.ExportedProperty(category = "text", mapping = {
   16291             @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
   16292             @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
   16293             @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
   16294             @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
   16295             @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
   16296             @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
   16297     })
   16298     public int getTextDirection() {
   16299         return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
   16300     }
   16301 
   16302     /**
   16303      * Set the text direction.
   16304      *
   16305      * @param textDirection the direction to set. Should be one of:
   16306      *
   16307      * {@link #TEXT_DIRECTION_INHERIT},
   16308      * {@link #TEXT_DIRECTION_FIRST_STRONG}
   16309      * {@link #TEXT_DIRECTION_ANY_RTL},
   16310      * {@link #TEXT_DIRECTION_LTR},
   16311      * {@link #TEXT_DIRECTION_RTL},
   16312      * {@link #TEXT_DIRECTION_LOCALE}
   16313      * @hide
   16314      */
   16315     public void setTextDirection(int textDirection) {
   16316         if (getTextDirection() != textDirection) {
   16317             // Reset the current text direction and the resolved one
   16318             mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
   16319             resetResolvedTextDirection();
   16320             // Set the new text direction
   16321             mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
   16322             // Refresh
   16323             requestLayout();
   16324             invalidate(true);
   16325         }
   16326     }
   16327 
   16328     /**
   16329      * Return the resolved text direction.
   16330      *
   16331      * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
   16332      * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
   16333      * up the parent chain of the view. if there is no parent, then it will return the default
   16334      * {@link #TEXT_DIRECTION_FIRST_STRONG}.
   16335      *
   16336      * @return the resolved text direction. Returns one of:
   16337      *
   16338      * {@link #TEXT_DIRECTION_FIRST_STRONG}
   16339      * {@link #TEXT_DIRECTION_ANY_RTL},
   16340      * {@link #TEXT_DIRECTION_LTR},
   16341      * {@link #TEXT_DIRECTION_RTL},
   16342      * {@link #TEXT_DIRECTION_LOCALE}
   16343      * @hide
   16344      */
   16345     public int getResolvedTextDirection() {
   16346         // The text direction will be resolved only if needed
   16347         if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
   16348             resolveTextDirection();
   16349         }
   16350         return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
   16351     }
   16352 
   16353     /**
   16354      * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
   16355      * resolution is done.
   16356      * @hide
   16357      */
   16358     public void resolveTextDirection() {
   16359         // Reset any previous text direction resolution
   16360         mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
   16361 
   16362         if (hasRtlSupport()) {
   16363             // Set resolved text direction flag depending on text direction flag
   16364             final int textDirection = getTextDirection();
   16365             switch(textDirection) {
   16366                 case TEXT_DIRECTION_INHERIT:
   16367                     if (canResolveTextDirection()) {
   16368                         ViewGroup viewGroup = ((ViewGroup) mParent);
   16369 
   16370                         // Set current resolved direction to the same value as the parent's one
   16371                         final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
   16372                         switch (parentResolvedDirection) {
   16373                             case TEXT_DIRECTION_FIRST_STRONG:
   16374                             case TEXT_DIRECTION_ANY_RTL:
   16375                             case TEXT_DIRECTION_LTR:
   16376                             case TEXT_DIRECTION_RTL:
   16377                             case TEXT_DIRECTION_LOCALE:
   16378                                 mPrivateFlags2 |=
   16379                                         (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
   16380                                 break;
   16381                             default:
   16382                                 // Default resolved direction is "first strong" heuristic
   16383                                 mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
   16384                         }
   16385                     } else {
   16386                         // We cannot do the resolution if there is no parent, so use the default one
   16387                         mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
   16388                     }
   16389                     break;
   16390                 case TEXT_DIRECTION_FIRST_STRONG:
   16391                 case TEXT_DIRECTION_ANY_RTL:
   16392                 case TEXT_DIRECTION_LTR:
   16393                 case TEXT_DIRECTION_RTL:
   16394                 case TEXT_DIRECTION_LOCALE:
   16395                     // Resolved direction is the same as text direction
   16396                     mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
   16397                     break;
   16398                 default:
   16399                     // Default resolved direction is "first strong" heuristic
   16400                     mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
   16401             }
   16402         } else {
   16403             // Default resolved direction is "first strong" heuristic
   16404             mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
   16405         }
   16406 
   16407         // Set to resolved
   16408         mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
   16409         onResolvedTextDirectionChanged();
   16410     }
   16411 
   16412     /**
   16413      * Called when text direction has been resolved. Subclasses that care about text direction
   16414      * resolution should override this method.
   16415      *
   16416      * The default implementation does nothing.
   16417      * @hide
   16418      */
   16419     public void onResolvedTextDirectionChanged() {
   16420     }
   16421 
   16422     /**
   16423      * Check if text direction resolution can be done.
   16424      *
   16425      * @return true if text direction resolution can be done otherwise return false.
   16426      * @hide
   16427      */
   16428     public boolean canResolveTextDirection() {
   16429         switch (getTextDirection()) {
   16430             case TEXT_DIRECTION_INHERIT:
   16431                 return (mParent != null) && (mParent instanceof ViewGroup);
   16432             default:
   16433                 return true;
   16434         }
   16435     }
   16436 
   16437     /**
   16438      * Reset resolved text direction. Text direction can be resolved with a call to
   16439      * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
   16440      * reset is done.
   16441      * @hide
   16442      */
   16443     public void resetResolvedTextDirection() {
   16444         mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
   16445         onResolvedTextDirectionReset();
   16446     }
   16447 
   16448     /**
   16449      * Called when text direction is reset. Subclasses that care about text direction reset should
   16450      * override this method and do a reset of the text direction of their children. The default
   16451      * implementation does nothing.
   16452      * @hide
   16453      */
   16454     public void onResolvedTextDirectionReset() {
   16455     }
   16456 
   16457     /**
   16458      * Return the value specifying the text alignment or policy that was set with
   16459      * {@link #setTextAlignment(int)}.
   16460      *
   16461      * @return the defined text alignment. It can be one of:
   16462      *
   16463      * {@link #TEXT_ALIGNMENT_INHERIT},
   16464      * {@link #TEXT_ALIGNMENT_GRAVITY},
   16465      * {@link #TEXT_ALIGNMENT_CENTER},
   16466      * {@link #TEXT_ALIGNMENT_TEXT_START},
   16467      * {@link #TEXT_ALIGNMENT_TEXT_END},
   16468      * {@link #TEXT_ALIGNMENT_VIEW_START},
   16469      * {@link #TEXT_ALIGNMENT_VIEW_END}
   16470      * @hide
   16471      */
   16472     @ViewDebug.ExportedProperty(category = "text", mapping = {
   16473             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
   16474             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
   16475             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
   16476             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
   16477             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
   16478             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
   16479             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
   16480     })
   16481     public int getTextAlignment() {
   16482         return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
   16483     }
   16484 
   16485     /**
   16486      * Set the text alignment.
   16487      *
   16488      * @param textAlignment The text alignment to set. Should be one of
   16489      *
   16490      * {@link #TEXT_ALIGNMENT_INHERIT},
   16491      * {@link #TEXT_ALIGNMENT_GRAVITY},
   16492      * {@link #TEXT_ALIGNMENT_CENTER},
   16493      * {@link #TEXT_ALIGNMENT_TEXT_START},
   16494      * {@link #TEXT_ALIGNMENT_TEXT_END},
   16495      * {@link #TEXT_ALIGNMENT_VIEW_START},
   16496      * {@link #TEXT_ALIGNMENT_VIEW_END}
   16497      *
   16498      * @attr ref android.R.styleable#View_textAlignment
   16499      * @hide
   16500      */
   16501     public void setTextAlignment(int textAlignment) {
   16502         if (textAlignment != getTextAlignment()) {
   16503             // Reset the current and resolved text alignment
   16504             mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
   16505             resetResolvedTextAlignment();
   16506             // Set the new text alignment
   16507             mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
   16508             // Refresh
   16509             requestLayout();
   16510             invalidate(true);
   16511         }
   16512     }
   16513 
   16514     /**
   16515      * Return the resolved text alignment.
   16516      *
   16517      * The resolved text alignment. This needs resolution if the value is
   16518      * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
   16519      * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
   16520      *
   16521      * @return the resolved text alignment. Returns one of:
   16522      *
   16523      * {@link #TEXT_ALIGNMENT_GRAVITY},
   16524      * {@link #TEXT_ALIGNMENT_CENTER},
   16525      * {@link #TEXT_ALIGNMENT_TEXT_START},
   16526      * {@link #TEXT_ALIGNMENT_TEXT_END},
   16527      * {@link #TEXT_ALIGNMENT_VIEW_START},
   16528      * {@link #TEXT_ALIGNMENT_VIEW_END}
   16529      * @hide
   16530      */
   16531     @ViewDebug.ExportedProperty(category = "text", mapping = {
   16532             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
   16533             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
   16534             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
   16535             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
   16536             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
   16537             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
   16538             @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
   16539     })
   16540     public int getResolvedTextAlignment() {
   16541         // If text alignment is not resolved, then resolve it
   16542         if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
   16543             resolveTextAlignment();
   16544         }
   16545         return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
   16546     }
   16547 
   16548     /**
   16549      * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
   16550      * resolution is done.
   16551      * @hide
   16552      */
   16553     public void resolveTextAlignment() {
   16554         // Reset any previous text alignment resolution
   16555         mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
   16556 
   16557         if (hasRtlSupport()) {
   16558             // Set resolved text alignment flag depending on text alignment flag
   16559             final int textAlignment = getTextAlignment();
   16560             switch (textAlignment) {
   16561                 case TEXT_ALIGNMENT_INHERIT:
   16562                     // Check if we can resolve the text alignment
   16563                     if (canResolveLayoutDirection() && mParent instanceof View) {
   16564                         View view = (View) mParent;
   16565 
   16566                         final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
   16567                         switch (parentResolvedTextAlignment) {
   16568                             case TEXT_ALIGNMENT_GRAVITY:
   16569                             case TEXT_ALIGNMENT_TEXT_START:
   16570                             case TEXT_ALIGNMENT_TEXT_END:
   16571                             case TEXT_ALIGNMENT_CENTER:
   16572                             case TEXT_ALIGNMENT_VIEW_START:
   16573                             case TEXT_ALIGNMENT_VIEW_END:
   16574                                 // Resolved text alignment is the same as the parent resolved
   16575                                 // text alignment
   16576                                 mPrivateFlags2 |=
   16577                                         (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
   16578                                 break;
   16579                             default:
   16580                                 // Use default resolved text alignment
   16581                                 mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
   16582                         }
   16583                     }
   16584                     else {
   16585                         // We cannot do the resolution if there is no parent so use the default
   16586                         mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
   16587                     }
   16588                     break;
   16589                 case TEXT_ALIGNMENT_GRAVITY:
   16590                 case TEXT_ALIGNMENT_TEXT_START:
   16591                 case TEXT_ALIGNMENT_TEXT_END:
   16592                 case TEXT_ALIGNMENT_CENTER:
   16593                 case TEXT_ALIGNMENT_VIEW_START:
   16594                 case TEXT_ALIGNMENT_VIEW_END:
   16595                     // Resolved text alignment is the same as text alignment
   16596                     mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
   16597                     break;
   16598                 default:
   16599                     // Use default resolved text alignment
   16600                     mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
   16601             }
   16602         } else {
   16603             // Use default resolved text alignment
   16604             mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
   16605         }
   16606 
   16607         // Set the resolved
   16608         mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
   16609         onResolvedTextAlignmentChanged();
   16610     }
   16611 
   16612     /**
   16613      * Check if text alignment resolution can be done.
   16614      *
   16615      * @return true if text alignment resolution can be done otherwise return false.
   16616      * @hide
   16617      */
   16618     public boolean canResolveTextAlignment() {
   16619         switch (getTextAlignment()) {
   16620             case TEXT_DIRECTION_INHERIT:
   16621                 return (mParent != null);
   16622             default:
   16623                 return true;
   16624         }
   16625     }
   16626 
   16627     /**
   16628      * Called when text alignment has been resolved. Subclasses that care about text alignment
   16629      * resolution should override this method.
   16630      *
   16631      * The default implementation does nothing.
   16632      * @hide
   16633      */
   16634     public void onResolvedTextAlignmentChanged() {
   16635     }
   16636 
   16637     /**
   16638      * Reset resolved text alignment. Text alignment can be resolved with a call to
   16639      * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
   16640      * reset is done.
   16641      * @hide
   16642      */
   16643     public void resetResolvedTextAlignment() {
   16644         // Reset any previous text alignment resolution
   16645         mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
   16646         onResolvedTextAlignmentReset();
   16647     }
   16648 
   16649     /**
   16650      * Called when text alignment is reset. Subclasses that care about text alignment reset should
   16651      * override this method and do a reset of the text alignment of their children. The default
   16652      * implementation does nothing.
   16653      * @hide
   16654      */
   16655     public void onResolvedTextAlignmentReset() {
   16656     }
   16657 
   16658     //
   16659     // Properties
   16660     //
   16661     /**
   16662      * A Property wrapper around the <code>alpha</code> functionality handled by the
   16663      * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
   16664      */
   16665     public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
   16666         @Override
   16667         public void setValue(View object, float value) {
   16668             object.setAlpha(value);
   16669         }
   16670 
   16671         @Override
   16672         public Float get(View object) {
   16673             return object.getAlpha();
   16674         }
   16675     };
   16676 
   16677     /**
   16678      * A Property wrapper around the <code>translationX</code> functionality handled by the
   16679      * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
   16680      */
   16681     public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
   16682         @Override
   16683         public void setValue(View object, float value) {
   16684             object.setTranslationX(value);
   16685         }
   16686 
   16687                 @Override
   16688         public Float get(View object) {
   16689             return object.getTranslationX();
   16690         }
   16691     };
   16692 
   16693     /**
   16694      * A Property wrapper around the <code>translationY</code> functionality handled by the
   16695      * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
   16696      */
   16697     public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
   16698         @Override
   16699         public void setValue(View object, float value) {
   16700             object.setTranslationY(value);
   16701         }
   16702 
   16703         @Override
   16704         public Float get(View object) {
   16705             return object.getTranslationY();
   16706         }
   16707     };
   16708 
   16709     /**
   16710      * A Property wrapper around the <code>x</code> functionality handled by the
   16711      * {@link View#setX(float)} and {@link View#getX()} methods.
   16712      */
   16713     public static final Property<View, Float> X = new FloatProperty<View>("x") {
   16714         @Override
   16715         public void setValue(View object, float value) {
   16716             object.setX(value);
   16717         }
   16718 
   16719         @Override
   16720         public Float get(View object) {
   16721             return object.getX();
   16722         }
   16723     };
   16724 
   16725     /**
   16726      * A Property wrapper around the <code>y</code> functionality handled by the
   16727      * {@link View#setY(float)} and {@link View#getY()} methods.
   16728      */
   16729     public static final Property<View, Float> Y = new FloatProperty<View>("y") {
   16730         @Override
   16731         public void setValue(View object, float value) {
   16732             object.setY(value);
   16733         }
   16734 
   16735         @Override
   16736         public Float get(View object) {
   16737             return object.getY();
   16738         }
   16739     };
   16740 
   16741     /**
   16742      * A Property wrapper around the <code>rotation</code> functionality handled by the
   16743      * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
   16744      */
   16745     public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
   16746         @Override
   16747         public void setValue(View object, float value) {
   16748             object.setRotation(value);
   16749         }
   16750 
   16751         @Override
   16752         public Float get(View object) {
   16753             return object.getRotation();
   16754         }
   16755     };
   16756 
   16757     /**
   16758      * A Property wrapper around the <code>rotationX</code> functionality handled by the
   16759      * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
   16760      */
   16761     public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
   16762         @Override
   16763         public void setValue(View object, float value) {
   16764             object.setRotationX(value);
   16765         }
   16766 
   16767         @Override
   16768         public Float get(View object) {
   16769             return object.getRotationX();
   16770         }
   16771     };
   16772 
   16773     /**
   16774      * A Property wrapper around the <code>rotationY</code> functionality handled by the
   16775      * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
   16776      */
   16777     public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
   16778         @Override
   16779         public void setValue(View object, float value) {
   16780             object.setRotationY(value);
   16781         }
   16782 
   16783         @Override
   16784         public Float get(View object) {
   16785             return object.getRotationY();
   16786         }
   16787     };
   16788 
   16789     /**
   16790      * A Property wrapper around the <code>scaleX</code> functionality handled by the
   16791      * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
   16792      */
   16793     public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
   16794         @Override
   16795         public void setValue(View object, float value) {
   16796             object.setScaleX(value);
   16797         }
   16798 
   16799         @Override
   16800         public Float get(View object) {
   16801             return object.getScaleX();
   16802         }
   16803     };
   16804 
   16805     /**
   16806      * A Property wrapper around the <code>scaleY</code> functionality handled by the
   16807      * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
   16808      */
   16809     public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
   16810         @Override
   16811         public void setValue(View object, float value) {
   16812             object.setScaleY(value);
   16813         }
   16814 
   16815         @Override
   16816         public Float get(View object) {
   16817             return object.getScaleY();
   16818         }
   16819     };
   16820 
   16821     /**
   16822      * A MeasureSpec encapsulates the layout requirements passed from parent to child.
   16823      * Each MeasureSpec represents a requirement for either the width or the height.
   16824      * A MeasureSpec is comprised of a size and a mode. There are three possible
   16825      * modes:
   16826      * <dl>
   16827      * <dt>UNSPECIFIED</dt>
   16828      * <dd>
   16829      * The parent has not imposed any constraint on the child. It can be whatever size
   16830      * it wants.
   16831      * </dd>
   16832      *
   16833      * <dt>EXACTLY</dt>
   16834      * <dd>
   16835      * The parent has determined an exact size for the child. The child is going to be
   16836      * given those bounds regardless of how big it wants to be.
   16837      * </dd>
   16838      *
   16839      * <dt>AT_MOST</dt>
   16840      * <dd>
   16841      * The child can be as large as it wants up to the specified size.
   16842      * </dd>
   16843      * </dl>
   16844      *
   16845      * MeasureSpecs are implemented as ints to reduce object allocation. This class
   16846      * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
   16847      */
   16848     public static class MeasureSpec {
   16849         private static final int MODE_SHIFT = 30;
   16850         private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
   16851 
   16852         /**
   16853          * Measure specification mode: The parent has not imposed any constraint
   16854          * on the child. It can be whatever size it wants.
   16855          */
   16856         public static final int UNSPECIFIED = 0 << MODE_SHIFT;
   16857 
   16858         /**
   16859          * Measure specification mode: The parent has determined an exact size
   16860          * for the child. The child is going to be given those bounds regardless
   16861          * of how big it wants to be.
   16862          */
   16863         public static final int EXACTLY     = 1 << MODE_SHIFT;
   16864 
   16865         /**
   16866          * Measure specification mode: The child can be as large as it wants up
   16867          * to the specified size.
   16868          */
   16869         public static final int AT_MOST     = 2 << MODE_SHIFT;
   16870 
   16871         /**
   16872          * Creates a measure specification based on the supplied size and mode.
   16873          *
   16874          * The mode must always be one of the following:
   16875          * <ul>
   16876          *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
   16877          *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
   16878          *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
   16879          * </ul>
   16880          *
   16881          * @param size the size of the measure specification
   16882          * @param mode the mode of the measure specification
   16883          * @return the measure specification based on size and mode
   16884          */
   16885         public static int makeMeasureSpec(int size, int mode) {
   16886             return size + mode;
   16887         }
   16888 
   16889         /**
   16890          * Extracts the mode from the supplied measure specification.
   16891          *
   16892          * @param measureSpec the measure specification to extract the mode from
   16893          * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
   16894          *         {@link android.view.View.MeasureSpec#AT_MOST} or
   16895          *         {@link android.view.View.MeasureSpec#EXACTLY}
   16896          */
   16897         public static int getMode(int measureSpec) {
   16898             return (measureSpec & MODE_MASK);
   16899         }
   16900 
   16901         /**
   16902          * Extracts the size from the supplied measure specification.
   16903          *
   16904          * @param measureSpec the measure specification to extract the size from
   16905          * @return the size in pixels defined in the supplied measure specification
   16906          */
   16907         public static int getSize(int measureSpec) {
   16908             return (measureSpec & ~MODE_MASK);
   16909         }
   16910 
   16911         /**
   16912          * Returns a String representation of the specified measure
   16913          * specification.
   16914          *
   16915          * @param measureSpec the measure specification to convert to a String
   16916          * @return a String with the following format: "MeasureSpec: MODE SIZE"
   16917          */
   16918         public static String toString(int measureSpec) {
   16919             int mode = getMode(measureSpec);
   16920             int size = getSize(measureSpec);
   16921 
   16922             StringBuilder sb = new StringBuilder("MeasureSpec: ");
   16923 
   16924             if (mode == UNSPECIFIED)
   16925                 sb.append("UNSPECIFIED ");
   16926             else if (mode == EXACTLY)
   16927                 sb.append("EXACTLY ");
   16928             else if (mode == AT_MOST)
   16929                 sb.append("AT_MOST ");
   16930             else
   16931                 sb.append(mode).append(" ");
   16932 
   16933             sb.append(size);
   16934             return sb.toString();
   16935         }
   16936     }
   16937 
   16938     class CheckForLongPress implements Runnable {
   16939 
   16940         private int mOriginalWindowAttachCount;
   16941 
   16942         public void run() {
   16943             if (isPressed() && (mParent != null)
   16944                     && mOriginalWindowAttachCount == mWindowAttachCount) {
   16945                 if (performLongClick()) {
   16946                     mHasPerformedLongPress = true;
   16947                 }
   16948             }
   16949         }
   16950 
   16951         public void rememberWindowAttachCount() {
   16952             mOriginalWindowAttachCount = mWindowAttachCount;
   16953         }
   16954     }
   16955 
   16956     private final class CheckForTap implements Runnable {
   16957         public void run() {
   16958             mPrivateFlags &= ~PREPRESSED;
   16959             setPressed(true);
   16960             checkForLongClick(ViewConfiguration.getTapTimeout());
   16961         }
   16962     }
   16963 
   16964     private final class PerformClick implements Runnable {
   16965         public void run() {
   16966             performClick();
   16967         }
   16968     }
   16969 
   16970     /** @hide */
   16971     public void hackTurnOffWindowResizeAnim(boolean off) {
   16972         mAttachInfo.mTurnOffWindowResizeAnim = off;
   16973     }
   16974 
   16975     /**
   16976      * This method returns a ViewPropertyAnimator object, which can be used to animate
   16977      * specific properties on this View.
   16978      *
   16979      * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
   16980      */
   16981     public ViewPropertyAnimator animate() {
   16982         if (mAnimator == null) {
   16983             mAnimator = new ViewPropertyAnimator(this);
   16984         }
   16985         return mAnimator;
   16986     }
   16987 
   16988     /**
   16989      * Interface definition for a callback to be invoked when a hardware key event is
   16990      * dispatched to this view. The callback will be invoked before the key event is
   16991      * given to the view. This is only useful for hardware keyboards; a software input
   16992      * method has no obligation to trigger this listener.
   16993      */
   16994     public interface OnKeyListener {
   16995         /**
   16996          * Called when a hardware key is dispatched to a view. This allows listeners to
   16997          * get a chance to respond before the target view.
   16998          * <p>Key presses in software keyboards will generally NOT trigger this method,
   16999          * although some may elect to do so in some situations. Do not assume a
   17000          * software input method has to be key-based; even if it is, it may use key presses
   17001          * in a different way than you expect, so there is no way to reliably catch soft
   17002          * input key presses.
   17003          *
   17004          * @param v The view the key has been dispatched to.
   17005          * @param keyCode The code for the physical key that was pressed
   17006          * @param event The KeyEvent object containing full information about
   17007          *        the event.
   17008          * @return True if the listener has consumed the event, false otherwise.
   17009          */
   17010         boolean onKey(View v, int keyCode, KeyEvent event);
   17011     }
   17012 
   17013     /**
   17014      * Interface definition for a callback to be invoked when a touch event is
   17015      * dispatched to this view. The callback will be invoked before the touch
   17016      * event is given to the view.
   17017      */
   17018     public interface OnTouchListener {
   17019         /**
   17020          * Called when a touch event is dispatched to a view. This allows listeners to
   17021          * get a chance to respond before the target view.
   17022          *
   17023          * @param v The view the touch event has been dispatched to.
   17024          * @param event The MotionEvent object containing full information about
   17025          *        the event.
   17026          * @return True if the listener has consumed the event, false otherwise.
   17027          */
   17028         boolean onTouch(View v, MotionEvent event);
   17029     }
   17030 
   17031     /**
   17032      * Interface definition for a callback to be invoked when a hover event is
   17033      * dispatched to this view. The callback will be invoked before the hover
   17034      * event is given to the view.
   17035      */
   17036     public interface OnHoverListener {
   17037         /**
   17038          * Called when a hover event is dispatched to a view. This allows listeners to
   17039          * get a chance to respond before the target view.
   17040          *
   17041          * @param v The view the hover event has been dispatched to.
   17042          * @param event The MotionEvent object containing full information about
   17043          *        the event.
   17044          * @return True if the listener has consumed the event, false otherwise.
   17045          */
   17046         boolean onHover(View v, MotionEvent event);
   17047     }
   17048 
   17049     /**
   17050      * Interface definition for a callback to be invoked when a generic motion event is
   17051      * dispatched to this view. The callback will be invoked before the generic motion
   17052      * event is given to the view.
   17053      */
   17054     public interface OnGenericMotionListener {
   17055         /**
   17056          * Called when a generic motion event is dispatched to a view. This allows listeners to
   17057          * get a chance to respond before the target view.
   17058          *
   17059          * @param v The view the generic motion event has been dispatched to.
   17060          * @param event The MotionEvent object containing full information about
   17061          *        the event.
   17062          * @return True if the listener has consumed the event, false otherwise.
   17063          */
   17064         boolean onGenericMotion(View v, MotionEvent event);
   17065     }
   17066 
   17067     /**
   17068      * Interface definition for a callback to be invoked when a view has been clicked and held.
   17069      */
   17070     public interface OnLongClickListener {
   17071         /**
   17072          * Called when a view has been clicked and held.
   17073          *
   17074          * @param v The view that was clicked and held.
   17075          *
   17076          * @return true if the callback consumed the long click, false otherwise.
   17077          */
   17078         boolean onLongClick(View v);
   17079     }
   17080 
   17081     /**
   17082      * Interface definition for a callback to be invoked when a drag is being dispatched
   17083      * to this view.  The callback will be invoked before the hosting view's own
   17084      * onDrag(event) method.  If the listener wants to fall back to the hosting view's
   17085      * onDrag(event) behavior, it should return 'false' from this callback.
   17086      *
   17087      * <div class="special reference">
   17088      * <h3>Developer Guides</h3>
   17089      * <p>For a guide to implementing drag and drop features, read the
   17090      * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
   17091      * </div>
   17092      */
   17093     public interface OnDragListener {
   17094         /**
   17095          * Called when a drag event is dispatched to a view. This allows listeners
   17096          * to get a chance to override base View behavior.
   17097          *
   17098          * @param v The View that received the drag event.
   17099          * @param event The {@link android.view.DragEvent} object for the drag event.
   17100          * @return {@code true} if the drag event was handled successfully, or {@code false}
   17101          * if the drag event was not handled. Note that {@code false} will trigger the View
   17102          * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
   17103          */
   17104         boolean onDrag(View v, DragEvent event);
   17105     }
   17106 
   17107     /**
   17108      * Interface definition for a callback to be invoked when the focus state of
   17109      * a view changed.
   17110      */
   17111     public interface OnFocusChangeListener {
   17112         /**
   17113          * Called when the focus state of a view has changed.
   17114          *
   17115          * @param v The view whose state has changed.
   17116          * @param hasFocus The new focus state of v.
   17117          */
   17118         void onFocusChange(View v, boolean hasFocus);
   17119     }
   17120 
   17121     /**
   17122      * Interface definition for a callback to be invoked when a view is clicked.
   17123      */
   17124     public interface OnClickListener {
   17125         /**
   17126          * Called when a view has been clicked.
   17127          *
   17128          * @param v The view that was clicked.
   17129          */
   17130         void onClick(View v);
   17131     }
   17132 
   17133     /**
   17134      * Interface definition for a callback to be invoked when the context menu
   17135      * for this view is being built.
   17136      */
   17137     public interface OnCreateContextMenuListener {
   17138         /**
   17139          * Called when the context menu for this view is being built. It is not
   17140          * safe to hold onto the menu after this method returns.
   17141          *
   17142          * @param menu The context menu that is being built
   17143          * @param v The view for which the context menu is being built
   17144          * @param menuInfo Extra information about the item for which the
   17145          *            context menu should be shown. This information will vary
   17146          *            depending on the class of v.
   17147          */
   17148         void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
   17149     }
   17150 
   17151     /**
   17152      * Interface definition for a callback to be invoked when the status bar changes
   17153      * visibility.  This reports <strong>global</strong> changes to the system UI
   17154      * state, not what the application is requesting.
   17155      *
   17156      * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
   17157      */
   17158     public interface OnSystemUiVisibilityChangeListener {
   17159         /**
   17160          * Called when the status bar changes visibility because of a call to
   17161          * {@link View#setSystemUiVisibility(int)}.
   17162          *
   17163          * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
   17164          * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
   17165          * This tells you the <strong>global</strong> state of these UI visibility
   17166          * flags, not what your app is currently applying.
   17167          */
   17168         public void onSystemUiVisibilityChange(int visibility);
   17169     }
   17170 
   17171     /**
   17172      * Interface definition for a callback to be invoked when this view is attached
   17173      * or detached from its window.
   17174      */
   17175     public interface OnAttachStateChangeListener {
   17176         /**
   17177          * Called when the view is attached to a window.
   17178          * @param v The view that was attached
   17179          */
   17180         public void onViewAttachedToWindow(View v);
   17181         /**
   17182          * Called when the view is detached from a window.
   17183          * @param v The view that was detached
   17184          */
   17185         public void onViewDetachedFromWindow(View v);
   17186     }
   17187 
   17188     private final class UnsetPressedState implements Runnable {
   17189         public void run() {
   17190             setPressed(false);
   17191         }
   17192     }
   17193 
   17194     /**
   17195      * Base class for derived classes that want to save and restore their own
   17196      * state in {@link android.view.View#onSaveInstanceState()}.
   17197      */
   17198     public static class BaseSavedState extends AbsSavedState {
   17199         /**
   17200          * Constructor used when reading from a parcel. Reads the state of the superclass.
   17201          *
   17202          * @param source
   17203          */
   17204         public BaseSavedState(Parcel source) {
   17205             super(source);
   17206         }
   17207 
   17208         /**
   17209          * Constructor called by derived classes when creating their SavedState objects
   17210          *
   17211          * @param superState The state of the superclass of this view
   17212          */
   17213         public BaseSavedState(Parcelable superState) {
   17214             super(superState);
   17215         }
   17216 
   17217         public static final Parcelable.Creator<BaseSavedState> CREATOR =
   17218                 new Parcelable.Creator<BaseSavedState>() {
   17219             public BaseSavedState createFromParcel(Parcel in) {
   17220                 return new BaseSavedState(in);
   17221             }
   17222 
   17223             public BaseSavedState[] newArray(int size) {
   17224                 return new BaseSavedState[size];
   17225             }
   17226         };
   17227     }
   17228 
   17229     /**
   17230      * A set of information given to a view when it is attached to its parent
   17231      * window.
   17232      */
   17233     static class AttachInfo {
   17234         interface Callbacks {
   17235             void playSoundEffect(int effectId);
   17236             boolean performHapticFeedback(int effectId, boolean always);
   17237         }
   17238 
   17239         /**
   17240          * InvalidateInfo is used to post invalidate(int, int, int, int) messages
   17241          * to a Handler. This class contains the target (View) to invalidate and
   17242          * the coordinates of the dirty rectangle.
   17243          *
   17244          * For performance purposes, this class also implements a pool of up to
   17245          * POOL_LIMIT objects that get reused. This reduces memory allocations
   17246          * whenever possible.
   17247          */
   17248         static class InvalidateInfo implements Poolable<InvalidateInfo> {
   17249             private static final int POOL_LIMIT = 10;
   17250             private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
   17251                     Pools.finitePool(new PoolableManager<InvalidateInfo>() {
   17252                         public InvalidateInfo newInstance() {
   17253                             return new InvalidateInfo();
   17254                         }
   17255 
   17256                         public void onAcquired(InvalidateInfo element) {
   17257                         }
   17258 
   17259                         public void onReleased(InvalidateInfo element) {
   17260                             element.target = null;
   17261                         }
   17262                     }, POOL_LIMIT)
   17263             );
   17264 
   17265             private InvalidateInfo mNext;
   17266             private boolean mIsPooled;
   17267 
   17268             View target;
   17269 
   17270             int left;
   17271             int top;
   17272             int right;
   17273             int bottom;
   17274 
   17275             public void setNextPoolable(InvalidateInfo element) {
   17276                 mNext = element;
   17277             }
   17278 
   17279             public InvalidateInfo getNextPoolable() {
   17280                 return mNext;
   17281             }
   17282 
   17283             static InvalidateInfo acquire() {
   17284                 return sPool.acquire();
   17285             }
   17286 
   17287             void release() {
   17288                 sPool.release(this);
   17289             }
   17290 
   17291             public boolean isPooled() {
   17292                 return mIsPooled;
   17293             }
   17294 
   17295             public void setPooled(boolean isPooled) {
   17296                 mIsPooled = isPooled;
   17297             }
   17298         }
   17299 
   17300         final IWindowSession mSession;
   17301 
   17302         final IWindow mWindow;
   17303 
   17304         final IBinder mWindowToken;
   17305 
   17306         final Callbacks mRootCallbacks;
   17307 
   17308         HardwareCanvas mHardwareCanvas;
   17309 
   17310         /**
   17311          * The top view of the hierarchy.
   17312          */
   17313         View mRootView;
   17314 
   17315         IBinder mPanelParentWindowToken;
   17316         Surface mSurface;
   17317 
   17318         boolean mHardwareAccelerated;
   17319         boolean mHardwareAccelerationRequested;
   17320         HardwareRenderer mHardwareRenderer;
   17321 
   17322         boolean mScreenOn;
   17323 
   17324         /**
   17325          * Scale factor used by the compatibility mode
   17326          */
   17327         float mApplicationScale;
   17328 
   17329         /**
   17330          * Indicates whether the application is in compatibility mode
   17331          */
   17332         boolean mScalingRequired;
   17333 
   17334         /**
   17335          * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
   17336          */
   17337         boolean mTurnOffWindowResizeAnim;
   17338 
   17339         /**
   17340          * Left position of this view's window
   17341          */
   17342         int mWindowLeft;
   17343 
   17344         /**
   17345          * Top position of this view's window
   17346          */
   17347         int mWindowTop;
   17348 
   17349         /**
   17350          * Left actual position of this view's window.
   17351          *
   17352          * TODO: This is a workaround for 6623031. Remove when fixed.
   17353          */
   17354         int mActualWindowLeft;
   17355 
   17356         /**
   17357          * Actual top position of this view's window.
   17358          *
   17359          * TODO: This is a workaround for 6623031. Remove when fixed.
   17360          */
   17361         int mActualWindowTop;
   17362 
   17363         /**
   17364          * Indicates whether views need to use 32-bit drawing caches
   17365          */
   17366         boolean mUse32BitDrawingCache;
   17367 
   17368         /**
   17369          * For windows that are full-screen but using insets to layout inside
   17370          * of the screen decorations, these are the current insets for the
   17371          * content of the window.
   17372          */
   17373         final Rect mContentInsets = new Rect();
   17374 
   17375         /**
   17376          * For windows that are full-screen but using insets to layout inside
   17377          * of the screen decorations, these are the current insets for the
   17378          * actual visible parts of the window.
   17379          */
   17380         final Rect mVisibleInsets = new Rect();
   17381 
   17382         /**
   17383          * The internal insets given by this window.  This value is
   17384          * supplied by the client (through
   17385          * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
   17386          * be given to the window manager when changed to be used in laying
   17387          * out windows behind it.
   17388          */
   17389         final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
   17390                 = new ViewTreeObserver.InternalInsetsInfo();
   17391 
   17392         /**
   17393          * All views in the window's hierarchy that serve as scroll containers,
   17394          * used to determine if the window can be resized or must be panned
   17395          * to adjust for a soft input area.
   17396          */
   17397         final ArrayList<View> mScrollContainers = new ArrayList<View>();
   17398 
   17399         final KeyEvent.DispatcherState mKeyDispatchState
   17400                 = new KeyEvent.DispatcherState();
   17401 
   17402         /**
   17403          * Indicates whether the view's window currently has the focus.
   17404          */
   17405         boolean mHasWindowFocus;
   17406 
   17407         /**
   17408          * The current visibility of the window.
   17409          */
   17410         int mWindowVisibility;
   17411 
   17412         /**
   17413          * Indicates the time at which drawing started to occur.
   17414          */
   17415         long mDrawingTime;
   17416 
   17417         /**
   17418          * Indicates whether or not ignoring the DIRTY_MASK flags.
   17419          */
   17420         boolean mIgnoreDirtyState;
   17421 
   17422         /**
   17423          * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
   17424          * to avoid clearing that flag prematurely.
   17425          */
   17426         boolean mSetIgnoreDirtyState = false;
   17427 
   17428         /**
   17429          * Indicates whether the view's window is currently in touch mode.
   17430          */
   17431         boolean mInTouchMode;
   17432 
   17433         /**
   17434          * Indicates that ViewAncestor should trigger a global layout change
   17435          * the next time it performs a traversal
   17436          */
   17437         boolean mRecomputeGlobalAttributes;
   17438 
   17439         /**
   17440          * Always report new attributes at next traversal.
   17441          */
   17442         boolean mForceReportNewAttributes;
   17443 
   17444         /**
   17445          * Set during a traveral if any views want to keep the screen on.
   17446          */
   17447         boolean mKeepScreenOn;
   17448 
   17449         /**
   17450          * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
   17451          */
   17452         int mSystemUiVisibility;
   17453 
   17454         /**
   17455          * Hack to force certain system UI visibility flags to be cleared.
   17456          */
   17457         int mDisabledSystemUiVisibility;
   17458 
   17459         /**
   17460          * Last global system UI visibility reported by the window manager.
   17461          */
   17462         int mGlobalSystemUiVisibility;
   17463 
   17464         /**
   17465          * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
   17466          * attached.
   17467          */
   17468         boolean mHasSystemUiListeners;
   17469 
   17470         /**
   17471          * Set if the visibility of any views has changed.
   17472          */
   17473         boolean mViewVisibilityChanged;
   17474 
   17475         /**
   17476          * Set to true if a view has been scrolled.
   17477          */
   17478         boolean mViewScrollChanged;
   17479 
   17480         /**
   17481          * Global to the view hierarchy used as a temporary for dealing with
   17482          * x/y points in the transparent region computations.
   17483          */
   17484         final int[] mTransparentLocation = new int[2];
   17485 
   17486         /**
   17487          * Global to the view hierarchy used as a temporary for dealing with
   17488          * x/y points in the ViewGroup.invalidateChild implementation.
   17489          */
   17490         final int[] mInvalidateChildLocation = new int[2];
   17491 
   17492 
   17493         /**
   17494          * Global to the view hierarchy used as a temporary for dealing with
   17495          * x/y location when view is transformed.
   17496          */
   17497         final float[] mTmpTransformLocation = new float[2];
   17498 
   17499         /**
   17500          * The view tree observer used to dispatch global events like
   17501          * layout, pre-draw, touch mode change, etc.
   17502          */
   17503         final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
   17504 
   17505         /**
   17506          * A Canvas used by the view hierarchy to perform bitmap caching.
   17507          */
   17508         Canvas mCanvas;
   17509 
   17510         /**
   17511          * The view root impl.
   17512          */
   17513         final ViewRootImpl mViewRootImpl;
   17514 
   17515         /**
   17516          * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
   17517          * handler can be used to pump events in the UI events queue.
   17518          */
   17519         final Handler mHandler;
   17520 
   17521         /**
   17522          * Temporary for use in computing invalidate rectangles while
   17523          * calling up the hierarchy.
   17524          */
   17525         final Rect mTmpInvalRect = new Rect();
   17526 
   17527         /**
   17528          * Temporary for use in computing hit areas with transformed views
   17529          */
   17530         final RectF mTmpTransformRect = new RectF();
   17531 
   17532         /**
   17533          * Temporary list for use in collecting focusable descendents of a view.
   17534          */
   17535         final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
   17536 
   17537         /**
   17538          * The id of the window for accessibility purposes.
   17539          */
   17540         int mAccessibilityWindowId = View.NO_ID;
   17541 
   17542         /**
   17543          * Whether to ingore not exposed for accessibility Views when
   17544          * reporting the view tree to accessibility services.
   17545          */
   17546         boolean mIncludeNotImportantViews;
   17547 
   17548         /**
   17549          * The drawable for highlighting accessibility focus.
   17550          */
   17551         Drawable mAccessibilityFocusDrawable;
   17552 
   17553         /**
   17554          * Show where the margins, bounds and layout bounds are for each view.
   17555          */
   17556         boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
   17557 
   17558         /**
   17559          * Point used to compute visible regions.
   17560          */
   17561         final Point mPoint = new Point();
   17562 
   17563         /**
   17564          * Creates a new set of attachment information with the specified
   17565          * events handler and thread.
   17566          *
   17567          * @param handler the events handler the view must use
   17568          */
   17569         AttachInfo(IWindowSession session, IWindow window,
   17570                 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
   17571             mSession = session;
   17572             mWindow = window;
   17573             mWindowToken = window.asBinder();
   17574             mViewRootImpl = viewRootImpl;
   17575             mHandler = handler;
   17576             mRootCallbacks = effectPlayer;
   17577         }
   17578     }
   17579 
   17580     /**
   17581      * <p>ScrollabilityCache holds various fields used by a View when scrolling
   17582      * is supported. This avoids keeping too many unused fields in most
   17583      * instances of View.</p>
   17584      */
   17585     private static class ScrollabilityCache implements Runnable {
   17586 
   17587         /**
   17588          * Scrollbars are not visible
   17589          */
   17590         public static final int OFF = 0;
   17591 
   17592         /**
   17593          * Scrollbars are visible
   17594          */
   17595         public static final int ON = 1;
   17596 
   17597         /**
   17598          * Scrollbars are fading away
   17599          */
   17600         public static final int FADING = 2;
   17601 
   17602         public boolean fadeScrollBars;
   17603 
   17604         public int fadingEdgeLength;
   17605         public int scrollBarDefaultDelayBeforeFade;
   17606         public int scrollBarFadeDuration;
   17607 
   17608         public int scrollBarSize;
   17609         public ScrollBarDrawable scrollBar;
   17610         public float[] interpolatorValues;
   17611         public View host;
   17612 
   17613         public final Paint paint;
   17614         public final Matrix matrix;
   17615         public Shader shader;
   17616 
   17617         public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
   17618 
   17619         private static final float[] OPAQUE = { 255 };
   17620         private static final float[] TRANSPARENT = { 0.0f };
   17621 
   17622         /**
   17623          * When fading should start. This time moves into the future every time
   17624          * a new scroll happens. Measured based on SystemClock.uptimeMillis()
   17625          */
   17626         public long fadeStartTime;
   17627 
   17628 
   17629         /**
   17630          * The current state of the scrollbars: ON, OFF, or FADING
   17631          */
   17632         public int state = OFF;
   17633 
   17634         private int mLastColor;
   17635 
   17636         public ScrollabilityCache(ViewConfiguration configuration, View host) {
   17637             fadingEdgeLength = configuration.getScaledFadingEdgeLength();
   17638             scrollBarSize = configuration.getScaledScrollBarSize();
   17639             scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
   17640             scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
   17641 
   17642             paint = new Paint();
   17643             matrix = new Matrix();
   17644             // use use a height of 1, and then wack the matrix each time we
   17645             // actually use it.
   17646             shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
   17647 
   17648             paint.setShader(shader);
   17649             paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
   17650             this.host = host;
   17651         }
   17652 
   17653         public void setFadeColor(int color) {
   17654             if (color != 0 && color != mLastColor) {
   17655                 mLastColor = color;
   17656                 color |= 0xFF000000;
   17657 
   17658                 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
   17659                         color & 0x00FFFFFF, Shader.TileMode.CLAMP);
   17660 
   17661                 paint.setShader(shader);
   17662                 // Restore the default transfer mode (src_over)
   17663                 paint.setXfermode(null);
   17664             }
   17665         }
   17666 
   17667         public void run() {
   17668             long now = AnimationUtils.currentAnimationTimeMillis();
   17669             if (now >= fadeStartTime) {
   17670 
   17671                 // the animation fades the scrollbars out by changing
   17672                 // the opacity (alpha) from fully opaque to fully
   17673                 // transparent
   17674                 int nextFrame = (int) now;
   17675                 int framesCount = 0;
   17676 
   17677                 Interpolator interpolator = scrollBarInterpolator;
   17678 
   17679                 // Start opaque
   17680                 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
   17681 
   17682                 // End transparent
   17683                 nextFrame += scrollBarFadeDuration;
   17684                 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
   17685 
   17686                 state = FADING;
   17687 
   17688                 // Kick off the fade animation
   17689                 host.invalidate(true);
   17690             }
   17691         }
   17692     }
   17693 
   17694     /**
   17695      * Resuable callback for sending
   17696      * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
   17697      */
   17698     private class SendViewScrolledAccessibilityEvent implements Runnable {
   17699         public volatile boolean mIsPending;
   17700 
   17701         public void run() {
   17702             sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
   17703             mIsPending = false;
   17704         }
   17705     }
   17706 
   17707     /**
   17708      * <p>
   17709      * This class represents a delegate that can be registered in a {@link View}
   17710      * to enhance accessibility support via composition rather via inheritance.
   17711      * It is specifically targeted to widget developers that extend basic View
   17712      * classes i.e. classes in package android.view, that would like their
   17713      * applications to be backwards compatible.
   17714      * </p>
   17715      * <div class="special reference">
   17716      * <h3>Developer Guides</h3>
   17717      * <p>For more information about making applications accessible, read the
   17718      * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
   17719      * developer guide.</p>
   17720      * </div>
   17721      * <p>
   17722      * A scenario in which a developer would like to use an accessibility delegate
   17723      * is overriding a method introduced in a later API version then the minimal API
   17724      * version supported by the application. For example, the method
   17725      * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
   17726      * in API version 4 when the accessibility APIs were first introduced. If a
   17727      * developer would like his application to run on API version 4 devices (assuming
   17728      * all other APIs used by the application are version 4 or lower) and take advantage
   17729      * of this method, instead of overriding the method which would break the application's
   17730      * backwards compatibility, he can override the corresponding method in this
   17731      * delegate and register the delegate in the target View if the API version of
   17732      * the system is high enough i.e. the API version is same or higher to the API
   17733      * version that introduced
   17734      * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
   17735      * </p>
   17736      * <p>
   17737      * Here is an example implementation:
   17738      * </p>
   17739      * <code><pre><p>
   17740      * if (Build.VERSION.SDK_INT >= 14) {
   17741      *     // If the API version is equal of higher than the version in
   17742      *     // which onInitializeAccessibilityNodeInfo was introduced we
   17743      *     // register a delegate with a customized implementation.
   17744      *     View view = findViewById(R.id.view_id);
   17745      *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
   17746      *         public void onInitializeAccessibilityNodeInfo(View host,
   17747      *                 AccessibilityNodeInfo info) {
   17748      *             // Let the default implementation populate the info.
   17749      *             super.onInitializeAccessibilityNodeInfo(host, info);
   17750      *             // Set some other information.
   17751      *             info.setEnabled(host.isEnabled());
   17752      *         }
   17753      *     });
   17754      * }
   17755      * </code></pre></p>
   17756      * <p>
   17757      * This delegate contains methods that correspond to the accessibility methods
   17758      * in View. If a delegate has been specified the implementation in View hands
   17759      * off handling to the corresponding method in this delegate. The default
   17760      * implementation the delegate methods behaves exactly as the corresponding
   17761      * method in View for the case of no accessibility delegate been set. Hence,
   17762      * to customize the behavior of a View method, clients can override only the
   17763      * corresponding delegate method without altering the behavior of the rest
   17764      * accessibility related methods of the host view.
   17765      * </p>
   17766      */
   17767     public static class AccessibilityDelegate {
   17768 
   17769         /**
   17770          * Sends an accessibility event of the given type. If accessibility is not
   17771          * enabled this method has no effect.
   17772          * <p>
   17773          * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
   17774          *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
   17775          * been set.
   17776          * </p>
   17777          *
   17778          * @param host The View hosting the delegate.
   17779          * @param eventType The type of the event to send.
   17780          *
   17781          * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
   17782          */
   17783         public void sendAccessibilityEvent(View host, int eventType) {
   17784             host.sendAccessibilityEventInternal(eventType);
   17785         }
   17786 
   17787         /**
   17788          * Performs the specified accessibility action on the view. For
   17789          * possible accessibility actions look at {@link AccessibilityNodeInfo}.
   17790          * <p>
   17791          * The default implementation behaves as
   17792          * {@link View#performAccessibilityAction(int, Bundle)
   17793          *  View#performAccessibilityAction(int, Bundle)} for the case of
   17794          *  no accessibility delegate been set.
   17795          * </p>
   17796          *
   17797          * @param action The action to perform.
   17798          * @return Whether the action was performed.
   17799          *
   17800          * @see View#performAccessibilityAction(int, Bundle)
   17801          *      View#performAccessibilityAction(int, Bundle)
   17802          */
   17803         public boolean performAccessibilityAction(View host, int action, Bundle args) {
   17804             return host.performAccessibilityActionInternal(action, args);
   17805         }
   17806 
   17807         /**
   17808          * Sends an accessibility event. This method behaves exactly as
   17809          * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
   17810          * empty {@link AccessibilityEvent} and does not perform a check whether
   17811          * accessibility is enabled.
   17812          * <p>
   17813          * The default implementation behaves as
   17814          * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
   17815          *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
   17816          * the case of no accessibility delegate been set.
   17817          * </p>
   17818          *
   17819          * @param host The View hosting the delegate.
   17820          * @param event The event to send.
   17821          *
   17822          * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
   17823          *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
   17824          */
   17825         public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
   17826             host.sendAccessibilityEventUncheckedInternal(event);
   17827         }
   17828 
   17829         /**
   17830          * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
   17831          * to its children for adding their text content to the event.
   17832          * <p>
   17833          * The default implementation behaves as
   17834          * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
   17835          *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
   17836          * the case of no accessibility delegate been set.
   17837          * </p>
   17838          *
   17839          * @param host The View hosting the delegate.
   17840          * @param event The event.
   17841          * @return True if the event population was completed.
   17842          *
   17843          * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
   17844          *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
   17845          */
   17846         public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
   17847             return host.dispatchPopulateAccessibilityEventInternal(event);
   17848         }
   17849 
   17850         /**
   17851          * Gives a chance to the host View to populate the accessibility event with its
   17852          * text content.
   17853          * <p>
   17854          * The default implementation behaves as
   17855          * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
   17856          *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
   17857          * the case of no accessibility delegate been set.
   17858          * </p>
   17859          *
   17860          * @param host The View hosting the delegate.
   17861          * @param event The accessibility event which to populate.
   17862          *
   17863          * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
   17864          *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
   17865          */
   17866         public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
   17867             host.onPopulateAccessibilityEventInternal(event);
   17868         }
   17869 
   17870         /**
   17871          * Initializes an {@link AccessibilityEvent} with information about the
   17872          * the host View which is the event source.
   17873          * <p>
   17874          * The default implementation behaves as
   17875          * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
   17876          *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
   17877          * the case of no accessibility delegate been set.
   17878          * </p>
   17879          *
   17880          * @param host The View hosting the delegate.
   17881          * @param event The event to initialize.
   17882          *
   17883          * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
   17884          *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
   17885          */
   17886         public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
   17887             host.onInitializeAccessibilityEventInternal(event);
   17888         }
   17889 
   17890         /**
   17891          * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
   17892          * <p>
   17893          * The default implementation behaves as
   17894          * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
   17895          *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
   17896          * the case of no accessibility delegate been set.
   17897          * </p>
   17898          *
   17899          * @param host The View hosting the delegate.
   17900          * @param info The instance to initialize.
   17901          *
   17902          * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
   17903          *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
   17904          */
   17905         public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
   17906             host.onInitializeAccessibilityNodeInfoInternal(info);
   17907         }
   17908 
   17909         /**
   17910          * Called when a child of the host View has requested sending an
   17911          * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
   17912          * to augment the event.
   17913          * <p>
   17914          * The default implementation behaves as
   17915          * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
   17916          *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
   17917          * the case of no accessibility delegate been set.
   17918          * </p>
   17919          *
   17920          * @param host The View hosting the delegate.
   17921          * @param child The child which requests sending the event.
   17922          * @param event The event to be sent.
   17923          * @return True if the event should be sent
   17924          *
   17925          * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
   17926          *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
   17927          */
   17928         public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
   17929                 AccessibilityEvent event) {
   17930             return host.onRequestSendAccessibilityEventInternal(child, event);
   17931         }
   17932 
   17933         /**
   17934          * Gets the provider for managing a virtual view hierarchy rooted at this View
   17935          * and reported to {@link android.accessibilityservice.AccessibilityService}s
   17936          * that explore the window content.
   17937          * <p>
   17938          * The default implementation behaves as
   17939          * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
   17940          * the case of no accessibility delegate been set.
   17941          * </p>
   17942          *
   17943          * @return The provider.
   17944          *
   17945          * @see AccessibilityNodeProvider
   17946          */
   17947         public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
   17948             return null;
   17949         }
   17950     }
   17951 }
   17952