View.java revision e051f6f1fdb5e21cbed394d29dfcab5c642e4129
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.StateListAnimator; 21import android.annotation.CallSuper; 22import android.annotation.ColorInt; 23import android.annotation.DrawableRes; 24import android.annotation.FloatRange; 25import android.annotation.IdRes; 26import android.annotation.IntDef; 27import android.annotation.IntRange; 28import android.annotation.LayoutRes; 29import android.annotation.NonNull; 30import android.annotation.Nullable; 31import android.annotation.Size; 32import android.annotation.UiThread; 33import android.content.ClipData; 34import android.content.Context; 35import android.content.ContextWrapper; 36import android.content.Intent; 37import android.content.res.ColorStateList; 38import android.content.res.Configuration; 39import android.content.res.Resources; 40import android.content.res.TypedArray; 41import android.graphics.Bitmap; 42import android.graphics.Canvas; 43import android.graphics.Insets; 44import android.graphics.Interpolator; 45import android.graphics.LinearGradient; 46import android.graphics.Matrix; 47import android.graphics.Outline; 48import android.graphics.Paint; 49import android.graphics.PixelFormat; 50import android.graphics.Point; 51import android.graphics.PorterDuff; 52import android.graphics.PorterDuffXfermode; 53import android.graphics.Rect; 54import android.graphics.RectF; 55import android.graphics.Region; 56import android.graphics.Shader; 57import android.graphics.drawable.ColorDrawable; 58import android.graphics.drawable.Drawable; 59import android.hardware.display.DisplayManagerGlobal; 60import android.os.Build.VERSION_CODES; 61import android.os.Bundle; 62import android.os.Handler; 63import android.os.IBinder; 64import android.os.Parcel; 65import android.os.Parcelable; 66import android.os.RemoteException; 67import android.os.SystemClock; 68import android.os.SystemProperties; 69import android.os.Trace; 70import android.text.TextUtils; 71import android.util.AttributeSet; 72import android.util.FloatProperty; 73import android.util.LayoutDirection; 74import android.util.Log; 75import android.util.LongSparseLongArray; 76import android.util.Pools.SynchronizedPool; 77import android.util.Property; 78import android.util.SparseArray; 79import android.util.StateSet; 80import android.util.SuperNotCalledException; 81import android.util.TypedValue; 82import android.view.ContextMenu.ContextMenuInfo; 83import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 85import android.view.AccessibilityIterators.TextSegmentIterator; 86import android.view.AccessibilityIterators.WordTextSegmentIterator; 87import android.view.accessibility.AccessibilityEvent; 88import android.view.accessibility.AccessibilityEventSource; 89import android.view.accessibility.AccessibilityManager; 90import android.view.accessibility.AccessibilityNodeInfo; 91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 92import android.view.accessibility.AccessibilityNodeProvider; 93import android.view.animation.Animation; 94import android.view.animation.AnimationUtils; 95import android.view.animation.Transformation; 96import android.view.inputmethod.EditorInfo; 97import android.view.inputmethod.InputConnection; 98import android.view.inputmethod.InputMethodManager; 99import android.widget.Checkable; 100import android.widget.FrameLayout; 101import android.widget.ScrollBarDrawable; 102import static android.os.Build.VERSION_CODES.*; 103import static java.lang.Math.max; 104 105import com.android.internal.R; 106import com.android.internal.util.Predicate; 107import com.android.internal.view.menu.MenuBuilder; 108import com.android.internal.widget.ScrollBarUtils; 109import com.google.android.collect.Lists; 110import com.google.android.collect.Maps; 111 112import java.lang.NullPointerException; 113import java.lang.annotation.Retention; 114import java.lang.annotation.RetentionPolicy; 115import java.lang.ref.WeakReference; 116import java.lang.reflect.Field; 117import java.lang.reflect.InvocationTargetException; 118import java.lang.reflect.Method; 119import java.lang.reflect.Modifier; 120import java.util.ArrayList; 121import java.util.Arrays; 122import java.util.Collections; 123import java.util.HashMap; 124import java.util.List; 125import java.util.Locale; 126import java.util.Map; 127import java.util.concurrent.CopyOnWriteArrayList; 128import java.util.concurrent.atomic.AtomicInteger; 129 130/** 131 * <p> 132 * This class represents the basic building block for user interface components. A View 133 * occupies a rectangular area on the screen and is responsible for drawing and 134 * event handling. View is the base class for <em>widgets</em>, which are 135 * used to create interactive UI components (buttons, text fields, etc.). The 136 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 137 * are invisible containers that hold other Views (or other ViewGroups) and define 138 * their layout properties. 139 * </p> 140 * 141 * <div class="special reference"> 142 * <h3>Developer Guides</h3> 143 * <p>For information about using this class to develop your application's user interface, 144 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 145 * </div> 146 * 147 * <a name="Using"></a> 148 * <h3>Using Views</h3> 149 * <p> 150 * All of the views in a window are arranged in a single tree. You can add views 151 * either from code or by specifying a tree of views in one or more XML layout 152 * files. There are many specialized subclasses of views that act as controls or 153 * are capable of displaying text, images, or other content. 154 * </p> 155 * <p> 156 * Once you have created a tree of views, there are typically a few types of 157 * common operations you may wish to perform: 158 * <ul> 159 * <li><strong>Set properties:</strong> for example setting the text of a 160 * {@link android.widget.TextView}. The available properties and the methods 161 * that set them will vary among the different subclasses of views. Note that 162 * properties that are known at build time can be set in the XML layout 163 * files.</li> 164 * <li><strong>Set focus:</strong> The framework will handle moving focus in 165 * response to user input. To force focus to a specific view, call 166 * {@link #requestFocus}.</li> 167 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 168 * that will be notified when something interesting happens to the view. For 169 * example, all views will let you set a listener to be notified when the view 170 * gains or loses focus. You can register such a listener using 171 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 172 * Other view subclasses offer more specialized listeners. For example, a Button 173 * exposes a listener to notify clients when the button is clicked.</li> 174 * <li><strong>Set visibility:</strong> You can hide or show views using 175 * {@link #setVisibility(int)}.</li> 176 * </ul> 177 * </p> 178 * <p><em> 179 * Note: The Android framework is responsible for measuring, laying out and 180 * drawing views. You should not call methods that perform these actions on 181 * views yourself unless you are actually implementing a 182 * {@link android.view.ViewGroup}. 183 * </em></p> 184 * 185 * <a name="Lifecycle"></a> 186 * <h3>Implementing a Custom View</h3> 187 * 188 * <p> 189 * To implement a custom view, you will usually begin by providing overrides for 190 * some of the standard methods that the framework calls on all views. You do 191 * not need to override all of these methods. In fact, you can start by just 192 * overriding {@link #onDraw(android.graphics.Canvas)}. 193 * <table border="2" width="85%" align="center" cellpadding="5"> 194 * <thead> 195 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 196 * </thead> 197 * 198 * <tbody> 199 * <tr> 200 * <td rowspan="2">Creation</td> 201 * <td>Constructors</td> 202 * <td>There is a form of the constructor that are called when the view 203 * is created from code and a form that is called when the view is 204 * inflated from a layout file. The second form should parse and apply 205 * any attributes defined in the layout file. 206 * </td> 207 * </tr> 208 * <tr> 209 * <td><code>{@link #onFinishInflate()}</code></td> 210 * <td>Called after a view and all of its children has been inflated 211 * from XML.</td> 212 * </tr> 213 * 214 * <tr> 215 * <td rowspan="3">Layout</td> 216 * <td><code>{@link #onMeasure(int, int)}</code></td> 217 * <td>Called to determine the size requirements for this view and all 218 * of its children. 219 * </td> 220 * </tr> 221 * <tr> 222 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 223 * <td>Called when this view should assign a size and position to all 224 * of its children. 225 * </td> 226 * </tr> 227 * <tr> 228 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 229 * <td>Called when the size of this view has changed. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td>Drawing</td> 235 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 236 * <td>Called when the view should render its content. 237 * </td> 238 * </tr> 239 * 240 * <tr> 241 * <td rowspan="4">Event processing</td> 242 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 243 * <td>Called when a new hardware key event occurs. 244 * </td> 245 * </tr> 246 * <tr> 247 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 248 * <td>Called when a hardware key up event occurs. 249 * </td> 250 * </tr> 251 * <tr> 252 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 253 * <td>Called when a trackball motion event occurs. 254 * </td> 255 * </tr> 256 * <tr> 257 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 258 * <td>Called when a touch screen motion event occurs. 259 * </td> 260 * </tr> 261 * 262 * <tr> 263 * <td rowspan="2">Focus</td> 264 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 265 * <td>Called when the view gains or loses focus. 266 * </td> 267 * </tr> 268 * 269 * <tr> 270 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 271 * <td>Called when the window containing the view gains or loses focus. 272 * </td> 273 * </tr> 274 * 275 * <tr> 276 * <td rowspan="3">Attaching</td> 277 * <td><code>{@link #onAttachedToWindow()}</code></td> 278 * <td>Called when the view is attached to a window. 279 * </td> 280 * </tr> 281 * 282 * <tr> 283 * <td><code>{@link #onDetachedFromWindow}</code></td> 284 * <td>Called when the view is detached from its window. 285 * </td> 286 * </tr> 287 * 288 * <tr> 289 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 290 * <td>Called when the visibility of the window containing the view 291 * has changed. 292 * </td> 293 * </tr> 294 * </tbody> 295 * 296 * </table> 297 * </p> 298 * 299 * <a name="IDs"></a> 300 * <h3>IDs</h3> 301 * Views may have an integer id associated with them. These ids are typically 302 * assigned in the layout XML files, and are used to find specific views within 303 * the view tree. A common pattern is to: 304 * <ul> 305 * <li>Define a Button in the layout file and assign it a unique ID. 306 * <pre> 307 * <Button 308 * android:id="@+id/my_button" 309 * android:layout_width="wrap_content" 310 * android:layout_height="wrap_content" 311 * android:text="@string/my_button_text"/> 312 * </pre></li> 313 * <li>From the onCreate method of an Activity, find the Button 314 * <pre class="prettyprint"> 315 * Button myButton = (Button) findViewById(R.id.my_button); 316 * </pre></li> 317 * </ul> 318 * <p> 319 * View IDs need not be unique throughout the tree, but it is good practice to 320 * ensure that they are at least unique within the part of the tree you are 321 * searching. 322 * </p> 323 * 324 * <a name="Position"></a> 325 * <h3>Position</h3> 326 * <p> 327 * The geometry of a view is that of a rectangle. A view has a location, 328 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 329 * two dimensions, expressed as a width and a height. The unit for location 330 * and dimensions is the pixel. 331 * </p> 332 * 333 * <p> 334 * It is possible to retrieve the location of a view by invoking the methods 335 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 336 * coordinate of the rectangle representing the view. The latter returns the 337 * top, or Y, coordinate of the rectangle representing the view. These methods 338 * both return the location of the view relative to its parent. For instance, 339 * when getLeft() returns 20, that means the view is located 20 pixels to the 340 * right of the left edge of its direct parent. 341 * </p> 342 * 343 * <p> 344 * In addition, several convenience methods are offered to avoid unnecessary 345 * computations, namely {@link #getRight()} and {@link #getBottom()}. 346 * These methods return the coordinates of the right and bottom edges of the 347 * rectangle representing the view. For instance, calling {@link #getRight()} 348 * is similar to the following computation: <code>getLeft() + getWidth()</code> 349 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 350 * </p> 351 * 352 * <a name="SizePaddingMargins"></a> 353 * <h3>Size, padding and margins</h3> 354 * <p> 355 * The size of a view is expressed with a width and a height. A view actually 356 * possess two pairs of width and height values. 357 * </p> 358 * 359 * <p> 360 * The first pair is known as <em>measured width</em> and 361 * <em>measured height</em>. These dimensions define how big a view wants to be 362 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 363 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 364 * and {@link #getMeasuredHeight()}. 365 * </p> 366 * 367 * <p> 368 * The second pair is simply known as <em>width</em> and <em>height</em>, or 369 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 370 * dimensions define the actual size of the view on screen, at drawing time and 371 * after layout. These values may, but do not have to, be different from the 372 * measured width and height. The width and height can be obtained by calling 373 * {@link #getWidth()} and {@link #getHeight()}. 374 * </p> 375 * 376 * <p> 377 * To measure its dimensions, a view takes into account its padding. The padding 378 * is expressed in pixels for the left, top, right and bottom parts of the view. 379 * Padding can be used to offset the content of the view by a specific amount of 380 * pixels. For instance, a left padding of 2 will push the view's content by 381 * 2 pixels to the right of the left edge. Padding can be set using the 382 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 383 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 384 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 385 * {@link #getPaddingEnd()}. 386 * </p> 387 * 388 * <p> 389 * Even though a view can define a padding, it does not provide any support for 390 * margins. However, view groups provide such a support. Refer to 391 * {@link android.view.ViewGroup} and 392 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 393 * </p> 394 * 395 * <a name="Layout"></a> 396 * <h3>Layout</h3> 397 * <p> 398 * Layout is a two pass process: a measure pass and a layout pass. The measuring 399 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 400 * of the view tree. Each view pushes dimension specifications down the tree 401 * during the recursion. At the end of the measure pass, every view has stored 402 * its measurements. The second pass happens in 403 * {@link #layout(int,int,int,int)} and is also top-down. During 404 * this pass each parent is responsible for positioning all of its children 405 * using the sizes computed in the measure pass. 406 * </p> 407 * 408 * <p> 409 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 410 * {@link #getMeasuredHeight()} values must be set, along with those for all of 411 * that view's descendants. A view's measured width and measured height values 412 * must respect the constraints imposed by the view's parents. This guarantees 413 * that at the end of the measure pass, all parents accept all of their 414 * children's measurements. A parent view may call measure() more than once on 415 * its children. For example, the parent may measure each child once with 416 * unspecified dimensions to find out how big they want to be, then call 417 * measure() on them again with actual numbers if the sum of all the children's 418 * unconstrained sizes is too big or too small. 419 * </p> 420 * 421 * <p> 422 * The measure pass uses two classes to communicate dimensions. The 423 * {@link MeasureSpec} class is used by views to tell their parents how they 424 * want to be measured and positioned. The base LayoutParams class just 425 * describes how big the view wants to be for both width and height. For each 426 * dimension, it can specify one of: 427 * <ul> 428 * <li> an exact number 429 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 430 * (minus padding) 431 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 432 * enclose its content (plus padding). 433 * </ul> 434 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 435 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 436 * an X and Y value. 437 * </p> 438 * 439 * <p> 440 * MeasureSpecs are used to push requirements down the tree from parent to 441 * child. A MeasureSpec can be in one of three modes: 442 * <ul> 443 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 444 * of a child view. For example, a LinearLayout may call measure() on its child 445 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 446 * tall the child view wants to be given a width of 240 pixels. 447 * <li>EXACTLY: This is used by the parent to impose an exact size on the 448 * child. The child must use this size, and guarantee that all of its 449 * descendants will fit within this size. 450 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 451 * child. The child must guarantee that it and all of its descendants will fit 452 * within this size. 453 * </ul> 454 * </p> 455 * 456 * <p> 457 * To initiate a layout, call {@link #requestLayout}. This method is typically 458 * called by a view on itself when it believes that is can no longer fit within 459 * its current bounds. 460 * </p> 461 * 462 * <a name="Drawing"></a> 463 * <h3>Drawing</h3> 464 * <p> 465 * Drawing is handled by walking the tree and recording the drawing commands of 466 * any View that needs to update. After this, the drawing commands of the 467 * entire tree are issued to screen, clipped to the newly damaged area. 468 * </p> 469 * 470 * <p> 471 * The tree is largely recorded and drawn in order, with parents drawn before 472 * (i.e., behind) their children, with siblings drawn in the order they appear 473 * in the tree. If you set a background drawable for a View, then the View will 474 * draw it before calling back to its <code>onDraw()</code> method. The child 475 * drawing order can be overridden with 476 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 477 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 478 * </p> 479 * 480 * <p> 481 * To force a view to draw, call {@link #invalidate()}. 482 * </p> 483 * 484 * <a name="EventHandlingThreading"></a> 485 * <h3>Event Handling and Threading</h3> 486 * <p> 487 * The basic cycle of a view is as follows: 488 * <ol> 489 * <li>An event comes in and is dispatched to the appropriate view. The view 490 * handles the event and notifies any listeners.</li> 491 * <li>If in the course of processing the event, the view's bounds may need 492 * to be changed, the view will call {@link #requestLayout()}.</li> 493 * <li>Similarly, if in the course of processing the event the view's appearance 494 * may need to be changed, the view will call {@link #invalidate()}.</li> 495 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 496 * the framework will take care of measuring, laying out, and drawing the tree 497 * as appropriate.</li> 498 * </ol> 499 * </p> 500 * 501 * <p><em>Note: The entire view tree is single threaded. You must always be on 502 * the UI thread when calling any method on any view.</em> 503 * If you are doing work on other threads and want to update the state of a view 504 * from that thread, you should use a {@link Handler}. 505 * </p> 506 * 507 * <a name="FocusHandling"></a> 508 * <h3>Focus Handling</h3> 509 * <p> 510 * The framework will handle routine focus movement in response to user input. 511 * This includes changing the focus as views are removed or hidden, or as new 512 * views become available. Views indicate their willingness to take focus 513 * through the {@link #isFocusable} method. To change whether a view can take 514 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 515 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 516 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 517 * </p> 518 * <p> 519 * Focus movement is based on an algorithm which finds the nearest neighbor in a 520 * given direction. In rare cases, the default algorithm may not match the 521 * intended behavior of the developer. In these situations, you can provide 522 * explicit overrides by using these XML attributes in the layout file: 523 * <pre> 524 * nextFocusDown 525 * nextFocusLeft 526 * nextFocusRight 527 * nextFocusUp 528 * </pre> 529 * </p> 530 * 531 * 532 * <p> 533 * To get a particular view to take focus, call {@link #requestFocus()}. 534 * </p> 535 * 536 * <a name="TouchMode"></a> 537 * <h3>Touch Mode</h3> 538 * <p> 539 * When a user is navigating a user interface via directional keys such as a D-pad, it is 540 * necessary to give focus to actionable items such as buttons so the user can see 541 * what will take input. If the device has touch capabilities, however, and the user 542 * begins interacting with the interface by touching it, it is no longer necessary to 543 * always highlight, or give focus to, a particular view. This motivates a mode 544 * for interaction named 'touch mode'. 545 * </p> 546 * <p> 547 * For a touch capable device, once the user touches the screen, the device 548 * will enter touch mode. From this point onward, only views for which 549 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 550 * Other views that are touchable, like buttons, will not take focus when touched; they will 551 * only fire the on click listeners. 552 * </p> 553 * <p> 554 * Any time a user hits a directional key, such as a D-pad direction, the view device will 555 * exit touch mode, and find a view to take focus, so that the user may resume interacting 556 * with the user interface without touching the screen again. 557 * </p> 558 * <p> 559 * The touch mode state is maintained across {@link android.app.Activity}s. Call 560 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 561 * </p> 562 * 563 * <a name="Scrolling"></a> 564 * <h3>Scrolling</h3> 565 * <p> 566 * The framework provides basic support for views that wish to internally 567 * scroll their content. This includes keeping track of the X and Y scroll 568 * offset as well as mechanisms for drawing scrollbars. See 569 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 570 * {@link #awakenScrollBars()} for more details. 571 * </p> 572 * 573 * <a name="Tags"></a> 574 * <h3>Tags</h3> 575 * <p> 576 * Unlike IDs, tags are not used to identify views. Tags are essentially an 577 * extra piece of information that can be associated with a view. They are most 578 * often used as a convenience to store data related to views in the views 579 * themselves rather than by putting them in a separate structure. 580 * </p> 581 * <p> 582 * Tags may be specified with character sequence values in layout XML as either 583 * a single tag using the {@link android.R.styleable#View_tag android:tag} 584 * attribute or multiple tags using the {@code <tag>} child element: 585 * <pre> 586 * <View ... 587 * android:tag="@string/mytag_value" /> 588 * <View ...> 589 * <tag android:id="@+id/mytag" 590 * android:value="@string/mytag_value" /> 591 * </View> 592 * </pre> 593 * </p> 594 * <p> 595 * Tags may also be specified with arbitrary objects from code using 596 * {@link #setTag(Object)} or {@link #setTag(int, Object)}. 597 * </p> 598 * 599 * <a name="Themes"></a> 600 * <h3>Themes</h3> 601 * <p> 602 * By default, Views are created using the theme of the Context object supplied 603 * to their constructor; however, a different theme may be specified by using 604 * the {@link android.R.styleable#View_theme android:theme} attribute in layout 605 * XML or by passing a {@link ContextThemeWrapper} to the constructor from 606 * code. 607 * </p> 608 * <p> 609 * When the {@link android.R.styleable#View_theme android:theme} attribute is 610 * used in XML, the specified theme is applied on top of the inflation 611 * context's theme (see {@link LayoutInflater}) and used for the view itself as 612 * well as any child elements. 613 * </p> 614 * <p> 615 * In the following example, both views will be created using the Material dark 616 * color scheme; however, because an overlay theme is used which only defines a 617 * subset of attributes, the value of 618 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on 619 * the inflation context's theme (e.g. the Activity theme) will be preserved. 620 * <pre> 621 * <LinearLayout 622 * ... 623 * android:theme="@android:theme/ThemeOverlay.Material.Dark"> 624 * <View ...> 625 * </LinearLayout> 626 * </pre> 627 * </p> 628 * 629 * <a name="Properties"></a> 630 * <h3>Properties</h3> 631 * <p> 632 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 633 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 634 * available both in the {@link Property} form as well as in similarly-named setter/getter 635 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 636 * be used to set persistent state associated with these rendering-related properties on the view. 637 * The properties and methods can also be used in conjunction with 638 * {@link android.animation.Animator Animator}-based animations, described more in the 639 * <a href="#Animation">Animation</a> section. 640 * </p> 641 * 642 * <a name="Animation"></a> 643 * <h3>Animation</h3> 644 * <p> 645 * Starting with Android 3.0, the preferred way of animating views is to use the 646 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 647 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 648 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 649 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 650 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 651 * makes animating these View properties particularly easy and efficient. 652 * </p> 653 * <p> 654 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 655 * You can attach an {@link Animation} object to a view using 656 * {@link #setAnimation(Animation)} or 657 * {@link #startAnimation(Animation)}. The animation can alter the scale, 658 * rotation, translation and alpha of a view over time. If the animation is 659 * attached to a view that has children, the animation will affect the entire 660 * subtree rooted by that node. When an animation is started, the framework will 661 * take care of redrawing the appropriate views until the animation completes. 662 * </p> 663 * 664 * <a name="Security"></a> 665 * <h3>Security</h3> 666 * <p> 667 * Sometimes it is essential that an application be able to verify that an action 668 * is being performed with the full knowledge and consent of the user, such as 669 * granting a permission request, making a purchase or clicking on an advertisement. 670 * Unfortunately, a malicious application could try to spoof the user into 671 * performing these actions, unaware, by concealing the intended purpose of the view. 672 * As a remedy, the framework offers a touch filtering mechanism that can be used to 673 * improve the security of views that provide access to sensitive functionality. 674 * </p><p> 675 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 676 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 677 * will discard touches that are received whenever the view's window is obscured by 678 * another visible window. As a result, the view will not receive touches whenever a 679 * toast, dialog or other window appears above the view's window. 680 * </p><p> 681 * For more fine-grained control over security, consider overriding the 682 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 683 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 684 * </p> 685 * 686 * @attr ref android.R.styleable#View_alpha 687 * @attr ref android.R.styleable#View_background 688 * @attr ref android.R.styleable#View_clickable 689 * @attr ref android.R.styleable#View_contentDescription 690 * @attr ref android.R.styleable#View_drawingCacheQuality 691 * @attr ref android.R.styleable#View_duplicateParentState 692 * @attr ref android.R.styleable#View_id 693 * @attr ref android.R.styleable#View_requiresFadingEdge 694 * @attr ref android.R.styleable#View_fadeScrollbars 695 * @attr ref android.R.styleable#View_fadingEdgeLength 696 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 697 * @attr ref android.R.styleable#View_fitsSystemWindows 698 * @attr ref android.R.styleable#View_isScrollContainer 699 * @attr ref android.R.styleable#View_focusable 700 * @attr ref android.R.styleable#View_focusableInTouchMode 701 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 702 * @attr ref android.R.styleable#View_keepScreenOn 703 * @attr ref android.R.styleable#View_layerType 704 * @attr ref android.R.styleable#View_layoutDirection 705 * @attr ref android.R.styleable#View_longClickable 706 * @attr ref android.R.styleable#View_minHeight 707 * @attr ref android.R.styleable#View_minWidth 708 * @attr ref android.R.styleable#View_nextFocusDown 709 * @attr ref android.R.styleable#View_nextFocusLeft 710 * @attr ref android.R.styleable#View_nextFocusRight 711 * @attr ref android.R.styleable#View_nextFocusUp 712 * @attr ref android.R.styleable#View_onClick 713 * @attr ref android.R.styleable#View_padding 714 * @attr ref android.R.styleable#View_paddingBottom 715 * @attr ref android.R.styleable#View_paddingLeft 716 * @attr ref android.R.styleable#View_paddingRight 717 * @attr ref android.R.styleable#View_paddingTop 718 * @attr ref android.R.styleable#View_paddingStart 719 * @attr ref android.R.styleable#View_paddingEnd 720 * @attr ref android.R.styleable#View_saveEnabled 721 * @attr ref android.R.styleable#View_rotation 722 * @attr ref android.R.styleable#View_rotationX 723 * @attr ref android.R.styleable#View_rotationY 724 * @attr ref android.R.styleable#View_scaleX 725 * @attr ref android.R.styleable#View_scaleY 726 * @attr ref android.R.styleable#View_scrollX 727 * @attr ref android.R.styleable#View_scrollY 728 * @attr ref android.R.styleable#View_scrollbarSize 729 * @attr ref android.R.styleable#View_scrollbarStyle 730 * @attr ref android.R.styleable#View_scrollbars 731 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 732 * @attr ref android.R.styleable#View_scrollbarFadeDuration 733 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 734 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 735 * @attr ref android.R.styleable#View_scrollbarThumbVertical 736 * @attr ref android.R.styleable#View_scrollbarTrackVertical 737 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 739 * @attr ref android.R.styleable#View_stateListAnimator 740 * @attr ref android.R.styleable#View_transitionName 741 * @attr ref android.R.styleable#View_soundEffectsEnabled 742 * @attr ref android.R.styleable#View_tag 743 * @attr ref android.R.styleable#View_textAlignment 744 * @attr ref android.R.styleable#View_textDirection 745 * @attr ref android.R.styleable#View_transformPivotX 746 * @attr ref android.R.styleable#View_transformPivotY 747 * @attr ref android.R.styleable#View_translationX 748 * @attr ref android.R.styleable#View_translationY 749 * @attr ref android.R.styleable#View_translationZ 750 * @attr ref android.R.styleable#View_visibility 751 * @attr ref android.R.styleable#View_theme 752 * 753 * @see android.view.ViewGroup 754 */ 755@UiThread 756public class View implements Drawable.Callback, KeyEvent.Callback, 757 AccessibilityEventSource { 758 private static final boolean DBG = false; 759 760 /** 761 * The logging tag used by this class with android.util.Log. 762 */ 763 protected static final String VIEW_LOG_TAG = "View"; 764 765 /** 766 * When set to true, apps will draw debugging information about their layouts. 767 * 768 * @hide 769 */ 770 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 771 772 /** 773 * When set to true, this view will save its attribute data. 774 * 775 * @hide 776 */ 777 public static boolean mDebugViewAttributes = false; 778 779 /** 780 * Used to mark a View that has no ID. 781 */ 782 public static final int NO_ID = -1; 783 784 /** 785 * Signals that compatibility booleans have been initialized according to 786 * target SDK versions. 787 */ 788 private static boolean sCompatibilityDone = false; 789 790 /** 791 * Use the old (broken) way of building MeasureSpecs. 792 */ 793 private static boolean sUseBrokenMakeMeasureSpec = false; 794 795 /** 796 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 797 */ 798 static boolean sUseZeroUnspecifiedMeasureSpec = false; 799 800 /** 801 * Ignore any optimizations using the measure cache. 802 */ 803 private static boolean sIgnoreMeasureCache = false; 804 805 /** 806 * Ignore an optimization that skips unnecessary EXACTLY layout passes. 807 */ 808 private static boolean sAlwaysRemeasureExactly = false; 809 810 /** 811 * Relax constraints around whether setLayoutParams() must be called after 812 * modifying the layout params. 813 */ 814 private static boolean sLayoutParamsAlwaysChanged = false; 815 816 /** 817 * Allow setForeground/setBackground to be called (and ignored) on a textureview, 818 * without throwing 819 */ 820 static boolean sTextureViewIgnoresDrawableSetters = false; 821 822 /** 823 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 824 * calling setFlags. 825 */ 826 private static final int NOT_FOCUSABLE = 0x00000000; 827 828 /** 829 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 830 * setFlags. 831 */ 832 private static final int FOCUSABLE = 0x00000001; 833 834 /** 835 * Mask for use with setFlags indicating bits used for focus. 836 */ 837 private static final int FOCUSABLE_MASK = 0x00000001; 838 839 /** 840 * This view will adjust its padding to fit sytem windows (e.g. status bar) 841 */ 842 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 843 844 /** @hide */ 845 @IntDef({VISIBLE, INVISIBLE, GONE}) 846 @Retention(RetentionPolicy.SOURCE) 847 public @interface Visibility {} 848 849 /** 850 * This view is visible. 851 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 852 * android:visibility}. 853 */ 854 public static final int VISIBLE = 0x00000000; 855 856 /** 857 * This view is invisible, but it still takes up space for layout purposes. 858 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 859 * android:visibility}. 860 */ 861 public static final int INVISIBLE = 0x00000004; 862 863 /** 864 * This view is invisible, and it doesn't take any space for layout 865 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 866 * android:visibility}. 867 */ 868 public static final int GONE = 0x00000008; 869 870 /** 871 * Mask for use with setFlags indicating bits used for visibility. 872 * {@hide} 873 */ 874 static final int VISIBILITY_MASK = 0x0000000C; 875 876 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 877 878 /** 879 * This view is enabled. Interpretation varies by subclass. 880 * Use with ENABLED_MASK when calling setFlags. 881 * {@hide} 882 */ 883 static final int ENABLED = 0x00000000; 884 885 /** 886 * This view is disabled. Interpretation varies by subclass. 887 * Use with ENABLED_MASK when calling setFlags. 888 * {@hide} 889 */ 890 static final int DISABLED = 0x00000020; 891 892 /** 893 * Mask for use with setFlags indicating bits used for indicating whether 894 * this view is enabled 895 * {@hide} 896 */ 897 static final int ENABLED_MASK = 0x00000020; 898 899 /** 900 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 901 * called and further optimizations will be performed. It is okay to have 902 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 903 * {@hide} 904 */ 905 static final int WILL_NOT_DRAW = 0x00000080; 906 907 /** 908 * Mask for use with setFlags indicating bits used for indicating whether 909 * this view is will draw 910 * {@hide} 911 */ 912 static final int DRAW_MASK = 0x00000080; 913 914 /** 915 * <p>This view doesn't show scrollbars.</p> 916 * {@hide} 917 */ 918 static final int SCROLLBARS_NONE = 0x00000000; 919 920 /** 921 * <p>This view shows horizontal scrollbars.</p> 922 * {@hide} 923 */ 924 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 925 926 /** 927 * <p>This view shows vertical scrollbars.</p> 928 * {@hide} 929 */ 930 static final int SCROLLBARS_VERTICAL = 0x00000200; 931 932 /** 933 * <p>Mask for use with setFlags indicating bits used for indicating which 934 * scrollbars are enabled.</p> 935 * {@hide} 936 */ 937 static final int SCROLLBARS_MASK = 0x00000300; 938 939 /** 940 * Indicates that the view should filter touches when its window is obscured. 941 * Refer to the class comments for more information about this security feature. 942 * {@hide} 943 */ 944 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 945 946 /** 947 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 948 * that they are optional and should be skipped if the window has 949 * requested system UI flags that ignore those insets for layout. 950 */ 951 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 952 953 /** 954 * <p>This view doesn't show fading edges.</p> 955 * {@hide} 956 */ 957 static final int FADING_EDGE_NONE = 0x00000000; 958 959 /** 960 * <p>This view shows horizontal fading edges.</p> 961 * {@hide} 962 */ 963 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 964 965 /** 966 * <p>This view shows vertical fading edges.</p> 967 * {@hide} 968 */ 969 static final int FADING_EDGE_VERTICAL = 0x00002000; 970 971 /** 972 * <p>Mask for use with setFlags indicating bits used for indicating which 973 * fading edges are enabled.</p> 974 * {@hide} 975 */ 976 static final int FADING_EDGE_MASK = 0x00003000; 977 978 /** 979 * <p>Indicates this view can be clicked. When clickable, a View reacts 980 * to clicks by notifying the OnClickListener.<p> 981 * {@hide} 982 */ 983 static final int CLICKABLE = 0x00004000; 984 985 /** 986 * <p>Indicates this view is caching its drawing into a bitmap.</p> 987 * {@hide} 988 */ 989 static final int DRAWING_CACHE_ENABLED = 0x00008000; 990 991 /** 992 * <p>Indicates that no icicle should be saved for this view.<p> 993 * {@hide} 994 */ 995 static final int SAVE_DISABLED = 0x000010000; 996 997 /** 998 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 999 * property.</p> 1000 * {@hide} 1001 */ 1002 static final int SAVE_DISABLED_MASK = 0x000010000; 1003 1004 /** 1005 * <p>Indicates that no drawing cache should ever be created for this view.<p> 1006 * {@hide} 1007 */ 1008 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 1009 1010 /** 1011 * <p>Indicates this view can take / keep focus when int touch mode.</p> 1012 * {@hide} 1013 */ 1014 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 1015 1016 /** @hide */ 1017 @Retention(RetentionPolicy.SOURCE) 1018 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 1019 public @interface DrawingCacheQuality {} 1020 1021 /** 1022 * <p>Enables low quality mode for the drawing cache.</p> 1023 */ 1024 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 1025 1026 /** 1027 * <p>Enables high quality mode for the drawing cache.</p> 1028 */ 1029 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 1030 1031 /** 1032 * <p>Enables automatic quality mode for the drawing cache.</p> 1033 */ 1034 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 1035 1036 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 1037 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 1038 }; 1039 1040 /** 1041 * <p>Mask for use with setFlags indicating bits used for the cache 1042 * quality property.</p> 1043 * {@hide} 1044 */ 1045 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 1046 1047 /** 1048 * <p> 1049 * Indicates this view can be long clicked. When long clickable, a View 1050 * reacts to long clicks by notifying the OnLongClickListener or showing a 1051 * context menu. 1052 * </p> 1053 * {@hide} 1054 */ 1055 static final int LONG_CLICKABLE = 0x00200000; 1056 1057 /** 1058 * <p>Indicates that this view gets its drawable states from its direct parent 1059 * and ignores its original internal states.</p> 1060 * 1061 * @hide 1062 */ 1063 static final int DUPLICATE_PARENT_STATE = 0x00400000; 1064 1065 /** 1066 * <p> 1067 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1068 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1069 * OnContextClickListener. 1070 * </p> 1071 * {@hide} 1072 */ 1073 static final int CONTEXT_CLICKABLE = 0x00800000; 1074 1075 1076 /** @hide */ 1077 @IntDef({ 1078 SCROLLBARS_INSIDE_OVERLAY, 1079 SCROLLBARS_INSIDE_INSET, 1080 SCROLLBARS_OUTSIDE_OVERLAY, 1081 SCROLLBARS_OUTSIDE_INSET 1082 }) 1083 @Retention(RetentionPolicy.SOURCE) 1084 public @interface ScrollBarStyle {} 1085 1086 /** 1087 * The scrollbar style to display the scrollbars inside the content area, 1088 * without increasing the padding. The scrollbars will be overlaid with 1089 * translucency on the view's content. 1090 */ 1091 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1092 1093 /** 1094 * The scrollbar style to display the scrollbars inside the padded area, 1095 * increasing the padding of the view. The scrollbars will not overlap the 1096 * content area of the view. 1097 */ 1098 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1099 1100 /** 1101 * The scrollbar style to display the scrollbars at the edge of the view, 1102 * without increasing the padding. The scrollbars will be overlaid with 1103 * translucency. 1104 */ 1105 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1106 1107 /** 1108 * The scrollbar style to display the scrollbars at the edge of the view, 1109 * increasing the padding of the view. The scrollbars will only overlap the 1110 * background, if any. 1111 */ 1112 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1113 1114 /** 1115 * Mask to check if the scrollbar style is overlay or inset. 1116 * {@hide} 1117 */ 1118 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1119 1120 /** 1121 * Mask to check if the scrollbar style is inside or outside. 1122 * {@hide} 1123 */ 1124 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1125 1126 /** 1127 * Mask for scrollbar style. 1128 * {@hide} 1129 */ 1130 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1131 1132 /** 1133 * View flag indicating that the screen should remain on while the 1134 * window containing this view is visible to the user. This effectively 1135 * takes care of automatically setting the WindowManager's 1136 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1137 */ 1138 public static final int KEEP_SCREEN_ON = 0x04000000; 1139 1140 /** 1141 * View flag indicating whether this view should have sound effects enabled 1142 * for events such as clicking and touching. 1143 */ 1144 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1145 1146 /** 1147 * View flag indicating whether this view should have haptic feedback 1148 * enabled for events such as long presses. 1149 */ 1150 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1151 1152 /** 1153 * <p>Indicates that the view hierarchy should stop saving state when 1154 * it reaches this view. If state saving is initiated immediately at 1155 * the view, it will be allowed. 1156 * {@hide} 1157 */ 1158 static final int PARENT_SAVE_DISABLED = 0x20000000; 1159 1160 /** 1161 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1162 * {@hide} 1163 */ 1164 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1165 1166 /** @hide */ 1167 @IntDef(flag = true, 1168 value = { 1169 FOCUSABLES_ALL, 1170 FOCUSABLES_TOUCH_MODE 1171 }) 1172 @Retention(RetentionPolicy.SOURCE) 1173 public @interface FocusableMode {} 1174 1175 /** 1176 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1177 * should add all focusable Views regardless if they are focusable in touch mode. 1178 */ 1179 public static final int FOCUSABLES_ALL = 0x00000000; 1180 1181 /** 1182 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1183 * should add only Views focusable in touch mode. 1184 */ 1185 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1186 1187 /** @hide */ 1188 @IntDef({ 1189 FOCUS_BACKWARD, 1190 FOCUS_FORWARD, 1191 FOCUS_LEFT, 1192 FOCUS_UP, 1193 FOCUS_RIGHT, 1194 FOCUS_DOWN 1195 }) 1196 @Retention(RetentionPolicy.SOURCE) 1197 public @interface FocusDirection {} 1198 1199 /** @hide */ 1200 @IntDef({ 1201 FOCUS_LEFT, 1202 FOCUS_UP, 1203 FOCUS_RIGHT, 1204 FOCUS_DOWN 1205 }) 1206 @Retention(RetentionPolicy.SOURCE) 1207 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1208 1209 /** 1210 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1211 * item. 1212 */ 1213 public static final int FOCUS_BACKWARD = 0x00000001; 1214 1215 /** 1216 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1217 * item. 1218 */ 1219 public static final int FOCUS_FORWARD = 0x00000002; 1220 1221 /** 1222 * Use with {@link #focusSearch(int)}. Move focus to the left. 1223 */ 1224 public static final int FOCUS_LEFT = 0x00000011; 1225 1226 /** 1227 * Use with {@link #focusSearch(int)}. Move focus up. 1228 */ 1229 public static final int FOCUS_UP = 0x00000021; 1230 1231 /** 1232 * Use with {@link #focusSearch(int)}. Move focus to the right. 1233 */ 1234 public static final int FOCUS_RIGHT = 0x00000042; 1235 1236 /** 1237 * Use with {@link #focusSearch(int)}. Move focus down. 1238 */ 1239 public static final int FOCUS_DOWN = 0x00000082; 1240 1241 /** 1242 * Bits of {@link #getMeasuredWidthAndState()} and 1243 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1244 */ 1245 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1246 1247 /** 1248 * Bits of {@link #getMeasuredWidthAndState()} and 1249 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1250 */ 1251 public static final int MEASURED_STATE_MASK = 0xff000000; 1252 1253 /** 1254 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1255 * for functions that combine both width and height into a single int, 1256 * such as {@link #getMeasuredState()} and the childState argument of 1257 * {@link #resolveSizeAndState(int, int, int)}. 1258 */ 1259 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1260 1261 /** 1262 * Bit of {@link #getMeasuredWidthAndState()} and 1263 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1264 * is smaller that the space the view would like to have. 1265 */ 1266 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1267 1268 /** 1269 * Base View state sets 1270 */ 1271 // Singles 1272 /** 1273 * Indicates the view has no states set. States are used with 1274 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1275 * view depending on its state. 1276 * 1277 * @see android.graphics.drawable.Drawable 1278 * @see #getDrawableState() 1279 */ 1280 protected static final int[] EMPTY_STATE_SET; 1281 /** 1282 * Indicates the view is enabled. States are used with 1283 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1284 * view depending on its state. 1285 * 1286 * @see android.graphics.drawable.Drawable 1287 * @see #getDrawableState() 1288 */ 1289 protected static final int[] ENABLED_STATE_SET; 1290 /** 1291 * Indicates the view is focused. States are used with 1292 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1293 * view depending on its state. 1294 * 1295 * @see android.graphics.drawable.Drawable 1296 * @see #getDrawableState() 1297 */ 1298 protected static final int[] FOCUSED_STATE_SET; 1299 /** 1300 * Indicates the view is selected. States are used with 1301 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1302 * view depending on its state. 1303 * 1304 * @see android.graphics.drawable.Drawable 1305 * @see #getDrawableState() 1306 */ 1307 protected static final int[] SELECTED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed. States are used with 1310 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1311 * view depending on its state. 1312 * 1313 * @see android.graphics.drawable.Drawable 1314 * @see #getDrawableState() 1315 */ 1316 protected static final int[] PRESSED_STATE_SET; 1317 /** 1318 * Indicates the view's window has focus. States are used with 1319 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1320 * view depending on its state. 1321 * 1322 * @see android.graphics.drawable.Drawable 1323 * @see #getDrawableState() 1324 */ 1325 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1326 // Doubles 1327 /** 1328 * Indicates the view is enabled and has the focus. 1329 * 1330 * @see #ENABLED_STATE_SET 1331 * @see #FOCUSED_STATE_SET 1332 */ 1333 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1334 /** 1335 * Indicates the view is enabled and selected. 1336 * 1337 * @see #ENABLED_STATE_SET 1338 * @see #SELECTED_STATE_SET 1339 */ 1340 protected static final int[] ENABLED_SELECTED_STATE_SET; 1341 /** 1342 * Indicates the view is enabled and that its window has focus. 1343 * 1344 * @see #ENABLED_STATE_SET 1345 * @see #WINDOW_FOCUSED_STATE_SET 1346 */ 1347 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1348 /** 1349 * Indicates the view is focused and selected. 1350 * 1351 * @see #FOCUSED_STATE_SET 1352 * @see #SELECTED_STATE_SET 1353 */ 1354 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1355 /** 1356 * Indicates the view has the focus and that its window has the focus. 1357 * 1358 * @see #FOCUSED_STATE_SET 1359 * @see #WINDOW_FOCUSED_STATE_SET 1360 */ 1361 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1362 /** 1363 * Indicates the view is selected and that its window has the focus. 1364 * 1365 * @see #SELECTED_STATE_SET 1366 * @see #WINDOW_FOCUSED_STATE_SET 1367 */ 1368 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1369 // Triples 1370 /** 1371 * Indicates the view is enabled, focused and selected. 1372 * 1373 * @see #ENABLED_STATE_SET 1374 * @see #FOCUSED_STATE_SET 1375 * @see #SELECTED_STATE_SET 1376 */ 1377 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1378 /** 1379 * Indicates the view is enabled, focused and its window has the focus. 1380 * 1381 * @see #ENABLED_STATE_SET 1382 * @see #FOCUSED_STATE_SET 1383 * @see #WINDOW_FOCUSED_STATE_SET 1384 */ 1385 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1386 /** 1387 * Indicates the view is enabled, selected and its window has the focus. 1388 * 1389 * @see #ENABLED_STATE_SET 1390 * @see #SELECTED_STATE_SET 1391 * @see #WINDOW_FOCUSED_STATE_SET 1392 */ 1393 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1394 /** 1395 * Indicates the view is focused, selected and its window has the focus. 1396 * 1397 * @see #FOCUSED_STATE_SET 1398 * @see #SELECTED_STATE_SET 1399 * @see #WINDOW_FOCUSED_STATE_SET 1400 */ 1401 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1402 /** 1403 * Indicates the view is enabled, focused, selected and its window 1404 * has the focus. 1405 * 1406 * @see #ENABLED_STATE_SET 1407 * @see #FOCUSED_STATE_SET 1408 * @see #SELECTED_STATE_SET 1409 * @see #WINDOW_FOCUSED_STATE_SET 1410 */ 1411 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1412 /** 1413 * Indicates the view is pressed and its window has the focus. 1414 * 1415 * @see #PRESSED_STATE_SET 1416 * @see #WINDOW_FOCUSED_STATE_SET 1417 */ 1418 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1419 /** 1420 * Indicates the view is pressed and selected. 1421 * 1422 * @see #PRESSED_STATE_SET 1423 * @see #SELECTED_STATE_SET 1424 */ 1425 protected static final int[] PRESSED_SELECTED_STATE_SET; 1426 /** 1427 * Indicates the view is pressed, selected and its window has the focus. 1428 * 1429 * @see #PRESSED_STATE_SET 1430 * @see #SELECTED_STATE_SET 1431 * @see #WINDOW_FOCUSED_STATE_SET 1432 */ 1433 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1434 /** 1435 * Indicates the view is pressed and focused. 1436 * 1437 * @see #PRESSED_STATE_SET 1438 * @see #FOCUSED_STATE_SET 1439 */ 1440 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1441 /** 1442 * Indicates the view is pressed, focused and its window has the focus. 1443 * 1444 * @see #PRESSED_STATE_SET 1445 * @see #FOCUSED_STATE_SET 1446 * @see #WINDOW_FOCUSED_STATE_SET 1447 */ 1448 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1449 /** 1450 * Indicates the view is pressed, focused and selected. 1451 * 1452 * @see #PRESSED_STATE_SET 1453 * @see #SELECTED_STATE_SET 1454 * @see #FOCUSED_STATE_SET 1455 */ 1456 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1457 /** 1458 * Indicates the view is pressed, focused, selected and its window has the focus. 1459 * 1460 * @see #PRESSED_STATE_SET 1461 * @see #FOCUSED_STATE_SET 1462 * @see #SELECTED_STATE_SET 1463 * @see #WINDOW_FOCUSED_STATE_SET 1464 */ 1465 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1466 /** 1467 * Indicates the view is pressed and enabled. 1468 * 1469 * @see #PRESSED_STATE_SET 1470 * @see #ENABLED_STATE_SET 1471 */ 1472 protected static final int[] PRESSED_ENABLED_STATE_SET; 1473 /** 1474 * Indicates the view is pressed, enabled and its window has the focus. 1475 * 1476 * @see #PRESSED_STATE_SET 1477 * @see #ENABLED_STATE_SET 1478 * @see #WINDOW_FOCUSED_STATE_SET 1479 */ 1480 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1481 /** 1482 * Indicates the view is pressed, enabled and selected. 1483 * 1484 * @see #PRESSED_STATE_SET 1485 * @see #ENABLED_STATE_SET 1486 * @see #SELECTED_STATE_SET 1487 */ 1488 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1489 /** 1490 * Indicates the view is pressed, enabled, selected and its window has the 1491 * focus. 1492 * 1493 * @see #PRESSED_STATE_SET 1494 * @see #ENABLED_STATE_SET 1495 * @see #SELECTED_STATE_SET 1496 * @see #WINDOW_FOCUSED_STATE_SET 1497 */ 1498 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1499 /** 1500 * Indicates the view is pressed, enabled and focused. 1501 * 1502 * @see #PRESSED_STATE_SET 1503 * @see #ENABLED_STATE_SET 1504 * @see #FOCUSED_STATE_SET 1505 */ 1506 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1507 /** 1508 * Indicates the view is pressed, enabled, focused and its window has the 1509 * focus. 1510 * 1511 * @see #PRESSED_STATE_SET 1512 * @see #ENABLED_STATE_SET 1513 * @see #FOCUSED_STATE_SET 1514 * @see #WINDOW_FOCUSED_STATE_SET 1515 */ 1516 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1517 /** 1518 * Indicates the view is pressed, enabled, focused and selected. 1519 * 1520 * @see #PRESSED_STATE_SET 1521 * @see #ENABLED_STATE_SET 1522 * @see #SELECTED_STATE_SET 1523 * @see #FOCUSED_STATE_SET 1524 */ 1525 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1526 /** 1527 * Indicates the view is pressed, enabled, focused, selected and its window 1528 * has the focus. 1529 * 1530 * @see #PRESSED_STATE_SET 1531 * @see #ENABLED_STATE_SET 1532 * @see #SELECTED_STATE_SET 1533 * @see #FOCUSED_STATE_SET 1534 * @see #WINDOW_FOCUSED_STATE_SET 1535 */ 1536 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1537 1538 static { 1539 EMPTY_STATE_SET = StateSet.get(0); 1540 1541 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1542 1543 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1544 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1545 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1546 1547 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1548 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1549 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1550 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1551 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1552 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1553 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1554 | StateSet.VIEW_STATE_FOCUSED); 1555 1556 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1557 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1558 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1559 ENABLED_SELECTED_STATE_SET = StateSet.get( 1560 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1561 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1562 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1563 | StateSet.VIEW_STATE_ENABLED); 1564 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1565 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1566 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1567 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1568 | StateSet.VIEW_STATE_ENABLED); 1569 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1570 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1571 | StateSet.VIEW_STATE_ENABLED); 1572 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1573 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1574 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1575 1576 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1577 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1578 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1579 PRESSED_SELECTED_STATE_SET = StateSet.get( 1580 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1581 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1582 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1583 | StateSet.VIEW_STATE_PRESSED); 1584 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1585 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1586 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1587 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1588 | StateSet.VIEW_STATE_PRESSED); 1589 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1590 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1591 | StateSet.VIEW_STATE_PRESSED); 1592 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1593 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1594 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1595 PRESSED_ENABLED_STATE_SET = StateSet.get( 1596 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1597 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1598 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1599 | StateSet.VIEW_STATE_PRESSED); 1600 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1601 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1602 | StateSet.VIEW_STATE_PRESSED); 1603 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1604 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1605 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1606 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1607 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1608 | StateSet.VIEW_STATE_PRESSED); 1609 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1610 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1611 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1612 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1613 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1614 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1615 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1616 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1617 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1618 | StateSet.VIEW_STATE_PRESSED); 1619 } 1620 1621 /** 1622 * Accessibility event types that are dispatched for text population. 1623 */ 1624 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1625 AccessibilityEvent.TYPE_VIEW_CLICKED 1626 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1627 | AccessibilityEvent.TYPE_VIEW_SELECTED 1628 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1629 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1630 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1631 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1632 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1633 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1634 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1635 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1636 1637 /** 1638 * Temporary Rect currently for use in setBackground(). This will probably 1639 * be extended in the future to hold our own class with more than just 1640 * a Rect. :) 1641 */ 1642 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1643 1644 /** 1645 * Map used to store views' tags. 1646 */ 1647 private SparseArray<Object> mKeyedTags; 1648 1649 /** 1650 * The next available accessibility id. 1651 */ 1652 private static int sNextAccessibilityViewId; 1653 1654 /** 1655 * The animation currently associated with this view. 1656 * @hide 1657 */ 1658 protected Animation mCurrentAnimation = null; 1659 1660 /** 1661 * Width as measured during measure pass. 1662 * {@hide} 1663 */ 1664 @ViewDebug.ExportedProperty(category = "measurement") 1665 int mMeasuredWidth; 1666 1667 /** 1668 * Height as measured during measure pass. 1669 * {@hide} 1670 */ 1671 @ViewDebug.ExportedProperty(category = "measurement") 1672 int mMeasuredHeight; 1673 1674 /** 1675 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1676 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1677 * its display list. This flag, used only when hw accelerated, allows us to clear the 1678 * flag while retaining this information until it's needed (at getDisplayList() time and 1679 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1680 * 1681 * {@hide} 1682 */ 1683 boolean mRecreateDisplayList = false; 1684 1685 /** 1686 * The view's identifier. 1687 * {@hide} 1688 * 1689 * @see #setId(int) 1690 * @see #getId() 1691 */ 1692 @IdRes 1693 @ViewDebug.ExportedProperty(resolveId = true) 1694 int mID = NO_ID; 1695 1696 /** 1697 * The stable ID of this view for accessibility purposes. 1698 */ 1699 int mAccessibilityViewId = NO_ID; 1700 1701 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1702 1703 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1704 1705 /** 1706 * The view's tag. 1707 * {@hide} 1708 * 1709 * @see #setTag(Object) 1710 * @see #getTag() 1711 */ 1712 protected Object mTag = null; 1713 1714 // for mPrivateFlags: 1715 /** {@hide} */ 1716 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1717 /** {@hide} */ 1718 static final int PFLAG_FOCUSED = 0x00000002; 1719 /** {@hide} */ 1720 static final int PFLAG_SELECTED = 0x00000004; 1721 /** {@hide} */ 1722 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1723 /** {@hide} */ 1724 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1725 /** {@hide} */ 1726 static final int PFLAG_DRAWN = 0x00000020; 1727 /** 1728 * When this flag is set, this view is running an animation on behalf of its 1729 * children and should therefore not cancel invalidate requests, even if they 1730 * lie outside of this view's bounds. 1731 * 1732 * {@hide} 1733 */ 1734 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1735 /** {@hide} */ 1736 static final int PFLAG_SKIP_DRAW = 0x00000080; 1737 /** {@hide} */ 1738 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1739 /** {@hide} */ 1740 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1741 /** {@hide} */ 1742 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1743 /** {@hide} */ 1744 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1745 /** {@hide} */ 1746 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1747 1748 private static final int PFLAG_PRESSED = 0x00004000; 1749 1750 /** {@hide} */ 1751 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1752 /** 1753 * Flag used to indicate that this view should be drawn once more (and only once 1754 * more) after its animation has completed. 1755 * {@hide} 1756 */ 1757 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1758 1759 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1760 1761 /** 1762 * Indicates that the View returned true when onSetAlpha() was called and that 1763 * the alpha must be restored. 1764 * {@hide} 1765 */ 1766 static final int PFLAG_ALPHA_SET = 0x00040000; 1767 1768 /** 1769 * Set by {@link #setScrollContainer(boolean)}. 1770 */ 1771 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1772 1773 /** 1774 * Set by {@link #setScrollContainer(boolean)}. 1775 */ 1776 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1777 1778 /** 1779 * View flag indicating whether this view was invalidated (fully or partially.) 1780 * 1781 * @hide 1782 */ 1783 static final int PFLAG_DIRTY = 0x00200000; 1784 1785 /** 1786 * View flag indicating whether this view was invalidated by an opaque 1787 * invalidate request. 1788 * 1789 * @hide 1790 */ 1791 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1792 1793 /** 1794 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1795 * 1796 * @hide 1797 */ 1798 static final int PFLAG_DIRTY_MASK = 0x00600000; 1799 1800 /** 1801 * Indicates whether the background is opaque. 1802 * 1803 * @hide 1804 */ 1805 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1806 1807 /** 1808 * Indicates whether the scrollbars are opaque. 1809 * 1810 * @hide 1811 */ 1812 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1813 1814 /** 1815 * Indicates whether the view is opaque. 1816 * 1817 * @hide 1818 */ 1819 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1820 1821 /** 1822 * Indicates a prepressed state; 1823 * the short time between ACTION_DOWN and recognizing 1824 * a 'real' press. Prepressed is used to recognize quick taps 1825 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1826 * 1827 * @hide 1828 */ 1829 private static final int PFLAG_PREPRESSED = 0x02000000; 1830 1831 /** 1832 * Indicates whether the view is temporarily detached. 1833 * 1834 * @hide 1835 */ 1836 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1837 1838 /** 1839 * Indicates that we should awaken scroll bars once attached 1840 * 1841 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 1842 * during window attachment and it is no longer needed. Feel free to repurpose it. 1843 * 1844 * @hide 1845 */ 1846 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1847 1848 /** 1849 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1850 * @hide 1851 */ 1852 private static final int PFLAG_HOVERED = 0x10000000; 1853 1854 /** 1855 * no longer needed, should be reused 1856 */ 1857 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1858 1859 /** {@hide} */ 1860 static final int PFLAG_ACTIVATED = 0x40000000; 1861 1862 /** 1863 * Indicates that this view was specifically invalidated, not just dirtied because some 1864 * child view was invalidated. The flag is used to determine when we need to recreate 1865 * a view's display list (as opposed to just returning a reference to its existing 1866 * display list). 1867 * 1868 * @hide 1869 */ 1870 static final int PFLAG_INVALIDATED = 0x80000000; 1871 1872 /** 1873 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1874 * 1875 * |-------|-------|-------|-------| 1876 * 1 PFLAG2_DRAG_CAN_ACCEPT 1877 * 1 PFLAG2_DRAG_HOVERED 1878 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1879 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1880 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1881 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1882 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1883 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1884 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1885 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1886 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1887 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 1888 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 1889 * 111 PFLAG2_TEXT_DIRECTION_MASK 1890 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1891 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1892 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1893 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1894 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1895 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1896 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1897 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1898 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1899 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1900 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1901 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1902 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1903 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1904 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1905 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1906 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1907 * 1 PFLAG2_VIEW_QUICK_REJECTED 1908 * 1 PFLAG2_PADDING_RESOLVED 1909 * 1 PFLAG2_DRAWABLE_RESOLVED 1910 * 1 PFLAG2_HAS_TRANSIENT_STATE 1911 * |-------|-------|-------|-------| 1912 */ 1913 1914 /** 1915 * Indicates that this view has reported that it can accept the current drag's content. 1916 * Cleared when the drag operation concludes. 1917 * @hide 1918 */ 1919 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1920 1921 /** 1922 * Indicates that this view is currently directly under the drag location in a 1923 * drag-and-drop operation involving content that it can accept. Cleared when 1924 * the drag exits the view, or when the drag operation concludes. 1925 * @hide 1926 */ 1927 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1928 1929 /** @hide */ 1930 @IntDef({ 1931 LAYOUT_DIRECTION_LTR, 1932 LAYOUT_DIRECTION_RTL, 1933 LAYOUT_DIRECTION_INHERIT, 1934 LAYOUT_DIRECTION_LOCALE 1935 }) 1936 @Retention(RetentionPolicy.SOURCE) 1937 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1938 public @interface LayoutDir {} 1939 1940 /** @hide */ 1941 @IntDef({ 1942 LAYOUT_DIRECTION_LTR, 1943 LAYOUT_DIRECTION_RTL 1944 }) 1945 @Retention(RetentionPolicy.SOURCE) 1946 public @interface ResolvedLayoutDir {} 1947 1948 /** 1949 * A flag to indicate that the layout direction of this view has not been defined yet. 1950 * @hide 1951 */ 1952 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 1953 1954 /** 1955 * Horizontal layout direction of this view is from Left to Right. 1956 * Use with {@link #setLayoutDirection}. 1957 */ 1958 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1959 1960 /** 1961 * Horizontal layout direction of this view is from Right to Left. 1962 * Use with {@link #setLayoutDirection}. 1963 */ 1964 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1965 1966 /** 1967 * Horizontal layout direction of this view is inherited from its parent. 1968 * Use with {@link #setLayoutDirection}. 1969 */ 1970 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1971 1972 /** 1973 * Horizontal layout direction of this view is from deduced from the default language 1974 * script for the locale. Use with {@link #setLayoutDirection}. 1975 */ 1976 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1977 1978 /** 1979 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1980 * @hide 1981 */ 1982 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1983 1984 /** 1985 * Mask for use with private flags indicating bits used for horizontal layout direction. 1986 * @hide 1987 */ 1988 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1989 1990 /** 1991 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1992 * right-to-left direction. 1993 * @hide 1994 */ 1995 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1996 1997 /** 1998 * Indicates whether the view horizontal layout direction has been resolved. 1999 * @hide 2000 */ 2001 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2002 2003 /** 2004 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 2005 * @hide 2006 */ 2007 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 2008 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2009 2010 /* 2011 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 2012 * flag value. 2013 * @hide 2014 */ 2015 private static final int[] LAYOUT_DIRECTION_FLAGS = { 2016 LAYOUT_DIRECTION_LTR, 2017 LAYOUT_DIRECTION_RTL, 2018 LAYOUT_DIRECTION_INHERIT, 2019 LAYOUT_DIRECTION_LOCALE 2020 }; 2021 2022 /** 2023 * Default horizontal layout direction. 2024 */ 2025 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 2026 2027 /** 2028 * Default horizontal layout direction. 2029 * @hide 2030 */ 2031 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 2032 2033 /** 2034 * Text direction is inherited through {@link ViewGroup} 2035 */ 2036 public static final int TEXT_DIRECTION_INHERIT = 0; 2037 2038 /** 2039 * Text direction is using "first strong algorithm". The first strong directional character 2040 * determines the paragraph direction. If there is no strong directional character, the 2041 * paragraph direction is the view's resolved layout direction. 2042 */ 2043 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2044 2045 /** 2046 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2047 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2048 * If there are neither, the paragraph direction is the view's resolved layout direction. 2049 */ 2050 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2051 2052 /** 2053 * Text direction is forced to LTR. 2054 */ 2055 public static final int TEXT_DIRECTION_LTR = 3; 2056 2057 /** 2058 * Text direction is forced to RTL. 2059 */ 2060 public static final int TEXT_DIRECTION_RTL = 4; 2061 2062 /** 2063 * Text direction is coming from the system Locale. 2064 */ 2065 public static final int TEXT_DIRECTION_LOCALE = 5; 2066 2067 /** 2068 * Text direction is using "first strong algorithm". The first strong directional character 2069 * determines the paragraph direction. If there is no strong directional character, the 2070 * paragraph direction is LTR. 2071 */ 2072 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2073 2074 /** 2075 * Text direction is using "first strong algorithm". The first strong directional character 2076 * determines the paragraph direction. If there is no strong directional character, the 2077 * paragraph direction is RTL. 2078 */ 2079 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2080 2081 /** 2082 * Default text direction is inherited 2083 */ 2084 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2085 2086 /** 2087 * Default resolved text direction 2088 * @hide 2089 */ 2090 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2091 2092 /** 2093 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2094 * @hide 2095 */ 2096 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2097 2098 /** 2099 * Mask for use with private flags indicating bits used for text direction. 2100 * @hide 2101 */ 2102 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2103 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2104 2105 /** 2106 * Array of text direction flags for mapping attribute "textDirection" to correct 2107 * flag value. 2108 * @hide 2109 */ 2110 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2111 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2112 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2113 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2114 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2115 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2116 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2117 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2118 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2119 }; 2120 2121 /** 2122 * Indicates whether the view text direction has been resolved. 2123 * @hide 2124 */ 2125 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2126 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2127 2128 /** 2129 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2130 * @hide 2131 */ 2132 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2133 2134 /** 2135 * Mask for use with private flags indicating bits used for resolved text direction. 2136 * @hide 2137 */ 2138 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2139 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2140 2141 /** 2142 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2143 * @hide 2144 */ 2145 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2146 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2147 2148 /** @hide */ 2149 @IntDef({ 2150 TEXT_ALIGNMENT_INHERIT, 2151 TEXT_ALIGNMENT_GRAVITY, 2152 TEXT_ALIGNMENT_CENTER, 2153 TEXT_ALIGNMENT_TEXT_START, 2154 TEXT_ALIGNMENT_TEXT_END, 2155 TEXT_ALIGNMENT_VIEW_START, 2156 TEXT_ALIGNMENT_VIEW_END 2157 }) 2158 @Retention(RetentionPolicy.SOURCE) 2159 public @interface TextAlignment {} 2160 2161 /** 2162 * Default text alignment. The text alignment of this View is inherited from its parent. 2163 * Use with {@link #setTextAlignment(int)} 2164 */ 2165 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2166 2167 /** 2168 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2169 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2170 * 2171 * Use with {@link #setTextAlignment(int)} 2172 */ 2173 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2174 2175 /** 2176 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2177 * 2178 * Use with {@link #setTextAlignment(int)} 2179 */ 2180 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2181 2182 /** 2183 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2184 * 2185 * Use with {@link #setTextAlignment(int)} 2186 */ 2187 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2188 2189 /** 2190 * Center the paragraph, e.g. ALIGN_CENTER. 2191 * 2192 * Use with {@link #setTextAlignment(int)} 2193 */ 2194 public static final int TEXT_ALIGNMENT_CENTER = 4; 2195 2196 /** 2197 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2198 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2199 * 2200 * Use with {@link #setTextAlignment(int)} 2201 */ 2202 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2203 2204 /** 2205 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2206 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2207 * 2208 * Use with {@link #setTextAlignment(int)} 2209 */ 2210 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2211 2212 /** 2213 * Default text alignment is inherited 2214 */ 2215 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2216 2217 /** 2218 * Default resolved text alignment 2219 * @hide 2220 */ 2221 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2222 2223 /** 2224 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2225 * @hide 2226 */ 2227 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2228 2229 /** 2230 * Mask for use with private flags indicating bits used for text alignment. 2231 * @hide 2232 */ 2233 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2234 2235 /** 2236 * Array of text direction flags for mapping attribute "textAlignment" to correct 2237 * flag value. 2238 * @hide 2239 */ 2240 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2241 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2242 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2243 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2244 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2245 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2246 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2247 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2248 }; 2249 2250 /** 2251 * Indicates whether the view text alignment has been resolved. 2252 * @hide 2253 */ 2254 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2255 2256 /** 2257 * Bit shift to get the resolved text alignment. 2258 * @hide 2259 */ 2260 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2261 2262 /** 2263 * Mask for use with private flags indicating bits used for text alignment. 2264 * @hide 2265 */ 2266 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2267 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2268 2269 /** 2270 * Indicates whether if the view text alignment has been resolved to gravity 2271 */ 2272 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2273 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2274 2275 // Accessiblity constants for mPrivateFlags2 2276 2277 /** 2278 * Shift for the bits in {@link #mPrivateFlags2} related to the 2279 * "importantForAccessibility" attribute. 2280 */ 2281 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2282 2283 /** 2284 * Automatically determine whether a view is important for accessibility. 2285 */ 2286 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2287 2288 /** 2289 * The view is important for accessibility. 2290 */ 2291 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2292 2293 /** 2294 * The view is not important for accessibility. 2295 */ 2296 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2297 2298 /** 2299 * The view is not important for accessibility, nor are any of its 2300 * descendant views. 2301 */ 2302 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2303 2304 /** 2305 * The default whether the view is important for accessibility. 2306 */ 2307 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2308 2309 /** 2310 * Mask for obtainig the bits which specify how to determine 2311 * whether a view is important for accessibility. 2312 */ 2313 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2314 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2315 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2316 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2317 2318 /** 2319 * Shift for the bits in {@link #mPrivateFlags2} related to the 2320 * "accessibilityLiveRegion" attribute. 2321 */ 2322 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2323 2324 /** 2325 * Live region mode specifying that accessibility services should not 2326 * automatically announce changes to this view. This is the default live 2327 * region mode for most views. 2328 * <p> 2329 * Use with {@link #setAccessibilityLiveRegion(int)}. 2330 */ 2331 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2332 2333 /** 2334 * Live region mode specifying that accessibility services should announce 2335 * changes to this view. 2336 * <p> 2337 * Use with {@link #setAccessibilityLiveRegion(int)}. 2338 */ 2339 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2340 2341 /** 2342 * Live region mode specifying that accessibility services should interrupt 2343 * ongoing speech to immediately announce changes to this view. 2344 * <p> 2345 * Use with {@link #setAccessibilityLiveRegion(int)}. 2346 */ 2347 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2348 2349 /** 2350 * The default whether the view is important for accessibility. 2351 */ 2352 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2353 2354 /** 2355 * Mask for obtaining the bits which specify a view's accessibility live 2356 * region mode. 2357 */ 2358 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2359 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2360 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2361 2362 /** 2363 * Flag indicating whether a view has accessibility focus. 2364 */ 2365 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2366 2367 /** 2368 * Flag whether the accessibility state of the subtree rooted at this view changed. 2369 */ 2370 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2371 2372 /** 2373 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2374 * is used to check whether later changes to the view's transform should invalidate the 2375 * view to force the quickReject test to run again. 2376 */ 2377 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2378 2379 /** 2380 * Flag indicating that start/end padding has been resolved into left/right padding 2381 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2382 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2383 * during measurement. In some special cases this is required such as when an adapter-based 2384 * view measures prospective children without attaching them to a window. 2385 */ 2386 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2387 2388 /** 2389 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2390 */ 2391 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2392 2393 /** 2394 * Indicates that the view is tracking some sort of transient state 2395 * that the app should not need to be aware of, but that the framework 2396 * should take special care to preserve. 2397 */ 2398 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2399 2400 /** 2401 * Group of bits indicating that RTL properties resolution is done. 2402 */ 2403 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2404 PFLAG2_TEXT_DIRECTION_RESOLVED | 2405 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2406 PFLAG2_PADDING_RESOLVED | 2407 PFLAG2_DRAWABLE_RESOLVED; 2408 2409 // There are a couple of flags left in mPrivateFlags2 2410 2411 /* End of masks for mPrivateFlags2 */ 2412 2413 /** 2414 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2415 * 2416 * |-------|-------|-------|-------| 2417 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2418 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2419 * 1 PFLAG3_IS_LAID_OUT 2420 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2421 * 1 PFLAG3_CALLED_SUPER 2422 * 1 PFLAG3_APPLYING_INSETS 2423 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2424 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2425 * 1 PFLAG3_SCROLL_INDICATOR_TOP 2426 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM 2427 * 1 PFLAG3_SCROLL_INDICATOR_LEFT 2428 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT 2429 * 1 PFLAG3_SCROLL_INDICATOR_START 2430 * 1 PFLAG3_SCROLL_INDICATOR_END 2431 * 1 PFLAG3_ASSIST_BLOCKED 2432 * 1 PFLAG3_POINTER_ICON_NULL 2433 * 1 PFLAG3_POINTER_ICON_VALUE_START 2434 * 11111111 PFLAG3_POINTER_ICON_MASK 2435 * 1 PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE 2436 * 1 PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED 2437 * 1 PFLAG3_TEMPORARY_DETACH 2438 * |-------|-------|-------|-------| 2439 */ 2440 2441 /** 2442 * Flag indicating that view has a transform animation set on it. This is used to track whether 2443 * an animation is cleared between successive frames, in order to tell the associated 2444 * DisplayList to clear its animation matrix. 2445 */ 2446 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2447 2448 /** 2449 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2450 * animation is cleared between successive frames, in order to tell the associated 2451 * DisplayList to restore its alpha value. 2452 */ 2453 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2454 2455 /** 2456 * Flag indicating that the view has been through at least one layout since it 2457 * was last attached to a window. 2458 */ 2459 static final int PFLAG3_IS_LAID_OUT = 0x4; 2460 2461 /** 2462 * Flag indicating that a call to measure() was skipped and should be done 2463 * instead when layout() is invoked. 2464 */ 2465 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2466 2467 /** 2468 * Flag indicating that an overridden method correctly called down to 2469 * the superclass implementation as required by the API spec. 2470 */ 2471 static final int PFLAG3_CALLED_SUPER = 0x10; 2472 2473 /** 2474 * Flag indicating that we're in the process of applying window insets. 2475 */ 2476 static final int PFLAG3_APPLYING_INSETS = 0x20; 2477 2478 /** 2479 * Flag indicating that we're in the process of fitting system windows using the old method. 2480 */ 2481 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2482 2483 /** 2484 * Flag indicating that nested scrolling is enabled for this view. 2485 * The view will optionally cooperate with views up its parent chain to allow for 2486 * integrated nested scrolling along the same axis. 2487 */ 2488 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2489 2490 /** 2491 * Flag indicating that the bottom scroll indicator should be displayed 2492 * when this view can scroll up. 2493 */ 2494 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2495 2496 /** 2497 * Flag indicating that the bottom scroll indicator should be displayed 2498 * when this view can scroll down. 2499 */ 2500 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2501 2502 /** 2503 * Flag indicating that the left scroll indicator should be displayed 2504 * when this view can scroll left. 2505 */ 2506 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2507 2508 /** 2509 * Flag indicating that the right scroll indicator should be displayed 2510 * when this view can scroll right. 2511 */ 2512 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2513 2514 /** 2515 * Flag indicating that the start scroll indicator should be displayed 2516 * when this view can scroll in the start direction. 2517 */ 2518 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2519 2520 /** 2521 * Flag indicating that the end scroll indicator should be displayed 2522 * when this view can scroll in the end direction. 2523 */ 2524 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2525 2526 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2527 2528 static final int SCROLL_INDICATORS_NONE = 0x0000; 2529 2530 /** 2531 * Mask for use with setFlags indicating bits used for indicating which 2532 * scroll indicators are enabled. 2533 */ 2534 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2535 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2536 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2537 | PFLAG3_SCROLL_INDICATOR_END; 2538 2539 /** 2540 * Left-shift required to translate between public scroll indicator flags 2541 * and internal PFLAGS3 flags. When used as a right-shift, translates 2542 * PFLAGS3 flags to public flags. 2543 */ 2544 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2545 2546 /** @hide */ 2547 @Retention(RetentionPolicy.SOURCE) 2548 @IntDef(flag = true, 2549 value = { 2550 SCROLL_INDICATOR_TOP, 2551 SCROLL_INDICATOR_BOTTOM, 2552 SCROLL_INDICATOR_LEFT, 2553 SCROLL_INDICATOR_RIGHT, 2554 SCROLL_INDICATOR_START, 2555 SCROLL_INDICATOR_END, 2556 }) 2557 public @interface ScrollIndicators {} 2558 2559 /** 2560 * Scroll indicator direction for the top edge of the view. 2561 * 2562 * @see #setScrollIndicators(int) 2563 * @see #setScrollIndicators(int, int) 2564 * @see #getScrollIndicators() 2565 */ 2566 public static final int SCROLL_INDICATOR_TOP = 2567 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2568 2569 /** 2570 * Scroll indicator direction for the bottom edge of the view. 2571 * 2572 * @see #setScrollIndicators(int) 2573 * @see #setScrollIndicators(int, int) 2574 * @see #getScrollIndicators() 2575 */ 2576 public static final int SCROLL_INDICATOR_BOTTOM = 2577 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2578 2579 /** 2580 * Scroll indicator direction for the left edge of the view. 2581 * 2582 * @see #setScrollIndicators(int) 2583 * @see #setScrollIndicators(int, int) 2584 * @see #getScrollIndicators() 2585 */ 2586 public static final int SCROLL_INDICATOR_LEFT = 2587 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2588 2589 /** 2590 * Scroll indicator direction for the right edge of the view. 2591 * 2592 * @see #setScrollIndicators(int) 2593 * @see #setScrollIndicators(int, int) 2594 * @see #getScrollIndicators() 2595 */ 2596 public static final int SCROLL_INDICATOR_RIGHT = 2597 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2598 2599 /** 2600 * Scroll indicator direction for the starting edge of the view. 2601 * <p> 2602 * Resolved according to the view's layout direction, see 2603 * {@link #getLayoutDirection()} for more information. 2604 * 2605 * @see #setScrollIndicators(int) 2606 * @see #setScrollIndicators(int, int) 2607 * @see #getScrollIndicators() 2608 */ 2609 public static final int SCROLL_INDICATOR_START = 2610 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2611 2612 /** 2613 * Scroll indicator direction for the ending edge of the view. 2614 * <p> 2615 * Resolved according to the view's layout direction, see 2616 * {@link #getLayoutDirection()} for more information. 2617 * 2618 * @see #setScrollIndicators(int) 2619 * @see #setScrollIndicators(int, int) 2620 * @see #getScrollIndicators() 2621 */ 2622 public static final int SCROLL_INDICATOR_END = 2623 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2624 2625 /** 2626 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2627 * into this view.<p> 2628 */ 2629 static final int PFLAG3_ASSIST_BLOCKED = 0x4000; 2630 2631 /** 2632 * The mask for use with private flags indicating bits used for pointer icon shapes. 2633 */ 2634 static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000; 2635 2636 /** 2637 * Left-shift used for pointer icon shape values in private flags. 2638 */ 2639 static final int PFLAG3_POINTER_ICON_LSHIFT = 15; 2640 2641 /** 2642 * Value indicating no specific pointer icons. 2643 */ 2644 private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT; 2645 2646 /** 2647 * Value indicating {@link PointerIcon.TYPE_NULL}. 2648 */ 2649 private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT; 2650 2651 /** 2652 * The base value for other pointer icon shapes. 2653 */ 2654 private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT; 2655 2656 /** 2657 * Whether this view has rendered elements that overlap (see {@link 2658 * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and 2659 * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when 2660 * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is 2661 * determined by whatever {@link #hasOverlappingRendering()} returns. 2662 */ 2663 private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000; 2664 2665 /** 2666 * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value 2667 * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid. 2668 */ 2669 private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000; 2670 2671 /** 2672 * Flag indicating that the view is temporarily detached from the parent view. 2673 * 2674 * @see #onStartTemporaryDetach() 2675 * @see #onFinishTemporaryDetach() 2676 */ 2677 static final int PFLAG3_TEMPORARY_DETACH = 0x2000000; 2678 2679 /* End of masks for mPrivateFlags3 */ 2680 2681 /** 2682 * Always allow a user to over-scroll this view, provided it is a 2683 * view that can scroll. 2684 * 2685 * @see #getOverScrollMode() 2686 * @see #setOverScrollMode(int) 2687 */ 2688 public static final int OVER_SCROLL_ALWAYS = 0; 2689 2690 /** 2691 * Allow a user to over-scroll this view only if the content is large 2692 * enough to meaningfully scroll, provided it is a view that can scroll. 2693 * 2694 * @see #getOverScrollMode() 2695 * @see #setOverScrollMode(int) 2696 */ 2697 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2698 2699 /** 2700 * Never allow a user to over-scroll this view. 2701 * 2702 * @see #getOverScrollMode() 2703 * @see #setOverScrollMode(int) 2704 */ 2705 public static final int OVER_SCROLL_NEVER = 2; 2706 2707 /** 2708 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2709 * requested the system UI (status bar) to be visible (the default). 2710 * 2711 * @see #setSystemUiVisibility(int) 2712 */ 2713 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2714 2715 /** 2716 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2717 * system UI to enter an unobtrusive "low profile" mode. 2718 * 2719 * <p>This is for use in games, book readers, video players, or any other 2720 * "immersive" application where the usual system chrome is deemed too distracting. 2721 * 2722 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2723 * 2724 * @see #setSystemUiVisibility(int) 2725 */ 2726 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2727 2728 /** 2729 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2730 * system navigation be temporarily hidden. 2731 * 2732 * <p>This is an even less obtrusive state than that called for by 2733 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2734 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2735 * those to disappear. This is useful (in conjunction with the 2736 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2737 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2738 * window flags) for displaying content using every last pixel on the display. 2739 * 2740 * <p>There is a limitation: because navigation controls are so important, the least user 2741 * interaction will cause them to reappear immediately. When this happens, both 2742 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2743 * so that both elements reappear at the same time. 2744 * 2745 * @see #setSystemUiVisibility(int) 2746 */ 2747 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2748 2749 /** 2750 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2751 * into the normal fullscreen mode so that its content can take over the screen 2752 * while still allowing the user to interact with the application. 2753 * 2754 * <p>This has the same visual effect as 2755 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2756 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2757 * meaning that non-critical screen decorations (such as the status bar) will be 2758 * hidden while the user is in the View's window, focusing the experience on 2759 * that content. Unlike the window flag, if you are using ActionBar in 2760 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2761 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2762 * hide the action bar. 2763 * 2764 * <p>This approach to going fullscreen is best used over the window flag when 2765 * it is a transient state -- that is, the application does this at certain 2766 * points in its user interaction where it wants to allow the user to focus 2767 * on content, but not as a continuous state. For situations where the application 2768 * would like to simply stay full screen the entire time (such as a game that 2769 * wants to take over the screen), the 2770 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2771 * is usually a better approach. The state set here will be removed by the system 2772 * in various situations (such as the user moving to another application) like 2773 * the other system UI states. 2774 * 2775 * <p>When using this flag, the application should provide some easy facility 2776 * for the user to go out of it. A common example would be in an e-book 2777 * reader, where tapping on the screen brings back whatever screen and UI 2778 * decorations that had been hidden while the user was immersed in reading 2779 * the book. 2780 * 2781 * @see #setSystemUiVisibility(int) 2782 */ 2783 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2784 2785 /** 2786 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2787 * flags, we would like a stable view of the content insets given to 2788 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2789 * will always represent the worst case that the application can expect 2790 * as a continuous state. In the stock Android UI this is the space for 2791 * the system bar, nav bar, and status bar, but not more transient elements 2792 * such as an input method. 2793 * 2794 * The stable layout your UI sees is based on the system UI modes you can 2795 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2796 * then you will get a stable layout for changes of the 2797 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2798 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2799 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2800 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2801 * with a stable layout. (Note that you should avoid using 2802 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2803 * 2804 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2805 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2806 * then a hidden status bar will be considered a "stable" state for purposes 2807 * here. This allows your UI to continually hide the status bar, while still 2808 * using the system UI flags to hide the action bar while still retaining 2809 * a stable layout. Note that changing the window fullscreen flag will never 2810 * provide a stable layout for a clean transition. 2811 * 2812 * <p>If you are using ActionBar in 2813 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2814 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2815 * insets it adds to those given to the application. 2816 */ 2817 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2818 2819 /** 2820 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2821 * to be laid out as if it has requested 2822 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2823 * allows it to avoid artifacts when switching in and out of that mode, at 2824 * the expense that some of its user interface may be covered by screen 2825 * decorations when they are shown. You can perform layout of your inner 2826 * UI elements to account for the navigation system UI through the 2827 * {@link #fitSystemWindows(Rect)} method. 2828 */ 2829 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2830 2831 /** 2832 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2833 * to be laid out as if it has requested 2834 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2835 * allows it to avoid artifacts when switching in and out of that mode, at 2836 * the expense that some of its user interface may be covered by screen 2837 * decorations when they are shown. You can perform layout of your inner 2838 * UI elements to account for non-fullscreen system UI through the 2839 * {@link #fitSystemWindows(Rect)} method. 2840 */ 2841 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2842 2843 /** 2844 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2845 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2846 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2847 * user interaction. 2848 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2849 * has an effect when used in combination with that flag.</p> 2850 */ 2851 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2852 2853 /** 2854 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2855 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2856 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2857 * experience while also hiding the system bars. If this flag is not set, 2858 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2859 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2860 * if the user swipes from the top of the screen. 2861 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2862 * system gestures, such as swiping from the top of the screen. These transient system bars 2863 * will overlay app’s content, may have some degree of transparency, and will automatically 2864 * hide after a short timeout. 2865 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2866 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2867 * with one or both of those flags.</p> 2868 */ 2869 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2870 2871 /** 2872 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2873 * is compatible with light status bar backgrounds. 2874 * 2875 * <p>For this to take effect, the window must request 2876 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2877 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2878 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2879 * FLAG_TRANSLUCENT_STATUS}. 2880 * 2881 * @see android.R.attr#windowLightStatusBar 2882 */ 2883 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2884 2885 /** 2886 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2887 */ 2888 @Deprecated 2889 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2890 2891 /** 2892 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2893 */ 2894 @Deprecated 2895 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2896 2897 /** 2898 * @hide 2899 * 2900 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2901 * out of the public fields to keep the undefined bits out of the developer's way. 2902 * 2903 * Flag to make the status bar not expandable. Unless you also 2904 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2905 */ 2906 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2907 2908 /** 2909 * @hide 2910 * 2911 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2912 * out of the public fields to keep the undefined bits out of the developer's way. 2913 * 2914 * Flag to hide notification icons and scrolling ticker text. 2915 */ 2916 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2917 2918 /** 2919 * @hide 2920 * 2921 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2922 * out of the public fields to keep the undefined bits out of the developer's way. 2923 * 2924 * Flag to disable incoming notification alerts. This will not block 2925 * icons, but it will block sound, vibrating and other visual or aural notifications. 2926 */ 2927 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2928 2929 /** 2930 * @hide 2931 * 2932 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2933 * out of the public fields to keep the undefined bits out of the developer's way. 2934 * 2935 * Flag to hide only the scrolling ticker. Note that 2936 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2937 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2938 */ 2939 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2940 2941 /** 2942 * @hide 2943 * 2944 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2945 * out of the public fields to keep the undefined bits out of the developer's way. 2946 * 2947 * Flag to hide the center system info area. 2948 */ 2949 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2950 2951 /** 2952 * @hide 2953 * 2954 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2955 * out of the public fields to keep the undefined bits out of the developer's way. 2956 * 2957 * Flag to hide only the home button. Don't use this 2958 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2959 */ 2960 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2961 2962 /** 2963 * @hide 2964 * 2965 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2966 * out of the public fields to keep the undefined bits out of the developer's way. 2967 * 2968 * Flag to hide only the back button. Don't use this 2969 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2970 */ 2971 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2972 2973 /** 2974 * @hide 2975 * 2976 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2977 * out of the public fields to keep the undefined bits out of the developer's way. 2978 * 2979 * Flag to hide only the clock. You might use this if your activity has 2980 * its own clock making the status bar's clock redundant. 2981 */ 2982 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2983 2984 /** 2985 * @hide 2986 * 2987 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2988 * out of the public fields to keep the undefined bits out of the developer's way. 2989 * 2990 * Flag to hide only the recent apps button. Don't use this 2991 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2992 */ 2993 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2994 2995 /** 2996 * @hide 2997 * 2998 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2999 * out of the public fields to keep the undefined bits out of the developer's way. 3000 * 3001 * Flag to disable the global search gesture. Don't use this 3002 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3003 */ 3004 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 3005 3006 /** 3007 * @hide 3008 * 3009 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3010 * out of the public fields to keep the undefined bits out of the developer's way. 3011 * 3012 * Flag to specify that the status bar is displayed in transient mode. 3013 */ 3014 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 3015 3016 /** 3017 * @hide 3018 * 3019 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3020 * out of the public fields to keep the undefined bits out of the developer's way. 3021 * 3022 * Flag to specify that the navigation bar is displayed in transient mode. 3023 */ 3024 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 3025 3026 /** 3027 * @hide 3028 * 3029 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3030 * out of the public fields to keep the undefined bits out of the developer's way. 3031 * 3032 * Flag to specify that the hidden status bar would like to be shown. 3033 */ 3034 public static final int STATUS_BAR_UNHIDE = 0x10000000; 3035 3036 /** 3037 * @hide 3038 * 3039 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3040 * out of the public fields to keep the undefined bits out of the developer's way. 3041 * 3042 * Flag to specify that the hidden navigation bar would like to be shown. 3043 */ 3044 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 3045 3046 /** 3047 * @hide 3048 * 3049 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3050 * out of the public fields to keep the undefined bits out of the developer's way. 3051 * 3052 * Flag to specify that the status bar is displayed in translucent mode. 3053 */ 3054 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 3055 3056 /** 3057 * @hide 3058 * 3059 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3060 * out of the public fields to keep the undefined bits out of the developer's way. 3061 * 3062 * Flag to specify that the navigation bar is displayed in translucent mode. 3063 */ 3064 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 3065 3066 /** 3067 * @hide 3068 * 3069 * Whether Recents is visible or not. 3070 */ 3071 public static final int RECENT_APPS_VISIBLE = 0x00004000; 3072 3073 /** 3074 * @hide 3075 * 3076 * Whether the TV's picture-in-picture is visible or not. 3077 */ 3078 public static final int TV_PICTURE_IN_PICTURE_VISIBLE = 0x00010000; 3079 3080 /** 3081 * @hide 3082 * 3083 * Makes navigation bar transparent (but not the status bar). 3084 */ 3085 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3086 3087 /** 3088 * @hide 3089 * 3090 * Makes status bar transparent (but not the navigation bar). 3091 */ 3092 public static final int STATUS_BAR_TRANSPARENT = 0x0000008; 3093 3094 /** 3095 * @hide 3096 * 3097 * Makes both status bar and navigation bar transparent. 3098 */ 3099 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3100 | STATUS_BAR_TRANSPARENT; 3101 3102 /** 3103 * @hide 3104 */ 3105 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3106 3107 /** 3108 * These are the system UI flags that can be cleared by events outside 3109 * of an application. Currently this is just the ability to tap on the 3110 * screen while hiding the navigation bar to have it return. 3111 * @hide 3112 */ 3113 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3114 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3115 | SYSTEM_UI_FLAG_FULLSCREEN; 3116 3117 /** 3118 * Flags that can impact the layout in relation to system UI. 3119 */ 3120 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3121 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3122 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3123 3124 /** @hide */ 3125 @IntDef(flag = true, 3126 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 3127 @Retention(RetentionPolicy.SOURCE) 3128 public @interface FindViewFlags {} 3129 3130 /** 3131 * Find views that render the specified text. 3132 * 3133 * @see #findViewsWithText(ArrayList, CharSequence, int) 3134 */ 3135 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3136 3137 /** 3138 * Find find views that contain the specified content description. 3139 * 3140 * @see #findViewsWithText(ArrayList, CharSequence, int) 3141 */ 3142 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3143 3144 /** 3145 * Find views that contain {@link AccessibilityNodeProvider}. Such 3146 * a View is a root of virtual view hierarchy and may contain the searched 3147 * text. If this flag is set Views with providers are automatically 3148 * added and it is a responsibility of the client to call the APIs of 3149 * the provider to determine whether the virtual tree rooted at this View 3150 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3151 * representing the virtual views with this text. 3152 * 3153 * @see #findViewsWithText(ArrayList, CharSequence, int) 3154 * 3155 * @hide 3156 */ 3157 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3158 3159 /** 3160 * The undefined cursor position. 3161 * 3162 * @hide 3163 */ 3164 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3165 3166 /** 3167 * Indicates that the screen has changed state and is now off. 3168 * 3169 * @see #onScreenStateChanged(int) 3170 */ 3171 public static final int SCREEN_STATE_OFF = 0x0; 3172 3173 /** 3174 * Indicates that the screen has changed state and is now on. 3175 * 3176 * @see #onScreenStateChanged(int) 3177 */ 3178 public static final int SCREEN_STATE_ON = 0x1; 3179 3180 /** 3181 * Indicates no axis of view scrolling. 3182 */ 3183 public static final int SCROLL_AXIS_NONE = 0; 3184 3185 /** 3186 * Indicates scrolling along the horizontal axis. 3187 */ 3188 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3189 3190 /** 3191 * Indicates scrolling along the vertical axis. 3192 */ 3193 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3194 3195 /** 3196 * Controls the over-scroll mode for this view. 3197 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3198 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3199 * and {@link #OVER_SCROLL_NEVER}. 3200 */ 3201 private int mOverScrollMode; 3202 3203 /** 3204 * The parent this view is attached to. 3205 * {@hide} 3206 * 3207 * @see #getParent() 3208 */ 3209 protected ViewParent mParent; 3210 3211 /** 3212 * {@hide} 3213 */ 3214 AttachInfo mAttachInfo; 3215 3216 /** 3217 * {@hide} 3218 */ 3219 @ViewDebug.ExportedProperty(flagMapping = { 3220 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3221 name = "FORCE_LAYOUT"), 3222 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3223 name = "LAYOUT_REQUIRED"), 3224 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3225 name = "DRAWING_CACHE_INVALID", outputIf = false), 3226 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3227 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3228 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3229 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3230 }, formatToHexString = true) 3231 int mPrivateFlags; 3232 int mPrivateFlags2; 3233 int mPrivateFlags3; 3234 3235 /** 3236 * This view's request for the visibility of the status bar. 3237 * @hide 3238 */ 3239 @ViewDebug.ExportedProperty(flagMapping = { 3240 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3241 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3242 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3243 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3244 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3245 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3246 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3247 equals = SYSTEM_UI_FLAG_VISIBLE, 3248 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3249 }, formatToHexString = true) 3250 int mSystemUiVisibility; 3251 3252 /** 3253 * Reference count for transient state. 3254 * @see #setHasTransientState(boolean) 3255 */ 3256 int mTransientStateCount = 0; 3257 3258 /** 3259 * Count of how many windows this view has been attached to. 3260 */ 3261 int mWindowAttachCount; 3262 3263 /** 3264 * The layout parameters associated with this view and used by the parent 3265 * {@link android.view.ViewGroup} to determine how this view should be 3266 * laid out. 3267 * {@hide} 3268 */ 3269 protected ViewGroup.LayoutParams mLayoutParams; 3270 3271 /** 3272 * The view flags hold various views states. 3273 * {@hide} 3274 */ 3275 @ViewDebug.ExportedProperty(formatToHexString = true) 3276 int mViewFlags; 3277 3278 static class TransformationInfo { 3279 /** 3280 * The transform matrix for the View. This transform is calculated internally 3281 * based on the translation, rotation, and scale properties. 3282 * 3283 * Do *not* use this variable directly; instead call getMatrix(), which will 3284 * load the value from the View's RenderNode. 3285 */ 3286 private final Matrix mMatrix = new Matrix(); 3287 3288 /** 3289 * The inverse transform matrix for the View. This transform is calculated 3290 * internally based on the translation, rotation, and scale properties. 3291 * 3292 * Do *not* use this variable directly; instead call getInverseMatrix(), 3293 * which will load the value from the View's RenderNode. 3294 */ 3295 private Matrix mInverseMatrix; 3296 3297 /** 3298 * The opacity of the View. This is a value from 0 to 1, where 0 means 3299 * completely transparent and 1 means completely opaque. 3300 */ 3301 @ViewDebug.ExportedProperty 3302 float mAlpha = 1f; 3303 3304 /** 3305 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3306 * property only used by transitions, which is composited with the other alpha 3307 * values to calculate the final visual alpha value. 3308 */ 3309 float mTransitionAlpha = 1f; 3310 } 3311 3312 TransformationInfo mTransformationInfo; 3313 3314 /** 3315 * Current clip bounds. to which all drawing of this view are constrained. 3316 */ 3317 Rect mClipBounds = null; 3318 3319 private boolean mLastIsOpaque; 3320 3321 /** 3322 * The distance in pixels from the left edge of this view's parent 3323 * to the left edge of this view. 3324 * {@hide} 3325 */ 3326 @ViewDebug.ExportedProperty(category = "layout") 3327 protected int mLeft; 3328 /** 3329 * The distance in pixels from the left edge of this view's parent 3330 * to the right edge of this view. 3331 * {@hide} 3332 */ 3333 @ViewDebug.ExportedProperty(category = "layout") 3334 protected int mRight; 3335 /** 3336 * The distance in pixels from the top edge of this view's parent 3337 * to the top edge of this view. 3338 * {@hide} 3339 */ 3340 @ViewDebug.ExportedProperty(category = "layout") 3341 protected int mTop; 3342 /** 3343 * The distance in pixels from the top edge of this view's parent 3344 * to the bottom edge of this view. 3345 * {@hide} 3346 */ 3347 @ViewDebug.ExportedProperty(category = "layout") 3348 protected int mBottom; 3349 3350 /** 3351 * The offset, in pixels, by which the content of this view is scrolled 3352 * horizontally. 3353 * {@hide} 3354 */ 3355 @ViewDebug.ExportedProperty(category = "scrolling") 3356 protected int mScrollX; 3357 /** 3358 * The offset, in pixels, by which the content of this view is scrolled 3359 * vertically. 3360 * {@hide} 3361 */ 3362 @ViewDebug.ExportedProperty(category = "scrolling") 3363 protected int mScrollY; 3364 3365 /** 3366 * The left padding in pixels, that is the distance in pixels between the 3367 * left edge of this view and the left edge of its content. 3368 * {@hide} 3369 */ 3370 @ViewDebug.ExportedProperty(category = "padding") 3371 protected int mPaddingLeft = 0; 3372 /** 3373 * The right padding in pixels, that is the distance in pixels between the 3374 * right edge of this view and the right edge of its content. 3375 * {@hide} 3376 */ 3377 @ViewDebug.ExportedProperty(category = "padding") 3378 protected int mPaddingRight = 0; 3379 /** 3380 * The top padding in pixels, that is the distance in pixels between the 3381 * top edge of this view and the top edge of its content. 3382 * {@hide} 3383 */ 3384 @ViewDebug.ExportedProperty(category = "padding") 3385 protected int mPaddingTop; 3386 /** 3387 * The bottom padding in pixels, that is the distance in pixels between the 3388 * bottom edge of this view and the bottom edge of its content. 3389 * {@hide} 3390 */ 3391 @ViewDebug.ExportedProperty(category = "padding") 3392 protected int mPaddingBottom; 3393 3394 /** 3395 * The layout insets in pixels, that is the distance in pixels between the 3396 * visible edges of this view its bounds. 3397 */ 3398 private Insets mLayoutInsets; 3399 3400 /** 3401 * Briefly describes the view and is primarily used for accessibility support. 3402 */ 3403 private CharSequence mContentDescription; 3404 3405 /** 3406 * Specifies the id of a view for which this view serves as a label for 3407 * accessibility purposes. 3408 */ 3409 private int mLabelForId = View.NO_ID; 3410 3411 /** 3412 * Predicate for matching labeled view id with its label for 3413 * accessibility purposes. 3414 */ 3415 private MatchLabelForPredicate mMatchLabelForPredicate; 3416 3417 /** 3418 * Specifies a view before which this one is visited in accessibility traversal. 3419 */ 3420 private int mAccessibilityTraversalBeforeId = NO_ID; 3421 3422 /** 3423 * Specifies a view after which this one is visited in accessibility traversal. 3424 */ 3425 private int mAccessibilityTraversalAfterId = NO_ID; 3426 3427 /** 3428 * Predicate for matching a view by its id. 3429 */ 3430 private MatchIdPredicate mMatchIdPredicate; 3431 3432 /** 3433 * Cache the paddingRight set by the user to append to the scrollbar's size. 3434 * 3435 * @hide 3436 */ 3437 @ViewDebug.ExportedProperty(category = "padding") 3438 protected int mUserPaddingRight; 3439 3440 /** 3441 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3442 * 3443 * @hide 3444 */ 3445 @ViewDebug.ExportedProperty(category = "padding") 3446 protected int mUserPaddingBottom; 3447 3448 /** 3449 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3450 * 3451 * @hide 3452 */ 3453 @ViewDebug.ExportedProperty(category = "padding") 3454 protected int mUserPaddingLeft; 3455 3456 /** 3457 * Cache the paddingStart set by the user to append to the scrollbar's size. 3458 * 3459 */ 3460 @ViewDebug.ExportedProperty(category = "padding") 3461 int mUserPaddingStart; 3462 3463 /** 3464 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3465 * 3466 */ 3467 @ViewDebug.ExportedProperty(category = "padding") 3468 int mUserPaddingEnd; 3469 3470 /** 3471 * Cache initial left padding. 3472 * 3473 * @hide 3474 */ 3475 int mUserPaddingLeftInitial; 3476 3477 /** 3478 * Cache initial right padding. 3479 * 3480 * @hide 3481 */ 3482 int mUserPaddingRightInitial; 3483 3484 /** 3485 * Default undefined padding 3486 */ 3487 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3488 3489 /** 3490 * Cache if a left padding has been defined 3491 */ 3492 private boolean mLeftPaddingDefined = false; 3493 3494 /** 3495 * Cache if a right padding has been defined 3496 */ 3497 private boolean mRightPaddingDefined = false; 3498 3499 /** 3500 * @hide 3501 */ 3502 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3503 /** 3504 * @hide 3505 */ 3506 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3507 3508 private LongSparseLongArray mMeasureCache; 3509 3510 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3511 private Drawable mBackground; 3512 private TintInfo mBackgroundTint; 3513 3514 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3515 private ForegroundInfo mForegroundInfo; 3516 3517 private Drawable mScrollIndicatorDrawable; 3518 3519 /** 3520 * RenderNode used for backgrounds. 3521 * <p> 3522 * When non-null and valid, this is expected to contain an up-to-date copy 3523 * of the background drawable. It is cleared on temporary detach, and reset 3524 * on cleanup. 3525 */ 3526 private RenderNode mBackgroundRenderNode; 3527 3528 private int mBackgroundResource; 3529 private boolean mBackgroundSizeChanged; 3530 3531 private String mTransitionName; 3532 3533 static class TintInfo { 3534 ColorStateList mTintList; 3535 PorterDuff.Mode mTintMode; 3536 boolean mHasTintMode; 3537 boolean mHasTintList; 3538 } 3539 3540 private static class ForegroundInfo { 3541 private Drawable mDrawable; 3542 private TintInfo mTintInfo; 3543 private int mGravity = Gravity.FILL; 3544 private boolean mInsidePadding = true; 3545 private boolean mBoundsChanged = true; 3546 private final Rect mSelfBounds = new Rect(); 3547 private final Rect mOverlayBounds = new Rect(); 3548 } 3549 3550 static class ListenerInfo { 3551 /** 3552 * Listener used to dispatch focus change events. 3553 * This field should be made private, so it is hidden from the SDK. 3554 * {@hide} 3555 */ 3556 protected OnFocusChangeListener mOnFocusChangeListener; 3557 3558 /** 3559 * Listeners for layout change events. 3560 */ 3561 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3562 3563 protected OnScrollChangeListener mOnScrollChangeListener; 3564 3565 /** 3566 * Listeners for attach events. 3567 */ 3568 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3569 3570 /** 3571 * Listener used to dispatch click events. 3572 * This field should be made private, so it is hidden from the SDK. 3573 * {@hide} 3574 */ 3575 public OnClickListener mOnClickListener; 3576 3577 /** 3578 * Listener used to dispatch long click events. 3579 * This field should be made private, so it is hidden from the SDK. 3580 * {@hide} 3581 */ 3582 protected OnLongClickListener mOnLongClickListener; 3583 3584 /** 3585 * Listener used to dispatch context click events. This field should be made private, so it 3586 * is hidden from the SDK. 3587 * {@hide} 3588 */ 3589 protected OnContextClickListener mOnContextClickListener; 3590 3591 /** 3592 * Listener used to build the context menu. 3593 * This field should be made private, so it is hidden from the SDK. 3594 * {@hide} 3595 */ 3596 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3597 3598 private OnKeyListener mOnKeyListener; 3599 3600 private OnTouchListener mOnTouchListener; 3601 3602 private OnHoverListener mOnHoverListener; 3603 3604 private OnGenericMotionListener mOnGenericMotionListener; 3605 3606 private OnDragListener mOnDragListener; 3607 3608 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3609 3610 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3611 } 3612 3613 ListenerInfo mListenerInfo; 3614 3615 // Temporary values used to hold (x,y) coordinates when delegating from the 3616 // two-arg performLongClick() method to the legacy no-arg version. 3617 private float mLongClickX = Float.NaN; 3618 private float mLongClickY = Float.NaN; 3619 3620 /** 3621 * The application environment this view lives in. 3622 * This field should be made private, so it is hidden from the SDK. 3623 * {@hide} 3624 */ 3625 @ViewDebug.ExportedProperty(deepExport = true) 3626 protected Context mContext; 3627 3628 private final Resources mResources; 3629 3630 private ScrollabilityCache mScrollCache; 3631 3632 private int[] mDrawableState = null; 3633 3634 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3635 3636 /** 3637 * Animator that automatically runs based on state changes. 3638 */ 3639 private StateListAnimator mStateListAnimator; 3640 3641 /** 3642 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3643 * the user may specify which view to go to next. 3644 */ 3645 private int mNextFocusLeftId = View.NO_ID; 3646 3647 /** 3648 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3649 * the user may specify which view to go to next. 3650 */ 3651 private int mNextFocusRightId = View.NO_ID; 3652 3653 /** 3654 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3655 * the user may specify which view to go to next. 3656 */ 3657 private int mNextFocusUpId = View.NO_ID; 3658 3659 /** 3660 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3661 * the user may specify which view to go to next. 3662 */ 3663 private int mNextFocusDownId = View.NO_ID; 3664 3665 /** 3666 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3667 * the user may specify which view to go to next. 3668 */ 3669 int mNextFocusForwardId = View.NO_ID; 3670 3671 private CheckForLongPress mPendingCheckForLongPress; 3672 private CheckForTap mPendingCheckForTap = null; 3673 private PerformClick mPerformClick; 3674 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3675 3676 private UnsetPressedState mUnsetPressedState; 3677 3678 /** 3679 * Whether the long press's action has been invoked. The tap's action is invoked on the 3680 * up event while a long press is invoked as soon as the long press duration is reached, so 3681 * a long press could be performed before the tap is checked, in which case the tap's action 3682 * should not be invoked. 3683 */ 3684 private boolean mHasPerformedLongPress; 3685 3686 /** 3687 * Whether a context click button is currently pressed down. This is true when the stylus is 3688 * touching the screen and the primary button has been pressed, or if a mouse's right button is 3689 * pressed. This is false once the button is released or if the stylus has been lifted. 3690 */ 3691 private boolean mInContextButtonPress; 3692 3693 /** 3694 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 3695 * true after a stylus button press has occured, when the next up event should not be recognized 3696 * as a tap. 3697 */ 3698 private boolean mIgnoreNextUpEvent; 3699 3700 /** 3701 * The minimum height of the view. We'll try our best to have the height 3702 * of this view to at least this amount. 3703 */ 3704 @ViewDebug.ExportedProperty(category = "measurement") 3705 private int mMinHeight; 3706 3707 /** 3708 * The minimum width of the view. We'll try our best to have the width 3709 * of this view to at least this amount. 3710 */ 3711 @ViewDebug.ExportedProperty(category = "measurement") 3712 private int mMinWidth; 3713 3714 /** 3715 * The delegate to handle touch events that are physically in this view 3716 * but should be handled by another view. 3717 */ 3718 private TouchDelegate mTouchDelegate = null; 3719 3720 /** 3721 * Solid color to use as a background when creating the drawing cache. Enables 3722 * the cache to use 16 bit bitmaps instead of 32 bit. 3723 */ 3724 private int mDrawingCacheBackgroundColor = 0; 3725 3726 /** 3727 * Special tree observer used when mAttachInfo is null. 3728 */ 3729 private ViewTreeObserver mFloatingTreeObserver; 3730 3731 /** 3732 * Cache the touch slop from the context that created the view. 3733 */ 3734 private int mTouchSlop; 3735 3736 /** 3737 * Object that handles automatic animation of view properties. 3738 */ 3739 private ViewPropertyAnimator mAnimator = null; 3740 3741 /** 3742 * List of registered FrameMetricsObservers. 3743 */ 3744 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 3745 3746 /** 3747 * Flag indicating that a drag can cross window boundaries. When 3748 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3749 * with this flag set, all visible applications will be able to participate 3750 * in the drag operation and receive the dragged content. 3751 * 3752 * If this is the only flag set, then the drag recipient will only have access to text data 3753 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 3754 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags. 3755 */ 3756 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 3757 3758 /** 3759 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3760 * request read access to the content URI(s) contained in the {@link ClipData} object. 3761 * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION 3762 */ 3763 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 3764 3765 /** 3766 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3767 * request write access to the content URI(s) contained in the {@link ClipData} object. 3768 * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION 3769 */ 3770 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 3771 3772 /** 3773 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3774 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 3775 * reboots until explicitly revoked with 3776 * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}. 3777 * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 3778 */ 3779 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 3780 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 3781 3782 /** 3783 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3784 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix 3785 * match against the original granted URI. 3786 * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION 3787 */ 3788 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 3789 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 3790 3791 /** 3792 * Flag indicating that the drag shadow will be opaque. When 3793 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3794 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 3795 */ 3796 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 3797 3798 /** 3799 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3800 */ 3801 private float mVerticalScrollFactor; 3802 3803 /** 3804 * Position of the vertical scroll bar. 3805 */ 3806 private int mVerticalScrollbarPosition; 3807 3808 /** 3809 * Position the scroll bar at the default position as determined by the system. 3810 */ 3811 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3812 3813 /** 3814 * Position the scroll bar along the left edge. 3815 */ 3816 public static final int SCROLLBAR_POSITION_LEFT = 1; 3817 3818 /** 3819 * Position the scroll bar along the right edge. 3820 */ 3821 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3822 3823 /** 3824 * Indicates that the view does not have a layer. 3825 * 3826 * @see #getLayerType() 3827 * @see #setLayerType(int, android.graphics.Paint) 3828 * @see #LAYER_TYPE_SOFTWARE 3829 * @see #LAYER_TYPE_HARDWARE 3830 */ 3831 public static final int LAYER_TYPE_NONE = 0; 3832 3833 /** 3834 * <p>Indicates that the view has a software layer. A software layer is backed 3835 * by a bitmap and causes the view to be rendered using Android's software 3836 * rendering pipeline, even if hardware acceleration is enabled.</p> 3837 * 3838 * <p>Software layers have various usages:</p> 3839 * <p>When the application is not using hardware acceleration, a software layer 3840 * is useful to apply a specific color filter and/or blending mode and/or 3841 * translucency to a view and all its children.</p> 3842 * <p>When the application is using hardware acceleration, a software layer 3843 * is useful to render drawing primitives not supported by the hardware 3844 * accelerated pipeline. It can also be used to cache a complex view tree 3845 * into a texture and reduce the complexity of drawing operations. For instance, 3846 * when animating a complex view tree with a translation, a software layer can 3847 * be used to render the view tree only once.</p> 3848 * <p>Software layers should be avoided when the affected view tree updates 3849 * often. Every update will require to re-render the software layer, which can 3850 * potentially be slow (particularly when hardware acceleration is turned on 3851 * since the layer will have to be uploaded into a hardware texture after every 3852 * update.)</p> 3853 * 3854 * @see #getLayerType() 3855 * @see #setLayerType(int, android.graphics.Paint) 3856 * @see #LAYER_TYPE_NONE 3857 * @see #LAYER_TYPE_HARDWARE 3858 */ 3859 public static final int LAYER_TYPE_SOFTWARE = 1; 3860 3861 /** 3862 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3863 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3864 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3865 * rendering pipeline, but only if hardware acceleration is turned on for the 3866 * view hierarchy. When hardware acceleration is turned off, hardware layers 3867 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3868 * 3869 * <p>A hardware layer is useful to apply a specific color filter and/or 3870 * blending mode and/or translucency to a view and all its children.</p> 3871 * <p>A hardware layer can be used to cache a complex view tree into a 3872 * texture and reduce the complexity of drawing operations. For instance, 3873 * when animating a complex view tree with a translation, a hardware layer can 3874 * be used to render the view tree only once.</p> 3875 * <p>A hardware layer can also be used to increase the rendering quality when 3876 * rotation transformations are applied on a view. It can also be used to 3877 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3878 * 3879 * @see #getLayerType() 3880 * @see #setLayerType(int, android.graphics.Paint) 3881 * @see #LAYER_TYPE_NONE 3882 * @see #LAYER_TYPE_SOFTWARE 3883 */ 3884 public static final int LAYER_TYPE_HARDWARE = 2; 3885 3886 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3887 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3888 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3889 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3890 }) 3891 int mLayerType = LAYER_TYPE_NONE; 3892 Paint mLayerPaint; 3893 3894 /** 3895 * Set to true when drawing cache is enabled and cannot be created. 3896 * 3897 * @hide 3898 */ 3899 public boolean mCachingFailed; 3900 private Bitmap mDrawingCache; 3901 private Bitmap mUnscaledDrawingCache; 3902 3903 /** 3904 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3905 * <p> 3906 * When non-null and valid, this is expected to contain an up-to-date copy 3907 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3908 * cleanup. 3909 */ 3910 final RenderNode mRenderNode; 3911 3912 /** 3913 * Set to true when the view is sending hover accessibility events because it 3914 * is the innermost hovered view. 3915 */ 3916 private boolean mSendingHoverAccessibilityEvents; 3917 3918 /** 3919 * Delegate for injecting accessibility functionality. 3920 */ 3921 AccessibilityDelegate mAccessibilityDelegate; 3922 3923 /** 3924 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3925 * and add/remove objects to/from the overlay directly through the Overlay methods. 3926 */ 3927 ViewOverlay mOverlay; 3928 3929 /** 3930 * The currently active parent view for receiving delegated nested scrolling events. 3931 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3932 * by {@link #stopNestedScroll()} at the same point where we clear 3933 * requestDisallowInterceptTouchEvent. 3934 */ 3935 private ViewParent mNestedScrollingParent; 3936 3937 /** 3938 * Consistency verifier for debugging purposes. 3939 * @hide 3940 */ 3941 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3942 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3943 new InputEventConsistencyVerifier(this, 0) : null; 3944 3945 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3946 3947 private int[] mTempNestedScrollConsumed; 3948 3949 /** 3950 * An overlay is going to draw this View instead of being drawn as part of this 3951 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3952 * when this view is invalidated. 3953 */ 3954 GhostView mGhostView; 3955 3956 /** 3957 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3958 * @hide 3959 */ 3960 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3961 public String[] mAttributes; 3962 3963 /** 3964 * Maps a Resource id to its name. 3965 */ 3966 private static SparseArray<String> mAttributeMap; 3967 3968 /** 3969 * Queue of pending runnables. Used to postpone calls to post() until this 3970 * view is attached and has a handler. 3971 */ 3972 private HandlerActionQueue mRunQueue; 3973 3974 /** 3975 * The pointer icon when the mouse hovers on this view. The default is null. 3976 */ 3977 private PointerIcon mPointerIcon; 3978 3979 /** 3980 * @hide 3981 */ 3982 String mStartActivityRequestWho; 3983 3984 /** 3985 * Simple constructor to use when creating a view from code. 3986 * 3987 * @param context The Context the view is running in, through which it can 3988 * access the current theme, resources, etc. 3989 */ 3990 public View(Context context) { 3991 mContext = context; 3992 mResources = context != null ? context.getResources() : null; 3993 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3994 // Set some flags defaults 3995 mPrivateFlags2 = 3996 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3997 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3998 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3999 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 4000 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 4001 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 4002 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 4003 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 4004 mUserPaddingStart = UNDEFINED_PADDING; 4005 mUserPaddingEnd = UNDEFINED_PADDING; 4006 mRenderNode = RenderNode.create(getClass().getName(), this); 4007 4008 if (!sCompatibilityDone && context != null) { 4009 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4010 4011 // Older apps may need this compatibility hack for measurement. 4012 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 4013 4014 // Older apps expect onMeasure() to always be called on a layout pass, regardless 4015 // of whether a layout was requested on that View. 4016 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 4017 4018 Canvas.sCompatibilityRestore = targetSdkVersion < M; 4019 4020 // In M and newer, our widgets can pass a "hint" value in the size 4021 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 4022 // know what the expected parent size is going to be, so e.g. list items can size 4023 // themselves at 1/3 the size of their container. It breaks older apps though, 4024 // specifically apps that use some popular open source libraries. 4025 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M; 4026 4027 // Old versions of the platform would give different results from 4028 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 4029 // modes, so we always need to run an additional EXACTLY pass. 4030 sAlwaysRemeasureExactly = targetSdkVersion <= M; 4031 4032 // Prior to N, layout params could change without requiring a 4033 // subsequent call to setLayoutParams() and they would usually 4034 // work. Partial layout breaks this assumption. 4035 sLayoutParamsAlwaysChanged = targetSdkVersion <= M; 4036 4037 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4038 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4039 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M; 4040 4041 sCompatibilityDone = true; 4042 } 4043 } 4044 4045 /** 4046 * Constructor that is called when inflating a view from XML. This is called 4047 * when a view is being constructed from an XML file, supplying attributes 4048 * that were specified in the XML file. This version uses a default style of 4049 * 0, so the only attribute values applied are those in the Context's Theme 4050 * and the given AttributeSet. 4051 * 4052 * <p> 4053 * The method onFinishInflate() will be called after all children have been 4054 * added. 4055 * 4056 * @param context The Context the view is running in, through which it can 4057 * access the current theme, resources, etc. 4058 * @param attrs The attributes of the XML tag that is inflating the view. 4059 * @see #View(Context, AttributeSet, int) 4060 */ 4061 public View(Context context, @Nullable AttributeSet attrs) { 4062 this(context, attrs, 0); 4063 } 4064 4065 /** 4066 * Perform inflation from XML and apply a class-specific base style from a 4067 * theme attribute. This constructor of View allows subclasses to use their 4068 * own base style when they are inflating. For example, a Button class's 4069 * constructor would call this version of the super class constructor and 4070 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4071 * allows the theme's button style to modify all of the base view attributes 4072 * (in particular its background) as well as the Button class's attributes. 4073 * 4074 * @param context The Context the view is running in, through which it can 4075 * access the current theme, resources, etc. 4076 * @param attrs The attributes of the XML tag that is inflating the view. 4077 * @param defStyleAttr An attribute in the current theme that contains a 4078 * reference to a style resource that supplies default values for 4079 * the view. Can be 0 to not look for defaults. 4080 * @see #View(Context, AttributeSet) 4081 */ 4082 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4083 this(context, attrs, defStyleAttr, 0); 4084 } 4085 4086 /** 4087 * Perform inflation from XML and apply a class-specific base style from a 4088 * theme attribute or style resource. This constructor of View allows 4089 * subclasses to use their own base style when they are inflating. 4090 * <p> 4091 * When determining the final value of a particular attribute, there are 4092 * four inputs that come into play: 4093 * <ol> 4094 * <li>Any attribute values in the given AttributeSet. 4095 * <li>The style resource specified in the AttributeSet (named "style"). 4096 * <li>The default style specified by <var>defStyleAttr</var>. 4097 * <li>The default style specified by <var>defStyleRes</var>. 4098 * <li>The base values in this theme. 4099 * </ol> 4100 * <p> 4101 * Each of these inputs is considered in-order, with the first listed taking 4102 * precedence over the following ones. In other words, if in the 4103 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4104 * , then the button's text will <em>always</em> be black, regardless of 4105 * what is specified in any of the styles. 4106 * 4107 * @param context The Context the view is running in, through which it can 4108 * access the current theme, resources, etc. 4109 * @param attrs The attributes of the XML tag that is inflating the view. 4110 * @param defStyleAttr An attribute in the current theme that contains a 4111 * reference to a style resource that supplies default values for 4112 * the view. Can be 0 to not look for defaults. 4113 * @param defStyleRes A resource identifier of a style resource that 4114 * supplies default values for the view, used only if 4115 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4116 * to not look for defaults. 4117 * @see #View(Context, AttributeSet, int) 4118 */ 4119 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4120 this(context); 4121 4122 final TypedArray a = context.obtainStyledAttributes( 4123 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4124 4125 if (mDebugViewAttributes) { 4126 saveAttributeData(attrs, a); 4127 } 4128 4129 Drawable background = null; 4130 4131 int leftPadding = -1; 4132 int topPadding = -1; 4133 int rightPadding = -1; 4134 int bottomPadding = -1; 4135 int startPadding = UNDEFINED_PADDING; 4136 int endPadding = UNDEFINED_PADDING; 4137 4138 int padding = -1; 4139 4140 int viewFlagValues = 0; 4141 int viewFlagMasks = 0; 4142 4143 boolean setScrollContainer = false; 4144 4145 int x = 0; 4146 int y = 0; 4147 4148 float tx = 0; 4149 float ty = 0; 4150 float tz = 0; 4151 float elevation = 0; 4152 float rotation = 0; 4153 float rotationX = 0; 4154 float rotationY = 0; 4155 float sx = 1f; 4156 float sy = 1f; 4157 boolean transformSet = false; 4158 4159 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4160 int overScrollMode = mOverScrollMode; 4161 boolean initializeScrollbars = false; 4162 boolean initializeScrollIndicators = false; 4163 4164 boolean startPaddingDefined = false; 4165 boolean endPaddingDefined = false; 4166 boolean leftPaddingDefined = false; 4167 boolean rightPaddingDefined = false; 4168 4169 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4170 4171 final int N = a.getIndexCount(); 4172 for (int i = 0; i < N; i++) { 4173 int attr = a.getIndex(i); 4174 switch (attr) { 4175 case com.android.internal.R.styleable.View_background: 4176 background = a.getDrawable(attr); 4177 break; 4178 case com.android.internal.R.styleable.View_padding: 4179 padding = a.getDimensionPixelSize(attr, -1); 4180 mUserPaddingLeftInitial = padding; 4181 mUserPaddingRightInitial = padding; 4182 leftPaddingDefined = true; 4183 rightPaddingDefined = true; 4184 break; 4185 case com.android.internal.R.styleable.View_paddingLeft: 4186 leftPadding = a.getDimensionPixelSize(attr, -1); 4187 mUserPaddingLeftInitial = leftPadding; 4188 leftPaddingDefined = true; 4189 break; 4190 case com.android.internal.R.styleable.View_paddingTop: 4191 topPadding = a.getDimensionPixelSize(attr, -1); 4192 break; 4193 case com.android.internal.R.styleable.View_paddingRight: 4194 rightPadding = a.getDimensionPixelSize(attr, -1); 4195 mUserPaddingRightInitial = rightPadding; 4196 rightPaddingDefined = true; 4197 break; 4198 case com.android.internal.R.styleable.View_paddingBottom: 4199 bottomPadding = a.getDimensionPixelSize(attr, -1); 4200 break; 4201 case com.android.internal.R.styleable.View_paddingStart: 4202 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4203 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 4204 break; 4205 case com.android.internal.R.styleable.View_paddingEnd: 4206 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4207 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 4208 break; 4209 case com.android.internal.R.styleable.View_scrollX: 4210 x = a.getDimensionPixelOffset(attr, 0); 4211 break; 4212 case com.android.internal.R.styleable.View_scrollY: 4213 y = a.getDimensionPixelOffset(attr, 0); 4214 break; 4215 case com.android.internal.R.styleable.View_alpha: 4216 setAlpha(a.getFloat(attr, 1f)); 4217 break; 4218 case com.android.internal.R.styleable.View_transformPivotX: 4219 setPivotX(a.getDimensionPixelOffset(attr, 0)); 4220 break; 4221 case com.android.internal.R.styleable.View_transformPivotY: 4222 setPivotY(a.getDimensionPixelOffset(attr, 0)); 4223 break; 4224 case com.android.internal.R.styleable.View_translationX: 4225 tx = a.getDimensionPixelOffset(attr, 0); 4226 transformSet = true; 4227 break; 4228 case com.android.internal.R.styleable.View_translationY: 4229 ty = a.getDimensionPixelOffset(attr, 0); 4230 transformSet = true; 4231 break; 4232 case com.android.internal.R.styleable.View_translationZ: 4233 tz = a.getDimensionPixelOffset(attr, 0); 4234 transformSet = true; 4235 break; 4236 case com.android.internal.R.styleable.View_elevation: 4237 elevation = a.getDimensionPixelOffset(attr, 0); 4238 transformSet = true; 4239 break; 4240 case com.android.internal.R.styleable.View_rotation: 4241 rotation = a.getFloat(attr, 0); 4242 transformSet = true; 4243 break; 4244 case com.android.internal.R.styleable.View_rotationX: 4245 rotationX = a.getFloat(attr, 0); 4246 transformSet = true; 4247 break; 4248 case com.android.internal.R.styleable.View_rotationY: 4249 rotationY = a.getFloat(attr, 0); 4250 transformSet = true; 4251 break; 4252 case com.android.internal.R.styleable.View_scaleX: 4253 sx = a.getFloat(attr, 1f); 4254 transformSet = true; 4255 break; 4256 case com.android.internal.R.styleable.View_scaleY: 4257 sy = a.getFloat(attr, 1f); 4258 transformSet = true; 4259 break; 4260 case com.android.internal.R.styleable.View_id: 4261 mID = a.getResourceId(attr, NO_ID); 4262 break; 4263 case com.android.internal.R.styleable.View_tag: 4264 mTag = a.getText(attr); 4265 break; 4266 case com.android.internal.R.styleable.View_fitsSystemWindows: 4267 if (a.getBoolean(attr, false)) { 4268 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4269 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4270 } 4271 break; 4272 case com.android.internal.R.styleable.View_focusable: 4273 if (a.getBoolean(attr, false)) { 4274 viewFlagValues |= FOCUSABLE; 4275 viewFlagMasks |= FOCUSABLE_MASK; 4276 } 4277 break; 4278 case com.android.internal.R.styleable.View_focusableInTouchMode: 4279 if (a.getBoolean(attr, false)) { 4280 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4281 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4282 } 4283 break; 4284 case com.android.internal.R.styleable.View_clickable: 4285 if (a.getBoolean(attr, false)) { 4286 viewFlagValues |= CLICKABLE; 4287 viewFlagMasks |= CLICKABLE; 4288 } 4289 break; 4290 case com.android.internal.R.styleable.View_longClickable: 4291 if (a.getBoolean(attr, false)) { 4292 viewFlagValues |= LONG_CLICKABLE; 4293 viewFlagMasks |= LONG_CLICKABLE; 4294 } 4295 break; 4296 case com.android.internal.R.styleable.View_contextClickable: 4297 if (a.getBoolean(attr, false)) { 4298 viewFlagValues |= CONTEXT_CLICKABLE; 4299 viewFlagMasks |= CONTEXT_CLICKABLE; 4300 } 4301 break; 4302 case com.android.internal.R.styleable.View_saveEnabled: 4303 if (!a.getBoolean(attr, true)) { 4304 viewFlagValues |= SAVE_DISABLED; 4305 viewFlagMasks |= SAVE_DISABLED_MASK; 4306 } 4307 break; 4308 case com.android.internal.R.styleable.View_duplicateParentState: 4309 if (a.getBoolean(attr, false)) { 4310 viewFlagValues |= DUPLICATE_PARENT_STATE; 4311 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4312 } 4313 break; 4314 case com.android.internal.R.styleable.View_visibility: 4315 final int visibility = a.getInt(attr, 0); 4316 if (visibility != 0) { 4317 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4318 viewFlagMasks |= VISIBILITY_MASK; 4319 } 4320 break; 4321 case com.android.internal.R.styleable.View_layoutDirection: 4322 // Clear any layout direction flags (included resolved bits) already set 4323 mPrivateFlags2 &= 4324 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4325 // Set the layout direction flags depending on the value of the attribute 4326 final int layoutDirection = a.getInt(attr, -1); 4327 final int value = (layoutDirection != -1) ? 4328 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4329 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4330 break; 4331 case com.android.internal.R.styleable.View_drawingCacheQuality: 4332 final int cacheQuality = a.getInt(attr, 0); 4333 if (cacheQuality != 0) { 4334 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4335 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4336 } 4337 break; 4338 case com.android.internal.R.styleable.View_contentDescription: 4339 setContentDescription(a.getString(attr)); 4340 break; 4341 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4342 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4343 break; 4344 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4345 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4346 break; 4347 case com.android.internal.R.styleable.View_labelFor: 4348 setLabelFor(a.getResourceId(attr, NO_ID)); 4349 break; 4350 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4351 if (!a.getBoolean(attr, true)) { 4352 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4353 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4354 } 4355 break; 4356 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4357 if (!a.getBoolean(attr, true)) { 4358 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4359 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4360 } 4361 break; 4362 case R.styleable.View_scrollbars: 4363 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4364 if (scrollbars != SCROLLBARS_NONE) { 4365 viewFlagValues |= scrollbars; 4366 viewFlagMasks |= SCROLLBARS_MASK; 4367 initializeScrollbars = true; 4368 } 4369 break; 4370 //noinspection deprecation 4371 case R.styleable.View_fadingEdge: 4372 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 4373 // Ignore the attribute starting with ICS 4374 break; 4375 } 4376 // With builds < ICS, fall through and apply fading edges 4377 case R.styleable.View_requiresFadingEdge: 4378 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4379 if (fadingEdge != FADING_EDGE_NONE) { 4380 viewFlagValues |= fadingEdge; 4381 viewFlagMasks |= FADING_EDGE_MASK; 4382 initializeFadingEdgeInternal(a); 4383 } 4384 break; 4385 case R.styleable.View_scrollbarStyle: 4386 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4387 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4388 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4389 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4390 } 4391 break; 4392 case R.styleable.View_isScrollContainer: 4393 setScrollContainer = true; 4394 if (a.getBoolean(attr, false)) { 4395 setScrollContainer(true); 4396 } 4397 break; 4398 case com.android.internal.R.styleable.View_keepScreenOn: 4399 if (a.getBoolean(attr, false)) { 4400 viewFlagValues |= KEEP_SCREEN_ON; 4401 viewFlagMasks |= KEEP_SCREEN_ON; 4402 } 4403 break; 4404 case R.styleable.View_filterTouchesWhenObscured: 4405 if (a.getBoolean(attr, false)) { 4406 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4407 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4408 } 4409 break; 4410 case R.styleable.View_nextFocusLeft: 4411 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4412 break; 4413 case R.styleable.View_nextFocusRight: 4414 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4415 break; 4416 case R.styleable.View_nextFocusUp: 4417 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4418 break; 4419 case R.styleable.View_nextFocusDown: 4420 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4421 break; 4422 case R.styleable.View_nextFocusForward: 4423 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4424 break; 4425 case R.styleable.View_minWidth: 4426 mMinWidth = a.getDimensionPixelSize(attr, 0); 4427 break; 4428 case R.styleable.View_minHeight: 4429 mMinHeight = a.getDimensionPixelSize(attr, 0); 4430 break; 4431 case R.styleable.View_onClick: 4432 if (context.isRestricted()) { 4433 throw new IllegalStateException("The android:onClick attribute cannot " 4434 + "be used within a restricted context"); 4435 } 4436 4437 final String handlerName = a.getString(attr); 4438 if (handlerName != null) { 4439 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4440 } 4441 break; 4442 case R.styleable.View_overScrollMode: 4443 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4444 break; 4445 case R.styleable.View_verticalScrollbarPosition: 4446 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4447 break; 4448 case R.styleable.View_layerType: 4449 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4450 break; 4451 case R.styleable.View_textDirection: 4452 // Clear any text direction flag already set 4453 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4454 // Set the text direction flags depending on the value of the attribute 4455 final int textDirection = a.getInt(attr, -1); 4456 if (textDirection != -1) { 4457 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4458 } 4459 break; 4460 case R.styleable.View_textAlignment: 4461 // Clear any text alignment flag already set 4462 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4463 // Set the text alignment flag depending on the value of the attribute 4464 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4465 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4466 break; 4467 case R.styleable.View_importantForAccessibility: 4468 setImportantForAccessibility(a.getInt(attr, 4469 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4470 break; 4471 case R.styleable.View_accessibilityLiveRegion: 4472 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4473 break; 4474 case R.styleable.View_transitionName: 4475 setTransitionName(a.getString(attr)); 4476 break; 4477 case R.styleable.View_nestedScrollingEnabled: 4478 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4479 break; 4480 case R.styleable.View_stateListAnimator: 4481 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4482 a.getResourceId(attr, 0))); 4483 break; 4484 case R.styleable.View_backgroundTint: 4485 // This will get applied later during setBackground(). 4486 if (mBackgroundTint == null) { 4487 mBackgroundTint = new TintInfo(); 4488 } 4489 mBackgroundTint.mTintList = a.getColorStateList( 4490 R.styleable.View_backgroundTint); 4491 mBackgroundTint.mHasTintList = true; 4492 break; 4493 case R.styleable.View_backgroundTintMode: 4494 // This will get applied later during setBackground(). 4495 if (mBackgroundTint == null) { 4496 mBackgroundTint = new TintInfo(); 4497 } 4498 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4499 R.styleable.View_backgroundTintMode, -1), null); 4500 mBackgroundTint.mHasTintMode = true; 4501 break; 4502 case R.styleable.View_outlineProvider: 4503 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4504 PROVIDER_BACKGROUND)); 4505 break; 4506 case R.styleable.View_foreground: 4507 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4508 setForeground(a.getDrawable(attr)); 4509 } 4510 break; 4511 case R.styleable.View_foregroundGravity: 4512 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4513 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4514 } 4515 break; 4516 case R.styleable.View_foregroundTintMode: 4517 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4518 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4519 } 4520 break; 4521 case R.styleable.View_foregroundTint: 4522 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4523 setForegroundTintList(a.getColorStateList(attr)); 4524 } 4525 break; 4526 case R.styleable.View_foregroundInsidePadding: 4527 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4528 if (mForegroundInfo == null) { 4529 mForegroundInfo = new ForegroundInfo(); 4530 } 4531 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4532 mForegroundInfo.mInsidePadding); 4533 } 4534 break; 4535 case R.styleable.View_scrollIndicators: 4536 final int scrollIndicators = 4537 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 4538 & SCROLL_INDICATORS_PFLAG3_MASK; 4539 if (scrollIndicators != 0) { 4540 mPrivateFlags3 |= scrollIndicators; 4541 initializeScrollIndicators = true; 4542 } 4543 break; 4544 case R.styleable.View_pointerIcon: 4545 final int resourceId = a.getResourceId(attr, 0); 4546 if (resourceId != 0) { 4547 setPointerIcon(PointerIcon.load( 4548 context.getResources(), resourceId)); 4549 } else { 4550 final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED); 4551 if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) { 4552 setPointerIcon(PointerIcon.getSystemIcon(context, pointerType)); 4553 } 4554 } 4555 break; 4556 case R.styleable.View_forceHasOverlappingRendering: 4557 if (a.peekValue(attr) != null) { 4558 forceHasOverlappingRendering(a.getBoolean(attr, true)); 4559 } 4560 break; 4561 4562 } 4563 } 4564 4565 setOverScrollMode(overScrollMode); 4566 4567 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4568 // the resolved layout direction). Those cached values will be used later during padding 4569 // resolution. 4570 mUserPaddingStart = startPadding; 4571 mUserPaddingEnd = endPadding; 4572 4573 if (background != null) { 4574 setBackground(background); 4575 } 4576 4577 // setBackground above will record that padding is currently provided by the background. 4578 // If we have padding specified via xml, record that here instead and use it. 4579 mLeftPaddingDefined = leftPaddingDefined; 4580 mRightPaddingDefined = rightPaddingDefined; 4581 4582 if (padding >= 0) { 4583 leftPadding = padding; 4584 topPadding = padding; 4585 rightPadding = padding; 4586 bottomPadding = padding; 4587 mUserPaddingLeftInitial = padding; 4588 mUserPaddingRightInitial = padding; 4589 } 4590 4591 if (isRtlCompatibilityMode()) { 4592 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4593 // left / right padding are used if defined (meaning here nothing to do). If they are not 4594 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4595 // start / end and resolve them as left / right (layout direction is not taken into account). 4596 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4597 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4598 // defined. 4599 if (!mLeftPaddingDefined && startPaddingDefined) { 4600 leftPadding = startPadding; 4601 } 4602 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4603 if (!mRightPaddingDefined && endPaddingDefined) { 4604 rightPadding = endPadding; 4605 } 4606 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4607 } else { 4608 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4609 // values defined. Otherwise, left /right values are used. 4610 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4611 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4612 // defined. 4613 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4614 4615 if (mLeftPaddingDefined && !hasRelativePadding) { 4616 mUserPaddingLeftInitial = leftPadding; 4617 } 4618 if (mRightPaddingDefined && !hasRelativePadding) { 4619 mUserPaddingRightInitial = rightPadding; 4620 } 4621 } 4622 4623 internalSetPadding( 4624 mUserPaddingLeftInitial, 4625 topPadding >= 0 ? topPadding : mPaddingTop, 4626 mUserPaddingRightInitial, 4627 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4628 4629 if (viewFlagMasks != 0) { 4630 setFlags(viewFlagValues, viewFlagMasks); 4631 } 4632 4633 if (initializeScrollbars) { 4634 initializeScrollbarsInternal(a); 4635 } 4636 4637 if (initializeScrollIndicators) { 4638 initializeScrollIndicatorsInternal(); 4639 } 4640 4641 a.recycle(); 4642 4643 // Needs to be called after mViewFlags is set 4644 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4645 recomputePadding(); 4646 } 4647 4648 if (x != 0 || y != 0) { 4649 scrollTo(x, y); 4650 } 4651 4652 if (transformSet) { 4653 setTranslationX(tx); 4654 setTranslationY(ty); 4655 setTranslationZ(tz); 4656 setElevation(elevation); 4657 setRotation(rotation); 4658 setRotationX(rotationX); 4659 setRotationY(rotationY); 4660 setScaleX(sx); 4661 setScaleY(sy); 4662 } 4663 4664 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4665 setScrollContainer(true); 4666 } 4667 4668 computeOpaqueFlags(); 4669 } 4670 4671 /** 4672 * An implementation of OnClickListener that attempts to lazily load a 4673 * named click handling method from a parent or ancestor context. 4674 */ 4675 private static class DeclaredOnClickListener implements OnClickListener { 4676 private final View mHostView; 4677 private final String mMethodName; 4678 4679 private Method mResolvedMethod; 4680 private Context mResolvedContext; 4681 4682 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 4683 mHostView = hostView; 4684 mMethodName = methodName; 4685 } 4686 4687 @Override 4688 public void onClick(@NonNull View v) { 4689 if (mResolvedMethod == null) { 4690 resolveMethod(mHostView.getContext(), mMethodName); 4691 } 4692 4693 try { 4694 mResolvedMethod.invoke(mResolvedContext, v); 4695 } catch (IllegalAccessException e) { 4696 throw new IllegalStateException( 4697 "Could not execute non-public method for android:onClick", e); 4698 } catch (InvocationTargetException e) { 4699 throw new IllegalStateException( 4700 "Could not execute method for android:onClick", e); 4701 } 4702 } 4703 4704 @NonNull 4705 private void resolveMethod(@Nullable Context context, @NonNull String name) { 4706 while (context != null) { 4707 try { 4708 if (!context.isRestricted()) { 4709 final Method method = context.getClass().getMethod(mMethodName, View.class); 4710 if (method != null) { 4711 mResolvedMethod = method; 4712 mResolvedContext = context; 4713 return; 4714 } 4715 } 4716 } catch (NoSuchMethodException e) { 4717 // Failed to find method, keep searching up the hierarchy. 4718 } 4719 4720 if (context instanceof ContextWrapper) { 4721 context = ((ContextWrapper) context).getBaseContext(); 4722 } else { 4723 // Can't search up the hierarchy, null out and fail. 4724 context = null; 4725 } 4726 } 4727 4728 final int id = mHostView.getId(); 4729 final String idText = id == NO_ID ? "" : " with id '" 4730 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 4731 throw new IllegalStateException("Could not find method " + mMethodName 4732 + "(View) in a parent or ancestor Context for android:onClick " 4733 + "attribute defined on view " + mHostView.getClass() + idText); 4734 } 4735 } 4736 4737 /** 4738 * Non-public constructor for use in testing 4739 */ 4740 View() { 4741 mResources = null; 4742 mRenderNode = RenderNode.create(getClass().getName(), this); 4743 } 4744 4745 private static SparseArray<String> getAttributeMap() { 4746 if (mAttributeMap == null) { 4747 mAttributeMap = new SparseArray<>(); 4748 } 4749 return mAttributeMap; 4750 } 4751 4752 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 4753 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 4754 final int indexCount = t.getIndexCount(); 4755 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 4756 4757 int i = 0; 4758 4759 // Store raw XML attributes. 4760 for (int j = 0; j < attrsCount; ++j) { 4761 attributes[i] = attrs.getAttributeName(j); 4762 attributes[i + 1] = attrs.getAttributeValue(j); 4763 i += 2; 4764 } 4765 4766 // Store resolved styleable attributes. 4767 final Resources res = t.getResources(); 4768 final SparseArray<String> attributeMap = getAttributeMap(); 4769 for (int j = 0; j < indexCount; ++j) { 4770 final int index = t.getIndex(j); 4771 if (!t.hasValueOrEmpty(index)) { 4772 // Value is undefined. Skip it. 4773 continue; 4774 } 4775 4776 final int resourceId = t.getResourceId(index, 0); 4777 if (resourceId == 0) { 4778 // Value is not a reference. Skip it. 4779 continue; 4780 } 4781 4782 String resourceName = attributeMap.get(resourceId); 4783 if (resourceName == null) { 4784 try { 4785 resourceName = res.getResourceName(resourceId); 4786 } catch (Resources.NotFoundException e) { 4787 resourceName = "0x" + Integer.toHexString(resourceId); 4788 } 4789 attributeMap.put(resourceId, resourceName); 4790 } 4791 4792 attributes[i] = resourceName; 4793 attributes[i + 1] = t.getString(index); 4794 i += 2; 4795 } 4796 4797 // Trim to fit contents. 4798 final String[] trimmed = new String[i]; 4799 System.arraycopy(attributes, 0, trimmed, 0, i); 4800 mAttributes = trimmed; 4801 } 4802 4803 public String toString() { 4804 StringBuilder out = new StringBuilder(128); 4805 out.append(getClass().getName()); 4806 out.append('{'); 4807 out.append(Integer.toHexString(System.identityHashCode(this))); 4808 out.append(' '); 4809 switch (mViewFlags&VISIBILITY_MASK) { 4810 case VISIBLE: out.append('V'); break; 4811 case INVISIBLE: out.append('I'); break; 4812 case GONE: out.append('G'); break; 4813 default: out.append('.'); break; 4814 } 4815 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4816 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4817 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4818 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4819 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4820 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4821 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4822 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 4823 out.append(' '); 4824 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4825 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4826 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4827 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4828 out.append('p'); 4829 } else { 4830 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4831 } 4832 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4833 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4834 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4835 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4836 out.append(' '); 4837 out.append(mLeft); 4838 out.append(','); 4839 out.append(mTop); 4840 out.append('-'); 4841 out.append(mRight); 4842 out.append(','); 4843 out.append(mBottom); 4844 final int id = getId(); 4845 if (id != NO_ID) { 4846 out.append(" #"); 4847 out.append(Integer.toHexString(id)); 4848 final Resources r = mResources; 4849 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 4850 try { 4851 String pkgname; 4852 switch (id&0xff000000) { 4853 case 0x7f000000: 4854 pkgname="app"; 4855 break; 4856 case 0x01000000: 4857 pkgname="android"; 4858 break; 4859 default: 4860 pkgname = r.getResourcePackageName(id); 4861 break; 4862 } 4863 String typename = r.getResourceTypeName(id); 4864 String entryname = r.getResourceEntryName(id); 4865 out.append(" "); 4866 out.append(pkgname); 4867 out.append(":"); 4868 out.append(typename); 4869 out.append("/"); 4870 out.append(entryname); 4871 } catch (Resources.NotFoundException e) { 4872 } 4873 } 4874 } 4875 out.append("}"); 4876 return out.toString(); 4877 } 4878 4879 /** 4880 * <p> 4881 * Initializes the fading edges from a given set of styled attributes. This 4882 * method should be called by subclasses that need fading edges and when an 4883 * instance of these subclasses is created programmatically rather than 4884 * being inflated from XML. This method is automatically called when the XML 4885 * is inflated. 4886 * </p> 4887 * 4888 * @param a the styled attributes set to initialize the fading edges from 4889 * 4890 * @removed 4891 */ 4892 protected void initializeFadingEdge(TypedArray a) { 4893 // This method probably shouldn't have been included in the SDK to begin with. 4894 // It relies on 'a' having been initialized using an attribute filter array that is 4895 // not publicly available to the SDK. The old method has been renamed 4896 // to initializeFadingEdgeInternal and hidden for framework use only; 4897 // this one initializes using defaults to make it safe to call for apps. 4898 4899 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4900 4901 initializeFadingEdgeInternal(arr); 4902 4903 arr.recycle(); 4904 } 4905 4906 /** 4907 * <p> 4908 * Initializes the fading edges from a given set of styled attributes. This 4909 * method should be called by subclasses that need fading edges and when an 4910 * instance of these subclasses is created programmatically rather than 4911 * being inflated from XML. This method is automatically called when the XML 4912 * is inflated. 4913 * </p> 4914 * 4915 * @param a the styled attributes set to initialize the fading edges from 4916 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4917 */ 4918 protected void initializeFadingEdgeInternal(TypedArray a) { 4919 initScrollCache(); 4920 4921 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4922 R.styleable.View_fadingEdgeLength, 4923 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4924 } 4925 4926 /** 4927 * Returns the size of the vertical faded edges used to indicate that more 4928 * content in this view is visible. 4929 * 4930 * @return The size in pixels of the vertical faded edge or 0 if vertical 4931 * faded edges are not enabled for this view. 4932 * @attr ref android.R.styleable#View_fadingEdgeLength 4933 */ 4934 public int getVerticalFadingEdgeLength() { 4935 if (isVerticalFadingEdgeEnabled()) { 4936 ScrollabilityCache cache = mScrollCache; 4937 if (cache != null) { 4938 return cache.fadingEdgeLength; 4939 } 4940 } 4941 return 0; 4942 } 4943 4944 /** 4945 * Set the size of the faded edge used to indicate that more content in this 4946 * view is available. Will not change whether the fading edge is enabled; use 4947 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4948 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4949 * for the vertical or horizontal fading edges. 4950 * 4951 * @param length The size in pixels of the faded edge used to indicate that more 4952 * content in this view is visible. 4953 */ 4954 public void setFadingEdgeLength(int length) { 4955 initScrollCache(); 4956 mScrollCache.fadingEdgeLength = length; 4957 } 4958 4959 /** 4960 * Returns the size of the horizontal faded edges used to indicate that more 4961 * content in this view is visible. 4962 * 4963 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4964 * faded edges are not enabled for this view. 4965 * @attr ref android.R.styleable#View_fadingEdgeLength 4966 */ 4967 public int getHorizontalFadingEdgeLength() { 4968 if (isHorizontalFadingEdgeEnabled()) { 4969 ScrollabilityCache cache = mScrollCache; 4970 if (cache != null) { 4971 return cache.fadingEdgeLength; 4972 } 4973 } 4974 return 0; 4975 } 4976 4977 /** 4978 * Returns the width of the vertical scrollbar. 4979 * 4980 * @return The width in pixels of the vertical scrollbar or 0 if there 4981 * is no vertical scrollbar. 4982 */ 4983 public int getVerticalScrollbarWidth() { 4984 ScrollabilityCache cache = mScrollCache; 4985 if (cache != null) { 4986 ScrollBarDrawable scrollBar = cache.scrollBar; 4987 if (scrollBar != null) { 4988 int size = scrollBar.getSize(true); 4989 if (size <= 0) { 4990 size = cache.scrollBarSize; 4991 } 4992 return size; 4993 } 4994 return 0; 4995 } 4996 return 0; 4997 } 4998 4999 /** 5000 * Returns the height of the horizontal scrollbar. 5001 * 5002 * @return The height in pixels of the horizontal scrollbar or 0 if 5003 * there is no horizontal scrollbar. 5004 */ 5005 protected int getHorizontalScrollbarHeight() { 5006 ScrollabilityCache cache = mScrollCache; 5007 if (cache != null) { 5008 ScrollBarDrawable scrollBar = cache.scrollBar; 5009 if (scrollBar != null) { 5010 int size = scrollBar.getSize(false); 5011 if (size <= 0) { 5012 size = cache.scrollBarSize; 5013 } 5014 return size; 5015 } 5016 return 0; 5017 } 5018 return 0; 5019 } 5020 5021 /** 5022 * <p> 5023 * Initializes the scrollbars from a given set of styled attributes. This 5024 * method should be called by subclasses that need scrollbars and when an 5025 * instance of these subclasses is created programmatically rather than 5026 * being inflated from XML. This method is automatically called when the XML 5027 * is inflated. 5028 * </p> 5029 * 5030 * @param a the styled attributes set to initialize the scrollbars from 5031 * 5032 * @removed 5033 */ 5034 protected void initializeScrollbars(TypedArray a) { 5035 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 5036 // using the View filter array which is not available to the SDK. As such, internal 5037 // framework usage now uses initializeScrollbarsInternal and we grab a default 5038 // TypedArray with the right filter instead here. 5039 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5040 5041 initializeScrollbarsInternal(arr); 5042 5043 // We ignored the method parameter. Recycle the one we actually did use. 5044 arr.recycle(); 5045 } 5046 5047 /** 5048 * <p> 5049 * Initializes the scrollbars from a given set of styled attributes. This 5050 * method should be called by subclasses that need scrollbars and when an 5051 * instance of these subclasses is created programmatically rather than 5052 * being inflated from XML. This method is automatically called when the XML 5053 * is inflated. 5054 * </p> 5055 * 5056 * @param a the styled attributes set to initialize the scrollbars from 5057 * @hide 5058 */ 5059 protected void initializeScrollbarsInternal(TypedArray a) { 5060 initScrollCache(); 5061 5062 final ScrollabilityCache scrollabilityCache = mScrollCache; 5063 5064 if (scrollabilityCache.scrollBar == null) { 5065 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 5066 scrollabilityCache.scrollBar.setState(getDrawableState()); 5067 scrollabilityCache.scrollBar.setCallback(this); 5068 } 5069 5070 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 5071 5072 if (!fadeScrollbars) { 5073 scrollabilityCache.state = ScrollabilityCache.ON; 5074 } 5075 scrollabilityCache.fadeScrollBars = fadeScrollbars; 5076 5077 5078 scrollabilityCache.scrollBarFadeDuration = a.getInt( 5079 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 5080 .getScrollBarFadeDuration()); 5081 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 5082 R.styleable.View_scrollbarDefaultDelayBeforeFade, 5083 ViewConfiguration.getScrollDefaultDelay()); 5084 5085 5086 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 5087 com.android.internal.R.styleable.View_scrollbarSize, 5088 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 5089 5090 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 5091 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 5092 5093 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 5094 if (thumb != null) { 5095 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 5096 } 5097 5098 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 5099 false); 5100 if (alwaysDraw) { 5101 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 5102 } 5103 5104 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 5105 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 5106 5107 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 5108 if (thumb != null) { 5109 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 5110 } 5111 5112 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 5113 false); 5114 if (alwaysDraw) { 5115 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 5116 } 5117 5118 // Apply layout direction to the new Drawables if needed 5119 final int layoutDirection = getLayoutDirection(); 5120 if (track != null) { 5121 track.setLayoutDirection(layoutDirection); 5122 } 5123 if (thumb != null) { 5124 thumb.setLayoutDirection(layoutDirection); 5125 } 5126 5127 // Re-apply user/background padding so that scrollbar(s) get added 5128 resolvePadding(); 5129 } 5130 5131 private void initializeScrollIndicatorsInternal() { 5132 // Some day maybe we'll break this into top/left/start/etc. and let the 5133 // client control it. Until then, you can have any scroll indicator you 5134 // want as long as it's a 1dp foreground-colored rectangle. 5135 if (mScrollIndicatorDrawable == null) { 5136 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 5137 } 5138 } 5139 5140 /** 5141 * <p> 5142 * Initalizes the scrollability cache if necessary. 5143 * </p> 5144 */ 5145 private void initScrollCache() { 5146 if (mScrollCache == null) { 5147 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 5148 } 5149 } 5150 5151 private ScrollabilityCache getScrollCache() { 5152 initScrollCache(); 5153 return mScrollCache; 5154 } 5155 5156 /** 5157 * Set the position of the vertical scroll bar. Should be one of 5158 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 5159 * {@link #SCROLLBAR_POSITION_RIGHT}. 5160 * 5161 * @param position Where the vertical scroll bar should be positioned. 5162 */ 5163 public void setVerticalScrollbarPosition(int position) { 5164 if (mVerticalScrollbarPosition != position) { 5165 mVerticalScrollbarPosition = position; 5166 computeOpaqueFlags(); 5167 resolvePadding(); 5168 } 5169 } 5170 5171 /** 5172 * @return The position where the vertical scroll bar will show, if applicable. 5173 * @see #setVerticalScrollbarPosition(int) 5174 */ 5175 public int getVerticalScrollbarPosition() { 5176 return mVerticalScrollbarPosition; 5177 } 5178 5179 boolean isOnScrollbar(float x, float y) { 5180 if (mScrollCache == null) { 5181 return false; 5182 } 5183 x += getScrollX(); 5184 y += getScrollY(); 5185 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5186 final Rect bounds = mScrollCache.mScrollBarBounds; 5187 getVerticalScrollBarBounds(bounds); 5188 if (bounds.contains((int)x, (int)y)) { 5189 return true; 5190 } 5191 } 5192 if (isHorizontalScrollBarEnabled()) { 5193 final Rect bounds = mScrollCache.mScrollBarBounds; 5194 getHorizontalScrollBarBounds(bounds); 5195 if (bounds.contains((int)x, (int)y)) { 5196 return true; 5197 } 5198 } 5199 return false; 5200 } 5201 5202 boolean isOnScrollbarThumb(float x, float y) { 5203 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 5204 } 5205 5206 private boolean isOnVerticalScrollbarThumb(float x, float y) { 5207 if (mScrollCache == null) { 5208 return false; 5209 } 5210 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5211 x += getScrollX(); 5212 y += getScrollY(); 5213 final Rect bounds = mScrollCache.mScrollBarBounds; 5214 getVerticalScrollBarBounds(bounds); 5215 final int range = computeVerticalScrollRange(); 5216 final int offset = computeVerticalScrollOffset(); 5217 final int extent = computeVerticalScrollExtent(); 5218 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 5219 extent, range); 5220 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 5221 extent, range, offset); 5222 final int thumbTop = bounds.top + thumbOffset; 5223 if (x >= bounds.left && x <= bounds.right && y >= thumbTop 5224 && y <= thumbTop + thumbLength) { 5225 return true; 5226 } 5227 } 5228 return false; 5229 } 5230 5231 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 5232 if (mScrollCache == null) { 5233 return false; 5234 } 5235 if (isHorizontalScrollBarEnabled()) { 5236 x += getScrollX(); 5237 y += getScrollY(); 5238 final Rect bounds = mScrollCache.mScrollBarBounds; 5239 getHorizontalScrollBarBounds(bounds); 5240 final int range = computeHorizontalScrollRange(); 5241 final int offset = computeHorizontalScrollOffset(); 5242 final int extent = computeHorizontalScrollExtent(); 5243 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 5244 extent, range); 5245 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 5246 extent, range, offset); 5247 final int thumbLeft = bounds.left + thumbOffset; 5248 if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top 5249 && y <= bounds.bottom) { 5250 return true; 5251 } 5252 } 5253 return false; 5254 } 5255 5256 boolean isDraggingScrollBar() { 5257 return mScrollCache != null 5258 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 5259 } 5260 5261 /** 5262 * Sets the state of all scroll indicators. 5263 * <p> 5264 * See {@link #setScrollIndicators(int, int)} for usage information. 5265 * 5266 * @param indicators a bitmask of indicators that should be enabled, or 5267 * {@code 0} to disable all indicators 5268 * @see #setScrollIndicators(int, int) 5269 * @see #getScrollIndicators() 5270 * @attr ref android.R.styleable#View_scrollIndicators 5271 */ 5272 public void setScrollIndicators(@ScrollIndicators int indicators) { 5273 setScrollIndicators(indicators, 5274 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 5275 } 5276 5277 /** 5278 * Sets the state of the scroll indicators specified by the mask. To change 5279 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 5280 * <p> 5281 * When a scroll indicator is enabled, it will be displayed if the view 5282 * can scroll in the direction of the indicator. 5283 * <p> 5284 * Multiple indicator types may be enabled or disabled by passing the 5285 * logical OR of the desired types. If multiple types are specified, they 5286 * will all be set to the same enabled state. 5287 * <p> 5288 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 5289 * 5290 * @param indicators the indicator direction, or the logical OR of multiple 5291 * indicator directions. One or more of: 5292 * <ul> 5293 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 5294 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 5295 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 5296 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 5297 * <li>{@link #SCROLL_INDICATOR_START}</li> 5298 * <li>{@link #SCROLL_INDICATOR_END}</li> 5299 * </ul> 5300 * @see #setScrollIndicators(int) 5301 * @see #getScrollIndicators() 5302 * @attr ref android.R.styleable#View_scrollIndicators 5303 */ 5304 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 5305 // Shift and sanitize mask. 5306 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5307 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 5308 5309 // Shift and mask indicators. 5310 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5311 indicators &= mask; 5312 5313 // Merge with non-masked flags. 5314 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 5315 5316 if (mPrivateFlags3 != updatedFlags) { 5317 mPrivateFlags3 = updatedFlags; 5318 5319 if (indicators != 0) { 5320 initializeScrollIndicatorsInternal(); 5321 } 5322 invalidate(); 5323 } 5324 } 5325 5326 /** 5327 * Returns a bitmask representing the enabled scroll indicators. 5328 * <p> 5329 * For example, if the top and left scroll indicators are enabled and all 5330 * other indicators are disabled, the return value will be 5331 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 5332 * <p> 5333 * To check whether the bottom scroll indicator is enabled, use the value 5334 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5335 * 5336 * @return a bitmask representing the enabled scroll indicators 5337 */ 5338 @ScrollIndicators 5339 public int getScrollIndicators() { 5340 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5341 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5342 } 5343 5344 ListenerInfo getListenerInfo() { 5345 if (mListenerInfo != null) { 5346 return mListenerInfo; 5347 } 5348 mListenerInfo = new ListenerInfo(); 5349 return mListenerInfo; 5350 } 5351 5352 /** 5353 * Register a callback to be invoked when the scroll X or Y positions of 5354 * this view change. 5355 * <p> 5356 * <b>Note:</b> Some views handle scrolling independently from View and may 5357 * have their own separate listeners for scroll-type events. For example, 5358 * {@link android.widget.ListView ListView} allows clients to register an 5359 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5360 * to listen for changes in list scroll position. 5361 * 5362 * @param l The listener to notify when the scroll X or Y position changes. 5363 * @see android.view.View#getScrollX() 5364 * @see android.view.View#getScrollY() 5365 */ 5366 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5367 getListenerInfo().mOnScrollChangeListener = l; 5368 } 5369 5370 /** 5371 * Register a callback to be invoked when focus of this view changed. 5372 * 5373 * @param l The callback that will run. 5374 */ 5375 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5376 getListenerInfo().mOnFocusChangeListener = l; 5377 } 5378 5379 /** 5380 * Add a listener that will be called when the bounds of the view change due to 5381 * layout processing. 5382 * 5383 * @param listener The listener that will be called when layout bounds change. 5384 */ 5385 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5386 ListenerInfo li = getListenerInfo(); 5387 if (li.mOnLayoutChangeListeners == null) { 5388 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5389 } 5390 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5391 li.mOnLayoutChangeListeners.add(listener); 5392 } 5393 } 5394 5395 /** 5396 * Remove a listener for layout changes. 5397 * 5398 * @param listener The listener for layout bounds change. 5399 */ 5400 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5401 ListenerInfo li = mListenerInfo; 5402 if (li == null || li.mOnLayoutChangeListeners == null) { 5403 return; 5404 } 5405 li.mOnLayoutChangeListeners.remove(listener); 5406 } 5407 5408 /** 5409 * Add a listener for attach state changes. 5410 * 5411 * This listener will be called whenever this view is attached or detached 5412 * from a window. Remove the listener using 5413 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5414 * 5415 * @param listener Listener to attach 5416 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5417 */ 5418 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5419 ListenerInfo li = getListenerInfo(); 5420 if (li.mOnAttachStateChangeListeners == null) { 5421 li.mOnAttachStateChangeListeners 5422 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5423 } 5424 li.mOnAttachStateChangeListeners.add(listener); 5425 } 5426 5427 /** 5428 * Remove a listener for attach state changes. The listener will receive no further 5429 * notification of window attach/detach events. 5430 * 5431 * @param listener Listener to remove 5432 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5433 */ 5434 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5435 ListenerInfo li = mListenerInfo; 5436 if (li == null || li.mOnAttachStateChangeListeners == null) { 5437 return; 5438 } 5439 li.mOnAttachStateChangeListeners.remove(listener); 5440 } 5441 5442 /** 5443 * Returns the focus-change callback registered for this view. 5444 * 5445 * @return The callback, or null if one is not registered. 5446 */ 5447 public OnFocusChangeListener getOnFocusChangeListener() { 5448 ListenerInfo li = mListenerInfo; 5449 return li != null ? li.mOnFocusChangeListener : null; 5450 } 5451 5452 /** 5453 * Register a callback to be invoked when this view is clicked. If this view is not 5454 * clickable, it becomes clickable. 5455 * 5456 * @param l The callback that will run 5457 * 5458 * @see #setClickable(boolean) 5459 */ 5460 public void setOnClickListener(@Nullable OnClickListener l) { 5461 if (!isClickable()) { 5462 setClickable(true); 5463 } 5464 getListenerInfo().mOnClickListener = l; 5465 } 5466 5467 /** 5468 * Return whether this view has an attached OnClickListener. Returns 5469 * true if there is a listener, false if there is none. 5470 */ 5471 public boolean hasOnClickListeners() { 5472 ListenerInfo li = mListenerInfo; 5473 return (li != null && li.mOnClickListener != null); 5474 } 5475 5476 /** 5477 * Register a callback to be invoked when this view is clicked and held. If this view is not 5478 * long clickable, it becomes long clickable. 5479 * 5480 * @param l The callback that will run 5481 * 5482 * @see #setLongClickable(boolean) 5483 */ 5484 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 5485 if (!isLongClickable()) { 5486 setLongClickable(true); 5487 } 5488 getListenerInfo().mOnLongClickListener = l; 5489 } 5490 5491 /** 5492 * Register a callback to be invoked when this view is context clicked. If the view is not 5493 * context clickable, it becomes context clickable. 5494 * 5495 * @param l The callback that will run 5496 * @see #setContextClickable(boolean) 5497 */ 5498 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 5499 if (!isContextClickable()) { 5500 setContextClickable(true); 5501 } 5502 getListenerInfo().mOnContextClickListener = l; 5503 } 5504 5505 /** 5506 * Register a callback to be invoked when the context menu for this view is 5507 * being built. If this view is not long clickable, it becomes long clickable. 5508 * 5509 * @param l The callback that will run 5510 * 5511 */ 5512 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 5513 if (!isLongClickable()) { 5514 setLongClickable(true); 5515 } 5516 getListenerInfo().mOnCreateContextMenuListener = l; 5517 } 5518 5519 /** 5520 * Set an observer to collect stats for each frame rendered for this view. 5521 * 5522 * @hide 5523 */ 5524 public void addFrameMetricsListener(Window window, 5525 Window.OnFrameMetricsAvailableListener listener, 5526 Handler handler) { 5527 if (mAttachInfo != null) { 5528 if (mAttachInfo.mHardwareRenderer != null) { 5529 if (mFrameMetricsObservers == null) { 5530 mFrameMetricsObservers = new ArrayList<>(); 5531 } 5532 5533 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5534 handler.getLooper(), listener); 5535 mFrameMetricsObservers.add(fmo); 5536 mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo); 5537 } else { 5538 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5539 } 5540 } else { 5541 if (mFrameMetricsObservers == null) { 5542 mFrameMetricsObservers = new ArrayList<>(); 5543 } 5544 5545 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5546 handler.getLooper(), listener); 5547 mFrameMetricsObservers.add(fmo); 5548 } 5549 } 5550 5551 /** 5552 * Remove observer configured to collect frame stats for this view. 5553 * 5554 * @hide 5555 */ 5556 public void removeFrameMetricsListener( 5557 Window.OnFrameMetricsAvailableListener listener) { 5558 ThreadedRenderer renderer = getHardwareRenderer(); 5559 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 5560 if (fmo == null) { 5561 throw new IllegalArgumentException( 5562 "attempt to remove OnFrameMetricsAvailableListener that was never added"); 5563 } 5564 5565 if (mFrameMetricsObservers != null) { 5566 mFrameMetricsObservers.remove(fmo); 5567 if (renderer != null) { 5568 renderer.removeFrameMetricsObserver(fmo); 5569 } 5570 } 5571 } 5572 5573 private void registerPendingFrameMetricsObservers() { 5574 if (mFrameMetricsObservers != null) { 5575 ThreadedRenderer renderer = getHardwareRenderer(); 5576 if (renderer != null) { 5577 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 5578 renderer.addFrameMetricsObserver(fmo); 5579 } 5580 } else { 5581 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5582 } 5583 } 5584 } 5585 5586 private FrameMetricsObserver findFrameMetricsObserver( 5587 Window.OnFrameMetricsAvailableListener listener) { 5588 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 5589 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 5590 if (observer.mListener == listener) { 5591 return observer; 5592 } 5593 } 5594 5595 return null; 5596 } 5597 5598 /** 5599 * Call this view's OnClickListener, if it is defined. Performs all normal 5600 * actions associated with clicking: reporting accessibility event, playing 5601 * a sound, etc. 5602 * 5603 * @return True there was an assigned OnClickListener that was called, false 5604 * otherwise is returned. 5605 */ 5606 public boolean performClick() { 5607 final boolean result; 5608 final ListenerInfo li = mListenerInfo; 5609 if (li != null && li.mOnClickListener != null) { 5610 playSoundEffect(SoundEffectConstants.CLICK); 5611 li.mOnClickListener.onClick(this); 5612 result = true; 5613 } else { 5614 result = false; 5615 } 5616 5617 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 5618 return result; 5619 } 5620 5621 /** 5622 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 5623 * this only calls the listener, and does not do any associated clicking 5624 * actions like reporting an accessibility event. 5625 * 5626 * @return True there was an assigned OnClickListener that was called, false 5627 * otherwise is returned. 5628 */ 5629 public boolean callOnClick() { 5630 ListenerInfo li = mListenerInfo; 5631 if (li != null && li.mOnClickListener != null) { 5632 li.mOnClickListener.onClick(this); 5633 return true; 5634 } 5635 return false; 5636 } 5637 5638 /** 5639 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5640 * context menu if the OnLongClickListener did not consume the event. 5641 * 5642 * @return {@code true} if one of the above receivers consumed the event, 5643 * {@code false} otherwise 5644 */ 5645 public boolean performLongClick() { 5646 return performLongClickInternal(mLongClickX, mLongClickY); 5647 } 5648 5649 /** 5650 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5651 * context menu if the OnLongClickListener did not consume the event, 5652 * anchoring it to an (x,y) coordinate. 5653 * 5654 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5655 * to disable anchoring 5656 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5657 * to disable anchoring 5658 * @return {@code true} if one of the above receivers consumed the event, 5659 * {@code false} otherwise 5660 */ 5661 public boolean performLongClick(float x, float y) { 5662 mLongClickX = x; 5663 mLongClickY = y; 5664 final boolean handled = performLongClick(); 5665 mLongClickX = Float.NaN; 5666 mLongClickY = Float.NaN; 5667 return handled; 5668 } 5669 5670 /** 5671 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5672 * context menu if the OnLongClickListener did not consume the event, 5673 * optionally anchoring it to an (x,y) coordinate. 5674 * 5675 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5676 * to disable anchoring 5677 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5678 * to disable anchoring 5679 * @return {@code true} if one of the above receivers consumed the event, 5680 * {@code false} otherwise 5681 */ 5682 private boolean performLongClickInternal(float x, float y) { 5683 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 5684 5685 boolean handled = false; 5686 final ListenerInfo li = mListenerInfo; 5687 if (li != null && li.mOnLongClickListener != null) { 5688 handled = li.mOnLongClickListener.onLongClick(View.this); 5689 } 5690 if (!handled) { 5691 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 5692 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 5693 } 5694 if (handled) { 5695 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 5696 } 5697 return handled; 5698 } 5699 5700 /** 5701 * Call this view's OnContextClickListener, if it is defined. 5702 * 5703 * @param x the x coordinate of the context click 5704 * @param y the y coordinate of the context click 5705 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5706 * otherwise. 5707 */ 5708 public boolean performContextClick(float x, float y) { 5709 return performContextClick(); 5710 } 5711 5712 /** 5713 * Call this view's OnContextClickListener, if it is defined. 5714 * 5715 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5716 * otherwise. 5717 */ 5718 public boolean performContextClick() { 5719 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 5720 5721 boolean handled = false; 5722 ListenerInfo li = mListenerInfo; 5723 if (li != null && li.mOnContextClickListener != null) { 5724 handled = li.mOnContextClickListener.onContextClick(View.this); 5725 } 5726 if (handled) { 5727 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 5728 } 5729 return handled; 5730 } 5731 5732 /** 5733 * Performs button-related actions during a touch down event. 5734 * 5735 * @param event The event. 5736 * @return True if the down was consumed. 5737 * 5738 * @hide 5739 */ 5740 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 5741 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 5742 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 5743 showContextMenu(event.getX(), event.getY()); 5744 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 5745 return true; 5746 } 5747 return false; 5748 } 5749 5750 /** 5751 * Shows the context menu for this view. 5752 * 5753 * @return {@code true} if the context menu was shown, {@code false} 5754 * otherwise 5755 * @see #showContextMenu(float, float) 5756 */ 5757 public boolean showContextMenu() { 5758 return getParent().showContextMenuForChild(this); 5759 } 5760 5761 /** 5762 * Shows the context menu for this view anchored to the specified 5763 * view-relative coordinate. 5764 * 5765 * @param x the X coordinate in pixels relative to the view to which the 5766 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5767 * @param y the Y coordinate in pixels relative to the view to which the 5768 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5769 * @return {@code true} if the context menu was shown, {@code false} 5770 * otherwise 5771 */ 5772 public boolean showContextMenu(float x, float y) { 5773 return getParent().showContextMenuForChild(this, x, y); 5774 } 5775 5776 /** 5777 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 5778 * 5779 * @param callback Callback that will control the lifecycle of the action mode 5780 * @return The new action mode if it is started, null otherwise 5781 * 5782 * @see ActionMode 5783 * @see #startActionMode(android.view.ActionMode.Callback, int) 5784 */ 5785 public ActionMode startActionMode(ActionMode.Callback callback) { 5786 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 5787 } 5788 5789 /** 5790 * Start an action mode with the given type. 5791 * 5792 * @param callback Callback that will control the lifecycle of the action mode 5793 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 5794 * @return The new action mode if it is started, null otherwise 5795 * 5796 * @see ActionMode 5797 */ 5798 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 5799 ViewParent parent = getParent(); 5800 if (parent == null) return null; 5801 try { 5802 return parent.startActionModeForChild(this, callback, type); 5803 } catch (AbstractMethodError ame) { 5804 // Older implementations of custom views might not implement this. 5805 return parent.startActionModeForChild(this, callback); 5806 } 5807 } 5808 5809 /** 5810 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 5811 * Context, creating a unique View identifier to retrieve the result. 5812 * 5813 * @param intent The Intent to be started. 5814 * @param requestCode The request code to use. 5815 * @hide 5816 */ 5817 public void startActivityForResult(Intent intent, int requestCode) { 5818 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 5819 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 5820 } 5821 5822 /** 5823 * If this View corresponds to the calling who, dispatches the activity result. 5824 * @param who The identifier for the targeted View to receive the result. 5825 * @param requestCode The integer request code originally supplied to 5826 * startActivityForResult(), allowing you to identify who this 5827 * result came from. 5828 * @param resultCode The integer result code returned by the child activity 5829 * through its setResult(). 5830 * @param data An Intent, which can return result data to the caller 5831 * (various data can be attached to Intent "extras"). 5832 * @return {@code true} if the activity result was dispatched. 5833 * @hide 5834 */ 5835 public boolean dispatchActivityResult( 5836 String who, int requestCode, int resultCode, Intent data) { 5837 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 5838 onActivityResult(requestCode, resultCode, data); 5839 mStartActivityRequestWho = null; 5840 return true; 5841 } 5842 return false; 5843 } 5844 5845 /** 5846 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 5847 * 5848 * @param requestCode The integer request code originally supplied to 5849 * startActivityForResult(), allowing you to identify who this 5850 * result came from. 5851 * @param resultCode The integer result code returned by the child activity 5852 * through its setResult(). 5853 * @param data An Intent, which can return result data to the caller 5854 * (various data can be attached to Intent "extras"). 5855 * @hide 5856 */ 5857 public void onActivityResult(int requestCode, int resultCode, Intent data) { 5858 // Do nothing. 5859 } 5860 5861 /** 5862 * Register a callback to be invoked when a hardware key is pressed in this view. 5863 * Key presses in software input methods will generally not trigger the methods of 5864 * this listener. 5865 * @param l the key listener to attach to this view 5866 */ 5867 public void setOnKeyListener(OnKeyListener l) { 5868 getListenerInfo().mOnKeyListener = l; 5869 } 5870 5871 /** 5872 * Register a callback to be invoked when a touch event is sent to this view. 5873 * @param l the touch listener to attach to this view 5874 */ 5875 public void setOnTouchListener(OnTouchListener l) { 5876 getListenerInfo().mOnTouchListener = l; 5877 } 5878 5879 /** 5880 * Register a callback to be invoked when a generic motion event is sent to this view. 5881 * @param l the generic motion listener to attach to this view 5882 */ 5883 public void setOnGenericMotionListener(OnGenericMotionListener l) { 5884 getListenerInfo().mOnGenericMotionListener = l; 5885 } 5886 5887 /** 5888 * Register a callback to be invoked when a hover event is sent to this view. 5889 * @param l the hover listener to attach to this view 5890 */ 5891 public void setOnHoverListener(OnHoverListener l) { 5892 getListenerInfo().mOnHoverListener = l; 5893 } 5894 5895 /** 5896 * Register a drag event listener callback object for this View. The parameter is 5897 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 5898 * View, the system calls the 5899 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 5900 * @param l An implementation of {@link android.view.View.OnDragListener}. 5901 */ 5902 public void setOnDragListener(OnDragListener l) { 5903 getListenerInfo().mOnDragListener = l; 5904 } 5905 5906 /** 5907 * Give this view focus. This will cause 5908 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 5909 * 5910 * Note: this does not check whether this {@link View} should get focus, it just 5911 * gives it focus no matter what. It should only be called internally by framework 5912 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 5913 * 5914 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5915 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 5916 * focus moved when requestFocus() is called. It may not always 5917 * apply, in which case use the default View.FOCUS_DOWN. 5918 * @param previouslyFocusedRect The rectangle of the view that had focus 5919 * prior in this View's coordinate system. 5920 */ 5921 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 5922 if (DBG) { 5923 System.out.println(this + " requestFocus()"); 5924 } 5925 5926 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 5927 mPrivateFlags |= PFLAG_FOCUSED; 5928 5929 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 5930 5931 if (mParent != null) { 5932 mParent.requestChildFocus(this, this); 5933 } 5934 5935 if (mAttachInfo != null) { 5936 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 5937 } 5938 5939 onFocusChanged(true, direction, previouslyFocusedRect); 5940 refreshDrawableState(); 5941 } 5942 } 5943 5944 /** 5945 * Populates <code>outRect</code> with the hotspot bounds. By default, 5946 * the hotspot bounds are identical to the screen bounds. 5947 * 5948 * @param outRect rect to populate with hotspot bounds 5949 * @hide Only for internal use by views and widgets. 5950 */ 5951 public void getHotspotBounds(Rect outRect) { 5952 final Drawable background = getBackground(); 5953 if (background != null) { 5954 background.getHotspotBounds(outRect); 5955 } else { 5956 getBoundsOnScreen(outRect); 5957 } 5958 } 5959 5960 /** 5961 * Request that a rectangle of this view be visible on the screen, 5962 * scrolling if necessary just enough. 5963 * 5964 * <p>A View should call this if it maintains some notion of which part 5965 * of its content is interesting. For example, a text editing view 5966 * should call this when its cursor moves. 5967 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 5968 * It should not be affected by which part of the View is currently visible or its scroll 5969 * position. 5970 * 5971 * @param rectangle The rectangle in the View's content coordinate space 5972 * @return Whether any parent scrolled. 5973 */ 5974 public boolean requestRectangleOnScreen(Rect rectangle) { 5975 return requestRectangleOnScreen(rectangle, false); 5976 } 5977 5978 /** 5979 * Request that a rectangle of this view be visible on the screen, 5980 * scrolling if necessary just enough. 5981 * 5982 * <p>A View should call this if it maintains some notion of which part 5983 * of its content is interesting. For example, a text editing view 5984 * should call this when its cursor moves. 5985 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 5986 * It should not be affected by which part of the View is currently visible or its scroll 5987 * position. 5988 * <p>When <code>immediate</code> is set to true, scrolling will not be 5989 * animated. 5990 * 5991 * @param rectangle The rectangle in the View's content coordinate space 5992 * @param immediate True to forbid animated scrolling, false otherwise 5993 * @return Whether any parent scrolled. 5994 */ 5995 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5996 if (mParent == null) { 5997 return false; 5998 } 5999 6000 View child = this; 6001 6002 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 6003 position.set(rectangle); 6004 6005 ViewParent parent = mParent; 6006 boolean scrolled = false; 6007 while (parent != null) { 6008 rectangle.set((int) position.left, (int) position.top, 6009 (int) position.right, (int) position.bottom); 6010 6011 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 6012 6013 if (!(parent instanceof View)) { 6014 break; 6015 } 6016 6017 // move it from child's content coordinate space to parent's content coordinate space 6018 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 6019 6020 child = (View) parent; 6021 parent = child.getParent(); 6022 } 6023 6024 return scrolled; 6025 } 6026 6027 /** 6028 * Called when this view wants to give up focus. If focus is cleared 6029 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 6030 * <p> 6031 * <strong>Note:</strong> When a View clears focus the framework is trying 6032 * to give focus to the first focusable View from the top. Hence, if this 6033 * View is the first from the top that can take focus, then all callbacks 6034 * related to clearing focus will be invoked after which the framework will 6035 * give focus to this view. 6036 * </p> 6037 */ 6038 public void clearFocus() { 6039 if (DBG) { 6040 System.out.println(this + " clearFocus()"); 6041 } 6042 6043 clearFocusInternal(null, true, true); 6044 } 6045 6046 /** 6047 * Clears focus from the view, optionally propagating the change up through 6048 * the parent hierarchy and requesting that the root view place new focus. 6049 * 6050 * @param propagate whether to propagate the change up through the parent 6051 * hierarchy 6052 * @param refocus when propagate is true, specifies whether to request the 6053 * root view place new focus 6054 */ 6055 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 6056 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 6057 mPrivateFlags &= ~PFLAG_FOCUSED; 6058 6059 if (propagate && mParent != null) { 6060 mParent.clearChildFocus(this); 6061 } 6062 6063 onFocusChanged(false, 0, null); 6064 refreshDrawableState(); 6065 6066 if (propagate && (!refocus || !rootViewRequestFocus())) { 6067 notifyGlobalFocusCleared(this); 6068 } 6069 } 6070 } 6071 6072 void notifyGlobalFocusCleared(View oldFocus) { 6073 if (oldFocus != null && mAttachInfo != null) { 6074 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 6075 } 6076 } 6077 6078 boolean rootViewRequestFocus() { 6079 final View root = getRootView(); 6080 return root != null && root.requestFocus(); 6081 } 6082 6083 /** 6084 * Called internally by the view system when a new view is getting focus. 6085 * This is what clears the old focus. 6086 * <p> 6087 * <b>NOTE:</b> The parent view's focused child must be updated manually 6088 * after calling this method. Otherwise, the view hierarchy may be left in 6089 * an inconstent state. 6090 */ 6091 void unFocus(View focused) { 6092 if (DBG) { 6093 System.out.println(this + " unFocus()"); 6094 } 6095 6096 clearFocusInternal(focused, false, false); 6097 } 6098 6099 /** 6100 * Returns true if this view has focus itself, or is the ancestor of the 6101 * view that has focus. 6102 * 6103 * @return True if this view has or contains focus, false otherwise. 6104 */ 6105 @ViewDebug.ExportedProperty(category = "focus") 6106 public boolean hasFocus() { 6107 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6108 } 6109 6110 /** 6111 * Returns true if this view is focusable or if it contains a reachable View 6112 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 6113 * is a View whose parents do not block descendants focus. 6114 * 6115 * Only {@link #VISIBLE} views are considered focusable. 6116 * 6117 * @return True if the view is focusable or if the view contains a focusable 6118 * View, false otherwise. 6119 * 6120 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 6121 * @see ViewGroup#getTouchscreenBlocksFocus() 6122 */ 6123 public boolean hasFocusable() { 6124 if (!isFocusableInTouchMode()) { 6125 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 6126 final ViewGroup g = (ViewGroup) p; 6127 if (g.shouldBlockFocusForTouchscreen()) { 6128 return false; 6129 } 6130 } 6131 } 6132 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 6133 } 6134 6135 /** 6136 * Called by the view system when the focus state of this view changes. 6137 * When the focus change event is caused by directional navigation, direction 6138 * and previouslyFocusedRect provide insight into where the focus is coming from. 6139 * When overriding, be sure to call up through to the super class so that 6140 * the standard focus handling will occur. 6141 * 6142 * @param gainFocus True if the View has focus; false otherwise. 6143 * @param direction The direction focus has moved when requestFocus() 6144 * is called to give this view focus. Values are 6145 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 6146 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 6147 * It may not always apply, in which case use the default. 6148 * @param previouslyFocusedRect The rectangle, in this view's coordinate 6149 * system, of the previously focused view. If applicable, this will be 6150 * passed in as finer grained information about where the focus is coming 6151 * from (in addition to direction). Will be <code>null</code> otherwise. 6152 */ 6153 @CallSuper 6154 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 6155 @Nullable Rect previouslyFocusedRect) { 6156 if (gainFocus) { 6157 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6158 } else { 6159 notifyViewAccessibilityStateChangedIfNeeded( 6160 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6161 } 6162 6163 InputMethodManager imm = InputMethodManager.peekInstance(); 6164 if (!gainFocus) { 6165 if (isPressed()) { 6166 setPressed(false); 6167 } 6168 if (imm != null && mAttachInfo != null 6169 && mAttachInfo.mHasWindowFocus) { 6170 imm.focusOut(this); 6171 } 6172 onFocusLost(); 6173 } else if (imm != null && mAttachInfo != null 6174 && mAttachInfo.mHasWindowFocus) { 6175 imm.focusIn(this); 6176 } 6177 6178 invalidate(true); 6179 ListenerInfo li = mListenerInfo; 6180 if (li != null && li.mOnFocusChangeListener != null) { 6181 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 6182 } 6183 6184 if (mAttachInfo != null) { 6185 mAttachInfo.mKeyDispatchState.reset(this); 6186 } 6187 } 6188 6189 /** 6190 * Sends an accessibility event of the given type. If accessibility is 6191 * not enabled this method has no effect. The default implementation calls 6192 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 6193 * to populate information about the event source (this View), then calls 6194 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 6195 * populate the text content of the event source including its descendants, 6196 * and last calls 6197 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 6198 * on its parent to request sending of the event to interested parties. 6199 * <p> 6200 * If an {@link AccessibilityDelegate} has been specified via calling 6201 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6202 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 6203 * responsible for handling this call. 6204 * </p> 6205 * 6206 * @param eventType The type of the event to send, as defined by several types from 6207 * {@link android.view.accessibility.AccessibilityEvent}, such as 6208 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 6209 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 6210 * 6211 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6212 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6213 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 6214 * @see AccessibilityDelegate 6215 */ 6216 public void sendAccessibilityEvent(int eventType) { 6217 if (mAccessibilityDelegate != null) { 6218 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 6219 } else { 6220 sendAccessibilityEventInternal(eventType); 6221 } 6222 } 6223 6224 /** 6225 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 6226 * {@link AccessibilityEvent} to make an announcement which is related to some 6227 * sort of a context change for which none of the events representing UI transitions 6228 * is a good fit. For example, announcing a new page in a book. If accessibility 6229 * is not enabled this method does nothing. 6230 * 6231 * @param text The announcement text. 6232 */ 6233 public void announceForAccessibility(CharSequence text) { 6234 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 6235 AccessibilityEvent event = AccessibilityEvent.obtain( 6236 AccessibilityEvent.TYPE_ANNOUNCEMENT); 6237 onInitializeAccessibilityEvent(event); 6238 event.getText().add(text); 6239 event.setContentDescription(null); 6240 mParent.requestSendAccessibilityEvent(this, event); 6241 } 6242 } 6243 6244 /** 6245 * @see #sendAccessibilityEvent(int) 6246 * 6247 * Note: Called from the default {@link AccessibilityDelegate}. 6248 * 6249 * @hide 6250 */ 6251 public void sendAccessibilityEventInternal(int eventType) { 6252 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6253 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 6254 } 6255 } 6256 6257 /** 6258 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 6259 * takes as an argument an empty {@link AccessibilityEvent} and does not 6260 * perform a check whether accessibility is enabled. 6261 * <p> 6262 * If an {@link AccessibilityDelegate} has been specified via calling 6263 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6264 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 6265 * is responsible for handling this call. 6266 * </p> 6267 * 6268 * @param event The event to send. 6269 * 6270 * @see #sendAccessibilityEvent(int) 6271 */ 6272 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 6273 if (mAccessibilityDelegate != null) { 6274 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 6275 } else { 6276 sendAccessibilityEventUncheckedInternal(event); 6277 } 6278 } 6279 6280 /** 6281 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 6282 * 6283 * Note: Called from the default {@link AccessibilityDelegate}. 6284 * 6285 * @hide 6286 */ 6287 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 6288 if (!isShown()) { 6289 return; 6290 } 6291 onInitializeAccessibilityEvent(event); 6292 // Only a subset of accessibility events populates text content. 6293 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 6294 dispatchPopulateAccessibilityEvent(event); 6295 } 6296 // In the beginning we called #isShown(), so we know that getParent() is not null. 6297 getParent().requestSendAccessibilityEvent(this, event); 6298 } 6299 6300 /** 6301 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 6302 * to its children for adding their text content to the event. Note that the 6303 * event text is populated in a separate dispatch path since we add to the 6304 * event not only the text of the source but also the text of all its descendants. 6305 * A typical implementation will call 6306 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 6307 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6308 * on each child. Override this method if custom population of the event text 6309 * content is required. 6310 * <p> 6311 * If an {@link AccessibilityDelegate} has been specified via calling 6312 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6313 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 6314 * is responsible for handling this call. 6315 * </p> 6316 * <p> 6317 * <em>Note:</em> Accessibility events of certain types are not dispatched for 6318 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 6319 * </p> 6320 * 6321 * @param event The event. 6322 * 6323 * @return True if the event population was completed. 6324 */ 6325 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 6326 if (mAccessibilityDelegate != null) { 6327 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 6328 } else { 6329 return dispatchPopulateAccessibilityEventInternal(event); 6330 } 6331 } 6332 6333 /** 6334 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6335 * 6336 * Note: Called from the default {@link AccessibilityDelegate}. 6337 * 6338 * @hide 6339 */ 6340 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6341 onPopulateAccessibilityEvent(event); 6342 return false; 6343 } 6344 6345 /** 6346 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6347 * giving a chance to this View to populate the accessibility event with its 6348 * text content. While this method is free to modify event 6349 * attributes other than text content, doing so should normally be performed in 6350 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 6351 * <p> 6352 * Example: Adding formatted date string to an accessibility event in addition 6353 * to the text added by the super implementation: 6354 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6355 * super.onPopulateAccessibilityEvent(event); 6356 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 6357 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 6358 * mCurrentDate.getTimeInMillis(), flags); 6359 * event.getText().add(selectedDateUtterance); 6360 * }</pre> 6361 * <p> 6362 * If an {@link AccessibilityDelegate} has been specified via calling 6363 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6364 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 6365 * is responsible for handling this call. 6366 * </p> 6367 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6368 * information to the event, in case the default implementation has basic information to add. 6369 * </p> 6370 * 6371 * @param event The accessibility event which to populate. 6372 * 6373 * @see #sendAccessibilityEvent(int) 6374 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6375 */ 6376 @CallSuper 6377 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6378 if (mAccessibilityDelegate != null) { 6379 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 6380 } else { 6381 onPopulateAccessibilityEventInternal(event); 6382 } 6383 } 6384 6385 /** 6386 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 6387 * 6388 * Note: Called from the default {@link AccessibilityDelegate}. 6389 * 6390 * @hide 6391 */ 6392 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6393 } 6394 6395 /** 6396 * Initializes an {@link AccessibilityEvent} with information about 6397 * this View which is the event source. In other words, the source of 6398 * an accessibility event is the view whose state change triggered firing 6399 * the event. 6400 * <p> 6401 * Example: Setting the password property of an event in addition 6402 * to properties set by the super implementation: 6403 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6404 * super.onInitializeAccessibilityEvent(event); 6405 * event.setPassword(true); 6406 * }</pre> 6407 * <p> 6408 * If an {@link AccessibilityDelegate} has been specified via calling 6409 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6410 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 6411 * is responsible for handling this call. 6412 * </p> 6413 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6414 * information to the event, in case the default implementation has basic information to add. 6415 * </p> 6416 * @param event The event to initialize. 6417 * 6418 * @see #sendAccessibilityEvent(int) 6419 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6420 */ 6421 @CallSuper 6422 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6423 if (mAccessibilityDelegate != null) { 6424 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 6425 } else { 6426 onInitializeAccessibilityEventInternal(event); 6427 } 6428 } 6429 6430 /** 6431 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6432 * 6433 * Note: Called from the default {@link AccessibilityDelegate}. 6434 * 6435 * @hide 6436 */ 6437 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 6438 event.setSource(this); 6439 event.setClassName(getAccessibilityClassName()); 6440 event.setPackageName(getContext().getPackageName()); 6441 event.setEnabled(isEnabled()); 6442 event.setContentDescription(mContentDescription); 6443 6444 switch (event.getEventType()) { 6445 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 6446 ArrayList<View> focusablesTempList = (mAttachInfo != null) 6447 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 6448 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 6449 event.setItemCount(focusablesTempList.size()); 6450 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 6451 if (mAttachInfo != null) { 6452 focusablesTempList.clear(); 6453 } 6454 } break; 6455 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 6456 CharSequence text = getIterableTextForAccessibility(); 6457 if (text != null && text.length() > 0) { 6458 event.setFromIndex(getAccessibilitySelectionStart()); 6459 event.setToIndex(getAccessibilitySelectionEnd()); 6460 event.setItemCount(text.length()); 6461 } 6462 } break; 6463 } 6464 } 6465 6466 /** 6467 * Returns an {@link AccessibilityNodeInfo} representing this view from the 6468 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 6469 * This method is responsible for obtaining an accessibility node info from a 6470 * pool of reusable instances and calling 6471 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 6472 * initialize the former. 6473 * <p> 6474 * Note: The client is responsible for recycling the obtained instance by calling 6475 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 6476 * </p> 6477 * 6478 * @return A populated {@link AccessibilityNodeInfo}. 6479 * 6480 * @see AccessibilityNodeInfo 6481 */ 6482 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 6483 if (mAccessibilityDelegate != null) { 6484 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 6485 } else { 6486 return createAccessibilityNodeInfoInternal(); 6487 } 6488 } 6489 6490 /** 6491 * @see #createAccessibilityNodeInfo() 6492 * 6493 * @hide 6494 */ 6495 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 6496 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6497 if (provider != null) { 6498 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 6499 } else { 6500 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 6501 onInitializeAccessibilityNodeInfo(info); 6502 return info; 6503 } 6504 } 6505 6506 /** 6507 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 6508 * The base implementation sets: 6509 * <ul> 6510 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 6511 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 6512 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 6513 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 6514 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 6515 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 6516 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 6517 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 6518 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 6519 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 6520 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 6521 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 6522 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 6523 * </ul> 6524 * <p> 6525 * Subclasses should override this method, call the super implementation, 6526 * and set additional attributes. 6527 * </p> 6528 * <p> 6529 * If an {@link AccessibilityDelegate} has been specified via calling 6530 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6531 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 6532 * is responsible for handling this call. 6533 * </p> 6534 * 6535 * @param info The instance to initialize. 6536 */ 6537 @CallSuper 6538 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 6539 if (mAccessibilityDelegate != null) { 6540 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 6541 } else { 6542 onInitializeAccessibilityNodeInfoInternal(info); 6543 } 6544 } 6545 6546 /** 6547 * Gets the location of this view in screen coordinates. 6548 * 6549 * @param outRect The output location 6550 * @hide 6551 */ 6552 public void getBoundsOnScreen(Rect outRect) { 6553 getBoundsOnScreen(outRect, false); 6554 } 6555 6556 /** 6557 * Gets the location of this view in screen coordinates. 6558 * 6559 * @param outRect The output location 6560 * @param clipToParent Whether to clip child bounds to the parent ones. 6561 * @hide 6562 */ 6563 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 6564 if (mAttachInfo == null) { 6565 return; 6566 } 6567 6568 RectF position = mAttachInfo.mTmpTransformRect; 6569 position.set(0, 0, mRight - mLeft, mBottom - mTop); 6570 6571 if (!hasIdentityMatrix()) { 6572 getMatrix().mapRect(position); 6573 } 6574 6575 position.offset(mLeft, mTop); 6576 6577 ViewParent parent = mParent; 6578 while (parent instanceof View) { 6579 View parentView = (View) parent; 6580 6581 position.offset(-parentView.mScrollX, -parentView.mScrollY); 6582 6583 if (clipToParent) { 6584 position.left = Math.max(position.left, 0); 6585 position.top = Math.max(position.top, 0); 6586 position.right = Math.min(position.right, parentView.getWidth()); 6587 position.bottom = Math.min(position.bottom, parentView.getHeight()); 6588 } 6589 6590 if (!parentView.hasIdentityMatrix()) { 6591 parentView.getMatrix().mapRect(position); 6592 } 6593 6594 position.offset(parentView.mLeft, parentView.mTop); 6595 6596 parent = parentView.mParent; 6597 } 6598 6599 if (parent instanceof ViewRootImpl) { 6600 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 6601 position.offset(0, -viewRootImpl.mCurScrollY); 6602 } 6603 6604 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6605 6606 outRect.set(Math.round(position.left), Math.round(position.top), 6607 Math.round(position.right), Math.round(position.bottom)); 6608 } 6609 6610 /** 6611 * Return the class name of this object to be used for accessibility purposes. 6612 * Subclasses should only override this if they are implementing something that 6613 * should be seen as a completely new class of view when used by accessibility, 6614 * unrelated to the class it is deriving from. This is used to fill in 6615 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 6616 */ 6617 public CharSequence getAccessibilityClassName() { 6618 return View.class.getName(); 6619 } 6620 6621 /** 6622 * Called when assist structure is being retrieved from a view as part of 6623 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 6624 * @param structure Fill in with structured view data. The default implementation 6625 * fills in all data that can be inferred from the view itself. 6626 */ 6627 public void onProvideStructure(ViewStructure structure) { 6628 final int id = mID; 6629 if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0 6630 && (id&0x0000ffff) != 0) { 6631 String pkg, type, entry; 6632 try { 6633 final Resources res = getResources(); 6634 entry = res.getResourceEntryName(id); 6635 type = res.getResourceTypeName(id); 6636 pkg = res.getResourcePackageName(id); 6637 } catch (Resources.NotFoundException e) { 6638 entry = type = pkg = null; 6639 } 6640 structure.setId(id, pkg, type, entry); 6641 } else { 6642 structure.setId(id, null, null, null); 6643 } 6644 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 6645 if (!hasIdentityMatrix()) { 6646 structure.setTransformation(getMatrix()); 6647 } 6648 structure.setElevation(getZ()); 6649 structure.setVisibility(getVisibility()); 6650 structure.setEnabled(isEnabled()); 6651 if (isClickable()) { 6652 structure.setClickable(true); 6653 } 6654 if (isFocusable()) { 6655 structure.setFocusable(true); 6656 } 6657 if (isFocused()) { 6658 structure.setFocused(true); 6659 } 6660 if (isAccessibilityFocused()) { 6661 structure.setAccessibilityFocused(true); 6662 } 6663 if (isSelected()) { 6664 structure.setSelected(true); 6665 } 6666 if (isActivated()) { 6667 structure.setActivated(true); 6668 } 6669 if (isLongClickable()) { 6670 structure.setLongClickable(true); 6671 } 6672 if (this instanceof Checkable) { 6673 structure.setCheckable(true); 6674 if (((Checkable)this).isChecked()) { 6675 structure.setChecked(true); 6676 } 6677 } 6678 if (isContextClickable()) { 6679 structure.setContextClickable(true); 6680 } 6681 structure.setClassName(getAccessibilityClassName().toString()); 6682 structure.setContentDescription(getContentDescription()); 6683 } 6684 6685 /** 6686 * Called when assist structure is being retrieved from a view as part of 6687 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 6688 * generate additional virtual structure under this view. The defaullt implementation 6689 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 6690 * view's virtual accessibility nodes, if any. You can override this for a more 6691 * optimal implementation providing this data. 6692 */ 6693 public void onProvideVirtualStructure(ViewStructure structure) { 6694 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6695 if (provider != null) { 6696 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 6697 structure.setChildCount(1); 6698 ViewStructure root = structure.newChild(0); 6699 populateVirtualStructure(root, provider, info); 6700 info.recycle(); 6701 } 6702 } 6703 6704 private void populateVirtualStructure(ViewStructure structure, 6705 AccessibilityNodeProvider provider, AccessibilityNodeInfo info) { 6706 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 6707 null, null, null); 6708 Rect rect = structure.getTempRect(); 6709 info.getBoundsInParent(rect); 6710 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 6711 structure.setVisibility(VISIBLE); 6712 structure.setEnabled(info.isEnabled()); 6713 if (info.isClickable()) { 6714 structure.setClickable(true); 6715 } 6716 if (info.isFocusable()) { 6717 structure.setFocusable(true); 6718 } 6719 if (info.isFocused()) { 6720 structure.setFocused(true); 6721 } 6722 if (info.isAccessibilityFocused()) { 6723 structure.setAccessibilityFocused(true); 6724 } 6725 if (info.isSelected()) { 6726 structure.setSelected(true); 6727 } 6728 if (info.isLongClickable()) { 6729 structure.setLongClickable(true); 6730 } 6731 if (info.isCheckable()) { 6732 structure.setCheckable(true); 6733 if (info.isChecked()) { 6734 structure.setChecked(true); 6735 } 6736 } 6737 if (info.isContextClickable()) { 6738 structure.setContextClickable(true); 6739 } 6740 CharSequence cname = info.getClassName(); 6741 structure.setClassName(cname != null ? cname.toString() : null); 6742 structure.setContentDescription(info.getContentDescription()); 6743 if (info.getText() != null || info.getError() != null) { 6744 structure.setText(info.getText(), info.getTextSelectionStart(), 6745 info.getTextSelectionEnd()); 6746 } 6747 final int NCHILDREN = info.getChildCount(); 6748 if (NCHILDREN > 0) { 6749 structure.setChildCount(NCHILDREN); 6750 for (int i=0; i<NCHILDREN; i++) { 6751 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 6752 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 6753 ViewStructure child = structure.newChild(i); 6754 populateVirtualStructure(child, provider, cinfo); 6755 cinfo.recycle(); 6756 } 6757 } 6758 } 6759 6760 /** 6761 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 6762 * implementation calls {@link #onProvideStructure} and 6763 * {@link #onProvideVirtualStructure}. 6764 */ 6765 public void dispatchProvideStructure(ViewStructure structure) { 6766 if (!isAssistBlocked()) { 6767 onProvideStructure(structure); 6768 onProvideVirtualStructure(structure); 6769 } else { 6770 structure.setClassName(getAccessibilityClassName().toString()); 6771 structure.setAssistBlocked(true); 6772 } 6773 } 6774 6775 /** 6776 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 6777 * 6778 * Note: Called from the default {@link AccessibilityDelegate}. 6779 * 6780 * @hide 6781 */ 6782 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 6783 if (mAttachInfo == null) { 6784 return; 6785 } 6786 6787 Rect bounds = mAttachInfo.mTmpInvalRect; 6788 6789 getDrawingRect(bounds); 6790 info.setBoundsInParent(bounds); 6791 6792 getBoundsOnScreen(bounds, true); 6793 info.setBoundsInScreen(bounds); 6794 6795 ViewParent parent = getParentForAccessibility(); 6796 if (parent instanceof View) { 6797 info.setParent((View) parent); 6798 } 6799 6800 if (mID != View.NO_ID) { 6801 View rootView = getRootView(); 6802 if (rootView == null) { 6803 rootView = this; 6804 } 6805 6806 View label = rootView.findLabelForView(this, mID); 6807 if (label != null) { 6808 info.setLabeledBy(label); 6809 } 6810 6811 if ((mAttachInfo.mAccessibilityFetchFlags 6812 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 6813 && Resources.resourceHasPackage(mID)) { 6814 try { 6815 String viewId = getResources().getResourceName(mID); 6816 info.setViewIdResourceName(viewId); 6817 } catch (Resources.NotFoundException nfe) { 6818 /* ignore */ 6819 } 6820 } 6821 } 6822 6823 if (mLabelForId != View.NO_ID) { 6824 View rootView = getRootView(); 6825 if (rootView == null) { 6826 rootView = this; 6827 } 6828 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 6829 if (labeled != null) { 6830 info.setLabelFor(labeled); 6831 } 6832 } 6833 6834 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 6835 View rootView = getRootView(); 6836 if (rootView == null) { 6837 rootView = this; 6838 } 6839 View next = rootView.findViewInsideOutShouldExist(this, 6840 mAccessibilityTraversalBeforeId); 6841 if (next != null && next.includeForAccessibility()) { 6842 info.setTraversalBefore(next); 6843 } 6844 } 6845 6846 if (mAccessibilityTraversalAfterId != View.NO_ID) { 6847 View rootView = getRootView(); 6848 if (rootView == null) { 6849 rootView = this; 6850 } 6851 View next = rootView.findViewInsideOutShouldExist(this, 6852 mAccessibilityTraversalAfterId); 6853 if (next != null && next.includeForAccessibility()) { 6854 info.setTraversalAfter(next); 6855 } 6856 } 6857 6858 info.setVisibleToUser(isVisibleToUser()); 6859 6860 if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags 6861 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) { 6862 info.setImportantForAccessibility(isImportantForAccessibility()); 6863 } else { 6864 info.setImportantForAccessibility(true); 6865 } 6866 6867 info.setPackageName(mContext.getPackageName()); 6868 info.setClassName(getAccessibilityClassName()); 6869 info.setContentDescription(getContentDescription()); 6870 6871 info.setEnabled(isEnabled()); 6872 info.setClickable(isClickable()); 6873 info.setFocusable(isFocusable()); 6874 info.setFocused(isFocused()); 6875 info.setAccessibilityFocused(isAccessibilityFocused()); 6876 info.setSelected(isSelected()); 6877 info.setLongClickable(isLongClickable()); 6878 info.setContextClickable(isContextClickable()); 6879 info.setLiveRegion(getAccessibilityLiveRegion()); 6880 6881 // TODO: These make sense only if we are in an AdapterView but all 6882 // views can be selected. Maybe from accessibility perspective 6883 // we should report as selectable view in an AdapterView. 6884 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 6885 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 6886 6887 if (isFocusable()) { 6888 if (isFocused()) { 6889 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 6890 } else { 6891 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 6892 } 6893 } 6894 6895 if (!isAccessibilityFocused()) { 6896 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 6897 } else { 6898 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 6899 } 6900 6901 if (isClickable() && isEnabled()) { 6902 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 6903 } 6904 6905 if (isLongClickable() && isEnabled()) { 6906 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 6907 } 6908 6909 if (isContextClickable() && isEnabled()) { 6910 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 6911 } 6912 6913 CharSequence text = getIterableTextForAccessibility(); 6914 if (text != null && text.length() > 0) { 6915 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 6916 6917 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 6918 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 6919 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 6920 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 6921 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 6922 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 6923 } 6924 6925 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 6926 populateAccessibilityNodeInfoDrawingOrderInParent(info); 6927 } 6928 6929 /** 6930 * Determine the order in which this view will be drawn relative to its siblings for a11y 6931 * 6932 * @param info The info whose drawing order should be populated 6933 */ 6934 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 6935 /* 6936 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 6937 * drawing order may not be well-defined, and some Views with custom drawing order may 6938 * not be initialized sufficiently to respond properly getChildDrawingOrder. 6939 */ 6940 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 6941 info.setDrawingOrder(0); 6942 return; 6943 } 6944 int drawingOrderInParent = 1; 6945 // Iterate up the hierarchy if parents are not important for a11y 6946 View viewAtDrawingLevel = this; 6947 final ViewParent parent = getParentForAccessibility(); 6948 while (viewAtDrawingLevel != parent) { 6949 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 6950 if (!(currentParent instanceof ViewGroup)) { 6951 // Should only happen for the Decor 6952 drawingOrderInParent = 0; 6953 break; 6954 } else { 6955 final ViewGroup parentGroup = (ViewGroup) currentParent; 6956 final int childCount = parentGroup.getChildCount(); 6957 if (childCount > 1) { 6958 List<View> preorderedList = parentGroup.buildOrderedChildList(); 6959 if (preorderedList != null) { 6960 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 6961 for (int i = 0; i < childDrawIndex; i++) { 6962 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 6963 } 6964 } else { 6965 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 6966 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 6967 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 6968 .getChildDrawingOrder(childCount, childIndex) : childIndex; 6969 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 6970 if (childDrawIndex != 0) { 6971 for (int i = 0; i < numChildrenToIterate; i++) { 6972 final int otherDrawIndex = (customOrder ? 6973 parentGroup.getChildDrawingOrder(childCount, i) : i); 6974 if (otherDrawIndex < childDrawIndex) { 6975 drawingOrderInParent += 6976 numViewsForAccessibility(parentGroup.getChildAt(i)); 6977 } 6978 } 6979 } 6980 } 6981 } 6982 } 6983 viewAtDrawingLevel = (View) currentParent; 6984 } 6985 info.setDrawingOrder(drawingOrderInParent); 6986 } 6987 6988 private static int numViewsForAccessibility(View view) { 6989 if (view != null) { 6990 if (view.includeForAccessibility()) { 6991 return 1; 6992 } else if (view instanceof ViewGroup) { 6993 return ((ViewGroup) view).getNumChildrenForAccessibility(); 6994 } 6995 } 6996 return 0; 6997 } 6998 6999 private View findLabelForView(View view, int labeledId) { 7000 if (mMatchLabelForPredicate == null) { 7001 mMatchLabelForPredicate = new MatchLabelForPredicate(); 7002 } 7003 mMatchLabelForPredicate.mLabeledId = labeledId; 7004 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 7005 } 7006 7007 /** 7008 * Computes whether this view is visible to the user. Such a view is 7009 * attached, visible, all its predecessors are visible, it is not clipped 7010 * entirely by its predecessors, and has an alpha greater than zero. 7011 * 7012 * @return Whether the view is visible on the screen. 7013 * 7014 * @hide 7015 */ 7016 protected boolean isVisibleToUser() { 7017 return isVisibleToUser(null); 7018 } 7019 7020 /** 7021 * Computes whether the given portion of this view is visible to the user. 7022 * Such a view is attached, visible, all its predecessors are visible, 7023 * has an alpha greater than zero, and the specified portion is not 7024 * clipped entirely by its predecessors. 7025 * 7026 * @param boundInView the portion of the view to test; coordinates should be relative; may be 7027 * <code>null</code>, and the entire view will be tested in this case. 7028 * When <code>true</code> is returned by the function, the actual visible 7029 * region will be stored in this parameter; that is, if boundInView is fully 7030 * contained within the view, no modification will be made, otherwise regions 7031 * outside of the visible area of the view will be clipped. 7032 * 7033 * @return Whether the specified portion of the view is visible on the screen. 7034 * 7035 * @hide 7036 */ 7037 protected boolean isVisibleToUser(Rect boundInView) { 7038 if (mAttachInfo != null) { 7039 // Attached to invisible window means this view is not visible. 7040 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 7041 return false; 7042 } 7043 // An invisible predecessor or one with alpha zero means 7044 // that this view is not visible to the user. 7045 Object current = this; 7046 while (current instanceof View) { 7047 View view = (View) current; 7048 // We have attach info so this view is attached and there is no 7049 // need to check whether we reach to ViewRootImpl on the way up. 7050 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 7051 view.getVisibility() != VISIBLE) { 7052 return false; 7053 } 7054 current = view.mParent; 7055 } 7056 // Check if the view is entirely covered by its predecessors. 7057 Rect visibleRect = mAttachInfo.mTmpInvalRect; 7058 Point offset = mAttachInfo.mPoint; 7059 if (!getGlobalVisibleRect(visibleRect, offset)) { 7060 return false; 7061 } 7062 // Check if the visible portion intersects the rectangle of interest. 7063 if (boundInView != null) { 7064 visibleRect.offset(-offset.x, -offset.y); 7065 return boundInView.intersect(visibleRect); 7066 } 7067 return true; 7068 } 7069 return false; 7070 } 7071 7072 /** 7073 * Returns the delegate for implementing accessibility support via 7074 * composition. For more details see {@link AccessibilityDelegate}. 7075 * 7076 * @return The delegate, or null if none set. 7077 * 7078 * @hide 7079 */ 7080 public AccessibilityDelegate getAccessibilityDelegate() { 7081 return mAccessibilityDelegate; 7082 } 7083 7084 /** 7085 * Sets a delegate for implementing accessibility support via composition 7086 * (as opposed to inheritance). For more details, see 7087 * {@link AccessibilityDelegate}. 7088 * <p> 7089 * <strong>Note:</strong> On platform versions prior to 7090 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 7091 * views in the {@code android.widget.*} package are called <i>before</i> 7092 * host methods. This prevents certain properties such as class name from 7093 * being modified by overriding 7094 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 7095 * as any changes will be overwritten by the host class. 7096 * <p> 7097 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 7098 * methods are called <i>after</i> host methods, which all properties to be 7099 * modified without being overwritten by the host class. 7100 * 7101 * @param delegate the object to which accessibility method calls should be 7102 * delegated 7103 * @see AccessibilityDelegate 7104 */ 7105 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 7106 mAccessibilityDelegate = delegate; 7107 } 7108 7109 /** 7110 * Gets the provider for managing a virtual view hierarchy rooted at this View 7111 * and reported to {@link android.accessibilityservice.AccessibilityService}s 7112 * that explore the window content. 7113 * <p> 7114 * If this method returns an instance, this instance is responsible for managing 7115 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 7116 * View including the one representing the View itself. Similarly the returned 7117 * instance is responsible for performing accessibility actions on any virtual 7118 * view or the root view itself. 7119 * </p> 7120 * <p> 7121 * If an {@link AccessibilityDelegate} has been specified via calling 7122 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7123 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 7124 * is responsible for handling this call. 7125 * </p> 7126 * 7127 * @return The provider. 7128 * 7129 * @see AccessibilityNodeProvider 7130 */ 7131 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 7132 if (mAccessibilityDelegate != null) { 7133 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 7134 } else { 7135 return null; 7136 } 7137 } 7138 7139 /** 7140 * Gets the unique identifier of this view on the screen for accessibility purposes. 7141 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 7142 * 7143 * @return The view accessibility id. 7144 * 7145 * @hide 7146 */ 7147 public int getAccessibilityViewId() { 7148 if (mAccessibilityViewId == NO_ID) { 7149 mAccessibilityViewId = sNextAccessibilityViewId++; 7150 } 7151 return mAccessibilityViewId; 7152 } 7153 7154 /** 7155 * Gets the unique identifier of the window in which this View reseides. 7156 * 7157 * @return The window accessibility id. 7158 * 7159 * @hide 7160 */ 7161 public int getAccessibilityWindowId() { 7162 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 7163 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 7164 } 7165 7166 /** 7167 * Returns the {@link View}'s content description. 7168 * <p> 7169 * <strong>Note:</strong> Do not override this method, as it will have no 7170 * effect on the content description presented to accessibility services. 7171 * You must call {@link #setContentDescription(CharSequence)} to modify the 7172 * content description. 7173 * 7174 * @return the content description 7175 * @see #setContentDescription(CharSequence) 7176 * @attr ref android.R.styleable#View_contentDescription 7177 */ 7178 @ViewDebug.ExportedProperty(category = "accessibility") 7179 public CharSequence getContentDescription() { 7180 return mContentDescription; 7181 } 7182 7183 /** 7184 * Sets the {@link View}'s content description. 7185 * <p> 7186 * A content description briefly describes the view and is primarily used 7187 * for accessibility support to determine how a view should be presented to 7188 * the user. In the case of a view with no textual representation, such as 7189 * {@link android.widget.ImageButton}, a useful content description 7190 * explains what the view does. For example, an image button with a phone 7191 * icon that is used to place a call may use "Call" as its content 7192 * description. An image of a floppy disk that is used to save a file may 7193 * use "Save". 7194 * 7195 * @param contentDescription The content description. 7196 * @see #getContentDescription() 7197 * @attr ref android.R.styleable#View_contentDescription 7198 */ 7199 @RemotableViewMethod 7200 public void setContentDescription(CharSequence contentDescription) { 7201 if (mContentDescription == null) { 7202 if (contentDescription == null) { 7203 return; 7204 } 7205 } else if (mContentDescription.equals(contentDescription)) { 7206 return; 7207 } 7208 mContentDescription = contentDescription; 7209 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 7210 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 7211 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 7212 notifySubtreeAccessibilityStateChangedIfNeeded(); 7213 } else { 7214 notifyViewAccessibilityStateChangedIfNeeded( 7215 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 7216 } 7217 } 7218 7219 /** 7220 * Sets the id of a view before which this one is visited in accessibility traversal. 7221 * A screen-reader must visit the content of this view before the content of the one 7222 * it precedes. For example, if view B is set to be before view A, then a screen-reader 7223 * will traverse the entire content of B before traversing the entire content of A, 7224 * regardles of what traversal strategy it is using. 7225 * <p> 7226 * Views that do not have specified before/after relationships are traversed in order 7227 * determined by the screen-reader. 7228 * </p> 7229 * <p> 7230 * Setting that this view is before a view that is not important for accessibility 7231 * or if this view is not important for accessibility will have no effect as the 7232 * screen-reader is not aware of unimportant views. 7233 * </p> 7234 * 7235 * @param beforeId The id of a view this one precedes in accessibility traversal. 7236 * 7237 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 7238 * 7239 * @see #setImportantForAccessibility(int) 7240 */ 7241 @RemotableViewMethod 7242 public void setAccessibilityTraversalBefore(int beforeId) { 7243 if (mAccessibilityTraversalBeforeId == beforeId) { 7244 return; 7245 } 7246 mAccessibilityTraversalBeforeId = beforeId; 7247 notifyViewAccessibilityStateChangedIfNeeded( 7248 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7249 } 7250 7251 /** 7252 * Gets the id of a view before which this one is visited in accessibility traversal. 7253 * 7254 * @return The id of a view this one precedes in accessibility traversal if 7255 * specified, otherwise {@link #NO_ID}. 7256 * 7257 * @see #setAccessibilityTraversalBefore(int) 7258 */ 7259 public int getAccessibilityTraversalBefore() { 7260 return mAccessibilityTraversalBeforeId; 7261 } 7262 7263 /** 7264 * Sets the id of a view after which this one is visited in accessibility traversal. 7265 * A screen-reader must visit the content of the other view before the content of this 7266 * one. For example, if view B is set to be after view A, then a screen-reader 7267 * will traverse the entire content of A before traversing the entire content of B, 7268 * regardles of what traversal strategy it is using. 7269 * <p> 7270 * Views that do not have specified before/after relationships are traversed in order 7271 * determined by the screen-reader. 7272 * </p> 7273 * <p> 7274 * Setting that this view is after a view that is not important for accessibility 7275 * or if this view is not important for accessibility will have no effect as the 7276 * screen-reader is not aware of unimportant views. 7277 * </p> 7278 * 7279 * @param afterId The id of a view this one succedees in accessibility traversal. 7280 * 7281 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 7282 * 7283 * @see #setImportantForAccessibility(int) 7284 */ 7285 @RemotableViewMethod 7286 public void setAccessibilityTraversalAfter(int afterId) { 7287 if (mAccessibilityTraversalAfterId == afterId) { 7288 return; 7289 } 7290 mAccessibilityTraversalAfterId = afterId; 7291 notifyViewAccessibilityStateChangedIfNeeded( 7292 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7293 } 7294 7295 /** 7296 * Gets the id of a view after which this one is visited in accessibility traversal. 7297 * 7298 * @return The id of a view this one succeedes in accessibility traversal if 7299 * specified, otherwise {@link #NO_ID}. 7300 * 7301 * @see #setAccessibilityTraversalAfter(int) 7302 */ 7303 public int getAccessibilityTraversalAfter() { 7304 return mAccessibilityTraversalAfterId; 7305 } 7306 7307 /** 7308 * Gets the id of a view for which this view serves as a label for 7309 * accessibility purposes. 7310 * 7311 * @return The labeled view id. 7312 */ 7313 @ViewDebug.ExportedProperty(category = "accessibility") 7314 public int getLabelFor() { 7315 return mLabelForId; 7316 } 7317 7318 /** 7319 * Sets the id of a view for which this view serves as a label for 7320 * accessibility purposes. 7321 * 7322 * @param id The labeled view id. 7323 */ 7324 @RemotableViewMethod 7325 public void setLabelFor(@IdRes int id) { 7326 if (mLabelForId == id) { 7327 return; 7328 } 7329 mLabelForId = id; 7330 if (mLabelForId != View.NO_ID 7331 && mID == View.NO_ID) { 7332 mID = generateViewId(); 7333 } 7334 notifyViewAccessibilityStateChangedIfNeeded( 7335 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7336 } 7337 7338 /** 7339 * Invoked whenever this view loses focus, either by losing window focus or by losing 7340 * focus within its window. This method can be used to clear any state tied to the 7341 * focus. For instance, if a button is held pressed with the trackball and the window 7342 * loses focus, this method can be used to cancel the press. 7343 * 7344 * Subclasses of View overriding this method should always call super.onFocusLost(). 7345 * 7346 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 7347 * @see #onWindowFocusChanged(boolean) 7348 * 7349 * @hide pending API council approval 7350 */ 7351 @CallSuper 7352 protected void onFocusLost() { 7353 resetPressedState(); 7354 } 7355 7356 private void resetPressedState() { 7357 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7358 return; 7359 } 7360 7361 if (isPressed()) { 7362 setPressed(false); 7363 7364 if (!mHasPerformedLongPress) { 7365 removeLongPressCallback(); 7366 } 7367 } 7368 } 7369 7370 /** 7371 * Returns true if this view has focus 7372 * 7373 * @return True if this view has focus, false otherwise. 7374 */ 7375 @ViewDebug.ExportedProperty(category = "focus") 7376 public boolean isFocused() { 7377 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7378 } 7379 7380 /** 7381 * Find the view in the hierarchy rooted at this view that currently has 7382 * focus. 7383 * 7384 * @return The view that currently has focus, or null if no focused view can 7385 * be found. 7386 */ 7387 public View findFocus() { 7388 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 7389 } 7390 7391 /** 7392 * Indicates whether this view is one of the set of scrollable containers in 7393 * its window. 7394 * 7395 * @return whether this view is one of the set of scrollable containers in 7396 * its window 7397 * 7398 * @attr ref android.R.styleable#View_isScrollContainer 7399 */ 7400 public boolean isScrollContainer() { 7401 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 7402 } 7403 7404 /** 7405 * Change whether this view is one of the set of scrollable containers in 7406 * its window. This will be used to determine whether the window can 7407 * resize or must pan when a soft input area is open -- scrollable 7408 * containers allow the window to use resize mode since the container 7409 * will appropriately shrink. 7410 * 7411 * @attr ref android.R.styleable#View_isScrollContainer 7412 */ 7413 public void setScrollContainer(boolean isScrollContainer) { 7414 if (isScrollContainer) { 7415 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 7416 mAttachInfo.mScrollContainers.add(this); 7417 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 7418 } 7419 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 7420 } else { 7421 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 7422 mAttachInfo.mScrollContainers.remove(this); 7423 } 7424 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 7425 } 7426 } 7427 7428 /** 7429 * Returns the quality of the drawing cache. 7430 * 7431 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7432 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7433 * 7434 * @see #setDrawingCacheQuality(int) 7435 * @see #setDrawingCacheEnabled(boolean) 7436 * @see #isDrawingCacheEnabled() 7437 * 7438 * @attr ref android.R.styleable#View_drawingCacheQuality 7439 */ 7440 @DrawingCacheQuality 7441 public int getDrawingCacheQuality() { 7442 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 7443 } 7444 7445 /** 7446 * Set the drawing cache quality of this view. This value is used only when the 7447 * drawing cache is enabled 7448 * 7449 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7450 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7451 * 7452 * @see #getDrawingCacheQuality() 7453 * @see #setDrawingCacheEnabled(boolean) 7454 * @see #isDrawingCacheEnabled() 7455 * 7456 * @attr ref android.R.styleable#View_drawingCacheQuality 7457 */ 7458 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 7459 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 7460 } 7461 7462 /** 7463 * Returns whether the screen should remain on, corresponding to the current 7464 * value of {@link #KEEP_SCREEN_ON}. 7465 * 7466 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 7467 * 7468 * @see #setKeepScreenOn(boolean) 7469 * 7470 * @attr ref android.R.styleable#View_keepScreenOn 7471 */ 7472 public boolean getKeepScreenOn() { 7473 return (mViewFlags & KEEP_SCREEN_ON) != 0; 7474 } 7475 7476 /** 7477 * Controls whether the screen should remain on, modifying the 7478 * value of {@link #KEEP_SCREEN_ON}. 7479 * 7480 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 7481 * 7482 * @see #getKeepScreenOn() 7483 * 7484 * @attr ref android.R.styleable#View_keepScreenOn 7485 */ 7486 public void setKeepScreenOn(boolean keepScreenOn) { 7487 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 7488 } 7489 7490 /** 7491 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7492 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7493 * 7494 * @attr ref android.R.styleable#View_nextFocusLeft 7495 */ 7496 public int getNextFocusLeftId() { 7497 return mNextFocusLeftId; 7498 } 7499 7500 /** 7501 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7502 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 7503 * decide automatically. 7504 * 7505 * @attr ref android.R.styleable#View_nextFocusLeft 7506 */ 7507 public void setNextFocusLeftId(int nextFocusLeftId) { 7508 mNextFocusLeftId = nextFocusLeftId; 7509 } 7510 7511 /** 7512 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7513 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7514 * 7515 * @attr ref android.R.styleable#View_nextFocusRight 7516 */ 7517 public int getNextFocusRightId() { 7518 return mNextFocusRightId; 7519 } 7520 7521 /** 7522 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7523 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 7524 * decide automatically. 7525 * 7526 * @attr ref android.R.styleable#View_nextFocusRight 7527 */ 7528 public void setNextFocusRightId(int nextFocusRightId) { 7529 mNextFocusRightId = nextFocusRightId; 7530 } 7531 7532 /** 7533 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7534 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7535 * 7536 * @attr ref android.R.styleable#View_nextFocusUp 7537 */ 7538 public int getNextFocusUpId() { 7539 return mNextFocusUpId; 7540 } 7541 7542 /** 7543 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7544 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 7545 * decide automatically. 7546 * 7547 * @attr ref android.R.styleable#View_nextFocusUp 7548 */ 7549 public void setNextFocusUpId(int nextFocusUpId) { 7550 mNextFocusUpId = nextFocusUpId; 7551 } 7552 7553 /** 7554 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7555 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7556 * 7557 * @attr ref android.R.styleable#View_nextFocusDown 7558 */ 7559 public int getNextFocusDownId() { 7560 return mNextFocusDownId; 7561 } 7562 7563 /** 7564 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7565 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7566 * decide automatically. 7567 * 7568 * @attr ref android.R.styleable#View_nextFocusDown 7569 */ 7570 public void setNextFocusDownId(int nextFocusDownId) { 7571 mNextFocusDownId = nextFocusDownId; 7572 } 7573 7574 /** 7575 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7576 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7577 * 7578 * @attr ref android.R.styleable#View_nextFocusForward 7579 */ 7580 public int getNextFocusForwardId() { 7581 return mNextFocusForwardId; 7582 } 7583 7584 /** 7585 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7586 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7587 * decide automatically. 7588 * 7589 * @attr ref android.R.styleable#View_nextFocusForward 7590 */ 7591 public void setNextFocusForwardId(int nextFocusForwardId) { 7592 mNextFocusForwardId = nextFocusForwardId; 7593 } 7594 7595 /** 7596 * Returns the visibility of this view and all of its ancestors 7597 * 7598 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7599 */ 7600 public boolean isShown() { 7601 View current = this; 7602 //noinspection ConstantConditions 7603 do { 7604 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7605 return false; 7606 } 7607 ViewParent parent = current.mParent; 7608 if (parent == null) { 7609 return false; // We are not attached to the view root 7610 } 7611 if (!(parent instanceof View)) { 7612 return true; 7613 } 7614 current = (View) parent; 7615 } while (current != null); 7616 7617 return false; 7618 } 7619 7620 /** 7621 * Called by the view hierarchy when the content insets for a window have 7622 * changed, to allow it to adjust its content to fit within those windows. 7623 * The content insets tell you the space that the status bar, input method, 7624 * and other system windows infringe on the application's window. 7625 * 7626 * <p>You do not normally need to deal with this function, since the default 7627 * window decoration given to applications takes care of applying it to the 7628 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7629 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7630 * and your content can be placed under those system elements. You can then 7631 * use this method within your view hierarchy if you have parts of your UI 7632 * which you would like to ensure are not being covered. 7633 * 7634 * <p>The default implementation of this method simply applies the content 7635 * insets to the view's padding, consuming that content (modifying the 7636 * insets to be 0), and returning true. This behavior is off by default, but can 7637 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7638 * 7639 * <p>This function's traversal down the hierarchy is depth-first. The same content 7640 * insets object is propagated down the hierarchy, so any changes made to it will 7641 * be seen by all following views (including potentially ones above in 7642 * the hierarchy since this is a depth-first traversal). The first view 7643 * that returns true will abort the entire traversal. 7644 * 7645 * <p>The default implementation works well for a situation where it is 7646 * used with a container that covers the entire window, allowing it to 7647 * apply the appropriate insets to its content on all edges. If you need 7648 * a more complicated layout (such as two different views fitting system 7649 * windows, one on the top of the window, and one on the bottom), 7650 * you can override the method and handle the insets however you would like. 7651 * Note that the insets provided by the framework are always relative to the 7652 * far edges of the window, not accounting for the location of the called view 7653 * within that window. (In fact when this method is called you do not yet know 7654 * where the layout will place the view, as it is done before layout happens.) 7655 * 7656 * <p>Note: unlike many View methods, there is no dispatch phase to this 7657 * call. If you are overriding it in a ViewGroup and want to allow the 7658 * call to continue to your children, you must be sure to call the super 7659 * implementation. 7660 * 7661 * <p>Here is a sample layout that makes use of fitting system windows 7662 * to have controls for a video view placed inside of the window decorations 7663 * that it hides and shows. This can be used with code like the second 7664 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7665 * 7666 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7667 * 7668 * @param insets Current content insets of the window. Prior to 7669 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7670 * the insets or else you and Android will be unhappy. 7671 * 7672 * @return {@code true} if this view applied the insets and it should not 7673 * continue propagating further down the hierarchy, {@code false} otherwise. 7674 * @see #getFitsSystemWindows() 7675 * @see #setFitsSystemWindows(boolean) 7676 * @see #setSystemUiVisibility(int) 7677 * 7678 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7679 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7680 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7681 * to implement handling their own insets. 7682 */ 7683 @Deprecated 7684 protected boolean fitSystemWindows(Rect insets) { 7685 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7686 if (insets == null) { 7687 // Null insets by definition have already been consumed. 7688 // This call cannot apply insets since there are none to apply, 7689 // so return false. 7690 return false; 7691 } 7692 // If we're not in the process of dispatching the newer apply insets call, 7693 // that means we're not in the compatibility path. Dispatch into the newer 7694 // apply insets path and take things from there. 7695 try { 7696 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7697 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7698 } finally { 7699 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7700 } 7701 } else { 7702 // We're being called from the newer apply insets path. 7703 // Perform the standard fallback behavior. 7704 return fitSystemWindowsInt(insets); 7705 } 7706 } 7707 7708 private boolean fitSystemWindowsInt(Rect insets) { 7709 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7710 mUserPaddingStart = UNDEFINED_PADDING; 7711 mUserPaddingEnd = UNDEFINED_PADDING; 7712 Rect localInsets = sThreadLocal.get(); 7713 if (localInsets == null) { 7714 localInsets = new Rect(); 7715 sThreadLocal.set(localInsets); 7716 } 7717 boolean res = computeFitSystemWindows(insets, localInsets); 7718 mUserPaddingLeftInitial = localInsets.left; 7719 mUserPaddingRightInitial = localInsets.right; 7720 internalSetPadding(localInsets.left, localInsets.top, 7721 localInsets.right, localInsets.bottom); 7722 return res; 7723 } 7724 return false; 7725 } 7726 7727 /** 7728 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7729 * 7730 * <p>This method should be overridden by views that wish to apply a policy different from or 7731 * in addition to the default behavior. Clients that wish to force a view subtree 7732 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7733 * 7734 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7735 * it will be called during dispatch instead of this method. The listener may optionally 7736 * call this method from its own implementation if it wishes to apply the view's default 7737 * insets policy in addition to its own.</p> 7738 * 7739 * <p>Implementations of this method should either return the insets parameter unchanged 7740 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7741 * that this view applied itself. This allows new inset types added in future platform 7742 * versions to pass through existing implementations unchanged without being erroneously 7743 * consumed.</p> 7744 * 7745 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7746 * property is set then the view will consume the system window insets and apply them 7747 * as padding for the view.</p> 7748 * 7749 * @param insets Insets to apply 7750 * @return The supplied insets with any applied insets consumed 7751 */ 7752 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7753 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7754 // We weren't called from within a direct call to fitSystemWindows, 7755 // call into it as a fallback in case we're in a class that overrides it 7756 // and has logic to perform. 7757 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7758 return insets.consumeSystemWindowInsets(); 7759 } 7760 } else { 7761 // We were called from within a direct call to fitSystemWindows. 7762 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7763 return insets.consumeSystemWindowInsets(); 7764 } 7765 } 7766 return insets; 7767 } 7768 7769 /** 7770 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7771 * window insets to this view. The listener's 7772 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7773 * method will be called instead of the view's 7774 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7775 * 7776 * @param listener Listener to set 7777 * 7778 * @see #onApplyWindowInsets(WindowInsets) 7779 */ 7780 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7781 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7782 } 7783 7784 /** 7785 * Request to apply the given window insets to this view or another view in its subtree. 7786 * 7787 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7788 * obscured by window decorations or overlays. This can include the status and navigation bars, 7789 * action bars, input methods and more. New inset categories may be added in the future. 7790 * The method returns the insets provided minus any that were applied by this view or its 7791 * children.</p> 7792 * 7793 * <p>Clients wishing to provide custom behavior should override the 7794 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7795 * {@link OnApplyWindowInsetsListener} via the 7796 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7797 * method.</p> 7798 * 7799 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7800 * </p> 7801 * 7802 * @param insets Insets to apply 7803 * @return The provided insets minus the insets that were consumed 7804 */ 7805 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7806 try { 7807 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7808 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7809 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7810 } else { 7811 return onApplyWindowInsets(insets); 7812 } 7813 } finally { 7814 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7815 } 7816 } 7817 7818 /** 7819 * Compute the view's coordinate within the surface. 7820 * 7821 * <p>Computes the coordinates of this view in its surface. The argument 7822 * must be an array of two integers. After the method returns, the array 7823 * contains the x and y location in that order.</p> 7824 * @hide 7825 * @param location an array of two integers in which to hold the coordinates 7826 */ 7827 public void getLocationInSurface(@Size(2) int[] location) { 7828 getLocationInWindow(location); 7829 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 7830 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 7831 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 7832 } 7833 } 7834 7835 /** 7836 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7837 * only available if the view is attached. 7838 * 7839 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7840 */ 7841 public WindowInsets getRootWindowInsets() { 7842 if (mAttachInfo != null) { 7843 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7844 } 7845 return null; 7846 } 7847 7848 /** 7849 * @hide Compute the insets that should be consumed by this view and the ones 7850 * that should propagate to those under it. 7851 */ 7852 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7853 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7854 || mAttachInfo == null 7855 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7856 && !mAttachInfo.mOverscanRequested)) { 7857 outLocalInsets.set(inoutInsets); 7858 inoutInsets.set(0, 0, 0, 0); 7859 return true; 7860 } else { 7861 // The application wants to take care of fitting system window for 7862 // the content... however we still need to take care of any overscan here. 7863 final Rect overscan = mAttachInfo.mOverscanInsets; 7864 outLocalInsets.set(overscan); 7865 inoutInsets.left -= overscan.left; 7866 inoutInsets.top -= overscan.top; 7867 inoutInsets.right -= overscan.right; 7868 inoutInsets.bottom -= overscan.bottom; 7869 return false; 7870 } 7871 } 7872 7873 /** 7874 * Compute insets that should be consumed by this view and the ones that should propagate 7875 * to those under it. 7876 * 7877 * @param in Insets currently being processed by this View, likely received as a parameter 7878 * to {@link #onApplyWindowInsets(WindowInsets)}. 7879 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7880 * by this view 7881 * @return Insets that should be passed along to views under this one 7882 */ 7883 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7884 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7885 || mAttachInfo == null 7886 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7887 outLocalInsets.set(in.getSystemWindowInsets()); 7888 return in.consumeSystemWindowInsets(); 7889 } else { 7890 outLocalInsets.set(0, 0, 0, 0); 7891 return in; 7892 } 7893 } 7894 7895 /** 7896 * Sets whether or not this view should account for system screen decorations 7897 * such as the status bar and inset its content; that is, controlling whether 7898 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7899 * executed. See that method for more details. 7900 * 7901 * <p>Note that if you are providing your own implementation of 7902 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7903 * flag to true -- your implementation will be overriding the default 7904 * implementation that checks this flag. 7905 * 7906 * @param fitSystemWindows If true, then the default implementation of 7907 * {@link #fitSystemWindows(Rect)} will be executed. 7908 * 7909 * @attr ref android.R.styleable#View_fitsSystemWindows 7910 * @see #getFitsSystemWindows() 7911 * @see #fitSystemWindows(Rect) 7912 * @see #setSystemUiVisibility(int) 7913 */ 7914 public void setFitsSystemWindows(boolean fitSystemWindows) { 7915 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7916 } 7917 7918 /** 7919 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7920 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7921 * will be executed. 7922 * 7923 * @return {@code true} if the default implementation of 7924 * {@link #fitSystemWindows(Rect)} will be executed. 7925 * 7926 * @attr ref android.R.styleable#View_fitsSystemWindows 7927 * @see #setFitsSystemWindows(boolean) 7928 * @see #fitSystemWindows(Rect) 7929 * @see #setSystemUiVisibility(int) 7930 */ 7931 @ViewDebug.ExportedProperty 7932 public boolean getFitsSystemWindows() { 7933 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7934 } 7935 7936 /** @hide */ 7937 public boolean fitsSystemWindows() { 7938 return getFitsSystemWindows(); 7939 } 7940 7941 /** 7942 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7943 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 7944 */ 7945 @Deprecated 7946 public void requestFitSystemWindows() { 7947 if (mParent != null) { 7948 mParent.requestFitSystemWindows(); 7949 } 7950 } 7951 7952 /** 7953 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 7954 */ 7955 public void requestApplyInsets() { 7956 requestFitSystemWindows(); 7957 } 7958 7959 /** 7960 * For use by PhoneWindow to make its own system window fitting optional. 7961 * @hide 7962 */ 7963 public void makeOptionalFitsSystemWindows() { 7964 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 7965 } 7966 7967 /** 7968 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 7969 * treat them as such. 7970 * @hide 7971 */ 7972 public void getOutsets(Rect outOutsetRect) { 7973 if (mAttachInfo != null) { 7974 outOutsetRect.set(mAttachInfo.mOutsets); 7975 } else { 7976 outOutsetRect.setEmpty(); 7977 } 7978 } 7979 7980 /** 7981 * Returns the visibility status for this view. 7982 * 7983 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7984 * @attr ref android.R.styleable#View_visibility 7985 */ 7986 @ViewDebug.ExportedProperty(mapping = { 7987 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 7988 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 7989 @ViewDebug.IntToString(from = GONE, to = "GONE") 7990 }) 7991 @Visibility 7992 public int getVisibility() { 7993 return mViewFlags & VISIBILITY_MASK; 7994 } 7995 7996 /** 7997 * Set the enabled state of this view. 7998 * 7999 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8000 * @attr ref android.R.styleable#View_visibility 8001 */ 8002 @RemotableViewMethod 8003 public void setVisibility(@Visibility int visibility) { 8004 setFlags(visibility, VISIBILITY_MASK); 8005 } 8006 8007 /** 8008 * Returns the enabled status for this view. The interpretation of the 8009 * enabled state varies by subclass. 8010 * 8011 * @return True if this view is enabled, false otherwise. 8012 */ 8013 @ViewDebug.ExportedProperty 8014 public boolean isEnabled() { 8015 return (mViewFlags & ENABLED_MASK) == ENABLED; 8016 } 8017 8018 /** 8019 * Set the enabled state of this view. The interpretation of the enabled 8020 * state varies by subclass. 8021 * 8022 * @param enabled True if this view is enabled, false otherwise. 8023 */ 8024 @RemotableViewMethod 8025 public void setEnabled(boolean enabled) { 8026 if (enabled == isEnabled()) return; 8027 8028 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 8029 8030 /* 8031 * The View most likely has to change its appearance, so refresh 8032 * the drawable state. 8033 */ 8034 refreshDrawableState(); 8035 8036 // Invalidate too, since the default behavior for views is to be 8037 // be drawn at 50% alpha rather than to change the drawable. 8038 invalidate(true); 8039 8040 if (!enabled) { 8041 cancelPendingInputEvents(); 8042 } 8043 } 8044 8045 /** 8046 * Set whether this view can receive the focus. 8047 * 8048 * Setting this to false will also ensure that this view is not focusable 8049 * in touch mode. 8050 * 8051 * @param focusable If true, this view can receive the focus. 8052 * 8053 * @see #setFocusableInTouchMode(boolean) 8054 * @attr ref android.R.styleable#View_focusable 8055 */ 8056 public void setFocusable(boolean focusable) { 8057 if (!focusable) { 8058 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 8059 } 8060 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 8061 } 8062 8063 /** 8064 * Set whether this view can receive focus while in touch mode. 8065 * 8066 * Setting this to true will also ensure that this view is focusable. 8067 * 8068 * @param focusableInTouchMode If true, this view can receive the focus while 8069 * in touch mode. 8070 * 8071 * @see #setFocusable(boolean) 8072 * @attr ref android.R.styleable#View_focusableInTouchMode 8073 */ 8074 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 8075 // Focusable in touch mode should always be set before the focusable flag 8076 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 8077 // which, in touch mode, will not successfully request focus on this view 8078 // because the focusable in touch mode flag is not set 8079 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 8080 if (focusableInTouchMode) { 8081 setFlags(FOCUSABLE, FOCUSABLE_MASK); 8082 } 8083 } 8084 8085 /** 8086 * Set whether this view should have sound effects enabled for events such as 8087 * clicking and touching. 8088 * 8089 * <p>You may wish to disable sound effects for a view if you already play sounds, 8090 * for instance, a dial key that plays dtmf tones. 8091 * 8092 * @param soundEffectsEnabled whether sound effects are enabled for this view. 8093 * @see #isSoundEffectsEnabled() 8094 * @see #playSoundEffect(int) 8095 * @attr ref android.R.styleable#View_soundEffectsEnabled 8096 */ 8097 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 8098 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 8099 } 8100 8101 /** 8102 * @return whether this view should have sound effects enabled for events such as 8103 * clicking and touching. 8104 * 8105 * @see #setSoundEffectsEnabled(boolean) 8106 * @see #playSoundEffect(int) 8107 * @attr ref android.R.styleable#View_soundEffectsEnabled 8108 */ 8109 @ViewDebug.ExportedProperty 8110 public boolean isSoundEffectsEnabled() { 8111 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 8112 } 8113 8114 /** 8115 * Set whether this view should have haptic feedback for events such as 8116 * long presses. 8117 * 8118 * <p>You may wish to disable haptic feedback if your view already controls 8119 * its own haptic feedback. 8120 * 8121 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 8122 * @see #isHapticFeedbackEnabled() 8123 * @see #performHapticFeedback(int) 8124 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8125 */ 8126 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 8127 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 8128 } 8129 8130 /** 8131 * @return whether this view should have haptic feedback enabled for events 8132 * long presses. 8133 * 8134 * @see #setHapticFeedbackEnabled(boolean) 8135 * @see #performHapticFeedback(int) 8136 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8137 */ 8138 @ViewDebug.ExportedProperty 8139 public boolean isHapticFeedbackEnabled() { 8140 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 8141 } 8142 8143 /** 8144 * Returns the layout direction for this view. 8145 * 8146 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 8147 * {@link #LAYOUT_DIRECTION_RTL}, 8148 * {@link #LAYOUT_DIRECTION_INHERIT} or 8149 * {@link #LAYOUT_DIRECTION_LOCALE}. 8150 * 8151 * @attr ref android.R.styleable#View_layoutDirection 8152 * 8153 * @hide 8154 */ 8155 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8156 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 8157 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 8158 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 8159 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 8160 }) 8161 @LayoutDir 8162 public int getRawLayoutDirection() { 8163 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 8164 } 8165 8166 /** 8167 * Set the layout direction for this view. This will propagate a reset of layout direction 8168 * resolution to the view's children and resolve layout direction for this view. 8169 * 8170 * @param layoutDirection the layout direction to set. Should be one of: 8171 * 8172 * {@link #LAYOUT_DIRECTION_LTR}, 8173 * {@link #LAYOUT_DIRECTION_RTL}, 8174 * {@link #LAYOUT_DIRECTION_INHERIT}, 8175 * {@link #LAYOUT_DIRECTION_LOCALE}. 8176 * 8177 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 8178 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 8179 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 8180 * 8181 * @attr ref android.R.styleable#View_layoutDirection 8182 */ 8183 @RemotableViewMethod 8184 public void setLayoutDirection(@LayoutDir int layoutDirection) { 8185 if (getRawLayoutDirection() != layoutDirection) { 8186 // Reset the current layout direction and the resolved one 8187 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 8188 resetRtlProperties(); 8189 // Set the new layout direction (filtered) 8190 mPrivateFlags2 |= 8191 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 8192 // We need to resolve all RTL properties as they all depend on layout direction 8193 resolveRtlPropertiesIfNeeded(); 8194 requestLayout(); 8195 invalidate(true); 8196 } 8197 } 8198 8199 /** 8200 * Returns the resolved layout direction for this view. 8201 * 8202 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 8203 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 8204 * 8205 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 8206 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 8207 * 8208 * @attr ref android.R.styleable#View_layoutDirection 8209 */ 8210 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8211 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 8212 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 8213 }) 8214 @ResolvedLayoutDir 8215 public int getLayoutDirection() { 8216 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 8217 if (targetSdkVersion < JELLY_BEAN_MR1) { 8218 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 8219 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 8220 } 8221 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 8222 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 8223 } 8224 8225 /** 8226 * Indicates whether or not this view's layout is right-to-left. This is resolved from 8227 * layout attribute and/or the inherited value from the parent 8228 * 8229 * @return true if the layout is right-to-left. 8230 * 8231 * @hide 8232 */ 8233 @ViewDebug.ExportedProperty(category = "layout") 8234 public boolean isLayoutRtl() { 8235 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 8236 } 8237 8238 /** 8239 * Indicates whether the view is currently tracking transient state that the 8240 * app should not need to concern itself with saving and restoring, but that 8241 * the framework should take special note to preserve when possible. 8242 * 8243 * <p>A view with transient state cannot be trivially rebound from an external 8244 * data source, such as an adapter binding item views in a list. This may be 8245 * because the view is performing an animation, tracking user selection 8246 * of content, or similar.</p> 8247 * 8248 * @return true if the view has transient state 8249 */ 8250 @ViewDebug.ExportedProperty(category = "layout") 8251 public boolean hasTransientState() { 8252 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 8253 } 8254 8255 /** 8256 * Set whether this view is currently tracking transient state that the 8257 * framework should attempt to preserve when possible. This flag is reference counted, 8258 * so every call to setHasTransientState(true) should be paired with a later call 8259 * to setHasTransientState(false). 8260 * 8261 * <p>A view with transient state cannot be trivially rebound from an external 8262 * data source, such as an adapter binding item views in a list. This may be 8263 * because the view is performing an animation, tracking user selection 8264 * of content, or similar.</p> 8265 * 8266 * @param hasTransientState true if this view has transient state 8267 */ 8268 public void setHasTransientState(boolean hasTransientState) { 8269 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 8270 mTransientStateCount - 1; 8271 if (mTransientStateCount < 0) { 8272 mTransientStateCount = 0; 8273 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 8274 "unmatched pair of setHasTransientState calls"); 8275 } else if ((hasTransientState && mTransientStateCount == 1) || 8276 (!hasTransientState && mTransientStateCount == 0)) { 8277 // update flag if we've just incremented up from 0 or decremented down to 0 8278 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 8279 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 8280 if (mParent != null) { 8281 try { 8282 mParent.childHasTransientStateChanged(this, hasTransientState); 8283 } catch (AbstractMethodError e) { 8284 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8285 " does not fully implement ViewParent", e); 8286 } 8287 } 8288 } 8289 } 8290 8291 /** 8292 * Returns true if this view is currently attached to a window. 8293 */ 8294 public boolean isAttachedToWindow() { 8295 return mAttachInfo != null; 8296 } 8297 8298 /** 8299 * Returns true if this view has been through at least one layout since it 8300 * was last attached to or detached from a window. 8301 */ 8302 public boolean isLaidOut() { 8303 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 8304 } 8305 8306 /** 8307 * If this view doesn't do any drawing on its own, set this flag to 8308 * allow further optimizations. By default, this flag is not set on 8309 * View, but could be set on some View subclasses such as ViewGroup. 8310 * 8311 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 8312 * you should clear this flag. 8313 * 8314 * @param willNotDraw whether or not this View draw on its own 8315 */ 8316 public void setWillNotDraw(boolean willNotDraw) { 8317 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 8318 } 8319 8320 /** 8321 * Returns whether or not this View draws on its own. 8322 * 8323 * @return true if this view has nothing to draw, false otherwise 8324 */ 8325 @ViewDebug.ExportedProperty(category = "drawing") 8326 public boolean willNotDraw() { 8327 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 8328 } 8329 8330 /** 8331 * When a View's drawing cache is enabled, drawing is redirected to an 8332 * offscreen bitmap. Some views, like an ImageView, must be able to 8333 * bypass this mechanism if they already draw a single bitmap, to avoid 8334 * unnecessary usage of the memory. 8335 * 8336 * @param willNotCacheDrawing true if this view does not cache its 8337 * drawing, false otherwise 8338 */ 8339 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 8340 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 8341 } 8342 8343 /** 8344 * Returns whether or not this View can cache its drawing or not. 8345 * 8346 * @return true if this view does not cache its drawing, false otherwise 8347 */ 8348 @ViewDebug.ExportedProperty(category = "drawing") 8349 public boolean willNotCacheDrawing() { 8350 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 8351 } 8352 8353 /** 8354 * Indicates whether this view reacts to click events or not. 8355 * 8356 * @return true if the view is clickable, false otherwise 8357 * 8358 * @see #setClickable(boolean) 8359 * @attr ref android.R.styleable#View_clickable 8360 */ 8361 @ViewDebug.ExportedProperty 8362 public boolean isClickable() { 8363 return (mViewFlags & CLICKABLE) == CLICKABLE; 8364 } 8365 8366 /** 8367 * Enables or disables click events for this view. When a view 8368 * is clickable it will change its state to "pressed" on every click. 8369 * Subclasses should set the view clickable to visually react to 8370 * user's clicks. 8371 * 8372 * @param clickable true to make the view clickable, false otherwise 8373 * 8374 * @see #isClickable() 8375 * @attr ref android.R.styleable#View_clickable 8376 */ 8377 public void setClickable(boolean clickable) { 8378 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 8379 } 8380 8381 /** 8382 * Indicates whether this view reacts to long click events or not. 8383 * 8384 * @return true if the view is long clickable, false otherwise 8385 * 8386 * @see #setLongClickable(boolean) 8387 * @attr ref android.R.styleable#View_longClickable 8388 */ 8389 public boolean isLongClickable() { 8390 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8391 } 8392 8393 /** 8394 * Enables or disables long click events for this view. When a view is long 8395 * clickable it reacts to the user holding down the button for a longer 8396 * duration than a tap. This event can either launch the listener or a 8397 * context menu. 8398 * 8399 * @param longClickable true to make the view long clickable, false otherwise 8400 * @see #isLongClickable() 8401 * @attr ref android.R.styleable#View_longClickable 8402 */ 8403 public void setLongClickable(boolean longClickable) { 8404 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 8405 } 8406 8407 /** 8408 * Indicates whether this view reacts to context clicks or not. 8409 * 8410 * @return true if the view is context clickable, false otherwise 8411 * @see #setContextClickable(boolean) 8412 * @attr ref android.R.styleable#View_contextClickable 8413 */ 8414 public boolean isContextClickable() { 8415 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 8416 } 8417 8418 /** 8419 * Enables or disables context clicking for this view. This event can launch the listener. 8420 * 8421 * @param contextClickable true to make the view react to a context click, false otherwise 8422 * @see #isContextClickable() 8423 * @attr ref android.R.styleable#View_contextClickable 8424 */ 8425 public void setContextClickable(boolean contextClickable) { 8426 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 8427 } 8428 8429 /** 8430 * Sets the pressed state for this view and provides a touch coordinate for 8431 * animation hinting. 8432 * 8433 * @param pressed Pass true to set the View's internal state to "pressed", 8434 * or false to reverts the View's internal state from a 8435 * previously set "pressed" state. 8436 * @param x The x coordinate of the touch that caused the press 8437 * @param y The y coordinate of the touch that caused the press 8438 */ 8439 private void setPressed(boolean pressed, float x, float y) { 8440 if (pressed) { 8441 drawableHotspotChanged(x, y); 8442 } 8443 8444 setPressed(pressed); 8445 } 8446 8447 /** 8448 * Sets the pressed state for this view. 8449 * 8450 * @see #isClickable() 8451 * @see #setClickable(boolean) 8452 * 8453 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 8454 * the View's internal state from a previously set "pressed" state. 8455 */ 8456 public void setPressed(boolean pressed) { 8457 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 8458 8459 if (pressed) { 8460 mPrivateFlags |= PFLAG_PRESSED; 8461 } else { 8462 mPrivateFlags &= ~PFLAG_PRESSED; 8463 } 8464 8465 if (needsRefresh) { 8466 refreshDrawableState(); 8467 } 8468 dispatchSetPressed(pressed); 8469 } 8470 8471 /** 8472 * Dispatch setPressed to all of this View's children. 8473 * 8474 * @see #setPressed(boolean) 8475 * 8476 * @param pressed The new pressed state 8477 */ 8478 protected void dispatchSetPressed(boolean pressed) { 8479 } 8480 8481 /** 8482 * Indicates whether the view is currently in pressed state. Unless 8483 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 8484 * the pressed state. 8485 * 8486 * @see #setPressed(boolean) 8487 * @see #isClickable() 8488 * @see #setClickable(boolean) 8489 * 8490 * @return true if the view is currently pressed, false otherwise 8491 */ 8492 @ViewDebug.ExportedProperty 8493 public boolean isPressed() { 8494 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 8495 } 8496 8497 /** 8498 * @hide 8499 * Indicates whether this view will participate in data collection through 8500 * {@link ViewStructure}. If true, it will not provide any data 8501 * for itself or its children. If false, the normal data collection will be allowed. 8502 * 8503 * @return Returns false if assist data collection is not blocked, else true. 8504 * 8505 * @see #setAssistBlocked(boolean) 8506 * @attr ref android.R.styleable#View_assistBlocked 8507 */ 8508 public boolean isAssistBlocked() { 8509 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 8510 } 8511 8512 /** 8513 * @hide 8514 * Controls whether assist data collection from this view and its children is enabled 8515 * (that is, whether {@link #onProvideStructure} and 8516 * {@link #onProvideVirtualStructure} will be called). The default value is false, 8517 * allowing normal assist collection. Setting this to false will disable assist collection. 8518 * 8519 * @param enabled Set to true to <em>disable</em> assist data collection, or false 8520 * (the default) to allow it. 8521 * 8522 * @see #isAssistBlocked() 8523 * @see #onProvideStructure 8524 * @see #onProvideVirtualStructure 8525 * @attr ref android.R.styleable#View_assistBlocked 8526 */ 8527 public void setAssistBlocked(boolean enabled) { 8528 if (enabled) { 8529 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 8530 } else { 8531 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 8532 } 8533 } 8534 8535 /** 8536 * Indicates whether this view will save its state (that is, 8537 * whether its {@link #onSaveInstanceState} method will be called). 8538 * 8539 * @return Returns true if the view state saving is enabled, else false. 8540 * 8541 * @see #setSaveEnabled(boolean) 8542 * @attr ref android.R.styleable#View_saveEnabled 8543 */ 8544 public boolean isSaveEnabled() { 8545 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 8546 } 8547 8548 /** 8549 * Controls whether the saving of this view's state is 8550 * enabled (that is, whether its {@link #onSaveInstanceState} method 8551 * will be called). Note that even if freezing is enabled, the 8552 * view still must have an id assigned to it (via {@link #setId(int)}) 8553 * for its state to be saved. This flag can only disable the 8554 * saving of this view; any child views may still have their state saved. 8555 * 8556 * @param enabled Set to false to <em>disable</em> state saving, or true 8557 * (the default) to allow it. 8558 * 8559 * @see #isSaveEnabled() 8560 * @see #setId(int) 8561 * @see #onSaveInstanceState() 8562 * @attr ref android.R.styleable#View_saveEnabled 8563 */ 8564 public void setSaveEnabled(boolean enabled) { 8565 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 8566 } 8567 8568 /** 8569 * Gets whether the framework should discard touches when the view's 8570 * window is obscured by another visible window. 8571 * Refer to the {@link View} security documentation for more details. 8572 * 8573 * @return True if touch filtering is enabled. 8574 * 8575 * @see #setFilterTouchesWhenObscured(boolean) 8576 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8577 */ 8578 @ViewDebug.ExportedProperty 8579 public boolean getFilterTouchesWhenObscured() { 8580 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 8581 } 8582 8583 /** 8584 * Sets whether the framework should discard touches when the view's 8585 * window is obscured by another visible window. 8586 * Refer to the {@link View} security documentation for more details. 8587 * 8588 * @param enabled True if touch filtering should be enabled. 8589 * 8590 * @see #getFilterTouchesWhenObscured 8591 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8592 */ 8593 public void setFilterTouchesWhenObscured(boolean enabled) { 8594 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 8595 FILTER_TOUCHES_WHEN_OBSCURED); 8596 } 8597 8598 /** 8599 * Indicates whether the entire hierarchy under this view will save its 8600 * state when a state saving traversal occurs from its parent. The default 8601 * is true; if false, these views will not be saved unless 8602 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8603 * 8604 * @return Returns true if the view state saving from parent is enabled, else false. 8605 * 8606 * @see #setSaveFromParentEnabled(boolean) 8607 */ 8608 public boolean isSaveFromParentEnabled() { 8609 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 8610 } 8611 8612 /** 8613 * Controls whether the entire hierarchy under this view will save its 8614 * state when a state saving traversal occurs from its parent. The default 8615 * is true; if false, these views will not be saved unless 8616 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8617 * 8618 * @param enabled Set to false to <em>disable</em> state saving, or true 8619 * (the default) to allow it. 8620 * 8621 * @see #isSaveFromParentEnabled() 8622 * @see #setId(int) 8623 * @see #onSaveInstanceState() 8624 */ 8625 public void setSaveFromParentEnabled(boolean enabled) { 8626 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8627 } 8628 8629 8630 /** 8631 * Returns whether this View is able to take focus. 8632 * 8633 * @return True if this view can take focus, or false otherwise. 8634 * @attr ref android.R.styleable#View_focusable 8635 */ 8636 @ViewDebug.ExportedProperty(category = "focus") 8637 public final boolean isFocusable() { 8638 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8639 } 8640 8641 /** 8642 * When a view is focusable, it may not want to take focus when in touch mode. 8643 * For example, a button would like focus when the user is navigating via a D-pad 8644 * so that the user can click on it, but once the user starts touching the screen, 8645 * the button shouldn't take focus 8646 * @return Whether the view is focusable in touch mode. 8647 * @attr ref android.R.styleable#View_focusableInTouchMode 8648 */ 8649 @ViewDebug.ExportedProperty 8650 public final boolean isFocusableInTouchMode() { 8651 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8652 } 8653 8654 /** 8655 * Find the nearest view in the specified direction that can take focus. 8656 * This does not actually give focus to that view. 8657 * 8658 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8659 * 8660 * @return The nearest focusable in the specified direction, or null if none 8661 * can be found. 8662 */ 8663 public View focusSearch(@FocusRealDirection int direction) { 8664 if (mParent != null) { 8665 return mParent.focusSearch(this, direction); 8666 } else { 8667 return null; 8668 } 8669 } 8670 8671 /** 8672 * This method is the last chance for the focused view and its ancestors to 8673 * respond to an arrow key. This is called when the focused view did not 8674 * consume the key internally, nor could the view system find a new view in 8675 * the requested direction to give focus to. 8676 * 8677 * @param focused The currently focused view. 8678 * @param direction The direction focus wants to move. One of FOCUS_UP, 8679 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8680 * @return True if the this view consumed this unhandled move. 8681 */ 8682 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8683 return false; 8684 } 8685 8686 /** 8687 * If a user manually specified the next view id for a particular direction, 8688 * use the root to look up the view. 8689 * @param root The root view of the hierarchy containing this view. 8690 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8691 * or FOCUS_BACKWARD. 8692 * @return The user specified next view, or null if there is none. 8693 */ 8694 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8695 switch (direction) { 8696 case FOCUS_LEFT: 8697 if (mNextFocusLeftId == View.NO_ID) return null; 8698 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8699 case FOCUS_RIGHT: 8700 if (mNextFocusRightId == View.NO_ID) return null; 8701 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8702 case FOCUS_UP: 8703 if (mNextFocusUpId == View.NO_ID) return null; 8704 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8705 case FOCUS_DOWN: 8706 if (mNextFocusDownId == View.NO_ID) return null; 8707 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8708 case FOCUS_FORWARD: 8709 if (mNextFocusForwardId == View.NO_ID) return null; 8710 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8711 case FOCUS_BACKWARD: { 8712 if (mID == View.NO_ID) return null; 8713 final int id = mID; 8714 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8715 @Override 8716 public boolean apply(View t) { 8717 return t.mNextFocusForwardId == id; 8718 } 8719 }); 8720 } 8721 } 8722 return null; 8723 } 8724 8725 private View findViewInsideOutShouldExist(View root, int id) { 8726 if (mMatchIdPredicate == null) { 8727 mMatchIdPredicate = new MatchIdPredicate(); 8728 } 8729 mMatchIdPredicate.mId = id; 8730 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8731 if (result == null) { 8732 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8733 } 8734 return result; 8735 } 8736 8737 /** 8738 * Find and return all focusable views that are descendants of this view, 8739 * possibly including this view if it is focusable itself. 8740 * 8741 * @param direction The direction of the focus 8742 * @return A list of focusable views 8743 */ 8744 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8745 ArrayList<View> result = new ArrayList<View>(24); 8746 addFocusables(result, direction); 8747 return result; 8748 } 8749 8750 /** 8751 * Add any focusable views that are descendants of this view (possibly 8752 * including this view if it is focusable itself) to views. If we are in touch mode, 8753 * only add views that are also focusable in touch mode. 8754 * 8755 * @param views Focusable views found so far 8756 * @param direction The direction of the focus 8757 */ 8758 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8759 addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL); 8760 } 8761 8762 /** 8763 * Adds any focusable views that are descendants of this view (possibly 8764 * including this view if it is focusable itself) to views. This method 8765 * adds all focusable views regardless if we are in touch mode or 8766 * only views focusable in touch mode if we are in touch mode or 8767 * only views that can take accessibility focus if accessibility is enabled 8768 * depending on the focusable mode parameter. 8769 * 8770 * @param views Focusable views found so far or null if all we are interested is 8771 * the number of focusables. 8772 * @param direction The direction of the focus. 8773 * @param focusableMode The type of focusables to be added. 8774 * 8775 * @see #FOCUSABLES_ALL 8776 * @see #FOCUSABLES_TOUCH_MODE 8777 */ 8778 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8779 @FocusableMode int focusableMode) { 8780 if (views == null) { 8781 return; 8782 } 8783 if (!isFocusable()) { 8784 return; 8785 } 8786 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8787 && !isFocusableInTouchMode()) { 8788 return; 8789 } 8790 views.add(this); 8791 } 8792 8793 /** 8794 * Finds the Views that contain given text. The containment is case insensitive. 8795 * The search is performed by either the text that the View renders or the content 8796 * description that describes the view for accessibility purposes and the view does 8797 * not render or both. Clients can specify how the search is to be performed via 8798 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8799 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8800 * 8801 * @param outViews The output list of matching Views. 8802 * @param searched The text to match against. 8803 * 8804 * @see #FIND_VIEWS_WITH_TEXT 8805 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8806 * @see #setContentDescription(CharSequence) 8807 */ 8808 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8809 @FindViewFlags int flags) { 8810 if (getAccessibilityNodeProvider() != null) { 8811 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8812 outViews.add(this); 8813 } 8814 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8815 && (searched != null && searched.length() > 0) 8816 && (mContentDescription != null && mContentDescription.length() > 0)) { 8817 String searchedLowerCase = searched.toString().toLowerCase(); 8818 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8819 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8820 outViews.add(this); 8821 } 8822 } 8823 } 8824 8825 /** 8826 * Find and return all touchable views that are descendants of this view, 8827 * possibly including this view if it is touchable itself. 8828 * 8829 * @return A list of touchable views 8830 */ 8831 public ArrayList<View> getTouchables() { 8832 ArrayList<View> result = new ArrayList<View>(); 8833 addTouchables(result); 8834 return result; 8835 } 8836 8837 /** 8838 * Add any touchable views that are descendants of this view (possibly 8839 * including this view if it is touchable itself) to views. 8840 * 8841 * @param views Touchable views found so far 8842 */ 8843 public void addTouchables(ArrayList<View> views) { 8844 final int viewFlags = mViewFlags; 8845 8846 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8847 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 8848 && (viewFlags & ENABLED_MASK) == ENABLED) { 8849 views.add(this); 8850 } 8851 } 8852 8853 /** 8854 * Returns whether this View is accessibility focused. 8855 * 8856 * @return True if this View is accessibility focused. 8857 */ 8858 public boolean isAccessibilityFocused() { 8859 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8860 } 8861 8862 /** 8863 * Call this to try to give accessibility focus to this view. 8864 * 8865 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8866 * returns false or the view is no visible or the view already has accessibility 8867 * focus. 8868 * 8869 * See also {@link #focusSearch(int)}, which is what you call to say that you 8870 * have focus, and you want your parent to look for the next one. 8871 * 8872 * @return Whether this view actually took accessibility focus. 8873 * 8874 * @hide 8875 */ 8876 public boolean requestAccessibilityFocus() { 8877 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8878 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8879 return false; 8880 } 8881 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8882 return false; 8883 } 8884 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8885 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8886 ViewRootImpl viewRootImpl = getViewRootImpl(); 8887 if (viewRootImpl != null) { 8888 viewRootImpl.setAccessibilityFocus(this, null); 8889 } 8890 invalidate(); 8891 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8892 return true; 8893 } 8894 return false; 8895 } 8896 8897 /** 8898 * Call this to try to clear accessibility focus of this view. 8899 * 8900 * See also {@link #focusSearch(int)}, which is what you call to say that you 8901 * have focus, and you want your parent to look for the next one. 8902 * 8903 * @hide 8904 */ 8905 public void clearAccessibilityFocus() { 8906 clearAccessibilityFocusNoCallbacks(0); 8907 8908 // Clear the global reference of accessibility focus if this view or 8909 // any of its descendants had accessibility focus. This will NOT send 8910 // an event or update internal state if focus is cleared from a 8911 // descendant view, which may leave views in inconsistent states. 8912 final ViewRootImpl viewRootImpl = getViewRootImpl(); 8913 if (viewRootImpl != null) { 8914 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8915 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8916 viewRootImpl.setAccessibilityFocus(null, null); 8917 } 8918 } 8919 } 8920 8921 private void sendAccessibilityHoverEvent(int eventType) { 8922 // Since we are not delivering to a client accessibility events from not 8923 // important views (unless the clinet request that) we need to fire the 8924 // event from the deepest view exposed to the client. As a consequence if 8925 // the user crosses a not exposed view the client will see enter and exit 8926 // of the exposed predecessor followed by and enter and exit of that same 8927 // predecessor when entering and exiting the not exposed descendant. This 8928 // is fine since the client has a clear idea which view is hovered at the 8929 // price of a couple more events being sent. This is a simple and 8930 // working solution. 8931 View source = this; 8932 while (true) { 8933 if (source.includeForAccessibility()) { 8934 source.sendAccessibilityEvent(eventType); 8935 return; 8936 } 8937 ViewParent parent = source.getParent(); 8938 if (parent instanceof View) { 8939 source = (View) parent; 8940 } else { 8941 return; 8942 } 8943 } 8944 } 8945 8946 /** 8947 * Clears accessibility focus without calling any callback methods 8948 * normally invoked in {@link #clearAccessibilityFocus()}. This method 8949 * is used separately from that one for clearing accessibility focus when 8950 * giving this focus to another view. 8951 * 8952 * @param action The action, if any, that led to focus being cleared. Set to 8953 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 8954 * the window. 8955 */ 8956 void clearAccessibilityFocusNoCallbacks(int action) { 8957 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 8958 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 8959 invalidate(); 8960 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8961 AccessibilityEvent event = AccessibilityEvent.obtain( 8962 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 8963 event.setAction(action); 8964 if (mAccessibilityDelegate != null) { 8965 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 8966 } else { 8967 sendAccessibilityEventUnchecked(event); 8968 } 8969 } 8970 } 8971 } 8972 8973 /** 8974 * Call this to try to give focus to a specific view or to one of its 8975 * descendants. 8976 * 8977 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8978 * false), or if it is focusable and it is not focusable in touch mode 8979 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8980 * 8981 * See also {@link #focusSearch(int)}, which is what you call to say that you 8982 * have focus, and you want your parent to look for the next one. 8983 * 8984 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 8985 * {@link #FOCUS_DOWN} and <code>null</code>. 8986 * 8987 * @return Whether this view or one of its descendants actually took focus. 8988 */ 8989 public final boolean requestFocus() { 8990 return requestFocus(View.FOCUS_DOWN); 8991 } 8992 8993 /** 8994 * Call this to try to give focus to a specific view or to one of its 8995 * descendants and give it a hint about what direction focus is heading. 8996 * 8997 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8998 * false), or if it is focusable and it is not focusable in touch mode 8999 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9000 * 9001 * See also {@link #focusSearch(int)}, which is what you call to say that you 9002 * have focus, and you want your parent to look for the next one. 9003 * 9004 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 9005 * <code>null</code> set for the previously focused rectangle. 9006 * 9007 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9008 * @return Whether this view or one of its descendants actually took focus. 9009 */ 9010 public final boolean requestFocus(int direction) { 9011 return requestFocus(direction, null); 9012 } 9013 9014 /** 9015 * Call this to try to give focus to a specific view or to one of its descendants 9016 * and give it hints about the direction and a specific rectangle that the focus 9017 * is coming from. The rectangle can help give larger views a finer grained hint 9018 * about where focus is coming from, and therefore, where to show selection, or 9019 * forward focus change internally. 9020 * 9021 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9022 * false), or if it is focusable and it is not focusable in touch mode 9023 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9024 * 9025 * A View will not take focus if it is not visible. 9026 * 9027 * A View will not take focus if one of its parents has 9028 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 9029 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 9030 * 9031 * See also {@link #focusSearch(int)}, which is what you call to say that you 9032 * have focus, and you want your parent to look for the next one. 9033 * 9034 * You may wish to override this method if your custom {@link View} has an internal 9035 * {@link View} that it wishes to forward the request to. 9036 * 9037 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9038 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 9039 * to give a finer grained hint about where focus is coming from. May be null 9040 * if there is no hint. 9041 * @return Whether this view or one of its descendants actually took focus. 9042 */ 9043 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 9044 return requestFocusNoSearch(direction, previouslyFocusedRect); 9045 } 9046 9047 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 9048 // need to be focusable 9049 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 9050 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 9051 return false; 9052 } 9053 9054 // need to be focusable in touch mode if in touch mode 9055 if (isInTouchMode() && 9056 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 9057 return false; 9058 } 9059 9060 // need to not have any parents blocking us 9061 if (hasAncestorThatBlocksDescendantFocus()) { 9062 return false; 9063 } 9064 9065 handleFocusGainInternal(direction, previouslyFocusedRect); 9066 return true; 9067 } 9068 9069 /** 9070 * Call this to try to give focus to a specific view or to one of its descendants. This is a 9071 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 9072 * touch mode to request focus when they are touched. 9073 * 9074 * @return Whether this view or one of its descendants actually took focus. 9075 * 9076 * @see #isInTouchMode() 9077 * 9078 */ 9079 public final boolean requestFocusFromTouch() { 9080 // Leave touch mode if we need to 9081 if (isInTouchMode()) { 9082 ViewRootImpl viewRoot = getViewRootImpl(); 9083 if (viewRoot != null) { 9084 viewRoot.ensureTouchMode(false); 9085 } 9086 } 9087 return requestFocus(View.FOCUS_DOWN); 9088 } 9089 9090 /** 9091 * @return Whether any ancestor of this view blocks descendant focus. 9092 */ 9093 private boolean hasAncestorThatBlocksDescendantFocus() { 9094 final boolean focusableInTouchMode = isFocusableInTouchMode(); 9095 ViewParent ancestor = mParent; 9096 while (ancestor instanceof ViewGroup) { 9097 final ViewGroup vgAncestor = (ViewGroup) ancestor; 9098 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 9099 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 9100 return true; 9101 } else { 9102 ancestor = vgAncestor.getParent(); 9103 } 9104 } 9105 return false; 9106 } 9107 9108 /** 9109 * Gets the mode for determining whether this View is important for accessibility 9110 * which is if it fires accessibility events and if it is reported to 9111 * accessibility services that query the screen. 9112 * 9113 * @return The mode for determining whether a View is important for accessibility. 9114 * 9115 * @attr ref android.R.styleable#View_importantForAccessibility 9116 * 9117 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9118 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9119 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9120 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9121 */ 9122 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 9123 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 9124 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 9125 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 9126 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 9127 to = "noHideDescendants") 9128 }) 9129 public int getImportantForAccessibility() { 9130 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9131 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9132 } 9133 9134 /** 9135 * Sets the live region mode for this view. This indicates to accessibility 9136 * services whether they should automatically notify the user about changes 9137 * to the view's content description or text, or to the content descriptions 9138 * or text of the view's children (where applicable). 9139 * <p> 9140 * For example, in a login screen with a TextView that displays an "incorrect 9141 * password" notification, that view should be marked as a live region with 9142 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9143 * <p> 9144 * To disable change notifications for this view, use 9145 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 9146 * mode for most views. 9147 * <p> 9148 * To indicate that the user should be notified of changes, use 9149 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9150 * <p> 9151 * If the view's changes should interrupt ongoing speech and notify the user 9152 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 9153 * 9154 * @param mode The live region mode for this view, one of: 9155 * <ul> 9156 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 9157 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 9158 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 9159 * </ul> 9160 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9161 */ 9162 public void setAccessibilityLiveRegion(int mode) { 9163 if (mode != getAccessibilityLiveRegion()) { 9164 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9165 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 9166 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9167 notifyViewAccessibilityStateChangedIfNeeded( 9168 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9169 } 9170 } 9171 9172 /** 9173 * Gets the live region mode for this View. 9174 * 9175 * @return The live region mode for the view. 9176 * 9177 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9178 * 9179 * @see #setAccessibilityLiveRegion(int) 9180 */ 9181 public int getAccessibilityLiveRegion() { 9182 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 9183 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 9184 } 9185 9186 /** 9187 * Sets how to determine whether this view is important for accessibility 9188 * which is if it fires accessibility events and if it is reported to 9189 * accessibility services that query the screen. 9190 * 9191 * @param mode How to determine whether this view is important for accessibility. 9192 * 9193 * @attr ref android.R.styleable#View_importantForAccessibility 9194 * 9195 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9196 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9197 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9198 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9199 */ 9200 public void setImportantForAccessibility(int mode) { 9201 final int oldMode = getImportantForAccessibility(); 9202 if (mode != oldMode) { 9203 final boolean hideDescendants = 9204 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 9205 9206 // If this node or its descendants are no longer important, try to 9207 // clear accessibility focus. 9208 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 9209 final View focusHost = findAccessibilityFocusHost(hideDescendants); 9210 if (focusHost != null) { 9211 focusHost.clearAccessibilityFocus(); 9212 } 9213 } 9214 9215 // If we're moving between AUTO and another state, we might not need 9216 // to send a subtree changed notification. We'll store the computed 9217 // importance, since we'll need to check it later to make sure. 9218 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 9219 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 9220 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 9221 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9222 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 9223 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9224 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 9225 notifySubtreeAccessibilityStateChangedIfNeeded(); 9226 } else { 9227 notifyViewAccessibilityStateChangedIfNeeded( 9228 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9229 } 9230 } 9231 } 9232 9233 /** 9234 * Returns the view within this view's hierarchy that is hosting 9235 * accessibility focus. 9236 * 9237 * @param searchDescendants whether to search for focus in descendant views 9238 * @return the view hosting accessibility focus, or {@code null} 9239 */ 9240 private View findAccessibilityFocusHost(boolean searchDescendants) { 9241 if (isAccessibilityFocusedViewOrHost()) { 9242 return this; 9243 } 9244 9245 if (searchDescendants) { 9246 final ViewRootImpl viewRoot = getViewRootImpl(); 9247 if (viewRoot != null) { 9248 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 9249 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9250 return focusHost; 9251 } 9252 } 9253 } 9254 9255 return null; 9256 } 9257 9258 /** 9259 * Computes whether this view should be exposed for accessibility. In 9260 * general, views that are interactive or provide information are exposed 9261 * while views that serve only as containers are hidden. 9262 * <p> 9263 * If an ancestor of this view has importance 9264 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 9265 * returns <code>false</code>. 9266 * <p> 9267 * Otherwise, the value is computed according to the view's 9268 * {@link #getImportantForAccessibility()} value: 9269 * <ol> 9270 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 9271 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 9272 * </code> 9273 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 9274 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 9275 * view satisfies any of the following: 9276 * <ul> 9277 * <li>Is actionable, e.g. {@link #isClickable()}, 9278 * {@link #isLongClickable()}, or {@link #isFocusable()} 9279 * <li>Has an {@link AccessibilityDelegate} 9280 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 9281 * {@link OnKeyListener}, etc. 9282 * <li>Is an accessibility live region, e.g. 9283 * {@link #getAccessibilityLiveRegion()} is not 9284 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 9285 * </ul> 9286 * </ol> 9287 * 9288 * @return Whether the view is exposed for accessibility. 9289 * @see #setImportantForAccessibility(int) 9290 * @see #getImportantForAccessibility() 9291 */ 9292 public boolean isImportantForAccessibility() { 9293 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9294 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9295 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 9296 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9297 return false; 9298 } 9299 9300 // Check parent mode to ensure we're not hidden. 9301 ViewParent parent = mParent; 9302 while (parent instanceof View) { 9303 if (((View) parent).getImportantForAccessibility() 9304 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9305 return false; 9306 } 9307 parent = parent.getParent(); 9308 } 9309 9310 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 9311 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 9312 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 9313 } 9314 9315 /** 9316 * Gets the parent for accessibility purposes. Note that the parent for 9317 * accessibility is not necessary the immediate parent. It is the first 9318 * predecessor that is important for accessibility. 9319 * 9320 * @return The parent for accessibility purposes. 9321 */ 9322 public ViewParent getParentForAccessibility() { 9323 if (mParent instanceof View) { 9324 View parentView = (View) mParent; 9325 if (parentView.includeForAccessibility()) { 9326 return mParent; 9327 } else { 9328 return mParent.getParentForAccessibility(); 9329 } 9330 } 9331 return null; 9332 } 9333 9334 /** 9335 * Adds the children of this View relevant for accessibility to the given list 9336 * as output. Since some Views are not important for accessibility the added 9337 * child views are not necessarily direct children of this view, rather they are 9338 * the first level of descendants important for accessibility. 9339 * 9340 * @param outChildren The output list that will receive children for accessibility. 9341 */ 9342 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 9343 9344 } 9345 9346 /** 9347 * Whether to regard this view for accessibility. A view is regarded for 9348 * accessibility if it is important for accessibility or the querying 9349 * accessibility service has explicitly requested that view not 9350 * important for accessibility are regarded. 9351 * 9352 * @return Whether to regard the view for accessibility. 9353 * 9354 * @hide 9355 */ 9356 public boolean includeForAccessibility() { 9357 if (mAttachInfo != null) { 9358 return (mAttachInfo.mAccessibilityFetchFlags 9359 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 9360 || isImportantForAccessibility(); 9361 } 9362 return false; 9363 } 9364 9365 /** 9366 * Returns whether the View is considered actionable from 9367 * accessibility perspective. Such view are important for 9368 * accessibility. 9369 * 9370 * @return True if the view is actionable for accessibility. 9371 * 9372 * @hide 9373 */ 9374 public boolean isActionableForAccessibility() { 9375 return (isClickable() || isLongClickable() || isFocusable()); 9376 } 9377 9378 /** 9379 * Returns whether the View has registered callbacks which makes it 9380 * important for accessibility. 9381 * 9382 * @return True if the view is actionable for accessibility. 9383 */ 9384 private boolean hasListenersForAccessibility() { 9385 ListenerInfo info = getListenerInfo(); 9386 return mTouchDelegate != null || info.mOnKeyListener != null 9387 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 9388 || info.mOnHoverListener != null || info.mOnDragListener != null; 9389 } 9390 9391 /** 9392 * Notifies that the accessibility state of this view changed. The change 9393 * is local to this view and does not represent structural changes such 9394 * as children and parent. For example, the view became focusable. The 9395 * notification is at at most once every 9396 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9397 * to avoid unnecessary load to the system. Also once a view has a pending 9398 * notification this method is a NOP until the notification has been sent. 9399 * 9400 * @hide 9401 */ 9402 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 9403 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9404 return; 9405 } 9406 if (mSendViewStateChangedAccessibilityEvent == null) { 9407 mSendViewStateChangedAccessibilityEvent = 9408 new SendViewStateChangedAccessibilityEvent(); 9409 } 9410 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 9411 } 9412 9413 /** 9414 * Notifies that the accessibility state of this view changed. The change 9415 * is *not* local to this view and does represent structural changes such 9416 * as children and parent. For example, the view size changed. The 9417 * notification is at at most once every 9418 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9419 * to avoid unnecessary load to the system. Also once a view has a pending 9420 * notification this method is a NOP until the notification has been sent. 9421 * 9422 * @hide 9423 */ 9424 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 9425 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9426 return; 9427 } 9428 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 9429 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9430 if (mParent != null) { 9431 try { 9432 mParent.notifySubtreeAccessibilityStateChanged( 9433 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 9434 } catch (AbstractMethodError e) { 9435 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9436 " does not fully implement ViewParent", e); 9437 } 9438 } 9439 } 9440 } 9441 9442 /** 9443 * Change the visibility of the View without triggering any other changes. This is 9444 * important for transitions, where visibility changes should not adjust focus or 9445 * trigger a new layout. This is only used when the visibility has already been changed 9446 * and we need a transient value during an animation. When the animation completes, 9447 * the original visibility value is always restored. 9448 * 9449 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9450 * @hide 9451 */ 9452 public void setTransitionVisibility(@Visibility int visibility) { 9453 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 9454 } 9455 9456 /** 9457 * Reset the flag indicating the accessibility state of the subtree rooted 9458 * at this view changed. 9459 */ 9460 void resetSubtreeAccessibilityStateChanged() { 9461 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9462 } 9463 9464 /** 9465 * Report an accessibility action to this view's parents for delegated processing. 9466 * 9467 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 9468 * call this method to delegate an accessibility action to a supporting parent. If the parent 9469 * returns true from its 9470 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 9471 * method this method will return true to signify that the action was consumed.</p> 9472 * 9473 * <p>This method is useful for implementing nested scrolling child views. If 9474 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 9475 * a custom view implementation may invoke this method to allow a parent to consume the 9476 * scroll first. If this method returns true the custom view should skip its own scrolling 9477 * behavior.</p> 9478 * 9479 * @param action Accessibility action to delegate 9480 * @param arguments Optional action arguments 9481 * @return true if the action was consumed by a parent 9482 */ 9483 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 9484 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 9485 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 9486 return true; 9487 } 9488 } 9489 return false; 9490 } 9491 9492 /** 9493 * Performs the specified accessibility action on the view. For 9494 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 9495 * <p> 9496 * If an {@link AccessibilityDelegate} has been specified via calling 9497 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 9498 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 9499 * is responsible for handling this call. 9500 * </p> 9501 * 9502 * <p>The default implementation will delegate 9503 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 9504 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 9505 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 9506 * 9507 * @param action The action to perform. 9508 * @param arguments Optional action arguments. 9509 * @return Whether the action was performed. 9510 */ 9511 public boolean performAccessibilityAction(int action, Bundle arguments) { 9512 if (mAccessibilityDelegate != null) { 9513 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 9514 } else { 9515 return performAccessibilityActionInternal(action, arguments); 9516 } 9517 } 9518 9519 /** 9520 * @see #performAccessibilityAction(int, Bundle) 9521 * 9522 * Note: Called from the default {@link AccessibilityDelegate}. 9523 * 9524 * @hide 9525 */ 9526 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 9527 if (isNestedScrollingEnabled() 9528 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 9529 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 9530 || action == R.id.accessibilityActionScrollUp 9531 || action == R.id.accessibilityActionScrollLeft 9532 || action == R.id.accessibilityActionScrollDown 9533 || action == R.id.accessibilityActionScrollRight)) { 9534 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 9535 return true; 9536 } 9537 } 9538 9539 switch (action) { 9540 case AccessibilityNodeInfo.ACTION_CLICK: { 9541 if (isClickable()) { 9542 performClick(); 9543 return true; 9544 } 9545 } break; 9546 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 9547 if (isLongClickable()) { 9548 performLongClick(); 9549 return true; 9550 } 9551 } break; 9552 case AccessibilityNodeInfo.ACTION_FOCUS: { 9553 if (!hasFocus()) { 9554 // Get out of touch mode since accessibility 9555 // wants to move focus around. 9556 getViewRootImpl().ensureTouchMode(false); 9557 return requestFocus(); 9558 } 9559 } break; 9560 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 9561 if (hasFocus()) { 9562 clearFocus(); 9563 return !isFocused(); 9564 } 9565 } break; 9566 case AccessibilityNodeInfo.ACTION_SELECT: { 9567 if (!isSelected()) { 9568 setSelected(true); 9569 return isSelected(); 9570 } 9571 } break; 9572 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 9573 if (isSelected()) { 9574 setSelected(false); 9575 return !isSelected(); 9576 } 9577 } break; 9578 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 9579 if (!isAccessibilityFocused()) { 9580 return requestAccessibilityFocus(); 9581 } 9582 } break; 9583 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 9584 if (isAccessibilityFocused()) { 9585 clearAccessibilityFocus(); 9586 return true; 9587 } 9588 } break; 9589 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 9590 if (arguments != null) { 9591 final int granularity = arguments.getInt( 9592 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9593 final boolean extendSelection = arguments.getBoolean( 9594 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9595 return traverseAtGranularity(granularity, true, extendSelection); 9596 } 9597 } break; 9598 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 9599 if (arguments != null) { 9600 final int granularity = arguments.getInt( 9601 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9602 final boolean extendSelection = arguments.getBoolean( 9603 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9604 return traverseAtGranularity(granularity, false, extendSelection); 9605 } 9606 } break; 9607 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 9608 CharSequence text = getIterableTextForAccessibility(); 9609 if (text == null) { 9610 return false; 9611 } 9612 final int start = (arguments != null) ? arguments.getInt( 9613 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 9614 final int end = (arguments != null) ? arguments.getInt( 9615 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 9616 // Only cursor position can be specified (selection length == 0) 9617 if ((getAccessibilitySelectionStart() != start 9618 || getAccessibilitySelectionEnd() != end) 9619 && (start == end)) { 9620 setAccessibilitySelection(start, end); 9621 notifyViewAccessibilityStateChangedIfNeeded( 9622 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9623 return true; 9624 } 9625 } break; 9626 case R.id.accessibilityActionShowOnScreen: { 9627 if (mAttachInfo != null) { 9628 final Rect r = mAttachInfo.mTmpInvalRect; 9629 getDrawingRect(r); 9630 return requestRectangleOnScreen(r, true); 9631 } 9632 } break; 9633 case R.id.accessibilityActionContextClick: { 9634 if (isContextClickable()) { 9635 performContextClick(); 9636 return true; 9637 } 9638 } break; 9639 } 9640 return false; 9641 } 9642 9643 private boolean traverseAtGranularity(int granularity, boolean forward, 9644 boolean extendSelection) { 9645 CharSequence text = getIterableTextForAccessibility(); 9646 if (text == null || text.length() == 0) { 9647 return false; 9648 } 9649 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 9650 if (iterator == null) { 9651 return false; 9652 } 9653 int current = getAccessibilitySelectionEnd(); 9654 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9655 current = forward ? 0 : text.length(); 9656 } 9657 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 9658 if (range == null) { 9659 return false; 9660 } 9661 final int segmentStart = range[0]; 9662 final int segmentEnd = range[1]; 9663 int selectionStart; 9664 int selectionEnd; 9665 if (extendSelection && isAccessibilitySelectionExtendable()) { 9666 selectionStart = getAccessibilitySelectionStart(); 9667 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9668 selectionStart = forward ? segmentStart : segmentEnd; 9669 } 9670 selectionEnd = forward ? segmentEnd : segmentStart; 9671 } else { 9672 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 9673 } 9674 setAccessibilitySelection(selectionStart, selectionEnd); 9675 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 9676 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 9677 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 9678 return true; 9679 } 9680 9681 /** 9682 * Gets the text reported for accessibility purposes. 9683 * 9684 * @return The accessibility text. 9685 * 9686 * @hide 9687 */ 9688 public CharSequence getIterableTextForAccessibility() { 9689 return getContentDescription(); 9690 } 9691 9692 /** 9693 * Gets whether accessibility selection can be extended. 9694 * 9695 * @return If selection is extensible. 9696 * 9697 * @hide 9698 */ 9699 public boolean isAccessibilitySelectionExtendable() { 9700 return false; 9701 } 9702 9703 /** 9704 * @hide 9705 */ 9706 public int getAccessibilitySelectionStart() { 9707 return mAccessibilityCursorPosition; 9708 } 9709 9710 /** 9711 * @hide 9712 */ 9713 public int getAccessibilitySelectionEnd() { 9714 return getAccessibilitySelectionStart(); 9715 } 9716 9717 /** 9718 * @hide 9719 */ 9720 public void setAccessibilitySelection(int start, int end) { 9721 if (start == end && end == mAccessibilityCursorPosition) { 9722 return; 9723 } 9724 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9725 mAccessibilityCursorPosition = start; 9726 } else { 9727 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9728 } 9729 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9730 } 9731 9732 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9733 int fromIndex, int toIndex) { 9734 if (mParent == null) { 9735 return; 9736 } 9737 AccessibilityEvent event = AccessibilityEvent.obtain( 9738 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9739 onInitializeAccessibilityEvent(event); 9740 onPopulateAccessibilityEvent(event); 9741 event.setFromIndex(fromIndex); 9742 event.setToIndex(toIndex); 9743 event.setAction(action); 9744 event.setMovementGranularity(granularity); 9745 mParent.requestSendAccessibilityEvent(this, event); 9746 } 9747 9748 /** 9749 * @hide 9750 */ 9751 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9752 switch (granularity) { 9753 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9754 CharSequence text = getIterableTextForAccessibility(); 9755 if (text != null && text.length() > 0) { 9756 CharacterTextSegmentIterator iterator = 9757 CharacterTextSegmentIterator.getInstance( 9758 mContext.getResources().getConfiguration().locale); 9759 iterator.initialize(text.toString()); 9760 return iterator; 9761 } 9762 } break; 9763 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9764 CharSequence text = getIterableTextForAccessibility(); 9765 if (text != null && text.length() > 0) { 9766 WordTextSegmentIterator iterator = 9767 WordTextSegmentIterator.getInstance( 9768 mContext.getResources().getConfiguration().locale); 9769 iterator.initialize(text.toString()); 9770 return iterator; 9771 } 9772 } break; 9773 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9774 CharSequence text = getIterableTextForAccessibility(); 9775 if (text != null && text.length() > 0) { 9776 ParagraphTextSegmentIterator iterator = 9777 ParagraphTextSegmentIterator.getInstance(); 9778 iterator.initialize(text.toString()); 9779 return iterator; 9780 } 9781 } break; 9782 } 9783 return null; 9784 } 9785 9786 /** 9787 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 9788 * and {@link #onFinishTemporaryDetach()}. 9789 */ 9790 public final boolean isTemporarilyDetached() { 9791 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 9792 } 9793 9794 /** 9795 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 9796 * a container View. 9797 */ 9798 @CallSuper 9799 public void dispatchStartTemporaryDetach() { 9800 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 9801 onStartTemporaryDetach(); 9802 } 9803 9804 /** 9805 * This is called when a container is going to temporarily detach a child, with 9806 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9807 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9808 * {@link #onDetachedFromWindow()} when the container is done. 9809 */ 9810 public void onStartTemporaryDetach() { 9811 removeUnsetPressCallback(); 9812 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9813 } 9814 9815 /** 9816 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 9817 * a container View. 9818 */ 9819 @CallSuper 9820 public void dispatchFinishTemporaryDetach() { 9821 onFinishTemporaryDetach(); 9822 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 9823 } 9824 9825 /** 9826 * Called after {@link #onStartTemporaryDetach} when the container is done 9827 * changing the view. 9828 */ 9829 public void onFinishTemporaryDetach() { 9830 } 9831 9832 /** 9833 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9834 * for this view's window. Returns null if the view is not currently attached 9835 * to the window. Normally you will not need to use this directly, but 9836 * just use the standard high-level event callbacks like 9837 * {@link #onKeyDown(int, KeyEvent)}. 9838 */ 9839 public KeyEvent.DispatcherState getKeyDispatcherState() { 9840 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9841 } 9842 9843 /** 9844 * Dispatch a key event before it is processed by any input method 9845 * associated with the view hierarchy. This can be used to intercept 9846 * key events in special situations before the IME consumes them; a 9847 * typical example would be handling the BACK key to update the application's 9848 * UI instead of allowing the IME to see it and close itself. 9849 * 9850 * @param event The key event to be dispatched. 9851 * @return True if the event was handled, false otherwise. 9852 */ 9853 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9854 return onKeyPreIme(event.getKeyCode(), event); 9855 } 9856 9857 /** 9858 * Dispatch a key event to the next view on the focus path. This path runs 9859 * from the top of the view tree down to the currently focused view. If this 9860 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9861 * the next node down the focus path. This method also fires any key 9862 * listeners. 9863 * 9864 * @param event The key event to be dispatched. 9865 * @return True if the event was handled, false otherwise. 9866 */ 9867 public boolean dispatchKeyEvent(KeyEvent event) { 9868 if (mInputEventConsistencyVerifier != null) { 9869 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9870 } 9871 9872 // Give any attached key listener a first crack at the event. 9873 //noinspection SimplifiableIfStatement 9874 ListenerInfo li = mListenerInfo; 9875 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9876 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9877 return true; 9878 } 9879 9880 if (event.dispatch(this, mAttachInfo != null 9881 ? mAttachInfo.mKeyDispatchState : null, this)) { 9882 return true; 9883 } 9884 9885 if (mInputEventConsistencyVerifier != null) { 9886 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9887 } 9888 return false; 9889 } 9890 9891 /** 9892 * Dispatches a key shortcut event. 9893 * 9894 * @param event The key event to be dispatched. 9895 * @return True if the event was handled by the view, false otherwise. 9896 */ 9897 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9898 return onKeyShortcut(event.getKeyCode(), event); 9899 } 9900 9901 /** 9902 * Pass the touch screen motion event down to the target view, or this 9903 * view if it is the target. 9904 * 9905 * @param event The motion event to be dispatched. 9906 * @return True if the event was handled by the view, false otherwise. 9907 */ 9908 public boolean dispatchTouchEvent(MotionEvent event) { 9909 // If the event should be handled by accessibility focus first. 9910 if (event.isTargetAccessibilityFocus()) { 9911 // We don't have focus or no virtual descendant has it, do not handle the event. 9912 if (!isAccessibilityFocusedViewOrHost()) { 9913 return false; 9914 } 9915 // We have focus and got the event, then use normal event dispatch. 9916 event.setTargetAccessibilityFocus(false); 9917 } 9918 9919 boolean result = false; 9920 9921 if (mInputEventConsistencyVerifier != null) { 9922 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9923 } 9924 9925 final int actionMasked = event.getActionMasked(); 9926 if (actionMasked == MotionEvent.ACTION_DOWN) { 9927 // Defensive cleanup for new gesture 9928 stopNestedScroll(); 9929 } 9930 9931 if (onFilterTouchEventForSecurity(event)) { 9932 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 9933 result = true; 9934 } 9935 //noinspection SimplifiableIfStatement 9936 ListenerInfo li = mListenerInfo; 9937 if (li != null && li.mOnTouchListener != null 9938 && (mViewFlags & ENABLED_MASK) == ENABLED 9939 && li.mOnTouchListener.onTouch(this, event)) { 9940 result = true; 9941 } 9942 9943 if (!result && onTouchEvent(event)) { 9944 result = true; 9945 } 9946 } 9947 9948 if (!result && mInputEventConsistencyVerifier != null) { 9949 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9950 } 9951 9952 // Clean up after nested scrolls if this is the end of a gesture; 9953 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 9954 // of the gesture. 9955 if (actionMasked == MotionEvent.ACTION_UP || 9956 actionMasked == MotionEvent.ACTION_CANCEL || 9957 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 9958 stopNestedScroll(); 9959 } 9960 9961 return result; 9962 } 9963 9964 boolean isAccessibilityFocusedViewOrHost() { 9965 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 9966 .getAccessibilityFocusedHost() == this); 9967 } 9968 9969 /** 9970 * Filter the touch event to apply security policies. 9971 * 9972 * @param event The motion event to be filtered. 9973 * @return True if the event should be dispatched, false if the event should be dropped. 9974 * 9975 * @see #getFilterTouchesWhenObscured 9976 */ 9977 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 9978 //noinspection RedundantIfStatement 9979 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 9980 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 9981 // Window is obscured, drop this touch. 9982 return false; 9983 } 9984 return true; 9985 } 9986 9987 /** 9988 * Pass a trackball motion event down to the focused view. 9989 * 9990 * @param event The motion event to be dispatched. 9991 * @return True if the event was handled by the view, false otherwise. 9992 */ 9993 public boolean dispatchTrackballEvent(MotionEvent event) { 9994 if (mInputEventConsistencyVerifier != null) { 9995 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 9996 } 9997 9998 return onTrackballEvent(event); 9999 } 10000 10001 /** 10002 * Dispatch a generic motion event. 10003 * <p> 10004 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10005 * are delivered to the view under the pointer. All other generic motion events are 10006 * delivered to the focused view. Hover events are handled specially and are delivered 10007 * to {@link #onHoverEvent(MotionEvent)}. 10008 * </p> 10009 * 10010 * @param event The motion event to be dispatched. 10011 * @return True if the event was handled by the view, false otherwise. 10012 */ 10013 public boolean dispatchGenericMotionEvent(MotionEvent event) { 10014 if (mInputEventConsistencyVerifier != null) { 10015 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 10016 } 10017 10018 final int source = event.getSource(); 10019 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 10020 final int action = event.getAction(); 10021 if (action == MotionEvent.ACTION_HOVER_ENTER 10022 || action == MotionEvent.ACTION_HOVER_MOVE 10023 || action == MotionEvent.ACTION_HOVER_EXIT) { 10024 if (dispatchHoverEvent(event)) { 10025 return true; 10026 } 10027 } else if (dispatchGenericPointerEvent(event)) { 10028 return true; 10029 } 10030 } else if (dispatchGenericFocusedEvent(event)) { 10031 return true; 10032 } 10033 10034 if (dispatchGenericMotionEventInternal(event)) { 10035 return true; 10036 } 10037 10038 if (mInputEventConsistencyVerifier != null) { 10039 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10040 } 10041 return false; 10042 } 10043 10044 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 10045 //noinspection SimplifiableIfStatement 10046 ListenerInfo li = mListenerInfo; 10047 if (li != null && li.mOnGenericMotionListener != null 10048 && (mViewFlags & ENABLED_MASK) == ENABLED 10049 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 10050 return true; 10051 } 10052 10053 if (onGenericMotionEvent(event)) { 10054 return true; 10055 } 10056 10057 final int actionButton = event.getActionButton(); 10058 switch (event.getActionMasked()) { 10059 case MotionEvent.ACTION_BUTTON_PRESS: 10060 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 10061 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10062 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10063 if (performContextClick(event.getX(), event.getY())) { 10064 mInContextButtonPress = true; 10065 setPressed(true, event.getX(), event.getY()); 10066 removeTapCallback(); 10067 removeLongPressCallback(); 10068 return true; 10069 } 10070 } 10071 break; 10072 10073 case MotionEvent.ACTION_BUTTON_RELEASE: 10074 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10075 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10076 mInContextButtonPress = false; 10077 mIgnoreNextUpEvent = true; 10078 } 10079 break; 10080 } 10081 10082 if (mInputEventConsistencyVerifier != null) { 10083 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10084 } 10085 return false; 10086 } 10087 10088 /** 10089 * Dispatch a hover event. 10090 * <p> 10091 * Do not call this method directly. 10092 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10093 * </p> 10094 * 10095 * @param event The motion event to be dispatched. 10096 * @return True if the event was handled by the view, false otherwise. 10097 */ 10098 protected boolean dispatchHoverEvent(MotionEvent event) { 10099 ListenerInfo li = mListenerInfo; 10100 //noinspection SimplifiableIfStatement 10101 if (li != null && li.mOnHoverListener != null 10102 && (mViewFlags & ENABLED_MASK) == ENABLED 10103 && li.mOnHoverListener.onHover(this, event)) { 10104 return true; 10105 } 10106 10107 return onHoverEvent(event); 10108 } 10109 10110 /** 10111 * Returns true if the view has a child to which it has recently sent 10112 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 10113 * it does not have a hovered child, then it must be the innermost hovered view. 10114 * @hide 10115 */ 10116 protected boolean hasHoveredChild() { 10117 return false; 10118 } 10119 10120 /** 10121 * Dispatch a generic motion event to the view under the first pointer. 10122 * <p> 10123 * Do not call this method directly. 10124 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10125 * </p> 10126 * 10127 * @param event The motion event to be dispatched. 10128 * @return True if the event was handled by the view, false otherwise. 10129 */ 10130 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 10131 return false; 10132 } 10133 10134 /** 10135 * Dispatch a generic motion event to the currently focused view. 10136 * <p> 10137 * Do not call this method directly. 10138 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10139 * </p> 10140 * 10141 * @param event The motion event to be dispatched. 10142 * @return True if the event was handled by the view, false otherwise. 10143 */ 10144 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 10145 return false; 10146 } 10147 10148 /** 10149 * Dispatch a pointer event. 10150 * <p> 10151 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 10152 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 10153 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 10154 * and should not be expected to handle other pointing device features. 10155 * </p> 10156 * 10157 * @param event The motion event to be dispatched. 10158 * @return True if the event was handled by the view, false otherwise. 10159 * @hide 10160 */ 10161 public final boolean dispatchPointerEvent(MotionEvent event) { 10162 if (event.isTouchEvent()) { 10163 return dispatchTouchEvent(event); 10164 } else { 10165 return dispatchGenericMotionEvent(event); 10166 } 10167 } 10168 10169 /** 10170 * Called when the window containing this view gains or loses window focus. 10171 * ViewGroups should override to route to their children. 10172 * 10173 * @param hasFocus True if the window containing this view now has focus, 10174 * false otherwise. 10175 */ 10176 public void dispatchWindowFocusChanged(boolean hasFocus) { 10177 onWindowFocusChanged(hasFocus); 10178 } 10179 10180 /** 10181 * Called when the window containing this view gains or loses focus. Note 10182 * that this is separate from view focus: to receive key events, both 10183 * your view and its window must have focus. If a window is displayed 10184 * on top of yours that takes input focus, then your own window will lose 10185 * focus but the view focus will remain unchanged. 10186 * 10187 * @param hasWindowFocus True if the window containing this view now has 10188 * focus, false otherwise. 10189 */ 10190 public void onWindowFocusChanged(boolean hasWindowFocus) { 10191 InputMethodManager imm = InputMethodManager.peekInstance(); 10192 if (!hasWindowFocus) { 10193 if (isPressed()) { 10194 setPressed(false); 10195 } 10196 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10197 imm.focusOut(this); 10198 } 10199 removeLongPressCallback(); 10200 removeTapCallback(); 10201 onFocusLost(); 10202 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10203 imm.focusIn(this); 10204 } 10205 refreshDrawableState(); 10206 } 10207 10208 /** 10209 * Returns true if this view is in a window that currently has window focus. 10210 * Note that this is not the same as the view itself having focus. 10211 * 10212 * @return True if this view is in a window that currently has window focus. 10213 */ 10214 public boolean hasWindowFocus() { 10215 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 10216 } 10217 10218 /** 10219 * Dispatch a view visibility change down the view hierarchy. 10220 * ViewGroups should override to route to their children. 10221 * @param changedView The view whose visibility changed. Could be 'this' or 10222 * an ancestor view. 10223 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 10224 * {@link #INVISIBLE} or {@link #GONE}. 10225 */ 10226 protected void dispatchVisibilityChanged(@NonNull View changedView, 10227 @Visibility int visibility) { 10228 onVisibilityChanged(changedView, visibility); 10229 } 10230 10231 /** 10232 * Called when the visibility of the view or an ancestor of the view has 10233 * changed. 10234 * 10235 * @param changedView The view whose visibility changed. May be 10236 * {@code this} or an ancestor view. 10237 * @param visibility The new visibility, one of {@link #VISIBLE}, 10238 * {@link #INVISIBLE} or {@link #GONE}. 10239 */ 10240 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 10241 } 10242 10243 /** 10244 * Dispatch a hint about whether this view is displayed. For instance, when 10245 * a View moves out of the screen, it might receives a display hint indicating 10246 * the view is not displayed. Applications should not <em>rely</em> on this hint 10247 * as there is no guarantee that they will receive one. 10248 * 10249 * @param hint A hint about whether or not this view is displayed: 10250 * {@link #VISIBLE} or {@link #INVISIBLE}. 10251 */ 10252 public void dispatchDisplayHint(@Visibility int hint) { 10253 onDisplayHint(hint); 10254 } 10255 10256 /** 10257 * Gives this view a hint about whether is displayed or not. For instance, when 10258 * a View moves out of the screen, it might receives a display hint indicating 10259 * the view is not displayed. Applications should not <em>rely</em> on this hint 10260 * as there is no guarantee that they will receive one. 10261 * 10262 * @param hint A hint about whether or not this view is displayed: 10263 * {@link #VISIBLE} or {@link #INVISIBLE}. 10264 */ 10265 protected void onDisplayHint(@Visibility int hint) { 10266 } 10267 10268 /** 10269 * Dispatch a window visibility change down the view hierarchy. 10270 * ViewGroups should override to route to their children. 10271 * 10272 * @param visibility The new visibility of the window. 10273 * 10274 * @see #onWindowVisibilityChanged(int) 10275 */ 10276 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 10277 onWindowVisibilityChanged(visibility); 10278 } 10279 10280 /** 10281 * Called when the window containing has change its visibility 10282 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 10283 * that this tells you whether or not your window is being made visible 10284 * to the window manager; this does <em>not</em> tell you whether or not 10285 * your window is obscured by other windows on the screen, even if it 10286 * is itself visible. 10287 * 10288 * @param visibility The new visibility of the window. 10289 */ 10290 protected void onWindowVisibilityChanged(@Visibility int visibility) { 10291 if (visibility == VISIBLE) { 10292 initialAwakenScrollBars(); 10293 } 10294 } 10295 10296 /** 10297 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 10298 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 10299 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 10300 * 10301 * @param isVisible true if this view's visibility to the user is uninterrupted by its 10302 * ancestors or by window visibility 10303 * @return true if this view is visible to the user, not counting clipping or overlapping 10304 */ 10305 @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) { 10306 final boolean thisVisible = getVisibility() == VISIBLE; 10307 // If we're not visible but something is telling us we are, ignore it. 10308 if (thisVisible || !isVisible) { 10309 onVisibilityAggregated(isVisible); 10310 } 10311 return thisVisible && isVisible; 10312 } 10313 10314 /** 10315 * Called when the user-visibility of this View is potentially affected by a change 10316 * to this view itself, an ancestor view or the window this view is attached to. 10317 * 10318 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 10319 * and this view's window is also visible 10320 */ 10321 @CallSuper 10322 public void onVisibilityAggregated(boolean isVisible) { 10323 if (isVisible && mAttachInfo != null) { 10324 initialAwakenScrollBars(); 10325 } 10326 10327 final Drawable dr = mBackground; 10328 if (dr != null && isVisible != dr.isVisible()) { 10329 dr.setVisible(isVisible, false); 10330 } 10331 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 10332 if (fg != null && isVisible != fg.isVisible()) { 10333 fg.setVisible(isVisible, false); 10334 } 10335 } 10336 10337 /** 10338 * Returns the current visibility of the window this view is attached to 10339 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 10340 * 10341 * @return Returns the current visibility of the view's window. 10342 */ 10343 @Visibility 10344 public int getWindowVisibility() { 10345 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 10346 } 10347 10348 /** 10349 * Retrieve the overall visible display size in which the window this view is 10350 * attached to has been positioned in. This takes into account screen 10351 * decorations above the window, for both cases where the window itself 10352 * is being position inside of them or the window is being placed under 10353 * then and covered insets are used for the window to position its content 10354 * inside. In effect, this tells you the available area where content can 10355 * be placed and remain visible to users. 10356 * 10357 * <p>This function requires an IPC back to the window manager to retrieve 10358 * the requested information, so should not be used in performance critical 10359 * code like drawing. 10360 * 10361 * @param outRect Filled in with the visible display frame. If the view 10362 * is not attached to a window, this is simply the raw display size. 10363 */ 10364 public void getWindowVisibleDisplayFrame(Rect outRect) { 10365 if (mAttachInfo != null) { 10366 try { 10367 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10368 } catch (RemoteException e) { 10369 return; 10370 } 10371 // XXX This is really broken, and probably all needs to be done 10372 // in the window manager, and we need to know more about whether 10373 // we want the area behind or in front of the IME. 10374 final Rect insets = mAttachInfo.mVisibleInsets; 10375 outRect.left += insets.left; 10376 outRect.top += insets.top; 10377 outRect.right -= insets.right; 10378 outRect.bottom -= insets.bottom; 10379 return; 10380 } 10381 // The view is not attached to a display so we don't have a context. 10382 // Make a best guess about the display size. 10383 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10384 d.getRectSize(outRect); 10385 } 10386 10387 /** 10388 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 10389 * is currently in without any insets. 10390 * 10391 * @hide 10392 */ 10393 public void getWindowDisplayFrame(Rect outRect) { 10394 if (mAttachInfo != null) { 10395 try { 10396 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10397 } catch (RemoteException e) { 10398 return; 10399 } 10400 return; 10401 } 10402 // The view is not attached to a display so we don't have a context. 10403 // Make a best guess about the display size. 10404 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10405 d.getRectSize(outRect); 10406 } 10407 10408 /** 10409 * Dispatch a notification about a resource configuration change down 10410 * the view hierarchy. 10411 * ViewGroups should override to route to their children. 10412 * 10413 * @param newConfig The new resource configuration. 10414 * 10415 * @see #onConfigurationChanged(android.content.res.Configuration) 10416 */ 10417 public void dispatchConfigurationChanged(Configuration newConfig) { 10418 onConfigurationChanged(newConfig); 10419 } 10420 10421 /** 10422 * Called when the current configuration of the resources being used 10423 * by the application have changed. You can use this to decide when 10424 * to reload resources that can changed based on orientation and other 10425 * configuration characteristics. You only need to use this if you are 10426 * not relying on the normal {@link android.app.Activity} mechanism of 10427 * recreating the activity instance upon a configuration change. 10428 * 10429 * @param newConfig The new resource configuration. 10430 */ 10431 protected void onConfigurationChanged(Configuration newConfig) { 10432 } 10433 10434 /** 10435 * Private function to aggregate all per-view attributes in to the view 10436 * root. 10437 */ 10438 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10439 performCollectViewAttributes(attachInfo, visibility); 10440 } 10441 10442 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10443 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 10444 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 10445 attachInfo.mKeepScreenOn = true; 10446 } 10447 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 10448 ListenerInfo li = mListenerInfo; 10449 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 10450 attachInfo.mHasSystemUiListeners = true; 10451 } 10452 } 10453 } 10454 10455 void needGlobalAttributesUpdate(boolean force) { 10456 final AttachInfo ai = mAttachInfo; 10457 if (ai != null && !ai.mRecomputeGlobalAttributes) { 10458 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 10459 || ai.mHasSystemUiListeners) { 10460 ai.mRecomputeGlobalAttributes = true; 10461 } 10462 } 10463 } 10464 10465 /** 10466 * Returns whether the device is currently in touch mode. Touch mode is entered 10467 * once the user begins interacting with the device by touch, and affects various 10468 * things like whether focus is always visible to the user. 10469 * 10470 * @return Whether the device is in touch mode. 10471 */ 10472 @ViewDebug.ExportedProperty 10473 public boolean isInTouchMode() { 10474 if (mAttachInfo != null) { 10475 return mAttachInfo.mInTouchMode; 10476 } else { 10477 return ViewRootImpl.isInTouchMode(); 10478 } 10479 } 10480 10481 /** 10482 * Returns the context the view is running in, through which it can 10483 * access the current theme, resources, etc. 10484 * 10485 * @return The view's Context. 10486 */ 10487 @ViewDebug.CapturedViewProperty 10488 public final Context getContext() { 10489 return mContext; 10490 } 10491 10492 /** 10493 * Handle a key event before it is processed by any input method 10494 * associated with the view hierarchy. This can be used to intercept 10495 * key events in special situations before the IME consumes them; a 10496 * typical example would be handling the BACK key to update the application's 10497 * UI instead of allowing the IME to see it and close itself. 10498 * 10499 * @param keyCode The value in event.getKeyCode(). 10500 * @param event Description of the key event. 10501 * @return If you handled the event, return true. If you want to allow the 10502 * event to be handled by the next receiver, return false. 10503 */ 10504 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 10505 return false; 10506 } 10507 10508 /** 10509 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 10510 * KeyEvent.Callback.onKeyDown()}: perform press of the view 10511 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 10512 * is released, if the view is enabled and clickable. 10513 * <p> 10514 * Key presses in software keyboards will generally NOT trigger this 10515 * listener, although some may elect to do so in some situations. Do not 10516 * rely on this to catch software key presses. 10517 * 10518 * @param keyCode a key code that represents the button pressed, from 10519 * {@link android.view.KeyEvent} 10520 * @param event the KeyEvent object that defines the button action 10521 */ 10522 public boolean onKeyDown(int keyCode, KeyEvent event) { 10523 if (KeyEvent.isConfirmKey(keyCode)) { 10524 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10525 return true; 10526 } 10527 10528 // Long clickable items don't necessarily have to be clickable. 10529 if (((mViewFlags & CLICKABLE) == CLICKABLE 10530 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10531 && (event.getRepeatCount() == 0)) { 10532 // For the purposes of menu anchoring and drawable hotspots, 10533 // key events are considered to be at the center of the view. 10534 final float x = getWidth() / 2f; 10535 final float y = getHeight() / 2f; 10536 setPressed(true, x, y); 10537 checkForLongClick(0, x, y); 10538 return true; 10539 } 10540 } 10541 10542 return false; 10543 } 10544 10545 /** 10546 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 10547 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 10548 * the event). 10549 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10550 * although some may elect to do so in some situations. Do not rely on this to 10551 * catch software key presses. 10552 */ 10553 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 10554 return false; 10555 } 10556 10557 /** 10558 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 10559 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 10560 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 10561 * or {@link KeyEvent#KEYCODE_SPACE} is released. 10562 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10563 * although some may elect to do so in some situations. Do not rely on this to 10564 * catch software key presses. 10565 * 10566 * @param keyCode A key code that represents the button pressed, from 10567 * {@link android.view.KeyEvent}. 10568 * @param event The KeyEvent object that defines the button action. 10569 */ 10570 public boolean onKeyUp(int keyCode, KeyEvent event) { 10571 if (KeyEvent.isConfirmKey(keyCode)) { 10572 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10573 return true; 10574 } 10575 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 10576 setPressed(false); 10577 10578 if (!mHasPerformedLongPress) { 10579 // This is a tap, so remove the longpress check 10580 removeLongPressCallback(); 10581 return performClick(); 10582 } 10583 } 10584 } 10585 return false; 10586 } 10587 10588 /** 10589 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 10590 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 10591 * the event). 10592 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10593 * although some may elect to do so in some situations. Do not rely on this to 10594 * catch software key presses. 10595 * 10596 * @param keyCode A key code that represents the button pressed, from 10597 * {@link android.view.KeyEvent}. 10598 * @param repeatCount The number of times the action was made. 10599 * @param event The KeyEvent object that defines the button action. 10600 */ 10601 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 10602 return false; 10603 } 10604 10605 /** 10606 * Called on the focused view when a key shortcut event is not handled. 10607 * Override this method to implement local key shortcuts for the View. 10608 * Key shortcuts can also be implemented by setting the 10609 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 10610 * 10611 * @param keyCode The value in event.getKeyCode(). 10612 * @param event Description of the key event. 10613 * @return If you handled the event, return true. If you want to allow the 10614 * event to be handled by the next receiver, return false. 10615 */ 10616 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 10617 return false; 10618 } 10619 10620 /** 10621 * Check whether the called view is a text editor, in which case it 10622 * would make sense to automatically display a soft input window for 10623 * it. Subclasses should override this if they implement 10624 * {@link #onCreateInputConnection(EditorInfo)} to return true if 10625 * a call on that method would return a non-null InputConnection, and 10626 * they are really a first-class editor that the user would normally 10627 * start typing on when the go into a window containing your view. 10628 * 10629 * <p>The default implementation always returns false. This does 10630 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 10631 * will not be called or the user can not otherwise perform edits on your 10632 * view; it is just a hint to the system that this is not the primary 10633 * purpose of this view. 10634 * 10635 * @return Returns true if this view is a text editor, else false. 10636 */ 10637 public boolean onCheckIsTextEditor() { 10638 return false; 10639 } 10640 10641 /** 10642 * Create a new InputConnection for an InputMethod to interact 10643 * with the view. The default implementation returns null, since it doesn't 10644 * support input methods. You can override this to implement such support. 10645 * This is only needed for views that take focus and text input. 10646 * 10647 * <p>When implementing this, you probably also want to implement 10648 * {@link #onCheckIsTextEditor()} to indicate you will return a 10649 * non-null InputConnection.</p> 10650 * 10651 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 10652 * object correctly and in its entirety, so that the connected IME can rely 10653 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 10654 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 10655 * must be filled in with the correct cursor position for IMEs to work correctly 10656 * with your application.</p> 10657 * 10658 * @param outAttrs Fill in with attribute information about the connection. 10659 */ 10660 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 10661 return null; 10662 } 10663 10664 /** 10665 * Called by the {@link android.view.inputmethod.InputMethodManager} 10666 * when a view who is not the current 10667 * input connection target is trying to make a call on the manager. The 10668 * default implementation returns false; you can override this to return 10669 * true for certain views if you are performing InputConnection proxying 10670 * to them. 10671 * @param view The View that is making the InputMethodManager call. 10672 * @return Return true to allow the call, false to reject. 10673 */ 10674 public boolean checkInputConnectionProxy(View view) { 10675 return false; 10676 } 10677 10678 /** 10679 * Show the context menu for this view. It is not safe to hold on to the 10680 * menu after returning from this method. 10681 * 10682 * You should normally not overload this method. Overload 10683 * {@link #onCreateContextMenu(ContextMenu)} or define an 10684 * {@link OnCreateContextMenuListener} to add items to the context menu. 10685 * 10686 * @param menu The context menu to populate 10687 */ 10688 public void createContextMenu(ContextMenu menu) { 10689 ContextMenuInfo menuInfo = getContextMenuInfo(); 10690 10691 // Sets the current menu info so all items added to menu will have 10692 // my extra info set. 10693 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 10694 10695 onCreateContextMenu(menu); 10696 ListenerInfo li = mListenerInfo; 10697 if (li != null && li.mOnCreateContextMenuListener != null) { 10698 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 10699 } 10700 10701 // Clear the extra information so subsequent items that aren't mine don't 10702 // have my extra info. 10703 ((MenuBuilder)menu).setCurrentMenuInfo(null); 10704 10705 if (mParent != null) { 10706 mParent.createContextMenu(menu); 10707 } 10708 } 10709 10710 /** 10711 * Views should implement this if they have extra information to associate 10712 * with the context menu. The return result is supplied as a parameter to 10713 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 10714 * callback. 10715 * 10716 * @return Extra information about the item for which the context menu 10717 * should be shown. This information will vary across different 10718 * subclasses of View. 10719 */ 10720 protected ContextMenuInfo getContextMenuInfo() { 10721 return null; 10722 } 10723 10724 /** 10725 * Views should implement this if the view itself is going to add items to 10726 * the context menu. 10727 * 10728 * @param menu the context menu to populate 10729 */ 10730 protected void onCreateContextMenu(ContextMenu menu) { 10731 } 10732 10733 /** 10734 * Implement this method to handle trackball motion events. The 10735 * <em>relative</em> movement of the trackball since the last event 10736 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 10737 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 10738 * that a movement of 1 corresponds to the user pressing one DPAD key (so 10739 * they will often be fractional values, representing the more fine-grained 10740 * movement information available from a trackball). 10741 * 10742 * @param event The motion event. 10743 * @return True if the event was handled, false otherwise. 10744 */ 10745 public boolean onTrackballEvent(MotionEvent event) { 10746 return false; 10747 } 10748 10749 /** 10750 * Implement this method to handle generic motion events. 10751 * <p> 10752 * Generic motion events describe joystick movements, mouse hovers, track pad 10753 * touches, scroll wheel movements and other input events. The 10754 * {@link MotionEvent#getSource() source} of the motion event specifies 10755 * the class of input that was received. Implementations of this method 10756 * must examine the bits in the source before processing the event. 10757 * The following code example shows how this is done. 10758 * </p><p> 10759 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10760 * are delivered to the view under the pointer. All other generic motion events are 10761 * delivered to the focused view. 10762 * </p> 10763 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 10764 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 10765 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 10766 * // process the joystick movement... 10767 * return true; 10768 * } 10769 * } 10770 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 10771 * switch (event.getAction()) { 10772 * case MotionEvent.ACTION_HOVER_MOVE: 10773 * // process the mouse hover movement... 10774 * return true; 10775 * case MotionEvent.ACTION_SCROLL: 10776 * // process the scroll wheel movement... 10777 * return true; 10778 * } 10779 * } 10780 * return super.onGenericMotionEvent(event); 10781 * }</pre> 10782 * 10783 * @param event The generic motion event being processed. 10784 * @return True if the event was handled, false otherwise. 10785 */ 10786 public boolean onGenericMotionEvent(MotionEvent event) { 10787 return false; 10788 } 10789 10790 /** 10791 * Implement this method to handle hover events. 10792 * <p> 10793 * This method is called whenever a pointer is hovering into, over, or out of the 10794 * bounds of a view and the view is not currently being touched. 10795 * Hover events are represented as pointer events with action 10796 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10797 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10798 * </p> 10799 * <ul> 10800 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10801 * when the pointer enters the bounds of the view.</li> 10802 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10803 * when the pointer has already entered the bounds of the view and has moved.</li> 10804 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10805 * when the pointer has exited the bounds of the view or when the pointer is 10806 * about to go down due to a button click, tap, or similar user action that 10807 * causes the view to be touched.</li> 10808 * </ul> 10809 * <p> 10810 * The view should implement this method to return true to indicate that it is 10811 * handling the hover event, such as by changing its drawable state. 10812 * </p><p> 10813 * The default implementation calls {@link #setHovered} to update the hovered state 10814 * of the view when a hover enter or hover exit event is received, if the view 10815 * is enabled and is clickable. The default implementation also sends hover 10816 * accessibility events. 10817 * </p> 10818 * 10819 * @param event The motion event that describes the hover. 10820 * @return True if the view handled the hover event. 10821 * 10822 * @see #isHovered 10823 * @see #setHovered 10824 * @see #onHoverChanged 10825 */ 10826 public boolean onHoverEvent(MotionEvent event) { 10827 // The root view may receive hover (or touch) events that are outside the bounds of 10828 // the window. This code ensures that we only send accessibility events for 10829 // hovers that are actually within the bounds of the root view. 10830 final int action = event.getActionMasked(); 10831 if (!mSendingHoverAccessibilityEvents) { 10832 if ((action == MotionEvent.ACTION_HOVER_ENTER 10833 || action == MotionEvent.ACTION_HOVER_MOVE) 10834 && !hasHoveredChild() 10835 && pointInView(event.getX(), event.getY())) { 10836 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10837 mSendingHoverAccessibilityEvents = true; 10838 } 10839 } else { 10840 if (action == MotionEvent.ACTION_HOVER_EXIT 10841 || (action == MotionEvent.ACTION_MOVE 10842 && !pointInView(event.getX(), event.getY()))) { 10843 mSendingHoverAccessibilityEvents = false; 10844 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10845 } 10846 } 10847 10848 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 10849 && event.isFromSource(InputDevice.SOURCE_MOUSE) 10850 && isOnScrollbar(event.getX(), event.getY())) { 10851 awakenScrollBars(); 10852 } 10853 if (isHoverable()) { 10854 switch (action) { 10855 case MotionEvent.ACTION_HOVER_ENTER: 10856 setHovered(true); 10857 break; 10858 case MotionEvent.ACTION_HOVER_EXIT: 10859 setHovered(false); 10860 break; 10861 } 10862 10863 // Dispatch the event to onGenericMotionEvent before returning true. 10864 // This is to provide compatibility with existing applications that 10865 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10866 // break because of the new default handling for hoverable views 10867 // in onHoverEvent. 10868 // Note that onGenericMotionEvent will be called by default when 10869 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10870 dispatchGenericMotionEventInternal(event); 10871 // The event was already handled by calling setHovered(), so always 10872 // return true. 10873 return true; 10874 } 10875 10876 return false; 10877 } 10878 10879 /** 10880 * Returns true if the view should handle {@link #onHoverEvent} 10881 * by calling {@link #setHovered} to change its hovered state. 10882 * 10883 * @return True if the view is hoverable. 10884 */ 10885 private boolean isHoverable() { 10886 final int viewFlags = mViewFlags; 10887 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10888 return false; 10889 } 10890 10891 return (viewFlags & CLICKABLE) == CLICKABLE 10892 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10893 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10894 } 10895 10896 /** 10897 * Returns true if the view is currently hovered. 10898 * 10899 * @return True if the view is currently hovered. 10900 * 10901 * @see #setHovered 10902 * @see #onHoverChanged 10903 */ 10904 @ViewDebug.ExportedProperty 10905 public boolean isHovered() { 10906 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10907 } 10908 10909 /** 10910 * Sets whether the view is currently hovered. 10911 * <p> 10912 * Calling this method also changes the drawable state of the view. This 10913 * enables the view to react to hover by using different drawable resources 10914 * to change its appearance. 10915 * </p><p> 10916 * The {@link #onHoverChanged} method is called when the hovered state changes. 10917 * </p> 10918 * 10919 * @param hovered True if the view is hovered. 10920 * 10921 * @see #isHovered 10922 * @see #onHoverChanged 10923 */ 10924 public void setHovered(boolean hovered) { 10925 if (hovered) { 10926 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 10927 mPrivateFlags |= PFLAG_HOVERED; 10928 refreshDrawableState(); 10929 onHoverChanged(true); 10930 } 10931 } else { 10932 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 10933 mPrivateFlags &= ~PFLAG_HOVERED; 10934 refreshDrawableState(); 10935 onHoverChanged(false); 10936 } 10937 } 10938 } 10939 10940 /** 10941 * Implement this method to handle hover state changes. 10942 * <p> 10943 * This method is called whenever the hover state changes as a result of a 10944 * call to {@link #setHovered}. 10945 * </p> 10946 * 10947 * @param hovered The current hover state, as returned by {@link #isHovered}. 10948 * 10949 * @see #isHovered 10950 * @see #setHovered 10951 */ 10952 public void onHoverChanged(boolean hovered) { 10953 } 10954 10955 /** 10956 * Handles scroll bar dragging by mouse input. 10957 * 10958 * @hide 10959 * @param event The motion event. 10960 * 10961 * @return true if the event was handled as a scroll bar dragging, false otherwise. 10962 */ 10963 protected boolean handleScrollBarDragging(MotionEvent event) { 10964 if (mScrollCache == null) { 10965 return false; 10966 } 10967 final float x = event.getX(); 10968 final float y = event.getY(); 10969 final int action = event.getAction(); 10970 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 10971 && action != MotionEvent.ACTION_DOWN) 10972 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 10973 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 10974 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 10975 return false; 10976 } 10977 10978 switch (action) { 10979 case MotionEvent.ACTION_MOVE: 10980 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 10981 return false; 10982 } 10983 if (mScrollCache.mScrollBarDraggingState 10984 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 10985 final Rect bounds = mScrollCache.mScrollBarBounds; 10986 getVerticalScrollBarBounds(bounds); 10987 final int range = computeVerticalScrollRange(); 10988 final int offset = computeVerticalScrollOffset(); 10989 final int extent = computeVerticalScrollExtent(); 10990 10991 final int thumbLength = ScrollBarUtils.getThumbLength( 10992 bounds.height(), bounds.width(), extent, range); 10993 final int thumbOffset = ScrollBarUtils.getThumbOffset( 10994 bounds.height(), thumbLength, extent, range, offset); 10995 10996 final float diff = y - mScrollCache.mScrollBarDraggingPos; 10997 final float maxThumbOffset = bounds.height() - thumbLength; 10998 final float newThumbOffset = 10999 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11000 final int height = getHeight(); 11001 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11002 && height > 0 && extent > 0) { 11003 final int newY = Math.round((range - extent) 11004 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 11005 if (newY != getScrollY()) { 11006 mScrollCache.mScrollBarDraggingPos = y; 11007 setScrollY(newY); 11008 } 11009 } 11010 return true; 11011 } 11012 if (mScrollCache.mScrollBarDraggingState 11013 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 11014 final Rect bounds = mScrollCache.mScrollBarBounds; 11015 getHorizontalScrollBarBounds(bounds); 11016 final int range = computeHorizontalScrollRange(); 11017 final int offset = computeHorizontalScrollOffset(); 11018 final int extent = computeHorizontalScrollExtent(); 11019 11020 final int thumbLength = ScrollBarUtils.getThumbLength( 11021 bounds.width(), bounds.height(), extent, range); 11022 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11023 bounds.width(), thumbLength, extent, range, offset); 11024 11025 final float diff = x - mScrollCache.mScrollBarDraggingPos; 11026 final float maxThumbOffset = bounds.width() - thumbLength; 11027 final float newThumbOffset = 11028 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11029 final int width = getWidth(); 11030 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11031 && width > 0 && extent > 0) { 11032 final int newX = Math.round((range - extent) 11033 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 11034 if (newX != getScrollX()) { 11035 mScrollCache.mScrollBarDraggingPos = x; 11036 setScrollX(newX); 11037 } 11038 } 11039 return true; 11040 } 11041 case MotionEvent.ACTION_DOWN: 11042 if (mScrollCache.state == ScrollabilityCache.OFF) { 11043 return false; 11044 } 11045 if (isOnVerticalScrollbarThumb(x, y)) { 11046 mScrollCache.mScrollBarDraggingState = 11047 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 11048 mScrollCache.mScrollBarDraggingPos = y; 11049 return true; 11050 } 11051 if (isOnHorizontalScrollbarThumb(x, y)) { 11052 mScrollCache.mScrollBarDraggingState = 11053 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 11054 mScrollCache.mScrollBarDraggingPos = x; 11055 return true; 11056 } 11057 } 11058 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11059 return false; 11060 } 11061 11062 /** 11063 * Implement this method to handle touch screen motion events. 11064 * <p> 11065 * If this method is used to detect click actions, it is recommended that 11066 * the actions be performed by implementing and calling 11067 * {@link #performClick()}. This will ensure consistent system behavior, 11068 * including: 11069 * <ul> 11070 * <li>obeying click sound preferences 11071 * <li>dispatching OnClickListener calls 11072 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 11073 * accessibility features are enabled 11074 * </ul> 11075 * 11076 * @param event The motion event. 11077 * @return True if the event was handled, false otherwise. 11078 */ 11079 public boolean onTouchEvent(MotionEvent event) { 11080 final float x = event.getX(); 11081 final float y = event.getY(); 11082 final int viewFlags = mViewFlags; 11083 final int action = event.getAction(); 11084 11085 if ((viewFlags & ENABLED_MASK) == DISABLED) { 11086 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 11087 setPressed(false); 11088 } 11089 // A disabled view that is clickable still consumes the touch 11090 // events, it just doesn't respond to them. 11091 return (((viewFlags & CLICKABLE) == CLICKABLE 11092 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 11093 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 11094 } 11095 if (mTouchDelegate != null) { 11096 if (mTouchDelegate.onTouchEvent(event)) { 11097 return true; 11098 } 11099 } 11100 11101 if (((viewFlags & CLICKABLE) == CLICKABLE || 11102 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 11103 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 11104 switch (action) { 11105 case MotionEvent.ACTION_UP: 11106 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 11107 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 11108 // take focus if we don't have it already and we should in 11109 // touch mode. 11110 boolean focusTaken = false; 11111 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 11112 focusTaken = requestFocus(); 11113 } 11114 11115 if (prepressed) { 11116 // The button is being released before we actually 11117 // showed it as pressed. Make it show the pressed 11118 // state now (before scheduling the click) to ensure 11119 // the user sees it. 11120 setPressed(true, x, y); 11121 } 11122 11123 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 11124 // This is a tap, so remove the longpress check 11125 removeLongPressCallback(); 11126 11127 // Only perform take click actions if we were in the pressed state 11128 if (!focusTaken) { 11129 // Use a Runnable and post this rather than calling 11130 // performClick directly. This lets other visual state 11131 // of the view update before click actions start. 11132 if (mPerformClick == null) { 11133 mPerformClick = new PerformClick(); 11134 } 11135 if (!post(mPerformClick)) { 11136 performClick(); 11137 } 11138 } 11139 } 11140 11141 if (mUnsetPressedState == null) { 11142 mUnsetPressedState = new UnsetPressedState(); 11143 } 11144 11145 if (prepressed) { 11146 postDelayed(mUnsetPressedState, 11147 ViewConfiguration.getPressedStateDuration()); 11148 } else if (!post(mUnsetPressedState)) { 11149 // If the post failed, unpress right now 11150 mUnsetPressedState.run(); 11151 } 11152 11153 removeTapCallback(); 11154 } 11155 mIgnoreNextUpEvent = false; 11156 break; 11157 11158 case MotionEvent.ACTION_DOWN: 11159 mHasPerformedLongPress = false; 11160 11161 if (performButtonActionOnTouchDown(event)) { 11162 break; 11163 } 11164 11165 // Walk up the hierarchy to determine if we're inside a scrolling container. 11166 boolean isInScrollingContainer = isInScrollingContainer(); 11167 11168 // For views inside a scrolling container, delay the pressed feedback for 11169 // a short period in case this is a scroll. 11170 if (isInScrollingContainer) { 11171 mPrivateFlags |= PFLAG_PREPRESSED; 11172 if (mPendingCheckForTap == null) { 11173 mPendingCheckForTap = new CheckForTap(); 11174 } 11175 mPendingCheckForTap.x = event.getX(); 11176 mPendingCheckForTap.y = event.getY(); 11177 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 11178 } else { 11179 // Not inside a scrolling container, so show the feedback right away 11180 setPressed(true, x, y); 11181 checkForLongClick(0, x, y); 11182 } 11183 break; 11184 11185 case MotionEvent.ACTION_CANCEL: 11186 setPressed(false); 11187 removeTapCallback(); 11188 removeLongPressCallback(); 11189 mInContextButtonPress = false; 11190 mHasPerformedLongPress = false; 11191 mIgnoreNextUpEvent = false; 11192 break; 11193 11194 case MotionEvent.ACTION_MOVE: 11195 drawableHotspotChanged(x, y); 11196 11197 // Be lenient about moving outside of buttons 11198 if (!pointInView(x, y, mTouchSlop)) { 11199 // Outside button 11200 removeTapCallback(); 11201 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 11202 // Remove any future long press/tap checks 11203 removeLongPressCallback(); 11204 11205 setPressed(false); 11206 } 11207 } 11208 break; 11209 } 11210 11211 return true; 11212 } 11213 11214 return false; 11215 } 11216 11217 /** 11218 * @hide 11219 */ 11220 public boolean isInScrollingContainer() { 11221 ViewParent p = getParent(); 11222 while (p != null && p instanceof ViewGroup) { 11223 if (((ViewGroup) p).shouldDelayChildPressedState()) { 11224 return true; 11225 } 11226 p = p.getParent(); 11227 } 11228 return false; 11229 } 11230 11231 /** 11232 * Remove the longpress detection timer. 11233 */ 11234 private void removeLongPressCallback() { 11235 if (mPendingCheckForLongPress != null) { 11236 removeCallbacks(mPendingCheckForLongPress); 11237 } 11238 } 11239 11240 /** 11241 * Remove the pending click action 11242 */ 11243 private void removePerformClickCallback() { 11244 if (mPerformClick != null) { 11245 removeCallbacks(mPerformClick); 11246 } 11247 } 11248 11249 /** 11250 * Remove the prepress detection timer. 11251 */ 11252 private void removeUnsetPressCallback() { 11253 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 11254 setPressed(false); 11255 removeCallbacks(mUnsetPressedState); 11256 } 11257 } 11258 11259 /** 11260 * Remove the tap detection timer. 11261 */ 11262 private void removeTapCallback() { 11263 if (mPendingCheckForTap != null) { 11264 mPrivateFlags &= ~PFLAG_PREPRESSED; 11265 removeCallbacks(mPendingCheckForTap); 11266 } 11267 } 11268 11269 /** 11270 * Cancels a pending long press. Your subclass can use this if you 11271 * want the context menu to come up if the user presses and holds 11272 * at the same place, but you don't want it to come up if they press 11273 * and then move around enough to cause scrolling. 11274 */ 11275 public void cancelLongPress() { 11276 removeLongPressCallback(); 11277 11278 /* 11279 * The prepressed state handled by the tap callback is a display 11280 * construct, but the tap callback will post a long press callback 11281 * less its own timeout. Remove it here. 11282 */ 11283 removeTapCallback(); 11284 } 11285 11286 /** 11287 * Remove the pending callback for sending a 11288 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 11289 */ 11290 private void removeSendViewScrolledAccessibilityEventCallback() { 11291 if (mSendViewScrolledAccessibilityEvent != null) { 11292 removeCallbacks(mSendViewScrolledAccessibilityEvent); 11293 mSendViewScrolledAccessibilityEvent.mIsPending = false; 11294 } 11295 } 11296 11297 /** 11298 * Sets the TouchDelegate for this View. 11299 */ 11300 public void setTouchDelegate(TouchDelegate delegate) { 11301 mTouchDelegate = delegate; 11302 } 11303 11304 /** 11305 * Gets the TouchDelegate for this View. 11306 */ 11307 public TouchDelegate getTouchDelegate() { 11308 return mTouchDelegate; 11309 } 11310 11311 /** 11312 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 11313 * 11314 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 11315 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 11316 * available. This method should only be called for touch events. 11317 * 11318 * <p class="note">This api is not intended for most applications. Buffered dispatch 11319 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 11320 * streams will not improve your input latency. Side effects include: increased latency, 11321 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 11322 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 11323 * you.</p> 11324 */ 11325 public final void requestUnbufferedDispatch(MotionEvent event) { 11326 final int action = event.getAction(); 11327 if (mAttachInfo == null 11328 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 11329 || !event.isTouchEvent()) { 11330 return; 11331 } 11332 mAttachInfo.mUnbufferedDispatchRequested = true; 11333 } 11334 11335 /** 11336 * Set flags controlling behavior of this view. 11337 * 11338 * @param flags Constant indicating the value which should be set 11339 * @param mask Constant indicating the bit range that should be changed 11340 */ 11341 void setFlags(int flags, int mask) { 11342 final boolean accessibilityEnabled = 11343 AccessibilityManager.getInstance(mContext).isEnabled(); 11344 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 11345 11346 int old = mViewFlags; 11347 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 11348 11349 int changed = mViewFlags ^ old; 11350 if (changed == 0) { 11351 return; 11352 } 11353 int privateFlags = mPrivateFlags; 11354 11355 /* Check if the FOCUSABLE bit has changed */ 11356 if (((changed & FOCUSABLE_MASK) != 0) && 11357 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 11358 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 11359 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 11360 /* Give up focus if we are no longer focusable */ 11361 clearFocus(); 11362 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 11363 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 11364 /* 11365 * Tell the view system that we are now available to take focus 11366 * if no one else already has it. 11367 */ 11368 if (mParent != null) mParent.focusableViewAvailable(this); 11369 } 11370 } 11371 11372 final int newVisibility = flags & VISIBILITY_MASK; 11373 if (newVisibility == VISIBLE) { 11374 if ((changed & VISIBILITY_MASK) != 0) { 11375 /* 11376 * If this view is becoming visible, invalidate it in case it changed while 11377 * it was not visible. Marking it drawn ensures that the invalidation will 11378 * go through. 11379 */ 11380 mPrivateFlags |= PFLAG_DRAWN; 11381 invalidate(true); 11382 11383 needGlobalAttributesUpdate(true); 11384 11385 // a view becoming visible is worth notifying the parent 11386 // about in case nothing has focus. even if this specific view 11387 // isn't focusable, it may contain something that is, so let 11388 // the root view try to give this focus if nothing else does. 11389 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 11390 mParent.focusableViewAvailable(this); 11391 } 11392 } 11393 } 11394 11395 /* Check if the GONE bit has changed */ 11396 if ((changed & GONE) != 0) { 11397 needGlobalAttributesUpdate(false); 11398 requestLayout(); 11399 11400 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 11401 if (hasFocus()) clearFocus(); 11402 clearAccessibilityFocus(); 11403 destroyDrawingCache(); 11404 if (mParent instanceof View) { 11405 // GONE views noop invalidation, so invalidate the parent 11406 ((View) mParent).invalidate(true); 11407 } 11408 // Mark the view drawn to ensure that it gets invalidated properly the next 11409 // time it is visible and gets invalidated 11410 mPrivateFlags |= PFLAG_DRAWN; 11411 } 11412 if (mAttachInfo != null) { 11413 mAttachInfo.mViewVisibilityChanged = true; 11414 } 11415 } 11416 11417 /* Check if the VISIBLE bit has changed */ 11418 if ((changed & INVISIBLE) != 0) { 11419 needGlobalAttributesUpdate(false); 11420 /* 11421 * If this view is becoming invisible, set the DRAWN flag so that 11422 * the next invalidate() will not be skipped. 11423 */ 11424 mPrivateFlags |= PFLAG_DRAWN; 11425 11426 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 11427 // root view becoming invisible shouldn't clear focus and accessibility focus 11428 if (getRootView() != this) { 11429 if (hasFocus()) clearFocus(); 11430 clearAccessibilityFocus(); 11431 } 11432 } 11433 if (mAttachInfo != null) { 11434 mAttachInfo.mViewVisibilityChanged = true; 11435 } 11436 } 11437 11438 if ((changed & VISIBILITY_MASK) != 0) { 11439 // If the view is invisible, cleanup its display list to free up resources 11440 if (newVisibility != VISIBLE && mAttachInfo != null) { 11441 cleanupDraw(); 11442 } 11443 11444 if (mParent instanceof ViewGroup) { 11445 ((ViewGroup) mParent).onChildVisibilityChanged(this, 11446 (changed & VISIBILITY_MASK), newVisibility); 11447 ((View) mParent).invalidate(true); 11448 } else if (mParent != null) { 11449 mParent.invalidateChild(this, null); 11450 } 11451 11452 if (mAttachInfo != null) { 11453 dispatchVisibilityChanged(this, newVisibility); 11454 11455 // Aggregated visibility changes are dispatched to attached views 11456 // in visible windows where the parent is currently shown/drawn 11457 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 11458 // discounting clipping or overlapping. This makes it a good place 11459 // to change animation states. 11460 if (mParent != null && getWindowVisibility() == VISIBLE && 11461 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 11462 dispatchVisibilityAggregated(newVisibility == VISIBLE); 11463 } 11464 notifySubtreeAccessibilityStateChangedIfNeeded(); 11465 } 11466 } 11467 11468 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 11469 destroyDrawingCache(); 11470 } 11471 11472 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 11473 destroyDrawingCache(); 11474 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11475 invalidateParentCaches(); 11476 } 11477 11478 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 11479 destroyDrawingCache(); 11480 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11481 } 11482 11483 if ((changed & DRAW_MASK) != 0) { 11484 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 11485 if (mBackground != null 11486 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 11487 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11488 } else { 11489 mPrivateFlags |= PFLAG_SKIP_DRAW; 11490 } 11491 } else { 11492 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11493 } 11494 requestLayout(); 11495 invalidate(true); 11496 } 11497 11498 if ((changed & KEEP_SCREEN_ON) != 0) { 11499 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11500 mParent.recomputeViewAttributes(this); 11501 } 11502 } 11503 11504 if (accessibilityEnabled) { 11505 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 11506 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 11507 || (changed & CONTEXT_CLICKABLE) != 0) { 11508 if (oldIncludeForAccessibility != includeForAccessibility()) { 11509 notifySubtreeAccessibilityStateChangedIfNeeded(); 11510 } else { 11511 notifyViewAccessibilityStateChangedIfNeeded( 11512 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11513 } 11514 } else if ((changed & ENABLED_MASK) != 0) { 11515 notifyViewAccessibilityStateChangedIfNeeded( 11516 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11517 } 11518 } 11519 } 11520 11521 /** 11522 * Change the view's z order in the tree, so it's on top of other sibling 11523 * views. This ordering change may affect layout, if the parent container 11524 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 11525 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 11526 * method should be followed by calls to {@link #requestLayout()} and 11527 * {@link View#invalidate()} on the view's parent to force the parent to redraw 11528 * with the new child ordering. 11529 * 11530 * @see ViewGroup#bringChildToFront(View) 11531 */ 11532 public void bringToFront() { 11533 if (mParent != null) { 11534 mParent.bringChildToFront(this); 11535 } 11536 } 11537 11538 /** 11539 * This is called in response to an internal scroll in this view (i.e., the 11540 * view scrolled its own contents). This is typically as a result of 11541 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 11542 * called. 11543 * 11544 * @param l Current horizontal scroll origin. 11545 * @param t Current vertical scroll origin. 11546 * @param oldl Previous horizontal scroll origin. 11547 * @param oldt Previous vertical scroll origin. 11548 */ 11549 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 11550 notifySubtreeAccessibilityStateChangedIfNeeded(); 11551 11552 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 11553 postSendViewScrolledAccessibilityEventCallback(); 11554 } 11555 11556 mBackgroundSizeChanged = true; 11557 if (mForegroundInfo != null) { 11558 mForegroundInfo.mBoundsChanged = true; 11559 } 11560 11561 final AttachInfo ai = mAttachInfo; 11562 if (ai != null) { 11563 ai.mViewScrollChanged = true; 11564 } 11565 11566 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 11567 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 11568 } 11569 } 11570 11571 /** 11572 * Interface definition for a callback to be invoked when the scroll 11573 * X or Y positions of a view change. 11574 * <p> 11575 * <b>Note:</b> Some views handle scrolling independently from View and may 11576 * have their own separate listeners for scroll-type events. For example, 11577 * {@link android.widget.ListView ListView} allows clients to register an 11578 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 11579 * to listen for changes in list scroll position. 11580 * 11581 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 11582 */ 11583 public interface OnScrollChangeListener { 11584 /** 11585 * Called when the scroll position of a view changes. 11586 * 11587 * @param v The view whose scroll position has changed. 11588 * @param scrollX Current horizontal scroll origin. 11589 * @param scrollY Current vertical scroll origin. 11590 * @param oldScrollX Previous horizontal scroll origin. 11591 * @param oldScrollY Previous vertical scroll origin. 11592 */ 11593 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 11594 } 11595 11596 /** 11597 * Interface definition for a callback to be invoked when the layout bounds of a view 11598 * changes due to layout processing. 11599 */ 11600 public interface OnLayoutChangeListener { 11601 /** 11602 * Called when the layout bounds of a view changes due to layout processing. 11603 * 11604 * @param v The view whose bounds have changed. 11605 * @param left The new value of the view's left property. 11606 * @param top The new value of the view's top property. 11607 * @param right The new value of the view's right property. 11608 * @param bottom The new value of the view's bottom property. 11609 * @param oldLeft The previous value of the view's left property. 11610 * @param oldTop The previous value of the view's top property. 11611 * @param oldRight The previous value of the view's right property. 11612 * @param oldBottom The previous value of the view's bottom property. 11613 */ 11614 void onLayoutChange(View v, int left, int top, int right, int bottom, 11615 int oldLeft, int oldTop, int oldRight, int oldBottom); 11616 } 11617 11618 /** 11619 * This is called during layout when the size of this view has changed. If 11620 * you were just added to the view hierarchy, you're called with the old 11621 * values of 0. 11622 * 11623 * @param w Current width of this view. 11624 * @param h Current height of this view. 11625 * @param oldw Old width of this view. 11626 * @param oldh Old height of this view. 11627 */ 11628 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 11629 } 11630 11631 /** 11632 * Called by draw to draw the child views. This may be overridden 11633 * by derived classes to gain control just before its children are drawn 11634 * (but after its own view has been drawn). 11635 * @param canvas the canvas on which to draw the view 11636 */ 11637 protected void dispatchDraw(Canvas canvas) { 11638 11639 } 11640 11641 /** 11642 * Gets the parent of this view. Note that the parent is a 11643 * ViewParent and not necessarily a View. 11644 * 11645 * @return Parent of this view. 11646 */ 11647 public final ViewParent getParent() { 11648 return mParent; 11649 } 11650 11651 /** 11652 * Set the horizontal scrolled position of your view. This will cause a call to 11653 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11654 * invalidated. 11655 * @param value the x position to scroll to 11656 */ 11657 public void setScrollX(int value) { 11658 scrollTo(value, mScrollY); 11659 } 11660 11661 /** 11662 * Set the vertical scrolled position of your view. This will cause a call to 11663 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11664 * invalidated. 11665 * @param value the y position to scroll to 11666 */ 11667 public void setScrollY(int value) { 11668 scrollTo(mScrollX, value); 11669 } 11670 11671 /** 11672 * Return the scrolled left position of this view. This is the left edge of 11673 * the displayed part of your view. You do not need to draw any pixels 11674 * farther left, since those are outside of the frame of your view on 11675 * screen. 11676 * 11677 * @return The left edge of the displayed part of your view, in pixels. 11678 */ 11679 public final int getScrollX() { 11680 return mScrollX; 11681 } 11682 11683 /** 11684 * Return the scrolled top position of this view. This is the top edge of 11685 * the displayed part of your view. You do not need to draw any pixels above 11686 * it, since those are outside of the frame of your view on screen. 11687 * 11688 * @return The top edge of the displayed part of your view, in pixels. 11689 */ 11690 public final int getScrollY() { 11691 return mScrollY; 11692 } 11693 11694 /** 11695 * Return the width of the your view. 11696 * 11697 * @return The width of your view, in pixels. 11698 */ 11699 @ViewDebug.ExportedProperty(category = "layout") 11700 public final int getWidth() { 11701 return mRight - mLeft; 11702 } 11703 11704 /** 11705 * Return the height of your view. 11706 * 11707 * @return The height of your view, in pixels. 11708 */ 11709 @ViewDebug.ExportedProperty(category = "layout") 11710 public final int getHeight() { 11711 return mBottom - mTop; 11712 } 11713 11714 /** 11715 * Return the visible drawing bounds of your view. Fills in the output 11716 * rectangle with the values from getScrollX(), getScrollY(), 11717 * getWidth(), and getHeight(). These bounds do not account for any 11718 * transformation properties currently set on the view, such as 11719 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 11720 * 11721 * @param outRect The (scrolled) drawing bounds of the view. 11722 */ 11723 public void getDrawingRect(Rect outRect) { 11724 outRect.left = mScrollX; 11725 outRect.top = mScrollY; 11726 outRect.right = mScrollX + (mRight - mLeft); 11727 outRect.bottom = mScrollY + (mBottom - mTop); 11728 } 11729 11730 /** 11731 * Like {@link #getMeasuredWidthAndState()}, but only returns the 11732 * raw width component (that is the result is masked by 11733 * {@link #MEASURED_SIZE_MASK}). 11734 * 11735 * @return The raw measured width of this view. 11736 */ 11737 public final int getMeasuredWidth() { 11738 return mMeasuredWidth & MEASURED_SIZE_MASK; 11739 } 11740 11741 /** 11742 * Return the full width measurement information for this view as computed 11743 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11744 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11745 * This should be used during measurement and layout calculations only. Use 11746 * {@link #getWidth()} to see how wide a view is after layout. 11747 * 11748 * @return The measured width of this view as a bit mask. 11749 */ 11750 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11751 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11752 name = "MEASURED_STATE_TOO_SMALL"), 11753 }) 11754 public final int getMeasuredWidthAndState() { 11755 return mMeasuredWidth; 11756 } 11757 11758 /** 11759 * Like {@link #getMeasuredHeightAndState()}, but only returns the 11760 * raw height component (that is the result is masked by 11761 * {@link #MEASURED_SIZE_MASK}). 11762 * 11763 * @return The raw measured height of this view. 11764 */ 11765 public final int getMeasuredHeight() { 11766 return mMeasuredHeight & MEASURED_SIZE_MASK; 11767 } 11768 11769 /** 11770 * Return the full height measurement information for this view as computed 11771 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11772 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11773 * This should be used during measurement and layout calculations only. Use 11774 * {@link #getHeight()} to see how wide a view is after layout. 11775 * 11776 * @return The measured height of this view as a bit mask. 11777 */ 11778 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11779 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11780 name = "MEASURED_STATE_TOO_SMALL"), 11781 }) 11782 public final int getMeasuredHeightAndState() { 11783 return mMeasuredHeight; 11784 } 11785 11786 /** 11787 * Return only the state bits of {@link #getMeasuredWidthAndState()} 11788 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 11789 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 11790 * and the height component is at the shifted bits 11791 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 11792 */ 11793 public final int getMeasuredState() { 11794 return (mMeasuredWidth&MEASURED_STATE_MASK) 11795 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 11796 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 11797 } 11798 11799 /** 11800 * The transform matrix of this view, which is calculated based on the current 11801 * rotation, scale, and pivot properties. 11802 * 11803 * @see #getRotation() 11804 * @see #getScaleX() 11805 * @see #getScaleY() 11806 * @see #getPivotX() 11807 * @see #getPivotY() 11808 * @return The current transform matrix for the view 11809 */ 11810 public Matrix getMatrix() { 11811 ensureTransformationInfo(); 11812 final Matrix matrix = mTransformationInfo.mMatrix; 11813 mRenderNode.getMatrix(matrix); 11814 return matrix; 11815 } 11816 11817 /** 11818 * Returns true if the transform matrix is the identity matrix. 11819 * Recomputes the matrix if necessary. 11820 * 11821 * @return True if the transform matrix is the identity matrix, false otherwise. 11822 */ 11823 final boolean hasIdentityMatrix() { 11824 return mRenderNode.hasIdentityMatrix(); 11825 } 11826 11827 void ensureTransformationInfo() { 11828 if (mTransformationInfo == null) { 11829 mTransformationInfo = new TransformationInfo(); 11830 } 11831 } 11832 11833 /** 11834 * Utility method to retrieve the inverse of the current mMatrix property. 11835 * We cache the matrix to avoid recalculating it when transform properties 11836 * have not changed. 11837 * 11838 * @return The inverse of the current matrix of this view. 11839 * @hide 11840 */ 11841 public final Matrix getInverseMatrix() { 11842 ensureTransformationInfo(); 11843 if (mTransformationInfo.mInverseMatrix == null) { 11844 mTransformationInfo.mInverseMatrix = new Matrix(); 11845 } 11846 final Matrix matrix = mTransformationInfo.mInverseMatrix; 11847 mRenderNode.getInverseMatrix(matrix); 11848 return matrix; 11849 } 11850 11851 /** 11852 * Gets the distance along the Z axis from the camera to this view. 11853 * 11854 * @see #setCameraDistance(float) 11855 * 11856 * @return The distance along the Z axis. 11857 */ 11858 public float getCameraDistance() { 11859 final float dpi = mResources.getDisplayMetrics().densityDpi; 11860 return -(mRenderNode.getCameraDistance() * dpi); 11861 } 11862 11863 /** 11864 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 11865 * views are drawn) from the camera to this view. The camera's distance 11866 * affects 3D transformations, for instance rotations around the X and Y 11867 * axis. If the rotationX or rotationY properties are changed and this view is 11868 * large (more than half the size of the screen), it is recommended to always 11869 * use a camera distance that's greater than the height (X axis rotation) or 11870 * the width (Y axis rotation) of this view.</p> 11871 * 11872 * <p>The distance of the camera from the view plane can have an affect on the 11873 * perspective distortion of the view when it is rotated around the x or y axis. 11874 * For example, a large distance will result in a large viewing angle, and there 11875 * will not be much perspective distortion of the view as it rotates. A short 11876 * distance may cause much more perspective distortion upon rotation, and can 11877 * also result in some drawing artifacts if the rotated view ends up partially 11878 * behind the camera (which is why the recommendation is to use a distance at 11879 * least as far as the size of the view, if the view is to be rotated.)</p> 11880 * 11881 * <p>The distance is expressed in "depth pixels." The default distance depends 11882 * on the screen density. For instance, on a medium density display, the 11883 * default distance is 1280. On a high density display, the default distance 11884 * is 1920.</p> 11885 * 11886 * <p>If you want to specify a distance that leads to visually consistent 11887 * results across various densities, use the following formula:</p> 11888 * <pre> 11889 * float scale = context.getResources().getDisplayMetrics().density; 11890 * view.setCameraDistance(distance * scale); 11891 * </pre> 11892 * 11893 * <p>The density scale factor of a high density display is 1.5, 11894 * and 1920 = 1280 * 1.5.</p> 11895 * 11896 * @param distance The distance in "depth pixels", if negative the opposite 11897 * value is used 11898 * 11899 * @see #setRotationX(float) 11900 * @see #setRotationY(float) 11901 */ 11902 public void setCameraDistance(float distance) { 11903 final float dpi = mResources.getDisplayMetrics().densityDpi; 11904 11905 invalidateViewProperty(true, false); 11906 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11907 invalidateViewProperty(false, false); 11908 11909 invalidateParentIfNeededAndWasQuickRejected(); 11910 } 11911 11912 /** 11913 * The degrees that the view is rotated around the pivot point. 11914 * 11915 * @see #setRotation(float) 11916 * @see #getPivotX() 11917 * @see #getPivotY() 11918 * 11919 * @return The degrees of rotation. 11920 */ 11921 @ViewDebug.ExportedProperty(category = "drawing") 11922 public float getRotation() { 11923 return mRenderNode.getRotation(); 11924 } 11925 11926 /** 11927 * Sets the degrees that the view is rotated around the pivot point. Increasing values 11928 * result in clockwise rotation. 11929 * 11930 * @param rotation The degrees of rotation. 11931 * 11932 * @see #getRotation() 11933 * @see #getPivotX() 11934 * @see #getPivotY() 11935 * @see #setRotationX(float) 11936 * @see #setRotationY(float) 11937 * 11938 * @attr ref android.R.styleable#View_rotation 11939 */ 11940 public void setRotation(float rotation) { 11941 if (rotation != getRotation()) { 11942 // Double-invalidation is necessary to capture view's old and new areas 11943 invalidateViewProperty(true, false); 11944 mRenderNode.setRotation(rotation); 11945 invalidateViewProperty(false, true); 11946 11947 invalidateParentIfNeededAndWasQuickRejected(); 11948 notifySubtreeAccessibilityStateChangedIfNeeded(); 11949 } 11950 } 11951 11952 /** 11953 * The degrees that the view is rotated around the vertical axis through the pivot point. 11954 * 11955 * @see #getPivotX() 11956 * @see #getPivotY() 11957 * @see #setRotationY(float) 11958 * 11959 * @return The degrees of Y rotation. 11960 */ 11961 @ViewDebug.ExportedProperty(category = "drawing") 11962 public float getRotationY() { 11963 return mRenderNode.getRotationY(); 11964 } 11965 11966 /** 11967 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 11968 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 11969 * down the y axis. 11970 * 11971 * When rotating large views, it is recommended to adjust the camera distance 11972 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11973 * 11974 * @param rotationY The degrees of Y rotation. 11975 * 11976 * @see #getRotationY() 11977 * @see #getPivotX() 11978 * @see #getPivotY() 11979 * @see #setRotation(float) 11980 * @see #setRotationX(float) 11981 * @see #setCameraDistance(float) 11982 * 11983 * @attr ref android.R.styleable#View_rotationY 11984 */ 11985 public void setRotationY(float rotationY) { 11986 if (rotationY != getRotationY()) { 11987 invalidateViewProperty(true, false); 11988 mRenderNode.setRotationY(rotationY); 11989 invalidateViewProperty(false, true); 11990 11991 invalidateParentIfNeededAndWasQuickRejected(); 11992 notifySubtreeAccessibilityStateChangedIfNeeded(); 11993 } 11994 } 11995 11996 /** 11997 * The degrees that the view is rotated around the horizontal axis through the pivot point. 11998 * 11999 * @see #getPivotX() 12000 * @see #getPivotY() 12001 * @see #setRotationX(float) 12002 * 12003 * @return The degrees of X rotation. 12004 */ 12005 @ViewDebug.ExportedProperty(category = "drawing") 12006 public float getRotationX() { 12007 return mRenderNode.getRotationX(); 12008 } 12009 12010 /** 12011 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 12012 * Increasing values result in clockwise rotation from the viewpoint of looking down the 12013 * x axis. 12014 * 12015 * When rotating large views, it is recommended to adjust the camera distance 12016 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12017 * 12018 * @param rotationX The degrees of X rotation. 12019 * 12020 * @see #getRotationX() 12021 * @see #getPivotX() 12022 * @see #getPivotY() 12023 * @see #setRotation(float) 12024 * @see #setRotationY(float) 12025 * @see #setCameraDistance(float) 12026 * 12027 * @attr ref android.R.styleable#View_rotationX 12028 */ 12029 public void setRotationX(float rotationX) { 12030 if (rotationX != getRotationX()) { 12031 invalidateViewProperty(true, false); 12032 mRenderNode.setRotationX(rotationX); 12033 invalidateViewProperty(false, true); 12034 12035 invalidateParentIfNeededAndWasQuickRejected(); 12036 notifySubtreeAccessibilityStateChangedIfNeeded(); 12037 } 12038 } 12039 12040 /** 12041 * The amount that the view is scaled in x around the pivot point, as a proportion of 12042 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 12043 * 12044 * <p>By default, this is 1.0f. 12045 * 12046 * @see #getPivotX() 12047 * @see #getPivotY() 12048 * @return The scaling factor. 12049 */ 12050 @ViewDebug.ExportedProperty(category = "drawing") 12051 public float getScaleX() { 12052 return mRenderNode.getScaleX(); 12053 } 12054 12055 /** 12056 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 12057 * the view's unscaled width. A value of 1 means that no scaling is applied. 12058 * 12059 * @param scaleX The scaling factor. 12060 * @see #getPivotX() 12061 * @see #getPivotY() 12062 * 12063 * @attr ref android.R.styleable#View_scaleX 12064 */ 12065 public void setScaleX(float scaleX) { 12066 if (scaleX != getScaleX()) { 12067 invalidateViewProperty(true, false); 12068 mRenderNode.setScaleX(scaleX); 12069 invalidateViewProperty(false, true); 12070 12071 invalidateParentIfNeededAndWasQuickRejected(); 12072 notifySubtreeAccessibilityStateChangedIfNeeded(); 12073 } 12074 } 12075 12076 /** 12077 * The amount that the view is scaled in y around the pivot point, as a proportion of 12078 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 12079 * 12080 * <p>By default, this is 1.0f. 12081 * 12082 * @see #getPivotX() 12083 * @see #getPivotY() 12084 * @return The scaling factor. 12085 */ 12086 @ViewDebug.ExportedProperty(category = "drawing") 12087 public float getScaleY() { 12088 return mRenderNode.getScaleY(); 12089 } 12090 12091 /** 12092 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 12093 * the view's unscaled width. A value of 1 means that no scaling is applied. 12094 * 12095 * @param scaleY The scaling factor. 12096 * @see #getPivotX() 12097 * @see #getPivotY() 12098 * 12099 * @attr ref android.R.styleable#View_scaleY 12100 */ 12101 public void setScaleY(float scaleY) { 12102 if (scaleY != getScaleY()) { 12103 invalidateViewProperty(true, false); 12104 mRenderNode.setScaleY(scaleY); 12105 invalidateViewProperty(false, true); 12106 12107 invalidateParentIfNeededAndWasQuickRejected(); 12108 notifySubtreeAccessibilityStateChangedIfNeeded(); 12109 } 12110 } 12111 12112 /** 12113 * The x location of the point around which the view is {@link #setRotation(float) rotated} 12114 * and {@link #setScaleX(float) scaled}. 12115 * 12116 * @see #getRotation() 12117 * @see #getScaleX() 12118 * @see #getScaleY() 12119 * @see #getPivotY() 12120 * @return The x location of the pivot point. 12121 * 12122 * @attr ref android.R.styleable#View_transformPivotX 12123 */ 12124 @ViewDebug.ExportedProperty(category = "drawing") 12125 public float getPivotX() { 12126 return mRenderNode.getPivotX(); 12127 } 12128 12129 /** 12130 * Sets the x location of the point around which the view is 12131 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 12132 * By default, the pivot point is centered on the object. 12133 * Setting this property disables this behavior and causes the view to use only the 12134 * explicitly set pivotX and pivotY values. 12135 * 12136 * @param pivotX The x location of the pivot point. 12137 * @see #getRotation() 12138 * @see #getScaleX() 12139 * @see #getScaleY() 12140 * @see #getPivotY() 12141 * 12142 * @attr ref android.R.styleable#View_transformPivotX 12143 */ 12144 public void setPivotX(float pivotX) { 12145 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 12146 invalidateViewProperty(true, false); 12147 mRenderNode.setPivotX(pivotX); 12148 invalidateViewProperty(false, true); 12149 12150 invalidateParentIfNeededAndWasQuickRejected(); 12151 } 12152 } 12153 12154 /** 12155 * The y location of the point around which the view is {@link #setRotation(float) rotated} 12156 * and {@link #setScaleY(float) scaled}. 12157 * 12158 * @see #getRotation() 12159 * @see #getScaleX() 12160 * @see #getScaleY() 12161 * @see #getPivotY() 12162 * @return The y location of the pivot point. 12163 * 12164 * @attr ref android.R.styleable#View_transformPivotY 12165 */ 12166 @ViewDebug.ExportedProperty(category = "drawing") 12167 public float getPivotY() { 12168 return mRenderNode.getPivotY(); 12169 } 12170 12171 /** 12172 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 12173 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 12174 * Setting this property disables this behavior and causes the view to use only the 12175 * explicitly set pivotX and pivotY values. 12176 * 12177 * @param pivotY The y location of the pivot point. 12178 * @see #getRotation() 12179 * @see #getScaleX() 12180 * @see #getScaleY() 12181 * @see #getPivotY() 12182 * 12183 * @attr ref android.R.styleable#View_transformPivotY 12184 */ 12185 public void setPivotY(float pivotY) { 12186 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 12187 invalidateViewProperty(true, false); 12188 mRenderNode.setPivotY(pivotY); 12189 invalidateViewProperty(false, true); 12190 12191 invalidateParentIfNeededAndWasQuickRejected(); 12192 } 12193 } 12194 12195 /** 12196 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 12197 * completely transparent and 1 means the view is completely opaque. 12198 * 12199 * <p>By default this is 1.0f. 12200 * @return The opacity of the view. 12201 */ 12202 @ViewDebug.ExportedProperty(category = "drawing") 12203 public float getAlpha() { 12204 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 12205 } 12206 12207 /** 12208 * Sets the behavior for overlapping rendering for this view (see {@link 12209 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 12210 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 12211 * providing the value which is then used internally. That is, when {@link 12212 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 12213 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 12214 * instead. 12215 * 12216 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 12217 * instead of that returned by {@link #hasOverlappingRendering()}. 12218 * 12219 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 12220 */ 12221 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 12222 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 12223 if (hasOverlappingRendering) { 12224 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12225 } else { 12226 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12227 } 12228 } 12229 12230 /** 12231 * Returns the value for overlapping rendering that is used internally. This is either 12232 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 12233 * the return value of {@link #hasOverlappingRendering()}, otherwise. 12234 * 12235 * @return The value for overlapping rendering being used internally. 12236 */ 12237 public final boolean getHasOverlappingRendering() { 12238 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 12239 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 12240 hasOverlappingRendering(); 12241 } 12242 12243 /** 12244 * Returns whether this View has content which overlaps. 12245 * 12246 * <p>This function, intended to be overridden by specific View types, is an optimization when 12247 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 12248 * an offscreen buffer and then composited into place, which can be expensive. If the view has 12249 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 12250 * directly. An example of overlapping rendering is a TextView with a background image, such as 12251 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 12252 * ImageView with only the foreground image. The default implementation returns true; subclasses 12253 * should override if they have cases which can be optimized.</p> 12254 * 12255 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 12256 * necessitates that a View return true if it uses the methods internally without passing the 12257 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 12258 * 12259 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 12260 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 12261 * 12262 * @return true if the content in this view might overlap, false otherwise. 12263 */ 12264 @ViewDebug.ExportedProperty(category = "drawing") 12265 public boolean hasOverlappingRendering() { 12266 return true; 12267 } 12268 12269 /** 12270 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 12271 * completely transparent and 1 means the view is completely opaque. 12272 * 12273 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 12274 * can have significant performance implications, especially for large views. It is best to use 12275 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 12276 * 12277 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 12278 * strongly recommended for performance reasons to either override 12279 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 12280 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 12281 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 12282 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 12283 * of rendering cost, even for simple or small views. Starting with 12284 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 12285 * applied to the view at the rendering level.</p> 12286 * 12287 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 12288 * responsible for applying the opacity itself.</p> 12289 * 12290 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 12291 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 12292 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 12293 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 12294 * 12295 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 12296 * value will clip a View to its bounds, unless the View returns <code>false</code> from 12297 * {@link #hasOverlappingRendering}.</p> 12298 * 12299 * @param alpha The opacity of the view. 12300 * 12301 * @see #hasOverlappingRendering() 12302 * @see #setLayerType(int, android.graphics.Paint) 12303 * 12304 * @attr ref android.R.styleable#View_alpha 12305 */ 12306 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 12307 ensureTransformationInfo(); 12308 if (mTransformationInfo.mAlpha != alpha) { 12309 mTransformationInfo.mAlpha = alpha; 12310 if (onSetAlpha((int) (alpha * 255))) { 12311 mPrivateFlags |= PFLAG_ALPHA_SET; 12312 // subclass is handling alpha - don't optimize rendering cache invalidation 12313 invalidateParentCaches(); 12314 invalidate(true); 12315 } else { 12316 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12317 invalidateViewProperty(true, false); 12318 mRenderNode.setAlpha(getFinalAlpha()); 12319 notifyViewAccessibilityStateChangedIfNeeded( 12320 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 12321 } 12322 } 12323 } 12324 12325 /** 12326 * Faster version of setAlpha() which performs the same steps except there are 12327 * no calls to invalidate(). The caller of this function should perform proper invalidation 12328 * on the parent and this object. The return value indicates whether the subclass handles 12329 * alpha (the return value for onSetAlpha()). 12330 * 12331 * @param alpha The new value for the alpha property 12332 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 12333 * the new value for the alpha property is different from the old value 12334 */ 12335 boolean setAlphaNoInvalidation(float alpha) { 12336 ensureTransformationInfo(); 12337 if (mTransformationInfo.mAlpha != alpha) { 12338 mTransformationInfo.mAlpha = alpha; 12339 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 12340 if (subclassHandlesAlpha) { 12341 mPrivateFlags |= PFLAG_ALPHA_SET; 12342 return true; 12343 } else { 12344 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12345 mRenderNode.setAlpha(getFinalAlpha()); 12346 } 12347 } 12348 return false; 12349 } 12350 12351 /** 12352 * This property is hidden and intended only for use by the Fade transition, which 12353 * animates it to produce a visual translucency that does not side-effect (or get 12354 * affected by) the real alpha property. This value is composited with the other 12355 * alpha value (and the AlphaAnimation value, when that is present) to produce 12356 * a final visual translucency result, which is what is passed into the DisplayList. 12357 * 12358 * @hide 12359 */ 12360 public void setTransitionAlpha(float alpha) { 12361 ensureTransformationInfo(); 12362 if (mTransformationInfo.mTransitionAlpha != alpha) { 12363 mTransformationInfo.mTransitionAlpha = alpha; 12364 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12365 invalidateViewProperty(true, false); 12366 mRenderNode.setAlpha(getFinalAlpha()); 12367 } 12368 } 12369 12370 /** 12371 * Calculates the visual alpha of this view, which is a combination of the actual 12372 * alpha value and the transitionAlpha value (if set). 12373 */ 12374 private float getFinalAlpha() { 12375 if (mTransformationInfo != null) { 12376 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 12377 } 12378 return 1; 12379 } 12380 12381 /** 12382 * This property is hidden and intended only for use by the Fade transition, which 12383 * animates it to produce a visual translucency that does not side-effect (or get 12384 * affected by) the real alpha property. This value is composited with the other 12385 * alpha value (and the AlphaAnimation value, when that is present) to produce 12386 * a final visual translucency result, which is what is passed into the DisplayList. 12387 * 12388 * @hide 12389 */ 12390 @ViewDebug.ExportedProperty(category = "drawing") 12391 public float getTransitionAlpha() { 12392 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 12393 } 12394 12395 /** 12396 * Top position of this view relative to its parent. 12397 * 12398 * @return The top of this view, in pixels. 12399 */ 12400 @ViewDebug.CapturedViewProperty 12401 public final int getTop() { 12402 return mTop; 12403 } 12404 12405 /** 12406 * Sets the top position of this view relative to its parent. This method is meant to be called 12407 * by the layout system and should not generally be called otherwise, because the property 12408 * may be changed at any time by the layout. 12409 * 12410 * @param top The top of this view, in pixels. 12411 */ 12412 public final void setTop(int top) { 12413 if (top != mTop) { 12414 final boolean matrixIsIdentity = hasIdentityMatrix(); 12415 if (matrixIsIdentity) { 12416 if (mAttachInfo != null) { 12417 int minTop; 12418 int yLoc; 12419 if (top < mTop) { 12420 minTop = top; 12421 yLoc = top - mTop; 12422 } else { 12423 minTop = mTop; 12424 yLoc = 0; 12425 } 12426 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 12427 } 12428 } else { 12429 // Double-invalidation is necessary to capture view's old and new areas 12430 invalidate(true); 12431 } 12432 12433 int width = mRight - mLeft; 12434 int oldHeight = mBottom - mTop; 12435 12436 mTop = top; 12437 mRenderNode.setTop(mTop); 12438 12439 sizeChange(width, mBottom - mTop, width, oldHeight); 12440 12441 if (!matrixIsIdentity) { 12442 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12443 invalidate(true); 12444 } 12445 mBackgroundSizeChanged = true; 12446 if (mForegroundInfo != null) { 12447 mForegroundInfo.mBoundsChanged = true; 12448 } 12449 invalidateParentIfNeeded(); 12450 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12451 // View was rejected last time it was drawn by its parent; this may have changed 12452 invalidateParentIfNeeded(); 12453 } 12454 } 12455 } 12456 12457 /** 12458 * Bottom position of this view relative to its parent. 12459 * 12460 * @return The bottom of this view, in pixels. 12461 */ 12462 @ViewDebug.CapturedViewProperty 12463 public final int getBottom() { 12464 return mBottom; 12465 } 12466 12467 /** 12468 * True if this view has changed since the last time being drawn. 12469 * 12470 * @return The dirty state of this view. 12471 */ 12472 public boolean isDirty() { 12473 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 12474 } 12475 12476 /** 12477 * Sets the bottom position of this view relative to its parent. This method is meant to be 12478 * called by the layout system and should not generally be called otherwise, because the 12479 * property may be changed at any time by the layout. 12480 * 12481 * @param bottom The bottom of this view, in pixels. 12482 */ 12483 public final void setBottom(int bottom) { 12484 if (bottom != mBottom) { 12485 final boolean matrixIsIdentity = hasIdentityMatrix(); 12486 if (matrixIsIdentity) { 12487 if (mAttachInfo != null) { 12488 int maxBottom; 12489 if (bottom < mBottom) { 12490 maxBottom = mBottom; 12491 } else { 12492 maxBottom = bottom; 12493 } 12494 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 12495 } 12496 } else { 12497 // Double-invalidation is necessary to capture view's old and new areas 12498 invalidate(true); 12499 } 12500 12501 int width = mRight - mLeft; 12502 int oldHeight = mBottom - mTop; 12503 12504 mBottom = bottom; 12505 mRenderNode.setBottom(mBottom); 12506 12507 sizeChange(width, mBottom - mTop, width, oldHeight); 12508 12509 if (!matrixIsIdentity) { 12510 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12511 invalidate(true); 12512 } 12513 mBackgroundSizeChanged = true; 12514 if (mForegroundInfo != null) { 12515 mForegroundInfo.mBoundsChanged = true; 12516 } 12517 invalidateParentIfNeeded(); 12518 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12519 // View was rejected last time it was drawn by its parent; this may have changed 12520 invalidateParentIfNeeded(); 12521 } 12522 } 12523 } 12524 12525 /** 12526 * Left position of this view relative to its parent. 12527 * 12528 * @return The left edge of this view, in pixels. 12529 */ 12530 @ViewDebug.CapturedViewProperty 12531 public final int getLeft() { 12532 return mLeft; 12533 } 12534 12535 /** 12536 * Sets the left position of this view relative to its parent. This method is meant to be called 12537 * by the layout system and should not generally be called otherwise, because the property 12538 * may be changed at any time by the layout. 12539 * 12540 * @param left The left of this view, in pixels. 12541 */ 12542 public final void setLeft(int left) { 12543 if (left != mLeft) { 12544 final boolean matrixIsIdentity = hasIdentityMatrix(); 12545 if (matrixIsIdentity) { 12546 if (mAttachInfo != null) { 12547 int minLeft; 12548 int xLoc; 12549 if (left < mLeft) { 12550 minLeft = left; 12551 xLoc = left - mLeft; 12552 } else { 12553 minLeft = mLeft; 12554 xLoc = 0; 12555 } 12556 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 12557 } 12558 } else { 12559 // Double-invalidation is necessary to capture view's old and new areas 12560 invalidate(true); 12561 } 12562 12563 int oldWidth = mRight - mLeft; 12564 int height = mBottom - mTop; 12565 12566 mLeft = left; 12567 mRenderNode.setLeft(left); 12568 12569 sizeChange(mRight - mLeft, height, oldWidth, height); 12570 12571 if (!matrixIsIdentity) { 12572 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12573 invalidate(true); 12574 } 12575 mBackgroundSizeChanged = true; 12576 if (mForegroundInfo != null) { 12577 mForegroundInfo.mBoundsChanged = true; 12578 } 12579 invalidateParentIfNeeded(); 12580 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12581 // View was rejected last time it was drawn by its parent; this may have changed 12582 invalidateParentIfNeeded(); 12583 } 12584 } 12585 } 12586 12587 /** 12588 * Right position of this view relative to its parent. 12589 * 12590 * @return The right edge of this view, in pixels. 12591 */ 12592 @ViewDebug.CapturedViewProperty 12593 public final int getRight() { 12594 return mRight; 12595 } 12596 12597 /** 12598 * Sets the right position of this view relative to its parent. This method is meant to be called 12599 * by the layout system and should not generally be called otherwise, because the property 12600 * may be changed at any time by the layout. 12601 * 12602 * @param right The right of this view, in pixels. 12603 */ 12604 public final void setRight(int right) { 12605 if (right != mRight) { 12606 final boolean matrixIsIdentity = hasIdentityMatrix(); 12607 if (matrixIsIdentity) { 12608 if (mAttachInfo != null) { 12609 int maxRight; 12610 if (right < mRight) { 12611 maxRight = mRight; 12612 } else { 12613 maxRight = right; 12614 } 12615 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 12616 } 12617 } else { 12618 // Double-invalidation is necessary to capture view's old and new areas 12619 invalidate(true); 12620 } 12621 12622 int oldWidth = mRight - mLeft; 12623 int height = mBottom - mTop; 12624 12625 mRight = right; 12626 mRenderNode.setRight(mRight); 12627 12628 sizeChange(mRight - mLeft, height, oldWidth, height); 12629 12630 if (!matrixIsIdentity) { 12631 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12632 invalidate(true); 12633 } 12634 mBackgroundSizeChanged = true; 12635 if (mForegroundInfo != null) { 12636 mForegroundInfo.mBoundsChanged = true; 12637 } 12638 invalidateParentIfNeeded(); 12639 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12640 // View was rejected last time it was drawn by its parent; this may have changed 12641 invalidateParentIfNeeded(); 12642 } 12643 } 12644 } 12645 12646 /** 12647 * The visual x position of this view, in pixels. This is equivalent to the 12648 * {@link #setTranslationX(float) translationX} property plus the current 12649 * {@link #getLeft() left} property. 12650 * 12651 * @return The visual x position of this view, in pixels. 12652 */ 12653 @ViewDebug.ExportedProperty(category = "drawing") 12654 public float getX() { 12655 return mLeft + getTranslationX(); 12656 } 12657 12658 /** 12659 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 12660 * {@link #setTranslationX(float) translationX} property to be the difference between 12661 * the x value passed in and the current {@link #getLeft() left} property. 12662 * 12663 * @param x The visual x position of this view, in pixels. 12664 */ 12665 public void setX(float x) { 12666 setTranslationX(x - mLeft); 12667 } 12668 12669 /** 12670 * The visual y position of this view, in pixels. This is equivalent to the 12671 * {@link #setTranslationY(float) translationY} property plus the current 12672 * {@link #getTop() top} property. 12673 * 12674 * @return The visual y position of this view, in pixels. 12675 */ 12676 @ViewDebug.ExportedProperty(category = "drawing") 12677 public float getY() { 12678 return mTop + getTranslationY(); 12679 } 12680 12681 /** 12682 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 12683 * {@link #setTranslationY(float) translationY} property to be the difference between 12684 * the y value passed in and the current {@link #getTop() top} property. 12685 * 12686 * @param y The visual y position of this view, in pixels. 12687 */ 12688 public void setY(float y) { 12689 setTranslationY(y - mTop); 12690 } 12691 12692 /** 12693 * The visual z position of this view, in pixels. This is equivalent to the 12694 * {@link #setTranslationZ(float) translationZ} property plus the current 12695 * {@link #getElevation() elevation} property. 12696 * 12697 * @return The visual z position of this view, in pixels. 12698 */ 12699 @ViewDebug.ExportedProperty(category = "drawing") 12700 public float getZ() { 12701 return getElevation() + getTranslationZ(); 12702 } 12703 12704 /** 12705 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 12706 * {@link #setTranslationZ(float) translationZ} property to be the difference between 12707 * the x value passed in and the current {@link #getElevation() elevation} property. 12708 * 12709 * @param z The visual z position of this view, in pixels. 12710 */ 12711 public void setZ(float z) { 12712 setTranslationZ(z - getElevation()); 12713 } 12714 12715 /** 12716 * The base elevation of this view relative to its parent, in pixels. 12717 * 12718 * @return The base depth position of the view, in pixels. 12719 */ 12720 @ViewDebug.ExportedProperty(category = "drawing") 12721 public float getElevation() { 12722 return mRenderNode.getElevation(); 12723 } 12724 12725 /** 12726 * Sets the base elevation of this view, in pixels. 12727 * 12728 * @attr ref android.R.styleable#View_elevation 12729 */ 12730 public void setElevation(float elevation) { 12731 if (elevation != getElevation()) { 12732 invalidateViewProperty(true, false); 12733 mRenderNode.setElevation(elevation); 12734 invalidateViewProperty(false, true); 12735 12736 invalidateParentIfNeededAndWasQuickRejected(); 12737 } 12738 } 12739 12740 /** 12741 * The horizontal location of this view relative to its {@link #getLeft() left} position. 12742 * This position is post-layout, in addition to wherever the object's 12743 * layout placed it. 12744 * 12745 * @return The horizontal position of this view relative to its left position, in pixels. 12746 */ 12747 @ViewDebug.ExportedProperty(category = "drawing") 12748 public float getTranslationX() { 12749 return mRenderNode.getTranslationX(); 12750 } 12751 12752 /** 12753 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 12754 * This effectively positions the object post-layout, in addition to wherever the object's 12755 * layout placed it. 12756 * 12757 * @param translationX The horizontal position of this view relative to its left position, 12758 * in pixels. 12759 * 12760 * @attr ref android.R.styleable#View_translationX 12761 */ 12762 public void setTranslationX(float translationX) { 12763 if (translationX != getTranslationX()) { 12764 invalidateViewProperty(true, false); 12765 mRenderNode.setTranslationX(translationX); 12766 invalidateViewProperty(false, true); 12767 12768 invalidateParentIfNeededAndWasQuickRejected(); 12769 notifySubtreeAccessibilityStateChangedIfNeeded(); 12770 } 12771 } 12772 12773 /** 12774 * The vertical location of this view relative to its {@link #getTop() top} position. 12775 * This position is post-layout, in addition to wherever the object's 12776 * layout placed it. 12777 * 12778 * @return The vertical position of this view relative to its top position, 12779 * in pixels. 12780 */ 12781 @ViewDebug.ExportedProperty(category = "drawing") 12782 public float getTranslationY() { 12783 return mRenderNode.getTranslationY(); 12784 } 12785 12786 /** 12787 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 12788 * This effectively positions the object post-layout, in addition to wherever the object's 12789 * layout placed it. 12790 * 12791 * @param translationY The vertical position of this view relative to its top position, 12792 * in pixels. 12793 * 12794 * @attr ref android.R.styleable#View_translationY 12795 */ 12796 public void setTranslationY(float translationY) { 12797 if (translationY != getTranslationY()) { 12798 invalidateViewProperty(true, false); 12799 mRenderNode.setTranslationY(translationY); 12800 invalidateViewProperty(false, true); 12801 12802 invalidateParentIfNeededAndWasQuickRejected(); 12803 notifySubtreeAccessibilityStateChangedIfNeeded(); 12804 } 12805 } 12806 12807 /** 12808 * The depth location of this view relative to its {@link #getElevation() elevation}. 12809 * 12810 * @return The depth of this view relative to its elevation. 12811 */ 12812 @ViewDebug.ExportedProperty(category = "drawing") 12813 public float getTranslationZ() { 12814 return mRenderNode.getTranslationZ(); 12815 } 12816 12817 /** 12818 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 12819 * 12820 * @attr ref android.R.styleable#View_translationZ 12821 */ 12822 public void setTranslationZ(float translationZ) { 12823 if (translationZ != getTranslationZ()) { 12824 invalidateViewProperty(true, false); 12825 mRenderNode.setTranslationZ(translationZ); 12826 invalidateViewProperty(false, true); 12827 12828 invalidateParentIfNeededAndWasQuickRejected(); 12829 } 12830 } 12831 12832 /** @hide */ 12833 public void setAnimationMatrix(Matrix matrix) { 12834 invalidateViewProperty(true, false); 12835 mRenderNode.setAnimationMatrix(matrix); 12836 invalidateViewProperty(false, true); 12837 12838 invalidateParentIfNeededAndWasQuickRejected(); 12839 } 12840 12841 /** 12842 * Returns the current StateListAnimator if exists. 12843 * 12844 * @return StateListAnimator or null if it does not exists 12845 * @see #setStateListAnimator(android.animation.StateListAnimator) 12846 */ 12847 public StateListAnimator getStateListAnimator() { 12848 return mStateListAnimator; 12849 } 12850 12851 /** 12852 * Attaches the provided StateListAnimator to this View. 12853 * <p> 12854 * Any previously attached StateListAnimator will be detached. 12855 * 12856 * @param stateListAnimator The StateListAnimator to update the view 12857 * @see {@link android.animation.StateListAnimator} 12858 */ 12859 public void setStateListAnimator(StateListAnimator stateListAnimator) { 12860 if (mStateListAnimator == stateListAnimator) { 12861 return; 12862 } 12863 if (mStateListAnimator != null) { 12864 mStateListAnimator.setTarget(null); 12865 } 12866 mStateListAnimator = stateListAnimator; 12867 if (stateListAnimator != null) { 12868 stateListAnimator.setTarget(this); 12869 if (isAttachedToWindow()) { 12870 stateListAnimator.setState(getDrawableState()); 12871 } 12872 } 12873 } 12874 12875 /** 12876 * Returns whether the Outline should be used to clip the contents of the View. 12877 * <p> 12878 * Note that this flag will only be respected if the View's Outline returns true from 12879 * {@link Outline#canClip()}. 12880 * 12881 * @see #setOutlineProvider(ViewOutlineProvider) 12882 * @see #setClipToOutline(boolean) 12883 */ 12884 public final boolean getClipToOutline() { 12885 return mRenderNode.getClipToOutline(); 12886 } 12887 12888 /** 12889 * Sets whether the View's Outline should be used to clip the contents of the View. 12890 * <p> 12891 * Only a single non-rectangular clip can be applied on a View at any time. 12892 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 12893 * circular reveal} animation take priority over Outline clipping, and 12894 * child Outline clipping takes priority over Outline clipping done by a 12895 * parent. 12896 * <p> 12897 * Note that this flag will only be respected if the View's Outline returns true from 12898 * {@link Outline#canClip()}. 12899 * 12900 * @see #setOutlineProvider(ViewOutlineProvider) 12901 * @see #getClipToOutline() 12902 */ 12903 public void setClipToOutline(boolean clipToOutline) { 12904 damageInParent(); 12905 if (getClipToOutline() != clipToOutline) { 12906 mRenderNode.setClipToOutline(clipToOutline); 12907 } 12908 } 12909 12910 // correspond to the enum values of View_outlineProvider 12911 private static final int PROVIDER_BACKGROUND = 0; 12912 private static final int PROVIDER_NONE = 1; 12913 private static final int PROVIDER_BOUNDS = 2; 12914 private static final int PROVIDER_PADDED_BOUNDS = 3; 12915 private void setOutlineProviderFromAttribute(int providerInt) { 12916 switch (providerInt) { 12917 case PROVIDER_BACKGROUND: 12918 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 12919 break; 12920 case PROVIDER_NONE: 12921 setOutlineProvider(null); 12922 break; 12923 case PROVIDER_BOUNDS: 12924 setOutlineProvider(ViewOutlineProvider.BOUNDS); 12925 break; 12926 case PROVIDER_PADDED_BOUNDS: 12927 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 12928 break; 12929 } 12930 } 12931 12932 /** 12933 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 12934 * the shape of the shadow it casts, and enables outline clipping. 12935 * <p> 12936 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 12937 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 12938 * outline provider with this method allows this behavior to be overridden. 12939 * <p> 12940 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 12941 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 12942 * <p> 12943 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 12944 * 12945 * @see #setClipToOutline(boolean) 12946 * @see #getClipToOutline() 12947 * @see #getOutlineProvider() 12948 */ 12949 public void setOutlineProvider(ViewOutlineProvider provider) { 12950 mOutlineProvider = provider; 12951 invalidateOutline(); 12952 } 12953 12954 /** 12955 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 12956 * that defines the shape of the shadow it casts, and enables outline clipping. 12957 * 12958 * @see #setOutlineProvider(ViewOutlineProvider) 12959 */ 12960 public ViewOutlineProvider getOutlineProvider() { 12961 return mOutlineProvider; 12962 } 12963 12964 /** 12965 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 12966 * 12967 * @see #setOutlineProvider(ViewOutlineProvider) 12968 */ 12969 public void invalidateOutline() { 12970 rebuildOutline(); 12971 12972 notifySubtreeAccessibilityStateChangedIfNeeded(); 12973 invalidateViewProperty(false, false); 12974 } 12975 12976 /** 12977 * Internal version of {@link #invalidateOutline()} which invalidates the 12978 * outline without invalidating the view itself. This is intended to be called from 12979 * within methods in the View class itself which are the result of the view being 12980 * invalidated already. For example, when we are drawing the background of a View, 12981 * we invalidate the outline in case it changed in the meantime, but we do not 12982 * need to invalidate the view because we're already drawing the background as part 12983 * of drawing the view in response to an earlier invalidation of the view. 12984 */ 12985 private void rebuildOutline() { 12986 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 12987 if (mAttachInfo == null) return; 12988 12989 if (mOutlineProvider == null) { 12990 // no provider, remove outline 12991 mRenderNode.setOutline(null); 12992 } else { 12993 final Outline outline = mAttachInfo.mTmpOutline; 12994 outline.setEmpty(); 12995 outline.setAlpha(1.0f); 12996 12997 mOutlineProvider.getOutline(this, outline); 12998 mRenderNode.setOutline(outline); 12999 } 13000 } 13001 13002 /** 13003 * HierarchyViewer only 13004 * 13005 * @hide 13006 */ 13007 @ViewDebug.ExportedProperty(category = "drawing") 13008 public boolean hasShadow() { 13009 return mRenderNode.hasShadow(); 13010 } 13011 13012 13013 /** @hide */ 13014 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 13015 mRenderNode.setRevealClip(shouldClip, x, y, radius); 13016 invalidateViewProperty(false, false); 13017 } 13018 13019 /** 13020 * Hit rectangle in parent's coordinates 13021 * 13022 * @param outRect The hit rectangle of the view. 13023 */ 13024 public void getHitRect(Rect outRect) { 13025 if (hasIdentityMatrix() || mAttachInfo == null) { 13026 outRect.set(mLeft, mTop, mRight, mBottom); 13027 } else { 13028 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 13029 tmpRect.set(0, 0, getWidth(), getHeight()); 13030 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 13031 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 13032 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 13033 } 13034 } 13035 13036 /** 13037 * Determines whether the given point, in local coordinates is inside the view. 13038 */ 13039 /*package*/ final boolean pointInView(float localX, float localY) { 13040 return pointInView(localX, localY, 0); 13041 } 13042 13043 /** 13044 * Utility method to determine whether the given point, in local coordinates, 13045 * is inside the view, where the area of the view is expanded by the slop factor. 13046 * This method is called while processing touch-move events to determine if the event 13047 * is still within the view. 13048 * 13049 * @hide 13050 */ 13051 public boolean pointInView(float localX, float localY, float slop) { 13052 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 13053 localY < ((mBottom - mTop) + slop); 13054 } 13055 13056 /** 13057 * When a view has focus and the user navigates away from it, the next view is searched for 13058 * starting from the rectangle filled in by this method. 13059 * 13060 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 13061 * of the view. However, if your view maintains some idea of internal selection, 13062 * such as a cursor, or a selected row or column, you should override this method and 13063 * fill in a more specific rectangle. 13064 * 13065 * @param r The rectangle to fill in, in this view's coordinates. 13066 */ 13067 public void getFocusedRect(Rect r) { 13068 getDrawingRect(r); 13069 } 13070 13071 /** 13072 * If some part of this view is not clipped by any of its parents, then 13073 * return that area in r in global (root) coordinates. To convert r to local 13074 * coordinates (without taking possible View rotations into account), offset 13075 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 13076 * If the view is completely clipped or translated out, return false. 13077 * 13078 * @param r If true is returned, r holds the global coordinates of the 13079 * visible portion of this view. 13080 * @param globalOffset If true is returned, globalOffset holds the dx,dy 13081 * between this view and its root. globalOffet may be null. 13082 * @return true if r is non-empty (i.e. part of the view is visible at the 13083 * root level. 13084 */ 13085 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 13086 int width = mRight - mLeft; 13087 int height = mBottom - mTop; 13088 if (width > 0 && height > 0) { 13089 r.set(0, 0, width, height); 13090 if (globalOffset != null) { 13091 globalOffset.set(-mScrollX, -mScrollY); 13092 } 13093 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 13094 } 13095 return false; 13096 } 13097 13098 public final boolean getGlobalVisibleRect(Rect r) { 13099 return getGlobalVisibleRect(r, null); 13100 } 13101 13102 public final boolean getLocalVisibleRect(Rect r) { 13103 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 13104 if (getGlobalVisibleRect(r, offset)) { 13105 r.offset(-offset.x, -offset.y); // make r local 13106 return true; 13107 } 13108 return false; 13109 } 13110 13111 /** 13112 * Offset this view's vertical location by the specified number of pixels. 13113 * 13114 * @param offset the number of pixels to offset the view by 13115 */ 13116 public void offsetTopAndBottom(int offset) { 13117 if (offset != 0) { 13118 final boolean matrixIsIdentity = hasIdentityMatrix(); 13119 if (matrixIsIdentity) { 13120 if (isHardwareAccelerated()) { 13121 invalidateViewProperty(false, false); 13122 } else { 13123 final ViewParent p = mParent; 13124 if (p != null && mAttachInfo != null) { 13125 final Rect r = mAttachInfo.mTmpInvalRect; 13126 int minTop; 13127 int maxBottom; 13128 int yLoc; 13129 if (offset < 0) { 13130 minTop = mTop + offset; 13131 maxBottom = mBottom; 13132 yLoc = offset; 13133 } else { 13134 minTop = mTop; 13135 maxBottom = mBottom + offset; 13136 yLoc = 0; 13137 } 13138 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 13139 p.invalidateChild(this, r); 13140 } 13141 } 13142 } else { 13143 invalidateViewProperty(false, false); 13144 } 13145 13146 mTop += offset; 13147 mBottom += offset; 13148 mRenderNode.offsetTopAndBottom(offset); 13149 if (isHardwareAccelerated()) { 13150 invalidateViewProperty(false, false); 13151 invalidateParentIfNeededAndWasQuickRejected(); 13152 } else { 13153 if (!matrixIsIdentity) { 13154 invalidateViewProperty(false, true); 13155 } 13156 invalidateParentIfNeeded(); 13157 } 13158 notifySubtreeAccessibilityStateChangedIfNeeded(); 13159 } 13160 } 13161 13162 /** 13163 * Offset this view's horizontal location by the specified amount of pixels. 13164 * 13165 * @param offset the number of pixels to offset the view by 13166 */ 13167 public void offsetLeftAndRight(int offset) { 13168 if (offset != 0) { 13169 final boolean matrixIsIdentity = hasIdentityMatrix(); 13170 if (matrixIsIdentity) { 13171 if (isHardwareAccelerated()) { 13172 invalidateViewProperty(false, false); 13173 } else { 13174 final ViewParent p = mParent; 13175 if (p != null && mAttachInfo != null) { 13176 final Rect r = mAttachInfo.mTmpInvalRect; 13177 int minLeft; 13178 int maxRight; 13179 if (offset < 0) { 13180 minLeft = mLeft + offset; 13181 maxRight = mRight; 13182 } else { 13183 minLeft = mLeft; 13184 maxRight = mRight + offset; 13185 } 13186 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 13187 p.invalidateChild(this, r); 13188 } 13189 } 13190 } else { 13191 invalidateViewProperty(false, false); 13192 } 13193 13194 mLeft += offset; 13195 mRight += offset; 13196 mRenderNode.offsetLeftAndRight(offset); 13197 if (isHardwareAccelerated()) { 13198 invalidateViewProperty(false, false); 13199 invalidateParentIfNeededAndWasQuickRejected(); 13200 } else { 13201 if (!matrixIsIdentity) { 13202 invalidateViewProperty(false, true); 13203 } 13204 invalidateParentIfNeeded(); 13205 } 13206 notifySubtreeAccessibilityStateChangedIfNeeded(); 13207 } 13208 } 13209 13210 /** 13211 * Get the LayoutParams associated with this view. All views should have 13212 * layout parameters. These supply parameters to the <i>parent</i> of this 13213 * view specifying how it should be arranged. There are many subclasses of 13214 * ViewGroup.LayoutParams, and these correspond to the different subclasses 13215 * of ViewGroup that are responsible for arranging their children. 13216 * 13217 * This method may return null if this View is not attached to a parent 13218 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 13219 * was not invoked successfully. When a View is attached to a parent 13220 * ViewGroup, this method must not return null. 13221 * 13222 * @return The LayoutParams associated with this view, or null if no 13223 * parameters have been set yet 13224 */ 13225 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 13226 public ViewGroup.LayoutParams getLayoutParams() { 13227 return mLayoutParams; 13228 } 13229 13230 /** 13231 * Set the layout parameters associated with this view. These supply 13232 * parameters to the <i>parent</i> of this view specifying how it should be 13233 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 13234 * correspond to the different subclasses of ViewGroup that are responsible 13235 * for arranging their children. 13236 * 13237 * @param params The layout parameters for this view, cannot be null 13238 */ 13239 public void setLayoutParams(ViewGroup.LayoutParams params) { 13240 if (params == null) { 13241 throw new NullPointerException("Layout parameters cannot be null"); 13242 } 13243 mLayoutParams = params; 13244 resolveLayoutParams(); 13245 if (mParent instanceof ViewGroup) { 13246 ((ViewGroup) mParent).onSetLayoutParams(this, params); 13247 } 13248 requestLayout(); 13249 } 13250 13251 /** 13252 * Resolve the layout parameters depending on the resolved layout direction 13253 * 13254 * @hide 13255 */ 13256 public void resolveLayoutParams() { 13257 if (mLayoutParams != null) { 13258 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 13259 } 13260 } 13261 13262 /** 13263 * Set the scrolled position of your view. This will cause a call to 13264 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13265 * invalidated. 13266 * @param x the x position to scroll to 13267 * @param y the y position to scroll to 13268 */ 13269 public void scrollTo(int x, int y) { 13270 if (mScrollX != x || mScrollY != y) { 13271 int oldX = mScrollX; 13272 int oldY = mScrollY; 13273 mScrollX = x; 13274 mScrollY = y; 13275 invalidateParentCaches(); 13276 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 13277 if (!awakenScrollBars()) { 13278 postInvalidateOnAnimation(); 13279 } 13280 } 13281 } 13282 13283 /** 13284 * Move the scrolled position of your view. This will cause a call to 13285 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13286 * invalidated. 13287 * @param x the amount of pixels to scroll by horizontally 13288 * @param y the amount of pixels to scroll by vertically 13289 */ 13290 public void scrollBy(int x, int y) { 13291 scrollTo(mScrollX + x, mScrollY + y); 13292 } 13293 13294 /** 13295 * <p>Trigger the scrollbars to draw. When invoked this method starts an 13296 * animation to fade the scrollbars out after a default delay. If a subclass 13297 * provides animated scrolling, the start delay should equal the duration 13298 * of the scrolling animation.</p> 13299 * 13300 * <p>The animation starts only if at least one of the scrollbars is 13301 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 13302 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13303 * this method returns true, and false otherwise. If the animation is 13304 * started, this method calls {@link #invalidate()}; in that case the 13305 * caller should not call {@link #invalidate()}.</p> 13306 * 13307 * <p>This method should be invoked every time a subclass directly updates 13308 * the scroll parameters.</p> 13309 * 13310 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 13311 * and {@link #scrollTo(int, int)}.</p> 13312 * 13313 * @return true if the animation is played, false otherwise 13314 * 13315 * @see #awakenScrollBars(int) 13316 * @see #scrollBy(int, int) 13317 * @see #scrollTo(int, int) 13318 * @see #isHorizontalScrollBarEnabled() 13319 * @see #isVerticalScrollBarEnabled() 13320 * @see #setHorizontalScrollBarEnabled(boolean) 13321 * @see #setVerticalScrollBarEnabled(boolean) 13322 */ 13323 protected boolean awakenScrollBars() { 13324 return mScrollCache != null && 13325 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 13326 } 13327 13328 /** 13329 * Trigger the scrollbars to draw. 13330 * This method differs from awakenScrollBars() only in its default duration. 13331 * initialAwakenScrollBars() will show the scroll bars for longer than 13332 * usual to give the user more of a chance to notice them. 13333 * 13334 * @return true if the animation is played, false otherwise. 13335 */ 13336 private boolean initialAwakenScrollBars() { 13337 return mScrollCache != null && 13338 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 13339 } 13340 13341 /** 13342 * <p> 13343 * Trigger the scrollbars to draw. When invoked this method starts an 13344 * animation to fade the scrollbars out after a fixed delay. If a subclass 13345 * provides animated scrolling, the start delay should equal the duration of 13346 * the scrolling animation. 13347 * </p> 13348 * 13349 * <p> 13350 * The animation starts only if at least one of the scrollbars is enabled, 13351 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13352 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13353 * this method returns true, and false otherwise. If the animation is 13354 * started, this method calls {@link #invalidate()}; in that case the caller 13355 * should not call {@link #invalidate()}. 13356 * </p> 13357 * 13358 * <p> 13359 * This method should be invoked every time a subclass directly updates the 13360 * scroll parameters. 13361 * </p> 13362 * 13363 * @param startDelay the delay, in milliseconds, after which the animation 13364 * should start; when the delay is 0, the animation starts 13365 * immediately 13366 * @return true if the animation is played, false otherwise 13367 * 13368 * @see #scrollBy(int, int) 13369 * @see #scrollTo(int, int) 13370 * @see #isHorizontalScrollBarEnabled() 13371 * @see #isVerticalScrollBarEnabled() 13372 * @see #setHorizontalScrollBarEnabled(boolean) 13373 * @see #setVerticalScrollBarEnabled(boolean) 13374 */ 13375 protected boolean awakenScrollBars(int startDelay) { 13376 return awakenScrollBars(startDelay, true); 13377 } 13378 13379 /** 13380 * <p> 13381 * Trigger the scrollbars to draw. When invoked this method starts an 13382 * animation to fade the scrollbars out after a fixed delay. If a subclass 13383 * provides animated scrolling, the start delay should equal the duration of 13384 * the scrolling animation. 13385 * </p> 13386 * 13387 * <p> 13388 * The animation starts only if at least one of the scrollbars is enabled, 13389 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13390 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13391 * this method returns true, and false otherwise. If the animation is 13392 * started, this method calls {@link #invalidate()} if the invalidate parameter 13393 * is set to true; in that case the caller 13394 * should not call {@link #invalidate()}. 13395 * </p> 13396 * 13397 * <p> 13398 * This method should be invoked every time a subclass directly updates the 13399 * scroll parameters. 13400 * </p> 13401 * 13402 * @param startDelay the delay, in milliseconds, after which the animation 13403 * should start; when the delay is 0, the animation starts 13404 * immediately 13405 * 13406 * @param invalidate Whether this method should call invalidate 13407 * 13408 * @return true if the animation is played, false otherwise 13409 * 13410 * @see #scrollBy(int, int) 13411 * @see #scrollTo(int, int) 13412 * @see #isHorizontalScrollBarEnabled() 13413 * @see #isVerticalScrollBarEnabled() 13414 * @see #setHorizontalScrollBarEnabled(boolean) 13415 * @see #setVerticalScrollBarEnabled(boolean) 13416 */ 13417 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 13418 final ScrollabilityCache scrollCache = mScrollCache; 13419 13420 if (scrollCache == null || !scrollCache.fadeScrollBars) { 13421 return false; 13422 } 13423 13424 if (scrollCache.scrollBar == null) { 13425 scrollCache.scrollBar = new ScrollBarDrawable(); 13426 scrollCache.scrollBar.setState(getDrawableState()); 13427 scrollCache.scrollBar.setCallback(this); 13428 } 13429 13430 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 13431 13432 if (invalidate) { 13433 // Invalidate to show the scrollbars 13434 postInvalidateOnAnimation(); 13435 } 13436 13437 if (scrollCache.state == ScrollabilityCache.OFF) { 13438 // FIXME: this is copied from WindowManagerService. 13439 // We should get this value from the system when it 13440 // is possible to do so. 13441 final int KEY_REPEAT_FIRST_DELAY = 750; 13442 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 13443 } 13444 13445 // Tell mScrollCache when we should start fading. This may 13446 // extend the fade start time if one was already scheduled 13447 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 13448 scrollCache.fadeStartTime = fadeStartTime; 13449 scrollCache.state = ScrollabilityCache.ON; 13450 13451 // Schedule our fader to run, unscheduling any old ones first 13452 if (mAttachInfo != null) { 13453 mAttachInfo.mHandler.removeCallbacks(scrollCache); 13454 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 13455 } 13456 13457 return true; 13458 } 13459 13460 return false; 13461 } 13462 13463 /** 13464 * Do not invalidate views which are not visible and which are not running an animation. They 13465 * will not get drawn and they should not set dirty flags as if they will be drawn 13466 */ 13467 private boolean skipInvalidate() { 13468 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 13469 (!(mParent instanceof ViewGroup) || 13470 !((ViewGroup) mParent).isViewTransitioning(this)); 13471 } 13472 13473 /** 13474 * Mark the area defined by dirty as needing to be drawn. If the view is 13475 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13476 * point in the future. 13477 * <p> 13478 * This must be called from a UI thread. To call from a non-UI thread, call 13479 * {@link #postInvalidate()}. 13480 * <p> 13481 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 13482 * {@code dirty}. 13483 * 13484 * @param dirty the rectangle representing the bounds of the dirty region 13485 */ 13486 public void invalidate(Rect dirty) { 13487 final int scrollX = mScrollX; 13488 final int scrollY = mScrollY; 13489 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 13490 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 13491 } 13492 13493 /** 13494 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 13495 * coordinates of the dirty rect are relative to the view. If the view is 13496 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13497 * point in the future. 13498 * <p> 13499 * This must be called from a UI thread. To call from a non-UI thread, call 13500 * {@link #postInvalidate()}. 13501 * 13502 * @param l the left position of the dirty region 13503 * @param t the top position of the dirty region 13504 * @param r the right position of the dirty region 13505 * @param b the bottom position of the dirty region 13506 */ 13507 public void invalidate(int l, int t, int r, int b) { 13508 final int scrollX = mScrollX; 13509 final int scrollY = mScrollY; 13510 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 13511 } 13512 13513 /** 13514 * Invalidate the whole view. If the view is visible, 13515 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 13516 * the future. 13517 * <p> 13518 * This must be called from a UI thread. To call from a non-UI thread, call 13519 * {@link #postInvalidate()}. 13520 */ 13521 public void invalidate() { 13522 invalidate(true); 13523 } 13524 13525 /** 13526 * This is where the invalidate() work actually happens. A full invalidate() 13527 * causes the drawing cache to be invalidated, but this function can be 13528 * called with invalidateCache set to false to skip that invalidation step 13529 * for cases that do not need it (for example, a component that remains at 13530 * the same dimensions with the same content). 13531 * 13532 * @param invalidateCache Whether the drawing cache for this view should be 13533 * invalidated as well. This is usually true for a full 13534 * invalidate, but may be set to false if the View's contents or 13535 * dimensions have not changed. 13536 */ 13537 void invalidate(boolean invalidateCache) { 13538 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 13539 } 13540 13541 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 13542 boolean fullInvalidate) { 13543 if (mGhostView != null) { 13544 mGhostView.invalidate(true); 13545 return; 13546 } 13547 13548 if (skipInvalidate()) { 13549 return; 13550 } 13551 13552 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 13553 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 13554 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 13555 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 13556 if (fullInvalidate) { 13557 mLastIsOpaque = isOpaque(); 13558 mPrivateFlags &= ~PFLAG_DRAWN; 13559 } 13560 13561 mPrivateFlags |= PFLAG_DIRTY; 13562 13563 if (invalidateCache) { 13564 mPrivateFlags |= PFLAG_INVALIDATED; 13565 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13566 } 13567 13568 // Propagate the damage rectangle to the parent view. 13569 final AttachInfo ai = mAttachInfo; 13570 final ViewParent p = mParent; 13571 if (p != null && ai != null && l < r && t < b) { 13572 final Rect damage = ai.mTmpInvalRect; 13573 damage.set(l, t, r, b); 13574 p.invalidateChild(this, damage); 13575 } 13576 13577 // Damage the entire projection receiver, if necessary. 13578 if (mBackground != null && mBackground.isProjected()) { 13579 final View receiver = getProjectionReceiver(); 13580 if (receiver != null) { 13581 receiver.damageInParent(); 13582 } 13583 } 13584 13585 // Damage the entire IsolatedZVolume receiving this view's shadow. 13586 if (isHardwareAccelerated() && getZ() != 0) { 13587 damageShadowReceiver(); 13588 } 13589 } 13590 } 13591 13592 /** 13593 * @return this view's projection receiver, or {@code null} if none exists 13594 */ 13595 private View getProjectionReceiver() { 13596 ViewParent p = getParent(); 13597 while (p != null && p instanceof View) { 13598 final View v = (View) p; 13599 if (v.isProjectionReceiver()) { 13600 return v; 13601 } 13602 p = p.getParent(); 13603 } 13604 13605 return null; 13606 } 13607 13608 /** 13609 * @return whether the view is a projection receiver 13610 */ 13611 private boolean isProjectionReceiver() { 13612 return mBackground != null; 13613 } 13614 13615 /** 13616 * Damage area of the screen that can be covered by this View's shadow. 13617 * 13618 * This method will guarantee that any changes to shadows cast by a View 13619 * are damaged on the screen for future redraw. 13620 */ 13621 private void damageShadowReceiver() { 13622 final AttachInfo ai = mAttachInfo; 13623 if (ai != null) { 13624 ViewParent p = getParent(); 13625 if (p != null && p instanceof ViewGroup) { 13626 final ViewGroup vg = (ViewGroup) p; 13627 vg.damageInParent(); 13628 } 13629 } 13630 } 13631 13632 /** 13633 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 13634 * set any flags or handle all of the cases handled by the default invalidation methods. 13635 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 13636 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 13637 * walk up the hierarchy, transforming the dirty rect as necessary. 13638 * 13639 * The method also handles normal invalidation logic if display list properties are not 13640 * being used in this view. The invalidateParent and forceRedraw flags are used by that 13641 * backup approach, to handle these cases used in the various property-setting methods. 13642 * 13643 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 13644 * are not being used in this view 13645 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 13646 * list properties are not being used in this view 13647 */ 13648 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 13649 if (!isHardwareAccelerated() 13650 || !mRenderNode.isValid() 13651 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 13652 if (invalidateParent) { 13653 invalidateParentCaches(); 13654 } 13655 if (forceRedraw) { 13656 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13657 } 13658 invalidate(false); 13659 } else { 13660 damageInParent(); 13661 } 13662 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 13663 damageShadowReceiver(); 13664 } 13665 } 13666 13667 /** 13668 * Tells the parent view to damage this view's bounds. 13669 * 13670 * @hide 13671 */ 13672 protected void damageInParent() { 13673 final AttachInfo ai = mAttachInfo; 13674 final ViewParent p = mParent; 13675 if (p != null && ai != null) { 13676 final Rect r = ai.mTmpInvalRect; 13677 r.set(0, 0, mRight - mLeft, mBottom - mTop); 13678 if (mParent instanceof ViewGroup) { 13679 ((ViewGroup) mParent).damageChild(this, r); 13680 } else { 13681 mParent.invalidateChild(this, r); 13682 } 13683 } 13684 } 13685 13686 /** 13687 * Utility method to transform a given Rect by the current matrix of this view. 13688 */ 13689 void transformRect(final Rect rect) { 13690 if (!getMatrix().isIdentity()) { 13691 RectF boundingRect = mAttachInfo.mTmpTransformRect; 13692 boundingRect.set(rect); 13693 getMatrix().mapRect(boundingRect); 13694 rect.set((int) Math.floor(boundingRect.left), 13695 (int) Math.floor(boundingRect.top), 13696 (int) Math.ceil(boundingRect.right), 13697 (int) Math.ceil(boundingRect.bottom)); 13698 } 13699 } 13700 13701 /** 13702 * Used to indicate that the parent of this view should clear its caches. This functionality 13703 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13704 * which is necessary when various parent-managed properties of the view change, such as 13705 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 13706 * clears the parent caches and does not causes an invalidate event. 13707 * 13708 * @hide 13709 */ 13710 protected void invalidateParentCaches() { 13711 if (mParent instanceof View) { 13712 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 13713 } 13714 } 13715 13716 /** 13717 * Used to indicate that the parent of this view should be invalidated. This functionality 13718 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13719 * which is necessary when various parent-managed properties of the view change, such as 13720 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 13721 * an invalidation event to the parent. 13722 * 13723 * @hide 13724 */ 13725 protected void invalidateParentIfNeeded() { 13726 if (isHardwareAccelerated() && mParent instanceof View) { 13727 ((View) mParent).invalidate(true); 13728 } 13729 } 13730 13731 /** 13732 * @hide 13733 */ 13734 protected void invalidateParentIfNeededAndWasQuickRejected() { 13735 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 13736 // View was rejected last time it was drawn by its parent; this may have changed 13737 invalidateParentIfNeeded(); 13738 } 13739 } 13740 13741 /** 13742 * Indicates whether this View is opaque. An opaque View guarantees that it will 13743 * draw all the pixels overlapping its bounds using a fully opaque color. 13744 * 13745 * Subclasses of View should override this method whenever possible to indicate 13746 * whether an instance is opaque. Opaque Views are treated in a special way by 13747 * the View hierarchy, possibly allowing it to perform optimizations during 13748 * invalidate/draw passes. 13749 * 13750 * @return True if this View is guaranteed to be fully opaque, false otherwise. 13751 */ 13752 @ViewDebug.ExportedProperty(category = "drawing") 13753 public boolean isOpaque() { 13754 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 13755 getFinalAlpha() >= 1.0f; 13756 } 13757 13758 /** 13759 * @hide 13760 */ 13761 protected void computeOpaqueFlags() { 13762 // Opaque if: 13763 // - Has a background 13764 // - Background is opaque 13765 // - Doesn't have scrollbars or scrollbars overlay 13766 13767 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 13768 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 13769 } else { 13770 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 13771 } 13772 13773 final int flags = mViewFlags; 13774 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 13775 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 13776 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 13777 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 13778 } else { 13779 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 13780 } 13781 } 13782 13783 /** 13784 * @hide 13785 */ 13786 protected boolean hasOpaqueScrollbars() { 13787 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 13788 } 13789 13790 /** 13791 * @return A handler associated with the thread running the View. This 13792 * handler can be used to pump events in the UI events queue. 13793 */ 13794 public Handler getHandler() { 13795 final AttachInfo attachInfo = mAttachInfo; 13796 if (attachInfo != null) { 13797 return attachInfo.mHandler; 13798 } 13799 return null; 13800 } 13801 13802 /** 13803 * Returns the queue of runnable for this view. 13804 * 13805 * @return the queue of runnables for this view 13806 */ 13807 private HandlerActionQueue getRunQueue() { 13808 if (mRunQueue == null) { 13809 mRunQueue = new HandlerActionQueue(); 13810 } 13811 return mRunQueue; 13812 } 13813 13814 /** 13815 * Gets the view root associated with the View. 13816 * @return The view root, or null if none. 13817 * @hide 13818 */ 13819 public ViewRootImpl getViewRootImpl() { 13820 if (mAttachInfo != null) { 13821 return mAttachInfo.mViewRootImpl; 13822 } 13823 return null; 13824 } 13825 13826 /** 13827 * @hide 13828 */ 13829 public ThreadedRenderer getHardwareRenderer() { 13830 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 13831 } 13832 13833 /** 13834 * <p>Causes the Runnable to be added to the message queue. 13835 * The runnable will be run on the user interface thread.</p> 13836 * 13837 * @param action The Runnable that will be executed. 13838 * 13839 * @return Returns true if the Runnable was successfully placed in to the 13840 * message queue. Returns false on failure, usually because the 13841 * looper processing the message queue is exiting. 13842 * 13843 * @see #postDelayed 13844 * @see #removeCallbacks 13845 */ 13846 public boolean post(Runnable action) { 13847 final AttachInfo attachInfo = mAttachInfo; 13848 if (attachInfo != null) { 13849 return attachInfo.mHandler.post(action); 13850 } 13851 13852 // Postpone the runnable until we know on which thread it needs to run. 13853 // Assume that the runnable will be successfully placed after attach. 13854 getRunQueue().post(action); 13855 return true; 13856 } 13857 13858 /** 13859 * <p>Causes the Runnable to be added to the message queue, to be run 13860 * after the specified amount of time elapses. 13861 * The runnable will be run on the user interface thread.</p> 13862 * 13863 * @param action The Runnable that will be executed. 13864 * @param delayMillis The delay (in milliseconds) until the Runnable 13865 * will be executed. 13866 * 13867 * @return true if the Runnable was successfully placed in to the 13868 * message queue. Returns false on failure, usually because the 13869 * looper processing the message queue is exiting. Note that a 13870 * result of true does not mean the Runnable will be processed -- 13871 * if the looper is quit before the delivery time of the message 13872 * occurs then the message will be dropped. 13873 * 13874 * @see #post 13875 * @see #removeCallbacks 13876 */ 13877 public boolean postDelayed(Runnable action, long delayMillis) { 13878 final AttachInfo attachInfo = mAttachInfo; 13879 if (attachInfo != null) { 13880 return attachInfo.mHandler.postDelayed(action, delayMillis); 13881 } 13882 13883 // Postpone the runnable until we know on which thread it needs to run. 13884 // Assume that the runnable will be successfully placed after attach. 13885 getRunQueue().postDelayed(action, delayMillis); 13886 return true; 13887 } 13888 13889 /** 13890 * <p>Causes the Runnable to execute on the next animation time step. 13891 * The runnable will be run on the user interface thread.</p> 13892 * 13893 * @param action The Runnable that will be executed. 13894 * 13895 * @see #postOnAnimationDelayed 13896 * @see #removeCallbacks 13897 */ 13898 public void postOnAnimation(Runnable action) { 13899 final AttachInfo attachInfo = mAttachInfo; 13900 if (attachInfo != null) { 13901 attachInfo.mViewRootImpl.mChoreographer.postCallback( 13902 Choreographer.CALLBACK_ANIMATION, action, null); 13903 } else { 13904 // Postpone the runnable until we know 13905 // on which thread it needs to run. 13906 getRunQueue().post(action); 13907 } 13908 } 13909 13910 /** 13911 * <p>Causes the Runnable to execute on the next animation time step, 13912 * after the specified amount of time elapses. 13913 * The runnable will be run on the user interface thread.</p> 13914 * 13915 * @param action The Runnable that will be executed. 13916 * @param delayMillis The delay (in milliseconds) until the Runnable 13917 * will be executed. 13918 * 13919 * @see #postOnAnimation 13920 * @see #removeCallbacks 13921 */ 13922 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 13923 final AttachInfo attachInfo = mAttachInfo; 13924 if (attachInfo != null) { 13925 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 13926 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 13927 } else { 13928 // Postpone the runnable until we know 13929 // on which thread it needs to run. 13930 getRunQueue().postDelayed(action, delayMillis); 13931 } 13932 } 13933 13934 /** 13935 * <p>Removes the specified Runnable from the message queue.</p> 13936 * 13937 * @param action The Runnable to remove from the message handling queue 13938 * 13939 * @return true if this view could ask the Handler to remove the Runnable, 13940 * false otherwise. When the returned value is true, the Runnable 13941 * may or may not have been actually removed from the message queue 13942 * (for instance, if the Runnable was not in the queue already.) 13943 * 13944 * @see #post 13945 * @see #postDelayed 13946 * @see #postOnAnimation 13947 * @see #postOnAnimationDelayed 13948 */ 13949 public boolean removeCallbacks(Runnable action) { 13950 if (action != null) { 13951 final AttachInfo attachInfo = mAttachInfo; 13952 if (attachInfo != null) { 13953 attachInfo.mHandler.removeCallbacks(action); 13954 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 13955 Choreographer.CALLBACK_ANIMATION, action, null); 13956 } 13957 getRunQueue().removeCallbacks(action); 13958 } 13959 return true; 13960 } 13961 13962 /** 13963 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 13964 * Use this to invalidate the View from a non-UI thread.</p> 13965 * 13966 * <p>This method can be invoked from outside of the UI thread 13967 * only when this View is attached to a window.</p> 13968 * 13969 * @see #invalidate() 13970 * @see #postInvalidateDelayed(long) 13971 */ 13972 public void postInvalidate() { 13973 postInvalidateDelayed(0); 13974 } 13975 13976 /** 13977 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13978 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 13979 * 13980 * <p>This method can be invoked from outside of the UI thread 13981 * only when this View is attached to a window.</p> 13982 * 13983 * @param left The left coordinate of the rectangle to invalidate. 13984 * @param top The top coordinate of the rectangle to invalidate. 13985 * @param right The right coordinate of the rectangle to invalidate. 13986 * @param bottom The bottom coordinate of the rectangle to invalidate. 13987 * 13988 * @see #invalidate(int, int, int, int) 13989 * @see #invalidate(Rect) 13990 * @see #postInvalidateDelayed(long, int, int, int, int) 13991 */ 13992 public void postInvalidate(int left, int top, int right, int bottom) { 13993 postInvalidateDelayed(0, left, top, right, bottom); 13994 } 13995 13996 /** 13997 * <p>Cause an invalidate to happen on a subsequent cycle through the event 13998 * loop. Waits for the specified amount of time.</p> 13999 * 14000 * <p>This method can be invoked from outside of the UI thread 14001 * only when this View is attached to a window.</p> 14002 * 14003 * @param delayMilliseconds the duration in milliseconds to delay the 14004 * invalidation by 14005 * 14006 * @see #invalidate() 14007 * @see #postInvalidate() 14008 */ 14009 public void postInvalidateDelayed(long delayMilliseconds) { 14010 // We try only with the AttachInfo because there's no point in invalidating 14011 // if we are not attached to our window 14012 final AttachInfo attachInfo = mAttachInfo; 14013 if (attachInfo != null) { 14014 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 14015 } 14016 } 14017 14018 /** 14019 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14020 * through the event loop. Waits for the specified amount of time.</p> 14021 * 14022 * <p>This method can be invoked from outside of the UI thread 14023 * only when this View is attached to a window.</p> 14024 * 14025 * @param delayMilliseconds the duration in milliseconds to delay the 14026 * invalidation by 14027 * @param left The left coordinate of the rectangle to invalidate. 14028 * @param top The top coordinate of the rectangle to invalidate. 14029 * @param right The right coordinate of the rectangle to invalidate. 14030 * @param bottom The bottom coordinate of the rectangle to invalidate. 14031 * 14032 * @see #invalidate(int, int, int, int) 14033 * @see #invalidate(Rect) 14034 * @see #postInvalidate(int, int, int, int) 14035 */ 14036 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 14037 int right, int bottom) { 14038 14039 // We try only with the AttachInfo because there's no point in invalidating 14040 // if we are not attached to our window 14041 final AttachInfo attachInfo = mAttachInfo; 14042 if (attachInfo != null) { 14043 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14044 info.target = this; 14045 info.left = left; 14046 info.top = top; 14047 info.right = right; 14048 info.bottom = bottom; 14049 14050 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 14051 } 14052 } 14053 14054 /** 14055 * <p>Cause an invalidate to happen on the next animation time step, typically the 14056 * next display frame.</p> 14057 * 14058 * <p>This method can be invoked from outside of the UI thread 14059 * only when this View is attached to a window.</p> 14060 * 14061 * @see #invalidate() 14062 */ 14063 public void postInvalidateOnAnimation() { 14064 // We try only with the AttachInfo because there's no point in invalidating 14065 // if we are not attached to our window 14066 final AttachInfo attachInfo = mAttachInfo; 14067 if (attachInfo != null) { 14068 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 14069 } 14070 } 14071 14072 /** 14073 * <p>Cause an invalidate of the specified area to happen on the next animation 14074 * time step, typically the next display frame.</p> 14075 * 14076 * <p>This method can be invoked from outside of the UI thread 14077 * only when this View is attached to a window.</p> 14078 * 14079 * @param left The left coordinate of the rectangle to invalidate. 14080 * @param top The top coordinate of the rectangle to invalidate. 14081 * @param right The right coordinate of the rectangle to invalidate. 14082 * @param bottom The bottom coordinate of the rectangle to invalidate. 14083 * 14084 * @see #invalidate(int, int, int, int) 14085 * @see #invalidate(Rect) 14086 */ 14087 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 14088 // We try only with the AttachInfo because there's no point in invalidating 14089 // if we are not attached to our window 14090 final AttachInfo attachInfo = mAttachInfo; 14091 if (attachInfo != null) { 14092 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14093 info.target = this; 14094 info.left = left; 14095 info.top = top; 14096 info.right = right; 14097 info.bottom = bottom; 14098 14099 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 14100 } 14101 } 14102 14103 /** 14104 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 14105 * This event is sent at most once every 14106 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 14107 */ 14108 private void postSendViewScrolledAccessibilityEventCallback() { 14109 if (mSendViewScrolledAccessibilityEvent == null) { 14110 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 14111 } 14112 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 14113 mSendViewScrolledAccessibilityEvent.mIsPending = true; 14114 postDelayed(mSendViewScrolledAccessibilityEvent, 14115 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 14116 } 14117 } 14118 14119 /** 14120 * Called by a parent to request that a child update its values for mScrollX 14121 * and mScrollY if necessary. This will typically be done if the child is 14122 * animating a scroll using a {@link android.widget.Scroller Scroller} 14123 * object. 14124 */ 14125 public void computeScroll() { 14126 } 14127 14128 /** 14129 * <p>Indicate whether the horizontal edges are faded when the view is 14130 * scrolled horizontally.</p> 14131 * 14132 * @return true if the horizontal edges should are faded on scroll, false 14133 * otherwise 14134 * 14135 * @see #setHorizontalFadingEdgeEnabled(boolean) 14136 * 14137 * @attr ref android.R.styleable#View_requiresFadingEdge 14138 */ 14139 public boolean isHorizontalFadingEdgeEnabled() { 14140 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 14141 } 14142 14143 /** 14144 * <p>Define whether the horizontal edges should be faded when this view 14145 * is scrolled horizontally.</p> 14146 * 14147 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 14148 * be faded when the view is scrolled 14149 * horizontally 14150 * 14151 * @see #isHorizontalFadingEdgeEnabled() 14152 * 14153 * @attr ref android.R.styleable#View_requiresFadingEdge 14154 */ 14155 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 14156 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 14157 if (horizontalFadingEdgeEnabled) { 14158 initScrollCache(); 14159 } 14160 14161 mViewFlags ^= FADING_EDGE_HORIZONTAL; 14162 } 14163 } 14164 14165 /** 14166 * <p>Indicate whether the vertical edges are faded when the view is 14167 * scrolled horizontally.</p> 14168 * 14169 * @return true if the vertical edges should are faded on scroll, false 14170 * otherwise 14171 * 14172 * @see #setVerticalFadingEdgeEnabled(boolean) 14173 * 14174 * @attr ref android.R.styleable#View_requiresFadingEdge 14175 */ 14176 public boolean isVerticalFadingEdgeEnabled() { 14177 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 14178 } 14179 14180 /** 14181 * <p>Define whether the vertical edges should be faded when this view 14182 * is scrolled vertically.</p> 14183 * 14184 * @param verticalFadingEdgeEnabled true if the vertical edges should 14185 * be faded when the view is scrolled 14186 * vertically 14187 * 14188 * @see #isVerticalFadingEdgeEnabled() 14189 * 14190 * @attr ref android.R.styleable#View_requiresFadingEdge 14191 */ 14192 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 14193 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 14194 if (verticalFadingEdgeEnabled) { 14195 initScrollCache(); 14196 } 14197 14198 mViewFlags ^= FADING_EDGE_VERTICAL; 14199 } 14200 } 14201 14202 /** 14203 * Returns the strength, or intensity, of the top faded edge. The strength is 14204 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14205 * returns 0.0 or 1.0 but no value in between. 14206 * 14207 * Subclasses should override this method to provide a smoother fade transition 14208 * when scrolling occurs. 14209 * 14210 * @return the intensity of the top fade as a float between 0.0f and 1.0f 14211 */ 14212 protected float getTopFadingEdgeStrength() { 14213 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 14214 } 14215 14216 /** 14217 * Returns the strength, or intensity, of the bottom faded edge. The strength is 14218 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14219 * returns 0.0 or 1.0 but no value in between. 14220 * 14221 * Subclasses should override this method to provide a smoother fade transition 14222 * when scrolling occurs. 14223 * 14224 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 14225 */ 14226 protected float getBottomFadingEdgeStrength() { 14227 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 14228 computeVerticalScrollRange() ? 1.0f : 0.0f; 14229 } 14230 14231 /** 14232 * Returns the strength, or intensity, of the left faded edge. The strength is 14233 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14234 * returns 0.0 or 1.0 but no value in between. 14235 * 14236 * Subclasses should override this method to provide a smoother fade transition 14237 * when scrolling occurs. 14238 * 14239 * @return the intensity of the left fade as a float between 0.0f and 1.0f 14240 */ 14241 protected float getLeftFadingEdgeStrength() { 14242 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 14243 } 14244 14245 /** 14246 * Returns the strength, or intensity, of the right faded edge. The strength is 14247 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14248 * returns 0.0 or 1.0 but no value in between. 14249 * 14250 * Subclasses should override this method to provide a smoother fade transition 14251 * when scrolling occurs. 14252 * 14253 * @return the intensity of the right fade as a float between 0.0f and 1.0f 14254 */ 14255 protected float getRightFadingEdgeStrength() { 14256 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 14257 computeHorizontalScrollRange() ? 1.0f : 0.0f; 14258 } 14259 14260 /** 14261 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 14262 * scrollbar is not drawn by default.</p> 14263 * 14264 * @return true if the horizontal scrollbar should be painted, false 14265 * otherwise 14266 * 14267 * @see #setHorizontalScrollBarEnabled(boolean) 14268 */ 14269 public boolean isHorizontalScrollBarEnabled() { 14270 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 14271 } 14272 14273 /** 14274 * <p>Define whether the horizontal scrollbar should be drawn or not. The 14275 * scrollbar is not drawn by default.</p> 14276 * 14277 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 14278 * be painted 14279 * 14280 * @see #isHorizontalScrollBarEnabled() 14281 */ 14282 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 14283 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 14284 mViewFlags ^= SCROLLBARS_HORIZONTAL; 14285 computeOpaqueFlags(); 14286 resolvePadding(); 14287 } 14288 } 14289 14290 /** 14291 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 14292 * scrollbar is not drawn by default.</p> 14293 * 14294 * @return true if the vertical scrollbar should be painted, false 14295 * otherwise 14296 * 14297 * @see #setVerticalScrollBarEnabled(boolean) 14298 */ 14299 public boolean isVerticalScrollBarEnabled() { 14300 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 14301 } 14302 14303 /** 14304 * <p>Define whether the vertical scrollbar should be drawn or not. The 14305 * scrollbar is not drawn by default.</p> 14306 * 14307 * @param verticalScrollBarEnabled true if the vertical scrollbar should 14308 * be painted 14309 * 14310 * @see #isVerticalScrollBarEnabled() 14311 */ 14312 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 14313 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 14314 mViewFlags ^= SCROLLBARS_VERTICAL; 14315 computeOpaqueFlags(); 14316 resolvePadding(); 14317 } 14318 } 14319 14320 /** 14321 * @hide 14322 */ 14323 protected void recomputePadding() { 14324 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14325 } 14326 14327 /** 14328 * Define whether scrollbars will fade when the view is not scrolling. 14329 * 14330 * @param fadeScrollbars whether to enable fading 14331 * 14332 * @attr ref android.R.styleable#View_fadeScrollbars 14333 */ 14334 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 14335 initScrollCache(); 14336 final ScrollabilityCache scrollabilityCache = mScrollCache; 14337 scrollabilityCache.fadeScrollBars = fadeScrollbars; 14338 if (fadeScrollbars) { 14339 scrollabilityCache.state = ScrollabilityCache.OFF; 14340 } else { 14341 scrollabilityCache.state = ScrollabilityCache.ON; 14342 } 14343 } 14344 14345 /** 14346 * 14347 * Returns true if scrollbars will fade when this view is not scrolling 14348 * 14349 * @return true if scrollbar fading is enabled 14350 * 14351 * @attr ref android.R.styleable#View_fadeScrollbars 14352 */ 14353 public boolean isScrollbarFadingEnabled() { 14354 return mScrollCache != null && mScrollCache.fadeScrollBars; 14355 } 14356 14357 /** 14358 * 14359 * Returns the delay before scrollbars fade. 14360 * 14361 * @return the delay before scrollbars fade 14362 * 14363 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14364 */ 14365 public int getScrollBarDefaultDelayBeforeFade() { 14366 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 14367 mScrollCache.scrollBarDefaultDelayBeforeFade; 14368 } 14369 14370 /** 14371 * Define the delay before scrollbars fade. 14372 * 14373 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 14374 * 14375 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14376 */ 14377 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 14378 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 14379 } 14380 14381 /** 14382 * 14383 * Returns the scrollbar fade duration. 14384 * 14385 * @return the scrollbar fade duration 14386 * 14387 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14388 */ 14389 public int getScrollBarFadeDuration() { 14390 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 14391 mScrollCache.scrollBarFadeDuration; 14392 } 14393 14394 /** 14395 * Define the scrollbar fade duration. 14396 * 14397 * @param scrollBarFadeDuration - the scrollbar fade duration 14398 * 14399 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14400 */ 14401 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 14402 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 14403 } 14404 14405 /** 14406 * 14407 * Returns the scrollbar size. 14408 * 14409 * @return the scrollbar size 14410 * 14411 * @attr ref android.R.styleable#View_scrollbarSize 14412 */ 14413 public int getScrollBarSize() { 14414 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 14415 mScrollCache.scrollBarSize; 14416 } 14417 14418 /** 14419 * Define the scrollbar size. 14420 * 14421 * @param scrollBarSize - the scrollbar size 14422 * 14423 * @attr ref android.R.styleable#View_scrollbarSize 14424 */ 14425 public void setScrollBarSize(int scrollBarSize) { 14426 getScrollCache().scrollBarSize = scrollBarSize; 14427 } 14428 14429 /** 14430 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 14431 * inset. When inset, they add to the padding of the view. And the scrollbars 14432 * can be drawn inside the padding area or on the edge of the view. For example, 14433 * if a view has a background drawable and you want to draw the scrollbars 14434 * inside the padding specified by the drawable, you can use 14435 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 14436 * appear at the edge of the view, ignoring the padding, then you can use 14437 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 14438 * @param style the style of the scrollbars. Should be one of 14439 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 14440 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 14441 * @see #SCROLLBARS_INSIDE_OVERLAY 14442 * @see #SCROLLBARS_INSIDE_INSET 14443 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14444 * @see #SCROLLBARS_OUTSIDE_INSET 14445 * 14446 * @attr ref android.R.styleable#View_scrollbarStyle 14447 */ 14448 public void setScrollBarStyle(@ScrollBarStyle int style) { 14449 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 14450 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 14451 computeOpaqueFlags(); 14452 resolvePadding(); 14453 } 14454 } 14455 14456 /** 14457 * <p>Returns the current scrollbar style.</p> 14458 * @return the current scrollbar style 14459 * @see #SCROLLBARS_INSIDE_OVERLAY 14460 * @see #SCROLLBARS_INSIDE_INSET 14461 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14462 * @see #SCROLLBARS_OUTSIDE_INSET 14463 * 14464 * @attr ref android.R.styleable#View_scrollbarStyle 14465 */ 14466 @ViewDebug.ExportedProperty(mapping = { 14467 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 14468 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 14469 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 14470 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 14471 }) 14472 @ScrollBarStyle 14473 public int getScrollBarStyle() { 14474 return mViewFlags & SCROLLBARS_STYLE_MASK; 14475 } 14476 14477 /** 14478 * <p>Compute the horizontal range that the horizontal scrollbar 14479 * represents.</p> 14480 * 14481 * <p>The range is expressed in arbitrary units that must be the same as the 14482 * units used by {@link #computeHorizontalScrollExtent()} and 14483 * {@link #computeHorizontalScrollOffset()}.</p> 14484 * 14485 * <p>The default range is the drawing width of this view.</p> 14486 * 14487 * @return the total horizontal range represented by the horizontal 14488 * scrollbar 14489 * 14490 * @see #computeHorizontalScrollExtent() 14491 * @see #computeHorizontalScrollOffset() 14492 * @see android.widget.ScrollBarDrawable 14493 */ 14494 protected int computeHorizontalScrollRange() { 14495 return getWidth(); 14496 } 14497 14498 /** 14499 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 14500 * within the horizontal range. This value is used to compute the position 14501 * of the thumb within the scrollbar's track.</p> 14502 * 14503 * <p>The range is expressed in arbitrary units that must be the same as the 14504 * units used by {@link #computeHorizontalScrollRange()} and 14505 * {@link #computeHorizontalScrollExtent()}.</p> 14506 * 14507 * <p>The default offset is the scroll offset of this view.</p> 14508 * 14509 * @return the horizontal offset of the scrollbar's thumb 14510 * 14511 * @see #computeHorizontalScrollRange() 14512 * @see #computeHorizontalScrollExtent() 14513 * @see android.widget.ScrollBarDrawable 14514 */ 14515 protected int computeHorizontalScrollOffset() { 14516 return mScrollX; 14517 } 14518 14519 /** 14520 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 14521 * within the horizontal range. This value is used to compute the length 14522 * of the thumb within the scrollbar's track.</p> 14523 * 14524 * <p>The range is expressed in arbitrary units that must be the same as the 14525 * units used by {@link #computeHorizontalScrollRange()} and 14526 * {@link #computeHorizontalScrollOffset()}.</p> 14527 * 14528 * <p>The default extent is the drawing width of this view.</p> 14529 * 14530 * @return the horizontal extent of the scrollbar's thumb 14531 * 14532 * @see #computeHorizontalScrollRange() 14533 * @see #computeHorizontalScrollOffset() 14534 * @see android.widget.ScrollBarDrawable 14535 */ 14536 protected int computeHorizontalScrollExtent() { 14537 return getWidth(); 14538 } 14539 14540 /** 14541 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 14542 * 14543 * <p>The range is expressed in arbitrary units that must be the same as the 14544 * units used by {@link #computeVerticalScrollExtent()} and 14545 * {@link #computeVerticalScrollOffset()}.</p> 14546 * 14547 * @return the total vertical range represented by the vertical scrollbar 14548 * 14549 * <p>The default range is the drawing height of this view.</p> 14550 * 14551 * @see #computeVerticalScrollExtent() 14552 * @see #computeVerticalScrollOffset() 14553 * @see android.widget.ScrollBarDrawable 14554 */ 14555 protected int computeVerticalScrollRange() { 14556 return getHeight(); 14557 } 14558 14559 /** 14560 * <p>Compute the vertical offset of the vertical scrollbar's thumb 14561 * within the horizontal range. This value is used to compute the position 14562 * of the thumb within the scrollbar's track.</p> 14563 * 14564 * <p>The range is expressed in arbitrary units that must be the same as the 14565 * units used by {@link #computeVerticalScrollRange()} and 14566 * {@link #computeVerticalScrollExtent()}.</p> 14567 * 14568 * <p>The default offset is the scroll offset of this view.</p> 14569 * 14570 * @return the vertical offset of the scrollbar's thumb 14571 * 14572 * @see #computeVerticalScrollRange() 14573 * @see #computeVerticalScrollExtent() 14574 * @see android.widget.ScrollBarDrawable 14575 */ 14576 protected int computeVerticalScrollOffset() { 14577 return mScrollY; 14578 } 14579 14580 /** 14581 * <p>Compute the vertical extent of the vertical scrollbar's thumb 14582 * within the vertical range. This value is used to compute the length 14583 * of the thumb within the scrollbar's track.</p> 14584 * 14585 * <p>The range is expressed in arbitrary units that must be the same as the 14586 * units used by {@link #computeVerticalScrollRange()} and 14587 * {@link #computeVerticalScrollOffset()}.</p> 14588 * 14589 * <p>The default extent is the drawing height of this view.</p> 14590 * 14591 * @return the vertical extent of the scrollbar's thumb 14592 * 14593 * @see #computeVerticalScrollRange() 14594 * @see #computeVerticalScrollOffset() 14595 * @see android.widget.ScrollBarDrawable 14596 */ 14597 protected int computeVerticalScrollExtent() { 14598 return getHeight(); 14599 } 14600 14601 /** 14602 * Check if this view can be scrolled horizontally in a certain direction. 14603 * 14604 * @param direction Negative to check scrolling left, positive to check scrolling right. 14605 * @return true if this view can be scrolled in the specified direction, false otherwise. 14606 */ 14607 public boolean canScrollHorizontally(int direction) { 14608 final int offset = computeHorizontalScrollOffset(); 14609 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 14610 if (range == 0) return false; 14611 if (direction < 0) { 14612 return offset > 0; 14613 } else { 14614 return offset < range - 1; 14615 } 14616 } 14617 14618 /** 14619 * Check if this view can be scrolled vertically in a certain direction. 14620 * 14621 * @param direction Negative to check scrolling up, positive to check scrolling down. 14622 * @return true if this view can be scrolled in the specified direction, false otherwise. 14623 */ 14624 public boolean canScrollVertically(int direction) { 14625 final int offset = computeVerticalScrollOffset(); 14626 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 14627 if (range == 0) return false; 14628 if (direction < 0) { 14629 return offset > 0; 14630 } else { 14631 return offset < range - 1; 14632 } 14633 } 14634 14635 void getScrollIndicatorBounds(@NonNull Rect out) { 14636 out.left = mScrollX; 14637 out.right = mScrollX + mRight - mLeft; 14638 out.top = mScrollY; 14639 out.bottom = mScrollY + mBottom - mTop; 14640 } 14641 14642 private void onDrawScrollIndicators(Canvas c) { 14643 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 14644 // No scroll indicators enabled. 14645 return; 14646 } 14647 14648 final Drawable dr = mScrollIndicatorDrawable; 14649 if (dr == null) { 14650 // Scroll indicators aren't supported here. 14651 return; 14652 } 14653 14654 final int h = dr.getIntrinsicHeight(); 14655 final int w = dr.getIntrinsicWidth(); 14656 final Rect rect = mAttachInfo.mTmpInvalRect; 14657 getScrollIndicatorBounds(rect); 14658 14659 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 14660 final boolean canScrollUp = canScrollVertically(-1); 14661 if (canScrollUp) { 14662 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 14663 dr.draw(c); 14664 } 14665 } 14666 14667 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 14668 final boolean canScrollDown = canScrollVertically(1); 14669 if (canScrollDown) { 14670 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 14671 dr.draw(c); 14672 } 14673 } 14674 14675 final int leftRtl; 14676 final int rightRtl; 14677 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14678 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 14679 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 14680 } else { 14681 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 14682 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 14683 } 14684 14685 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 14686 if ((mPrivateFlags3 & leftMask) != 0) { 14687 final boolean canScrollLeft = canScrollHorizontally(-1); 14688 if (canScrollLeft) { 14689 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 14690 dr.draw(c); 14691 } 14692 } 14693 14694 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 14695 if ((mPrivateFlags3 & rightMask) != 0) { 14696 final boolean canScrollRight = canScrollHorizontally(1); 14697 if (canScrollRight) { 14698 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 14699 dr.draw(c); 14700 } 14701 } 14702 } 14703 14704 private void getHorizontalScrollBarBounds(Rect bounds) { 14705 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14706 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14707 && !isVerticalScrollBarHidden(); 14708 final int size = getHorizontalScrollbarHeight(); 14709 final int verticalScrollBarGap = drawVerticalScrollBar ? 14710 getVerticalScrollbarWidth() : 0; 14711 final int width = mRight - mLeft; 14712 final int height = mBottom - mTop; 14713 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 14714 bounds.left = mScrollX + (mPaddingLeft & inside); 14715 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 14716 bounds.bottom = bounds.top + size; 14717 } 14718 14719 private void getVerticalScrollBarBounds(Rect bounds) { 14720 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14721 final int size = getVerticalScrollbarWidth(); 14722 int verticalScrollbarPosition = mVerticalScrollbarPosition; 14723 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 14724 verticalScrollbarPosition = isLayoutRtl() ? 14725 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 14726 } 14727 final int width = mRight - mLeft; 14728 final int height = mBottom - mTop; 14729 switch (verticalScrollbarPosition) { 14730 default: 14731 case SCROLLBAR_POSITION_RIGHT: 14732 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 14733 break; 14734 case SCROLLBAR_POSITION_LEFT: 14735 bounds.left = mScrollX + (mUserPaddingLeft & inside); 14736 break; 14737 } 14738 bounds.top = mScrollY + (mPaddingTop & inside); 14739 bounds.right = bounds.left + size; 14740 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 14741 } 14742 14743 /** 14744 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 14745 * scrollbars are painted only if they have been awakened first.</p> 14746 * 14747 * @param canvas the canvas on which to draw the scrollbars 14748 * 14749 * @see #awakenScrollBars(int) 14750 */ 14751 protected final void onDrawScrollBars(Canvas canvas) { 14752 // scrollbars are drawn only when the animation is running 14753 final ScrollabilityCache cache = mScrollCache; 14754 if (cache != null) { 14755 14756 int state = cache.state; 14757 14758 if (state == ScrollabilityCache.OFF) { 14759 return; 14760 } 14761 14762 boolean invalidate = false; 14763 14764 if (state == ScrollabilityCache.FADING) { 14765 // We're fading -- get our fade interpolation 14766 if (cache.interpolatorValues == null) { 14767 cache.interpolatorValues = new float[1]; 14768 } 14769 14770 float[] values = cache.interpolatorValues; 14771 14772 // Stops the animation if we're done 14773 if (cache.scrollBarInterpolator.timeToValues(values) == 14774 Interpolator.Result.FREEZE_END) { 14775 cache.state = ScrollabilityCache.OFF; 14776 } else { 14777 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 14778 } 14779 14780 // This will make the scroll bars inval themselves after 14781 // drawing. We only want this when we're fading so that 14782 // we prevent excessive redraws 14783 invalidate = true; 14784 } else { 14785 // We're just on -- but we may have been fading before so 14786 // reset alpha 14787 cache.scrollBar.mutate().setAlpha(255); 14788 } 14789 14790 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 14791 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14792 && !isVerticalScrollBarHidden(); 14793 14794 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 14795 final ScrollBarDrawable scrollBar = cache.scrollBar; 14796 14797 if (drawHorizontalScrollBar) { 14798 scrollBar.setParameters(computeHorizontalScrollRange(), 14799 computeHorizontalScrollOffset(), 14800 computeHorizontalScrollExtent(), false); 14801 final Rect bounds = cache.mScrollBarBounds; 14802 getHorizontalScrollBarBounds(bounds); 14803 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14804 bounds.right, bounds.bottom); 14805 if (invalidate) { 14806 invalidate(bounds); 14807 } 14808 } 14809 14810 if (drawVerticalScrollBar) { 14811 scrollBar.setParameters(computeVerticalScrollRange(), 14812 computeVerticalScrollOffset(), 14813 computeVerticalScrollExtent(), true); 14814 final Rect bounds = cache.mScrollBarBounds; 14815 getVerticalScrollBarBounds(bounds); 14816 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14817 bounds.right, bounds.bottom); 14818 if (invalidate) { 14819 invalidate(bounds); 14820 } 14821 } 14822 } 14823 } 14824 } 14825 14826 /** 14827 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 14828 * FastScroller is visible. 14829 * @return whether to temporarily hide the vertical scrollbar 14830 * @hide 14831 */ 14832 protected boolean isVerticalScrollBarHidden() { 14833 return false; 14834 } 14835 14836 /** 14837 * <p>Draw the horizontal scrollbar if 14838 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 14839 * 14840 * @param canvas the canvas on which to draw the scrollbar 14841 * @param scrollBar the scrollbar's drawable 14842 * 14843 * @see #isHorizontalScrollBarEnabled() 14844 * @see #computeHorizontalScrollRange() 14845 * @see #computeHorizontalScrollExtent() 14846 * @see #computeHorizontalScrollOffset() 14847 * @see android.widget.ScrollBarDrawable 14848 * @hide 14849 */ 14850 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 14851 int l, int t, int r, int b) { 14852 scrollBar.setBounds(l, t, r, b); 14853 scrollBar.draw(canvas); 14854 } 14855 14856 /** 14857 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 14858 * returns true.</p> 14859 * 14860 * @param canvas the canvas on which to draw the scrollbar 14861 * @param scrollBar the scrollbar's drawable 14862 * 14863 * @see #isVerticalScrollBarEnabled() 14864 * @see #computeVerticalScrollRange() 14865 * @see #computeVerticalScrollExtent() 14866 * @see #computeVerticalScrollOffset() 14867 * @see android.widget.ScrollBarDrawable 14868 * @hide 14869 */ 14870 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 14871 int l, int t, int r, int b) { 14872 scrollBar.setBounds(l, t, r, b); 14873 scrollBar.draw(canvas); 14874 } 14875 14876 /** 14877 * Implement this to do your drawing. 14878 * 14879 * @param canvas the canvas on which the background will be drawn 14880 */ 14881 protected void onDraw(Canvas canvas) { 14882 } 14883 14884 /* 14885 * Caller is responsible for calling requestLayout if necessary. 14886 * (This allows addViewInLayout to not request a new layout.) 14887 */ 14888 void assignParent(ViewParent parent) { 14889 if (mParent == null) { 14890 mParent = parent; 14891 } else if (parent == null) { 14892 mParent = null; 14893 } else { 14894 throw new RuntimeException("view " + this + " being added, but" 14895 + " it already has a parent"); 14896 } 14897 } 14898 14899 /** 14900 * This is called when the view is attached to a window. At this point it 14901 * has a Surface and will start drawing. Note that this function is 14902 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 14903 * however it may be called any time before the first onDraw -- including 14904 * before or after {@link #onMeasure(int, int)}. 14905 * 14906 * @see #onDetachedFromWindow() 14907 */ 14908 @CallSuper 14909 protected void onAttachedToWindow() { 14910 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 14911 mParent.requestTransparentRegion(this); 14912 } 14913 14914 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 14915 14916 jumpDrawablesToCurrentState(); 14917 14918 resetSubtreeAccessibilityStateChanged(); 14919 14920 // rebuild, since Outline not maintained while View is detached 14921 rebuildOutline(); 14922 14923 if (isFocused()) { 14924 InputMethodManager imm = InputMethodManager.peekInstance(); 14925 if (imm != null) { 14926 imm.focusIn(this); 14927 } 14928 } 14929 } 14930 14931 /** 14932 * Resolve all RTL related properties. 14933 * 14934 * @return true if resolution of RTL properties has been done 14935 * 14936 * @hide 14937 */ 14938 public boolean resolveRtlPropertiesIfNeeded() { 14939 if (!needRtlPropertiesResolution()) return false; 14940 14941 // Order is important here: LayoutDirection MUST be resolved first 14942 if (!isLayoutDirectionResolved()) { 14943 resolveLayoutDirection(); 14944 resolveLayoutParams(); 14945 } 14946 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 14947 if (!isTextDirectionResolved()) { 14948 resolveTextDirection(); 14949 } 14950 if (!isTextAlignmentResolved()) { 14951 resolveTextAlignment(); 14952 } 14953 // Should resolve Drawables before Padding because we need the layout direction of the 14954 // Drawable to correctly resolve Padding. 14955 if (!areDrawablesResolved()) { 14956 resolveDrawables(); 14957 } 14958 if (!isPaddingResolved()) { 14959 resolvePadding(); 14960 } 14961 onRtlPropertiesChanged(getLayoutDirection()); 14962 return true; 14963 } 14964 14965 /** 14966 * Reset resolution of all RTL related properties. 14967 * 14968 * @hide 14969 */ 14970 public void resetRtlProperties() { 14971 resetResolvedLayoutDirection(); 14972 resetResolvedTextDirection(); 14973 resetResolvedTextAlignment(); 14974 resetResolvedPadding(); 14975 resetResolvedDrawables(); 14976 } 14977 14978 /** 14979 * @see #onScreenStateChanged(int) 14980 */ 14981 void dispatchScreenStateChanged(int screenState) { 14982 onScreenStateChanged(screenState); 14983 } 14984 14985 /** 14986 * This method is called whenever the state of the screen this view is 14987 * attached to changes. A state change will usually occurs when the screen 14988 * turns on or off (whether it happens automatically or the user does it 14989 * manually.) 14990 * 14991 * @param screenState The new state of the screen. Can be either 14992 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 14993 */ 14994 public void onScreenStateChanged(int screenState) { 14995 } 14996 14997 /** 14998 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 14999 */ 15000 private boolean hasRtlSupport() { 15001 return mContext.getApplicationInfo().hasRtlSupport(); 15002 } 15003 15004 /** 15005 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 15006 * RTL not supported) 15007 */ 15008 private boolean isRtlCompatibilityMode() { 15009 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 15010 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 15011 } 15012 15013 /** 15014 * @return true if RTL properties need resolution. 15015 * 15016 */ 15017 private boolean needRtlPropertiesResolution() { 15018 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 15019 } 15020 15021 /** 15022 * Called when any RTL property (layout direction or text direction or text alignment) has 15023 * been changed. 15024 * 15025 * Subclasses need to override this method to take care of cached information that depends on the 15026 * resolved layout direction, or to inform child views that inherit their layout direction. 15027 * 15028 * The default implementation does nothing. 15029 * 15030 * @param layoutDirection the direction of the layout 15031 * 15032 * @see #LAYOUT_DIRECTION_LTR 15033 * @see #LAYOUT_DIRECTION_RTL 15034 */ 15035 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 15036 } 15037 15038 /** 15039 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 15040 * that the parent directionality can and will be resolved before its children. 15041 * 15042 * @return true if resolution has been done, false otherwise. 15043 * 15044 * @hide 15045 */ 15046 public boolean resolveLayoutDirection() { 15047 // Clear any previous layout direction resolution 15048 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15049 15050 if (hasRtlSupport()) { 15051 // Set resolved depending on layout direction 15052 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 15053 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 15054 case LAYOUT_DIRECTION_INHERIT: 15055 // We cannot resolve yet. LTR is by default and let the resolution happen again 15056 // later to get the correct resolved value 15057 if (!canResolveLayoutDirection()) return false; 15058 15059 // Parent has not yet resolved, LTR is still the default 15060 try { 15061 if (!mParent.isLayoutDirectionResolved()) return false; 15062 15063 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 15064 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15065 } 15066 } catch (AbstractMethodError e) { 15067 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15068 " does not fully implement ViewParent", e); 15069 } 15070 break; 15071 case LAYOUT_DIRECTION_RTL: 15072 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15073 break; 15074 case LAYOUT_DIRECTION_LOCALE: 15075 if((LAYOUT_DIRECTION_RTL == 15076 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 15077 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15078 } 15079 break; 15080 default: 15081 // Nothing to do, LTR by default 15082 } 15083 } 15084 15085 // Set to resolved 15086 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15087 return true; 15088 } 15089 15090 /** 15091 * Check if layout direction resolution can be done. 15092 * 15093 * @return true if layout direction resolution can be done otherwise return false. 15094 */ 15095 public boolean canResolveLayoutDirection() { 15096 switch (getRawLayoutDirection()) { 15097 case LAYOUT_DIRECTION_INHERIT: 15098 if (mParent != null) { 15099 try { 15100 return mParent.canResolveLayoutDirection(); 15101 } catch (AbstractMethodError e) { 15102 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15103 " does not fully implement ViewParent", e); 15104 } 15105 } 15106 return false; 15107 15108 default: 15109 return true; 15110 } 15111 } 15112 15113 /** 15114 * Reset the resolved layout direction. Layout direction will be resolved during a call to 15115 * {@link #onMeasure(int, int)}. 15116 * 15117 * @hide 15118 */ 15119 public void resetResolvedLayoutDirection() { 15120 // Reset the current resolved bits 15121 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15122 } 15123 15124 /** 15125 * @return true if the layout direction is inherited. 15126 * 15127 * @hide 15128 */ 15129 public boolean isLayoutDirectionInherited() { 15130 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 15131 } 15132 15133 /** 15134 * @return true if layout direction has been resolved. 15135 */ 15136 public boolean isLayoutDirectionResolved() { 15137 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15138 } 15139 15140 /** 15141 * Return if padding has been resolved 15142 * 15143 * @hide 15144 */ 15145 boolean isPaddingResolved() { 15146 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 15147 } 15148 15149 /** 15150 * Resolves padding depending on layout direction, if applicable, and 15151 * recomputes internal padding values to adjust for scroll bars. 15152 * 15153 * @hide 15154 */ 15155 public void resolvePadding() { 15156 final int resolvedLayoutDirection = getLayoutDirection(); 15157 15158 if (!isRtlCompatibilityMode()) { 15159 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 15160 // If start / end padding are defined, they will be resolved (hence overriding) to 15161 // left / right or right / left depending on the resolved layout direction. 15162 // If start / end padding are not defined, use the left / right ones. 15163 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 15164 Rect padding = sThreadLocal.get(); 15165 if (padding == null) { 15166 padding = new Rect(); 15167 sThreadLocal.set(padding); 15168 } 15169 mBackground.getPadding(padding); 15170 if (!mLeftPaddingDefined) { 15171 mUserPaddingLeftInitial = padding.left; 15172 } 15173 if (!mRightPaddingDefined) { 15174 mUserPaddingRightInitial = padding.right; 15175 } 15176 } 15177 switch (resolvedLayoutDirection) { 15178 case LAYOUT_DIRECTION_RTL: 15179 if (mUserPaddingStart != UNDEFINED_PADDING) { 15180 mUserPaddingRight = mUserPaddingStart; 15181 } else { 15182 mUserPaddingRight = mUserPaddingRightInitial; 15183 } 15184 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15185 mUserPaddingLeft = mUserPaddingEnd; 15186 } else { 15187 mUserPaddingLeft = mUserPaddingLeftInitial; 15188 } 15189 break; 15190 case LAYOUT_DIRECTION_LTR: 15191 default: 15192 if (mUserPaddingStart != UNDEFINED_PADDING) { 15193 mUserPaddingLeft = mUserPaddingStart; 15194 } else { 15195 mUserPaddingLeft = mUserPaddingLeftInitial; 15196 } 15197 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15198 mUserPaddingRight = mUserPaddingEnd; 15199 } else { 15200 mUserPaddingRight = mUserPaddingRightInitial; 15201 } 15202 } 15203 15204 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 15205 } 15206 15207 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15208 onRtlPropertiesChanged(resolvedLayoutDirection); 15209 15210 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 15211 } 15212 15213 /** 15214 * Reset the resolved layout direction. 15215 * 15216 * @hide 15217 */ 15218 public void resetResolvedPadding() { 15219 resetResolvedPaddingInternal(); 15220 } 15221 15222 /** 15223 * Used when we only want to reset *this* view's padding and not trigger overrides 15224 * in ViewGroup that reset children too. 15225 */ 15226 void resetResolvedPaddingInternal() { 15227 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 15228 } 15229 15230 /** 15231 * This is called when the view is detached from a window. At this point it 15232 * no longer has a surface for drawing. 15233 * 15234 * @see #onAttachedToWindow() 15235 */ 15236 @CallSuper 15237 protected void onDetachedFromWindow() { 15238 } 15239 15240 /** 15241 * This is a framework-internal mirror of onDetachedFromWindow() that's called 15242 * after onDetachedFromWindow(). 15243 * 15244 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 15245 * The super method should be called at the end of the overridden method to ensure 15246 * subclasses are destroyed first 15247 * 15248 * @hide 15249 */ 15250 @CallSuper 15251 protected void onDetachedFromWindowInternal() { 15252 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 15253 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15254 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 15255 15256 removeUnsetPressCallback(); 15257 removeLongPressCallback(); 15258 removePerformClickCallback(); 15259 removeSendViewScrolledAccessibilityEventCallback(); 15260 stopNestedScroll(); 15261 15262 // Anything that started animating right before detach should already 15263 // be in its final state when re-attached. 15264 jumpDrawablesToCurrentState(); 15265 15266 destroyDrawingCache(); 15267 15268 cleanupDraw(); 15269 releasePointerCapture(); 15270 mCurrentAnimation = null; 15271 } 15272 15273 private void cleanupDraw() { 15274 resetDisplayList(); 15275 if (mAttachInfo != null) { 15276 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 15277 } 15278 } 15279 15280 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 15281 } 15282 15283 /** 15284 * @return The number of times this view has been attached to a window 15285 */ 15286 protected int getWindowAttachCount() { 15287 return mWindowAttachCount; 15288 } 15289 15290 /** 15291 * Retrieve a unique token identifying the window this view is attached to. 15292 * @return Return the window's token for use in 15293 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 15294 */ 15295 public IBinder getWindowToken() { 15296 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 15297 } 15298 15299 /** 15300 * Retrieve the {@link WindowId} for the window this view is 15301 * currently attached to. 15302 */ 15303 public WindowId getWindowId() { 15304 if (mAttachInfo == null) { 15305 return null; 15306 } 15307 if (mAttachInfo.mWindowId == null) { 15308 try { 15309 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 15310 mAttachInfo.mWindowToken); 15311 mAttachInfo.mWindowId = new WindowId( 15312 mAttachInfo.mIWindowId); 15313 } catch (RemoteException e) { 15314 } 15315 } 15316 return mAttachInfo.mWindowId; 15317 } 15318 15319 /** 15320 * Retrieve a unique token identifying the top-level "real" window of 15321 * the window that this view is attached to. That is, this is like 15322 * {@link #getWindowToken}, except if the window this view in is a panel 15323 * window (attached to another containing window), then the token of 15324 * the containing window is returned instead. 15325 * 15326 * @return Returns the associated window token, either 15327 * {@link #getWindowToken()} or the containing window's token. 15328 */ 15329 public IBinder getApplicationWindowToken() { 15330 AttachInfo ai = mAttachInfo; 15331 if (ai != null) { 15332 IBinder appWindowToken = ai.mPanelParentWindowToken; 15333 if (appWindowToken == null) { 15334 appWindowToken = ai.mWindowToken; 15335 } 15336 return appWindowToken; 15337 } 15338 return null; 15339 } 15340 15341 /** 15342 * Gets the logical display to which the view's window has been attached. 15343 * 15344 * @return The logical display, or null if the view is not currently attached to a window. 15345 */ 15346 public Display getDisplay() { 15347 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 15348 } 15349 15350 /** 15351 * Retrieve private session object this view hierarchy is using to 15352 * communicate with the window manager. 15353 * @return the session object to communicate with the window manager 15354 */ 15355 /*package*/ IWindowSession getWindowSession() { 15356 return mAttachInfo != null ? mAttachInfo.mSession : null; 15357 } 15358 15359 /** 15360 * Return the visibility value of the least visible component passed. 15361 */ 15362 int combineVisibility(int vis1, int vis2) { 15363 // This works because VISIBLE < INVISIBLE < GONE. 15364 return Math.max(vis1, vis2); 15365 } 15366 15367 /** 15368 * @param info the {@link android.view.View.AttachInfo} to associated with 15369 * this view 15370 */ 15371 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 15372 mAttachInfo = info; 15373 if (mOverlay != null) { 15374 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 15375 } 15376 mWindowAttachCount++; 15377 // We will need to evaluate the drawable state at least once. 15378 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15379 if (mFloatingTreeObserver != null) { 15380 info.mTreeObserver.merge(mFloatingTreeObserver); 15381 mFloatingTreeObserver = null; 15382 } 15383 15384 registerPendingFrameMetricsObservers(); 15385 15386 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 15387 mAttachInfo.mScrollContainers.add(this); 15388 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 15389 } 15390 // Transfer all pending runnables. 15391 if (mRunQueue != null) { 15392 mRunQueue.executeActions(info.mHandler); 15393 mRunQueue = null; 15394 } 15395 performCollectViewAttributes(mAttachInfo, visibility); 15396 onAttachedToWindow(); 15397 15398 ListenerInfo li = mListenerInfo; 15399 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15400 li != null ? li.mOnAttachStateChangeListeners : null; 15401 if (listeners != null && listeners.size() > 0) { 15402 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15403 // perform the dispatching. The iterator is a safe guard against listeners that 15404 // could mutate the list by calling the various add/remove methods. This prevents 15405 // the array from being modified while we iterate it. 15406 for (OnAttachStateChangeListener listener : listeners) { 15407 listener.onViewAttachedToWindow(this); 15408 } 15409 } 15410 15411 int vis = info.mWindowVisibility; 15412 if (vis != GONE) { 15413 onWindowVisibilityChanged(vis); 15414 if (isShown()) { 15415 // Calling onVisibilityChanged directly here since the subtree will also 15416 // receive dispatchAttachedToWindow and this same call 15417 onVisibilityAggregated(vis == VISIBLE); 15418 } 15419 } 15420 15421 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 15422 // As all views in the subtree will already receive dispatchAttachedToWindow 15423 // traversing the subtree again here is not desired. 15424 onVisibilityChanged(this, visibility); 15425 15426 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 15427 // If nobody has evaluated the drawable state yet, then do it now. 15428 refreshDrawableState(); 15429 } 15430 needGlobalAttributesUpdate(false); 15431 } 15432 15433 void dispatchDetachedFromWindow() { 15434 AttachInfo info = mAttachInfo; 15435 if (info != null) { 15436 int vis = info.mWindowVisibility; 15437 if (vis != GONE) { 15438 onWindowVisibilityChanged(GONE); 15439 if (isShown()) { 15440 // Invoking onVisibilityAggregated directly here since the subtree 15441 // will also receive detached from window 15442 onVisibilityAggregated(false); 15443 } 15444 } 15445 } 15446 15447 onDetachedFromWindow(); 15448 onDetachedFromWindowInternal(); 15449 15450 InputMethodManager imm = InputMethodManager.peekInstance(); 15451 if (imm != null) { 15452 imm.onViewDetachedFromWindow(this); 15453 } 15454 15455 ListenerInfo li = mListenerInfo; 15456 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15457 li != null ? li.mOnAttachStateChangeListeners : null; 15458 if (listeners != null && listeners.size() > 0) { 15459 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15460 // perform the dispatching. The iterator is a safe guard against listeners that 15461 // could mutate the list by calling the various add/remove methods. This prevents 15462 // the array from being modified while we iterate it. 15463 for (OnAttachStateChangeListener listener : listeners) { 15464 listener.onViewDetachedFromWindow(this); 15465 } 15466 } 15467 15468 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 15469 mAttachInfo.mScrollContainers.remove(this); 15470 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 15471 } 15472 15473 mAttachInfo = null; 15474 if (mOverlay != null) { 15475 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 15476 } 15477 } 15478 15479 /** 15480 * Cancel any deferred high-level input events that were previously posted to the event queue. 15481 * 15482 * <p>Many views post high-level events such as click handlers to the event queue 15483 * to run deferred in order to preserve a desired user experience - clearing visible 15484 * pressed states before executing, etc. This method will abort any events of this nature 15485 * that are currently in flight.</p> 15486 * 15487 * <p>Custom views that generate their own high-level deferred input events should override 15488 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 15489 * 15490 * <p>This will also cancel pending input events for any child views.</p> 15491 * 15492 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 15493 * This will not impact newer events posted after this call that may occur as a result of 15494 * lower-level input events still waiting in the queue. If you are trying to prevent 15495 * double-submitted events for the duration of some sort of asynchronous transaction 15496 * you should also take other steps to protect against unexpected double inputs e.g. calling 15497 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 15498 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 15499 */ 15500 public final void cancelPendingInputEvents() { 15501 dispatchCancelPendingInputEvents(); 15502 } 15503 15504 /** 15505 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 15506 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 15507 */ 15508 void dispatchCancelPendingInputEvents() { 15509 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 15510 onCancelPendingInputEvents(); 15511 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 15512 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 15513 " did not call through to super.onCancelPendingInputEvents()"); 15514 } 15515 } 15516 15517 /** 15518 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 15519 * a parent view. 15520 * 15521 * <p>This method is responsible for removing any pending high-level input events that were 15522 * posted to the event queue to run later. Custom view classes that post their own deferred 15523 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 15524 * {@link android.os.Handler} should override this method, call 15525 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 15526 * </p> 15527 */ 15528 public void onCancelPendingInputEvents() { 15529 removePerformClickCallback(); 15530 cancelLongPress(); 15531 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 15532 } 15533 15534 /** 15535 * Store this view hierarchy's frozen state into the given container. 15536 * 15537 * @param container The SparseArray in which to save the view's state. 15538 * 15539 * @see #restoreHierarchyState(android.util.SparseArray) 15540 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15541 * @see #onSaveInstanceState() 15542 */ 15543 public void saveHierarchyState(SparseArray<Parcelable> container) { 15544 dispatchSaveInstanceState(container); 15545 } 15546 15547 /** 15548 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 15549 * this view and its children. May be overridden to modify how freezing happens to a 15550 * view's children; for example, some views may want to not store state for their children. 15551 * 15552 * @param container The SparseArray in which to save the view's state. 15553 * 15554 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15555 * @see #saveHierarchyState(android.util.SparseArray) 15556 * @see #onSaveInstanceState() 15557 */ 15558 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 15559 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 15560 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15561 Parcelable state = onSaveInstanceState(); 15562 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15563 throw new IllegalStateException( 15564 "Derived class did not call super.onSaveInstanceState()"); 15565 } 15566 if (state != null) { 15567 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 15568 // + ": " + state); 15569 container.put(mID, state); 15570 } 15571 } 15572 } 15573 15574 /** 15575 * Hook allowing a view to generate a representation of its internal state 15576 * that can later be used to create a new instance with that same state. 15577 * This state should only contain information that is not persistent or can 15578 * not be reconstructed later. For example, you will never store your 15579 * current position on screen because that will be computed again when a 15580 * new instance of the view is placed in its view hierarchy. 15581 * <p> 15582 * Some examples of things you may store here: the current cursor position 15583 * in a text view (but usually not the text itself since that is stored in a 15584 * content provider or other persistent storage), the currently selected 15585 * item in a list view. 15586 * 15587 * @return Returns a Parcelable object containing the view's current dynamic 15588 * state, or null if there is nothing interesting to save. The 15589 * default implementation returns null. 15590 * @see #onRestoreInstanceState(android.os.Parcelable) 15591 * @see #saveHierarchyState(android.util.SparseArray) 15592 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15593 * @see #setSaveEnabled(boolean) 15594 */ 15595 @CallSuper 15596 protected Parcelable onSaveInstanceState() { 15597 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15598 if (mStartActivityRequestWho != null) { 15599 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 15600 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 15601 return state; 15602 } 15603 return BaseSavedState.EMPTY_STATE; 15604 } 15605 15606 /** 15607 * Restore this view hierarchy's frozen state from the given container. 15608 * 15609 * @param container The SparseArray which holds previously frozen states. 15610 * 15611 * @see #saveHierarchyState(android.util.SparseArray) 15612 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15613 * @see #onRestoreInstanceState(android.os.Parcelable) 15614 */ 15615 public void restoreHierarchyState(SparseArray<Parcelable> container) { 15616 dispatchRestoreInstanceState(container); 15617 } 15618 15619 /** 15620 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 15621 * state for this view and its children. May be overridden to modify how restoring 15622 * happens to a view's children; for example, some views may want to not store state 15623 * for their children. 15624 * 15625 * @param container The SparseArray which holds previously saved state. 15626 * 15627 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15628 * @see #restoreHierarchyState(android.util.SparseArray) 15629 * @see #onRestoreInstanceState(android.os.Parcelable) 15630 */ 15631 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 15632 if (mID != NO_ID) { 15633 Parcelable state = container.get(mID); 15634 if (state != null) { 15635 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 15636 // + ": " + state); 15637 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15638 onRestoreInstanceState(state); 15639 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15640 throw new IllegalStateException( 15641 "Derived class did not call super.onRestoreInstanceState()"); 15642 } 15643 } 15644 } 15645 } 15646 15647 /** 15648 * Hook allowing a view to re-apply a representation of its internal state that had previously 15649 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 15650 * null state. 15651 * 15652 * @param state The frozen state that had previously been returned by 15653 * {@link #onSaveInstanceState}. 15654 * 15655 * @see #onSaveInstanceState() 15656 * @see #restoreHierarchyState(android.util.SparseArray) 15657 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15658 */ 15659 @CallSuper 15660 protected void onRestoreInstanceState(Parcelable state) { 15661 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15662 if (state != null && !(state instanceof AbsSavedState)) { 15663 throw new IllegalArgumentException("Wrong state class, expecting View State but " 15664 + "received " + state.getClass().toString() + " instead. This usually happens " 15665 + "when two views of different type have the same id in the same hierarchy. " 15666 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 15667 + "other views do not use the same id."); 15668 } 15669 if (state != null && state instanceof BaseSavedState) { 15670 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 15671 } 15672 } 15673 15674 /** 15675 * <p>Return the time at which the drawing of the view hierarchy started.</p> 15676 * 15677 * @return the drawing start time in milliseconds 15678 */ 15679 public long getDrawingTime() { 15680 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 15681 } 15682 15683 /** 15684 * <p>Enables or disables the duplication of the parent's state into this view. When 15685 * duplication is enabled, this view gets its drawable state from its parent rather 15686 * than from its own internal properties.</p> 15687 * 15688 * <p>Note: in the current implementation, setting this property to true after the 15689 * view was added to a ViewGroup might have no effect at all. This property should 15690 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 15691 * 15692 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 15693 * property is enabled, an exception will be thrown.</p> 15694 * 15695 * <p>Note: if the child view uses and updates additional states which are unknown to the 15696 * parent, these states should not be affected by this method.</p> 15697 * 15698 * @param enabled True to enable duplication of the parent's drawable state, false 15699 * to disable it. 15700 * 15701 * @see #getDrawableState() 15702 * @see #isDuplicateParentStateEnabled() 15703 */ 15704 public void setDuplicateParentStateEnabled(boolean enabled) { 15705 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 15706 } 15707 15708 /** 15709 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 15710 * 15711 * @return True if this view's drawable state is duplicated from the parent, 15712 * false otherwise 15713 * 15714 * @see #getDrawableState() 15715 * @see #setDuplicateParentStateEnabled(boolean) 15716 */ 15717 public boolean isDuplicateParentStateEnabled() { 15718 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 15719 } 15720 15721 /** 15722 * <p>Specifies the type of layer backing this view. The layer can be 15723 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15724 * {@link #LAYER_TYPE_HARDWARE}.</p> 15725 * 15726 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15727 * instance that controls how the layer is composed on screen. The following 15728 * properties of the paint are taken into account when composing the layer:</p> 15729 * <ul> 15730 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15731 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15732 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15733 * </ul> 15734 * 15735 * <p>If this view has an alpha value set to < 1.0 by calling 15736 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 15737 * by this view's alpha value.</p> 15738 * 15739 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 15740 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 15741 * for more information on when and how to use layers.</p> 15742 * 15743 * @param layerType The type of layer to use with this view, must be one of 15744 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15745 * {@link #LAYER_TYPE_HARDWARE} 15746 * @param paint The paint used to compose the layer. This argument is optional 15747 * and can be null. It is ignored when the layer type is 15748 * {@link #LAYER_TYPE_NONE} 15749 * 15750 * @see #getLayerType() 15751 * @see #LAYER_TYPE_NONE 15752 * @see #LAYER_TYPE_SOFTWARE 15753 * @see #LAYER_TYPE_HARDWARE 15754 * @see #setAlpha(float) 15755 * 15756 * @attr ref android.R.styleable#View_layerType 15757 */ 15758 public void setLayerType(int layerType, @Nullable Paint paint) { 15759 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 15760 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 15761 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 15762 } 15763 15764 boolean typeChanged = mRenderNode.setLayerType(layerType); 15765 15766 if (!typeChanged) { 15767 setLayerPaint(paint); 15768 return; 15769 } 15770 15771 if (layerType != LAYER_TYPE_SOFTWARE) { 15772 // Destroy any previous software drawing cache if present 15773 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 15774 // drawing cache created in View#draw when drawing to a SW canvas. 15775 destroyDrawingCache(); 15776 } 15777 15778 mLayerType = layerType; 15779 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 15780 mRenderNode.setLayerPaint(mLayerPaint); 15781 15782 // draw() behaves differently if we are on a layer, so we need to 15783 // invalidate() here 15784 invalidateParentCaches(); 15785 invalidate(true); 15786 } 15787 15788 /** 15789 * Updates the {@link Paint} object used with the current layer (used only if the current 15790 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 15791 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 15792 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 15793 * ensure that the view gets redrawn immediately. 15794 * 15795 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15796 * instance that controls how the layer is composed on screen. The following 15797 * properties of the paint are taken into account when composing the layer:</p> 15798 * <ul> 15799 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15800 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15801 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15802 * </ul> 15803 * 15804 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 15805 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 15806 * 15807 * @param paint The paint used to compose the layer. This argument is optional 15808 * and can be null. It is ignored when the layer type is 15809 * {@link #LAYER_TYPE_NONE} 15810 * 15811 * @see #setLayerType(int, android.graphics.Paint) 15812 */ 15813 public void setLayerPaint(@Nullable Paint paint) { 15814 int layerType = getLayerType(); 15815 if (layerType != LAYER_TYPE_NONE) { 15816 mLayerPaint = paint; 15817 if (layerType == LAYER_TYPE_HARDWARE) { 15818 if (mRenderNode.setLayerPaint(paint)) { 15819 invalidateViewProperty(false, false); 15820 } 15821 } else { 15822 invalidate(); 15823 } 15824 } 15825 } 15826 15827 /** 15828 * Indicates what type of layer is currently associated with this view. By default 15829 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 15830 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 15831 * for more information on the different types of layers. 15832 * 15833 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15834 * {@link #LAYER_TYPE_HARDWARE} 15835 * 15836 * @see #setLayerType(int, android.graphics.Paint) 15837 * @see #buildLayer() 15838 * @see #LAYER_TYPE_NONE 15839 * @see #LAYER_TYPE_SOFTWARE 15840 * @see #LAYER_TYPE_HARDWARE 15841 */ 15842 public int getLayerType() { 15843 return mLayerType; 15844 } 15845 15846 /** 15847 * Forces this view's layer to be created and this view to be rendered 15848 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 15849 * invoking this method will have no effect. 15850 * 15851 * This method can for instance be used to render a view into its layer before 15852 * starting an animation. If this view is complex, rendering into the layer 15853 * before starting the animation will avoid skipping frames. 15854 * 15855 * @throws IllegalStateException If this view is not attached to a window 15856 * 15857 * @see #setLayerType(int, android.graphics.Paint) 15858 */ 15859 public void buildLayer() { 15860 if (mLayerType == LAYER_TYPE_NONE) return; 15861 15862 final AttachInfo attachInfo = mAttachInfo; 15863 if (attachInfo == null) { 15864 throw new IllegalStateException("This view must be attached to a window first"); 15865 } 15866 15867 if (getWidth() == 0 || getHeight() == 0) { 15868 return; 15869 } 15870 15871 switch (mLayerType) { 15872 case LAYER_TYPE_HARDWARE: 15873 updateDisplayListIfDirty(); 15874 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 15875 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 15876 } 15877 break; 15878 case LAYER_TYPE_SOFTWARE: 15879 buildDrawingCache(true); 15880 break; 15881 } 15882 } 15883 15884 /** 15885 * Destroys all hardware rendering resources. This method is invoked 15886 * when the system needs to reclaim resources. Upon execution of this 15887 * method, you should free any OpenGL resources created by the view. 15888 * 15889 * Note: you <strong>must</strong> call 15890 * <code>super.destroyHardwareResources()</code> when overriding 15891 * this method. 15892 * 15893 * @hide 15894 */ 15895 @CallSuper 15896 protected void destroyHardwareResources() { 15897 // Although the Layer will be destroyed by RenderNode, we want to release 15898 // the staging display list, which is also a signal to RenderNode that it's 15899 // safe to free its copy of the display list as it knows that we will 15900 // push an updated DisplayList if we try to draw again 15901 resetDisplayList(); 15902 } 15903 15904 /** 15905 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 15906 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 15907 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 15908 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 15909 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 15910 * null.</p> 15911 * 15912 * <p>Enabling the drawing cache is similar to 15913 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 15914 * acceleration is turned off. When hardware acceleration is turned on, enabling the 15915 * drawing cache has no effect on rendering because the system uses a different mechanism 15916 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 15917 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 15918 * for information on how to enable software and hardware layers.</p> 15919 * 15920 * <p>This API can be used to manually generate 15921 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 15922 * {@link #getDrawingCache()}.</p> 15923 * 15924 * @param enabled true to enable the drawing cache, false otherwise 15925 * 15926 * @see #isDrawingCacheEnabled() 15927 * @see #getDrawingCache() 15928 * @see #buildDrawingCache() 15929 * @see #setLayerType(int, android.graphics.Paint) 15930 */ 15931 public void setDrawingCacheEnabled(boolean enabled) { 15932 mCachingFailed = false; 15933 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 15934 } 15935 15936 /** 15937 * <p>Indicates whether the drawing cache is enabled for this view.</p> 15938 * 15939 * @return true if the drawing cache is enabled 15940 * 15941 * @see #setDrawingCacheEnabled(boolean) 15942 * @see #getDrawingCache() 15943 */ 15944 @ViewDebug.ExportedProperty(category = "drawing") 15945 public boolean isDrawingCacheEnabled() { 15946 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 15947 } 15948 15949 /** 15950 * Debugging utility which recursively outputs the dirty state of a view and its 15951 * descendants. 15952 * 15953 * @hide 15954 */ 15955 @SuppressWarnings({"UnusedDeclaration"}) 15956 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 15957 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 15958 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 15959 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 15960 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 15961 if (clear) { 15962 mPrivateFlags &= clearMask; 15963 } 15964 if (this instanceof ViewGroup) { 15965 ViewGroup parent = (ViewGroup) this; 15966 final int count = parent.getChildCount(); 15967 for (int i = 0; i < count; i++) { 15968 final View child = parent.getChildAt(i); 15969 child.outputDirtyFlags(indent + " ", clear, clearMask); 15970 } 15971 } 15972 } 15973 15974 /** 15975 * This method is used by ViewGroup to cause its children to restore or recreate their 15976 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 15977 * to recreate its own display list, which would happen if it went through the normal 15978 * draw/dispatchDraw mechanisms. 15979 * 15980 * @hide 15981 */ 15982 protected void dispatchGetDisplayList() {} 15983 15984 /** 15985 * A view that is not attached or hardware accelerated cannot create a display list. 15986 * This method checks these conditions and returns the appropriate result. 15987 * 15988 * @return true if view has the ability to create a display list, false otherwise. 15989 * 15990 * @hide 15991 */ 15992 public boolean canHaveDisplayList() { 15993 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 15994 } 15995 15996 /** 15997 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 15998 * @hide 15999 */ 16000 @NonNull 16001 public RenderNode updateDisplayListIfDirty() { 16002 final RenderNode renderNode = mRenderNode; 16003 if (!canHaveDisplayList()) { 16004 // can't populate RenderNode, don't try 16005 return renderNode; 16006 } 16007 16008 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 16009 || !renderNode.isValid() 16010 || (mRecreateDisplayList)) { 16011 // Don't need to recreate the display list, just need to tell our 16012 // children to restore/recreate theirs 16013 if (renderNode.isValid() 16014 && !mRecreateDisplayList) { 16015 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16016 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16017 dispatchGetDisplayList(); 16018 16019 return renderNode; // no work needed 16020 } 16021 16022 // If we got here, we're recreating it. Mark it as such to ensure that 16023 // we copy in child display lists into ours in drawChild() 16024 mRecreateDisplayList = true; 16025 16026 int width = mRight - mLeft; 16027 int height = mBottom - mTop; 16028 int layerType = getLayerType(); 16029 16030 final DisplayListCanvas canvas = renderNode.start(width, height); 16031 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 16032 16033 try { 16034 if (layerType == LAYER_TYPE_SOFTWARE) { 16035 buildDrawingCache(true); 16036 Bitmap cache = getDrawingCache(true); 16037 if (cache != null) { 16038 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 16039 } 16040 } else { 16041 computeScroll(); 16042 16043 canvas.translate(-mScrollX, -mScrollY); 16044 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16045 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16046 16047 // Fast path for layouts with no backgrounds 16048 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16049 dispatchDraw(canvas); 16050 if (mOverlay != null && !mOverlay.isEmpty()) { 16051 mOverlay.getOverlayView().draw(canvas); 16052 } 16053 } else { 16054 draw(canvas); 16055 } 16056 } 16057 } finally { 16058 renderNode.end(canvas); 16059 setDisplayListProperties(renderNode); 16060 } 16061 } else { 16062 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16063 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16064 } 16065 return renderNode; 16066 } 16067 16068 private void resetDisplayList() { 16069 if (mRenderNode.isValid()) { 16070 mRenderNode.discardDisplayList(); 16071 } 16072 16073 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 16074 mBackgroundRenderNode.discardDisplayList(); 16075 } 16076 } 16077 16078 /** 16079 * Called when the passed RenderNode is removed from the draw tree 16080 * @hide 16081 */ 16082 public void onRenderNodeDetached(RenderNode renderNode) { 16083 } 16084 16085 /** 16086 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 16087 * 16088 * @return A non-scaled bitmap representing this view or null if cache is disabled. 16089 * 16090 * @see #getDrawingCache(boolean) 16091 */ 16092 public Bitmap getDrawingCache() { 16093 return getDrawingCache(false); 16094 } 16095 16096 /** 16097 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 16098 * is null when caching is disabled. If caching is enabled and the cache is not ready, 16099 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 16100 * draw from the cache when the cache is enabled. To benefit from the cache, you must 16101 * request the drawing cache by calling this method and draw it on screen if the 16102 * returned bitmap is not null.</p> 16103 * 16104 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16105 * this method will create a bitmap of the same size as this view. Because this bitmap 16106 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16107 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16108 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16109 * size than the view. This implies that your application must be able to handle this 16110 * size.</p> 16111 * 16112 * @param autoScale Indicates whether the generated bitmap should be scaled based on 16113 * the current density of the screen when the application is in compatibility 16114 * mode. 16115 * 16116 * @return A bitmap representing this view or null if cache is disabled. 16117 * 16118 * @see #setDrawingCacheEnabled(boolean) 16119 * @see #isDrawingCacheEnabled() 16120 * @see #buildDrawingCache(boolean) 16121 * @see #destroyDrawingCache() 16122 */ 16123 public Bitmap getDrawingCache(boolean autoScale) { 16124 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 16125 return null; 16126 } 16127 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 16128 buildDrawingCache(autoScale); 16129 } 16130 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 16131 } 16132 16133 /** 16134 * <p>Frees the resources used by the drawing cache. If you call 16135 * {@link #buildDrawingCache()} manually without calling 16136 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16137 * should cleanup the cache with this method afterwards.</p> 16138 * 16139 * @see #setDrawingCacheEnabled(boolean) 16140 * @see #buildDrawingCache() 16141 * @see #getDrawingCache() 16142 */ 16143 public void destroyDrawingCache() { 16144 if (mDrawingCache != null) { 16145 mDrawingCache.recycle(); 16146 mDrawingCache = null; 16147 } 16148 if (mUnscaledDrawingCache != null) { 16149 mUnscaledDrawingCache.recycle(); 16150 mUnscaledDrawingCache = null; 16151 } 16152 } 16153 16154 /** 16155 * Setting a solid background color for the drawing cache's bitmaps will improve 16156 * performance and memory usage. Note, though that this should only be used if this 16157 * view will always be drawn on top of a solid color. 16158 * 16159 * @param color The background color to use for the drawing cache's bitmap 16160 * 16161 * @see #setDrawingCacheEnabled(boolean) 16162 * @see #buildDrawingCache() 16163 * @see #getDrawingCache() 16164 */ 16165 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 16166 if (color != mDrawingCacheBackgroundColor) { 16167 mDrawingCacheBackgroundColor = color; 16168 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 16169 } 16170 } 16171 16172 /** 16173 * @see #setDrawingCacheBackgroundColor(int) 16174 * 16175 * @return The background color to used for the drawing cache's bitmap 16176 */ 16177 @ColorInt 16178 public int getDrawingCacheBackgroundColor() { 16179 return mDrawingCacheBackgroundColor; 16180 } 16181 16182 /** 16183 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 16184 * 16185 * @see #buildDrawingCache(boolean) 16186 */ 16187 public void buildDrawingCache() { 16188 buildDrawingCache(false); 16189 } 16190 16191 /** 16192 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 16193 * 16194 * <p>If you call {@link #buildDrawingCache()} manually without calling 16195 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16196 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 16197 * 16198 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16199 * this method will create a bitmap of the same size as this view. Because this bitmap 16200 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16201 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16202 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16203 * size than the view. This implies that your application must be able to handle this 16204 * size.</p> 16205 * 16206 * <p>You should avoid calling this method when hardware acceleration is enabled. If 16207 * you do not need the drawing cache bitmap, calling this method will increase memory 16208 * usage and cause the view to be rendered in software once, thus negatively impacting 16209 * performance.</p> 16210 * 16211 * @see #getDrawingCache() 16212 * @see #destroyDrawingCache() 16213 */ 16214 public void buildDrawingCache(boolean autoScale) { 16215 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 16216 mDrawingCache == null : mUnscaledDrawingCache == null)) { 16217 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 16218 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 16219 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 16220 } 16221 try { 16222 buildDrawingCacheImpl(autoScale); 16223 } finally { 16224 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 16225 } 16226 } 16227 } 16228 16229 /** 16230 * private, internal implementation of buildDrawingCache, used to enable tracing 16231 */ 16232 private void buildDrawingCacheImpl(boolean autoScale) { 16233 mCachingFailed = false; 16234 16235 int width = mRight - mLeft; 16236 int height = mBottom - mTop; 16237 16238 final AttachInfo attachInfo = mAttachInfo; 16239 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 16240 16241 if (autoScale && scalingRequired) { 16242 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 16243 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 16244 } 16245 16246 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 16247 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 16248 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 16249 16250 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 16251 final long drawingCacheSize = 16252 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 16253 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 16254 if (width > 0 && height > 0) { 16255 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 16256 + " too large to fit into a software layer (or drawing cache), needs " 16257 + projectedBitmapSize + " bytes, only " 16258 + drawingCacheSize + " available"); 16259 } 16260 destroyDrawingCache(); 16261 mCachingFailed = true; 16262 return; 16263 } 16264 16265 boolean clear = true; 16266 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 16267 16268 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 16269 Bitmap.Config quality; 16270 if (!opaque) { 16271 // Never pick ARGB_4444 because it looks awful 16272 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 16273 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 16274 case DRAWING_CACHE_QUALITY_AUTO: 16275 case DRAWING_CACHE_QUALITY_LOW: 16276 case DRAWING_CACHE_QUALITY_HIGH: 16277 default: 16278 quality = Bitmap.Config.ARGB_8888; 16279 break; 16280 } 16281 } else { 16282 // Optimization for translucent windows 16283 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 16284 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 16285 } 16286 16287 // Try to cleanup memory 16288 if (bitmap != null) bitmap.recycle(); 16289 16290 try { 16291 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16292 width, height, quality); 16293 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 16294 if (autoScale) { 16295 mDrawingCache = bitmap; 16296 } else { 16297 mUnscaledDrawingCache = bitmap; 16298 } 16299 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 16300 } catch (OutOfMemoryError e) { 16301 // If there is not enough memory to create the bitmap cache, just 16302 // ignore the issue as bitmap caches are not required to draw the 16303 // view hierarchy 16304 if (autoScale) { 16305 mDrawingCache = null; 16306 } else { 16307 mUnscaledDrawingCache = null; 16308 } 16309 mCachingFailed = true; 16310 return; 16311 } 16312 16313 clear = drawingCacheBackgroundColor != 0; 16314 } 16315 16316 Canvas canvas; 16317 if (attachInfo != null) { 16318 canvas = attachInfo.mCanvas; 16319 if (canvas == null) { 16320 canvas = new Canvas(); 16321 } 16322 canvas.setBitmap(bitmap); 16323 // Temporarily clobber the cached Canvas in case one of our children 16324 // is also using a drawing cache. Without this, the children would 16325 // steal the canvas by attaching their own bitmap to it and bad, bad 16326 // thing would happen (invisible views, corrupted drawings, etc.) 16327 attachInfo.mCanvas = null; 16328 } else { 16329 // This case should hopefully never or seldom happen 16330 canvas = new Canvas(bitmap); 16331 } 16332 16333 if (clear) { 16334 bitmap.eraseColor(drawingCacheBackgroundColor); 16335 } 16336 16337 computeScroll(); 16338 final int restoreCount = canvas.save(); 16339 16340 if (autoScale && scalingRequired) { 16341 final float scale = attachInfo.mApplicationScale; 16342 canvas.scale(scale, scale); 16343 } 16344 16345 canvas.translate(-mScrollX, -mScrollY); 16346 16347 mPrivateFlags |= PFLAG_DRAWN; 16348 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 16349 mLayerType != LAYER_TYPE_NONE) { 16350 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 16351 } 16352 16353 // Fast path for layouts with no backgrounds 16354 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16355 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16356 dispatchDraw(canvas); 16357 if (mOverlay != null && !mOverlay.isEmpty()) { 16358 mOverlay.getOverlayView().draw(canvas); 16359 } 16360 } else { 16361 draw(canvas); 16362 } 16363 16364 canvas.restoreToCount(restoreCount); 16365 canvas.setBitmap(null); 16366 16367 if (attachInfo != null) { 16368 // Restore the cached Canvas for our siblings 16369 attachInfo.mCanvas = canvas; 16370 } 16371 } 16372 16373 /** 16374 * Create a snapshot of the view into a bitmap. We should probably make 16375 * some form of this public, but should think about the API. 16376 * 16377 * @hide 16378 */ 16379 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 16380 int width = mRight - mLeft; 16381 int height = mBottom - mTop; 16382 16383 final AttachInfo attachInfo = mAttachInfo; 16384 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 16385 width = (int) ((width * scale) + 0.5f); 16386 height = (int) ((height * scale) + 0.5f); 16387 16388 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16389 width > 0 ? width : 1, height > 0 ? height : 1, quality); 16390 if (bitmap == null) { 16391 throw new OutOfMemoryError(); 16392 } 16393 16394 Resources resources = getResources(); 16395 if (resources != null) { 16396 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 16397 } 16398 16399 Canvas canvas; 16400 if (attachInfo != null) { 16401 canvas = attachInfo.mCanvas; 16402 if (canvas == null) { 16403 canvas = new Canvas(); 16404 } 16405 canvas.setBitmap(bitmap); 16406 // Temporarily clobber the cached Canvas in case one of our children 16407 // is also using a drawing cache. Without this, the children would 16408 // steal the canvas by attaching their own bitmap to it and bad, bad 16409 // things would happen (invisible views, corrupted drawings, etc.) 16410 attachInfo.mCanvas = null; 16411 } else { 16412 // This case should hopefully never or seldom happen 16413 canvas = new Canvas(bitmap); 16414 } 16415 16416 if ((backgroundColor & 0xff000000) != 0) { 16417 bitmap.eraseColor(backgroundColor); 16418 } 16419 16420 computeScroll(); 16421 final int restoreCount = canvas.save(); 16422 canvas.scale(scale, scale); 16423 canvas.translate(-mScrollX, -mScrollY); 16424 16425 // Temporarily remove the dirty mask 16426 int flags = mPrivateFlags; 16427 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16428 16429 // Fast path for layouts with no backgrounds 16430 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16431 dispatchDraw(canvas); 16432 if (mOverlay != null && !mOverlay.isEmpty()) { 16433 mOverlay.getOverlayView().draw(canvas); 16434 } 16435 } else { 16436 draw(canvas); 16437 } 16438 16439 mPrivateFlags = flags; 16440 16441 canvas.restoreToCount(restoreCount); 16442 canvas.setBitmap(null); 16443 16444 if (attachInfo != null) { 16445 // Restore the cached Canvas for our siblings 16446 attachInfo.mCanvas = canvas; 16447 } 16448 16449 return bitmap; 16450 } 16451 16452 /** 16453 * Indicates whether this View is currently in edit mode. A View is usually 16454 * in edit mode when displayed within a developer tool. For instance, if 16455 * this View is being drawn by a visual user interface builder, this method 16456 * should return true. 16457 * 16458 * Subclasses should check the return value of this method to provide 16459 * different behaviors if their normal behavior might interfere with the 16460 * host environment. For instance: the class spawns a thread in its 16461 * constructor, the drawing code relies on device-specific features, etc. 16462 * 16463 * This method is usually checked in the drawing code of custom widgets. 16464 * 16465 * @return True if this View is in edit mode, false otherwise. 16466 */ 16467 public boolean isInEditMode() { 16468 return false; 16469 } 16470 16471 /** 16472 * If the View draws content inside its padding and enables fading edges, 16473 * it needs to support padding offsets. Padding offsets are added to the 16474 * fading edges to extend the length of the fade so that it covers pixels 16475 * drawn inside the padding. 16476 * 16477 * Subclasses of this class should override this method if they need 16478 * to draw content inside the padding. 16479 * 16480 * @return True if padding offset must be applied, false otherwise. 16481 * 16482 * @see #getLeftPaddingOffset() 16483 * @see #getRightPaddingOffset() 16484 * @see #getTopPaddingOffset() 16485 * @see #getBottomPaddingOffset() 16486 * 16487 * @since CURRENT 16488 */ 16489 protected boolean isPaddingOffsetRequired() { 16490 return false; 16491 } 16492 16493 /** 16494 * Amount by which to extend the left fading region. Called only when 16495 * {@link #isPaddingOffsetRequired()} returns true. 16496 * 16497 * @return The left padding offset in pixels. 16498 * 16499 * @see #isPaddingOffsetRequired() 16500 * 16501 * @since CURRENT 16502 */ 16503 protected int getLeftPaddingOffset() { 16504 return 0; 16505 } 16506 16507 /** 16508 * Amount by which to extend the right fading region. Called only when 16509 * {@link #isPaddingOffsetRequired()} returns true. 16510 * 16511 * @return The right padding offset in pixels. 16512 * 16513 * @see #isPaddingOffsetRequired() 16514 * 16515 * @since CURRENT 16516 */ 16517 protected int getRightPaddingOffset() { 16518 return 0; 16519 } 16520 16521 /** 16522 * Amount by which to extend the top fading region. Called only when 16523 * {@link #isPaddingOffsetRequired()} returns true. 16524 * 16525 * @return The top padding offset in pixels. 16526 * 16527 * @see #isPaddingOffsetRequired() 16528 * 16529 * @since CURRENT 16530 */ 16531 protected int getTopPaddingOffset() { 16532 return 0; 16533 } 16534 16535 /** 16536 * Amount by which to extend the bottom fading region. Called only when 16537 * {@link #isPaddingOffsetRequired()} returns true. 16538 * 16539 * @return The bottom padding offset in pixels. 16540 * 16541 * @see #isPaddingOffsetRequired() 16542 * 16543 * @since CURRENT 16544 */ 16545 protected int getBottomPaddingOffset() { 16546 return 0; 16547 } 16548 16549 /** 16550 * @hide 16551 * @param offsetRequired 16552 */ 16553 protected int getFadeTop(boolean offsetRequired) { 16554 int top = mPaddingTop; 16555 if (offsetRequired) top += getTopPaddingOffset(); 16556 return top; 16557 } 16558 16559 /** 16560 * @hide 16561 * @param offsetRequired 16562 */ 16563 protected int getFadeHeight(boolean offsetRequired) { 16564 int padding = mPaddingTop; 16565 if (offsetRequired) padding += getTopPaddingOffset(); 16566 return mBottom - mTop - mPaddingBottom - padding; 16567 } 16568 16569 /** 16570 * <p>Indicates whether this view is attached to a hardware accelerated 16571 * window or not.</p> 16572 * 16573 * <p>Even if this method returns true, it does not mean that every call 16574 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 16575 * accelerated {@link android.graphics.Canvas}. For instance, if this view 16576 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 16577 * window is hardware accelerated, 16578 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 16579 * return false, and this method will return true.</p> 16580 * 16581 * @return True if the view is attached to a window and the window is 16582 * hardware accelerated; false in any other case. 16583 */ 16584 @ViewDebug.ExportedProperty(category = "drawing") 16585 public boolean isHardwareAccelerated() { 16586 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 16587 } 16588 16589 /** 16590 * Sets a rectangular area on this view to which the view will be clipped 16591 * when it is drawn. Setting the value to null will remove the clip bounds 16592 * and the view will draw normally, using its full bounds. 16593 * 16594 * @param clipBounds The rectangular area, in the local coordinates of 16595 * this view, to which future drawing operations will be clipped. 16596 */ 16597 public void setClipBounds(Rect clipBounds) { 16598 if (clipBounds == mClipBounds 16599 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 16600 return; 16601 } 16602 if (clipBounds != null) { 16603 if (mClipBounds == null) { 16604 mClipBounds = new Rect(clipBounds); 16605 } else { 16606 mClipBounds.set(clipBounds); 16607 } 16608 } else { 16609 mClipBounds = null; 16610 } 16611 mRenderNode.setClipBounds(mClipBounds); 16612 invalidateViewProperty(false, false); 16613 } 16614 16615 /** 16616 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 16617 * 16618 * @return A copy of the current clip bounds if clip bounds are set, 16619 * otherwise null. 16620 */ 16621 public Rect getClipBounds() { 16622 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 16623 } 16624 16625 16626 /** 16627 * Populates an output rectangle with the clip bounds of the view, 16628 * returning {@code true} if successful or {@code false} if the view's 16629 * clip bounds are {@code null}. 16630 * 16631 * @param outRect rectangle in which to place the clip bounds of the view 16632 * @return {@code true} if successful or {@code false} if the view's 16633 * clip bounds are {@code null} 16634 */ 16635 public boolean getClipBounds(Rect outRect) { 16636 if (mClipBounds != null) { 16637 outRect.set(mClipBounds); 16638 return true; 16639 } 16640 return false; 16641 } 16642 16643 /** 16644 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 16645 * case of an active Animation being run on the view. 16646 */ 16647 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 16648 Animation a, boolean scalingRequired) { 16649 Transformation invalidationTransform; 16650 final int flags = parent.mGroupFlags; 16651 final boolean initialized = a.isInitialized(); 16652 if (!initialized) { 16653 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 16654 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 16655 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 16656 onAnimationStart(); 16657 } 16658 16659 final Transformation t = parent.getChildTransformation(); 16660 boolean more = a.getTransformation(drawingTime, t, 1f); 16661 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 16662 if (parent.mInvalidationTransformation == null) { 16663 parent.mInvalidationTransformation = new Transformation(); 16664 } 16665 invalidationTransform = parent.mInvalidationTransformation; 16666 a.getTransformation(drawingTime, invalidationTransform, 1f); 16667 } else { 16668 invalidationTransform = t; 16669 } 16670 16671 if (more) { 16672 if (!a.willChangeBounds()) { 16673 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 16674 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 16675 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 16676 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 16677 // The child need to draw an animation, potentially offscreen, so 16678 // make sure we do not cancel invalidate requests 16679 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16680 parent.invalidate(mLeft, mTop, mRight, mBottom); 16681 } 16682 } else { 16683 if (parent.mInvalidateRegion == null) { 16684 parent.mInvalidateRegion = new RectF(); 16685 } 16686 final RectF region = parent.mInvalidateRegion; 16687 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 16688 invalidationTransform); 16689 16690 // The child need to draw an animation, potentially offscreen, so 16691 // make sure we do not cancel invalidate requests 16692 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16693 16694 final int left = mLeft + (int) region.left; 16695 final int top = mTop + (int) region.top; 16696 parent.invalidate(left, top, left + (int) (region.width() + .5f), 16697 top + (int) (region.height() + .5f)); 16698 } 16699 } 16700 return more; 16701 } 16702 16703 /** 16704 * This method is called by getDisplayList() when a display list is recorded for a View. 16705 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 16706 */ 16707 void setDisplayListProperties(RenderNode renderNode) { 16708 if (renderNode != null) { 16709 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 16710 renderNode.setClipToBounds(mParent instanceof ViewGroup 16711 && ((ViewGroup) mParent).getClipChildren()); 16712 16713 float alpha = 1; 16714 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 16715 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16716 ViewGroup parentVG = (ViewGroup) mParent; 16717 final Transformation t = parentVG.getChildTransformation(); 16718 if (parentVG.getChildStaticTransformation(this, t)) { 16719 final int transformType = t.getTransformationType(); 16720 if (transformType != Transformation.TYPE_IDENTITY) { 16721 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 16722 alpha = t.getAlpha(); 16723 } 16724 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 16725 renderNode.setStaticMatrix(t.getMatrix()); 16726 } 16727 } 16728 } 16729 } 16730 if (mTransformationInfo != null) { 16731 alpha *= getFinalAlpha(); 16732 if (alpha < 1) { 16733 final int multipliedAlpha = (int) (255 * alpha); 16734 if (onSetAlpha(multipliedAlpha)) { 16735 alpha = 1; 16736 } 16737 } 16738 renderNode.setAlpha(alpha); 16739 } else if (alpha < 1) { 16740 renderNode.setAlpha(alpha); 16741 } 16742 } 16743 } 16744 16745 /** 16746 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 16747 * 16748 * This is where the View specializes rendering behavior based on layer type, 16749 * and hardware acceleration. 16750 */ 16751 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 16752 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 16753 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 16754 * 16755 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 16756 * HW accelerated, it can't handle drawing RenderNodes. 16757 */ 16758 boolean drawingWithRenderNode = mAttachInfo != null 16759 && mAttachInfo.mHardwareAccelerated 16760 && hardwareAcceleratedCanvas; 16761 16762 boolean more = false; 16763 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 16764 final int parentFlags = parent.mGroupFlags; 16765 16766 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 16767 parent.getChildTransformation().clear(); 16768 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16769 } 16770 16771 Transformation transformToApply = null; 16772 boolean concatMatrix = false; 16773 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 16774 final Animation a = getAnimation(); 16775 if (a != null) { 16776 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 16777 concatMatrix = a.willChangeTransformationMatrix(); 16778 if (concatMatrix) { 16779 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16780 } 16781 transformToApply = parent.getChildTransformation(); 16782 } else { 16783 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 16784 // No longer animating: clear out old animation matrix 16785 mRenderNode.setAnimationMatrix(null); 16786 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16787 } 16788 if (!drawingWithRenderNode 16789 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16790 final Transformation t = parent.getChildTransformation(); 16791 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 16792 if (hasTransform) { 16793 final int transformType = t.getTransformationType(); 16794 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 16795 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 16796 } 16797 } 16798 } 16799 16800 concatMatrix |= !childHasIdentityMatrix; 16801 16802 // Sets the flag as early as possible to allow draw() implementations 16803 // to call invalidate() successfully when doing animations 16804 mPrivateFlags |= PFLAG_DRAWN; 16805 16806 if (!concatMatrix && 16807 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 16808 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 16809 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 16810 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 16811 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 16812 return more; 16813 } 16814 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 16815 16816 if (hardwareAcceleratedCanvas) { 16817 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 16818 // retain the flag's value temporarily in the mRecreateDisplayList flag 16819 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 16820 mPrivateFlags &= ~PFLAG_INVALIDATED; 16821 } 16822 16823 RenderNode renderNode = null; 16824 Bitmap cache = null; 16825 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 16826 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 16827 if (layerType != LAYER_TYPE_NONE) { 16828 // If not drawing with RenderNode, treat HW layers as SW 16829 layerType = LAYER_TYPE_SOFTWARE; 16830 buildDrawingCache(true); 16831 } 16832 cache = getDrawingCache(true); 16833 } 16834 16835 if (drawingWithRenderNode) { 16836 // Delay getting the display list until animation-driven alpha values are 16837 // set up and possibly passed on to the view 16838 renderNode = updateDisplayListIfDirty(); 16839 if (!renderNode.isValid()) { 16840 // Uncommon, but possible. If a view is removed from the hierarchy during the call 16841 // to getDisplayList(), the display list will be marked invalid and we should not 16842 // try to use it again. 16843 renderNode = null; 16844 drawingWithRenderNode = false; 16845 } 16846 } 16847 16848 int sx = 0; 16849 int sy = 0; 16850 if (!drawingWithRenderNode) { 16851 computeScroll(); 16852 sx = mScrollX; 16853 sy = mScrollY; 16854 } 16855 16856 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 16857 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 16858 16859 int restoreTo = -1; 16860 if (!drawingWithRenderNode || transformToApply != null) { 16861 restoreTo = canvas.save(); 16862 } 16863 if (offsetForScroll) { 16864 canvas.translate(mLeft - sx, mTop - sy); 16865 } else { 16866 if (!drawingWithRenderNode) { 16867 canvas.translate(mLeft, mTop); 16868 } 16869 if (scalingRequired) { 16870 if (drawingWithRenderNode) { 16871 // TODO: Might not need this if we put everything inside the DL 16872 restoreTo = canvas.save(); 16873 } 16874 // mAttachInfo cannot be null, otherwise scalingRequired == false 16875 final float scale = 1.0f / mAttachInfo.mApplicationScale; 16876 canvas.scale(scale, scale); 16877 } 16878 } 16879 16880 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 16881 if (transformToApply != null 16882 || alpha < 1 16883 || !hasIdentityMatrix() 16884 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16885 if (transformToApply != null || !childHasIdentityMatrix) { 16886 int transX = 0; 16887 int transY = 0; 16888 16889 if (offsetForScroll) { 16890 transX = -sx; 16891 transY = -sy; 16892 } 16893 16894 if (transformToApply != null) { 16895 if (concatMatrix) { 16896 if (drawingWithRenderNode) { 16897 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 16898 } else { 16899 // Undo the scroll translation, apply the transformation matrix, 16900 // then redo the scroll translate to get the correct result. 16901 canvas.translate(-transX, -transY); 16902 canvas.concat(transformToApply.getMatrix()); 16903 canvas.translate(transX, transY); 16904 } 16905 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16906 } 16907 16908 float transformAlpha = transformToApply.getAlpha(); 16909 if (transformAlpha < 1) { 16910 alpha *= transformAlpha; 16911 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16912 } 16913 } 16914 16915 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 16916 canvas.translate(-transX, -transY); 16917 canvas.concat(getMatrix()); 16918 canvas.translate(transX, transY); 16919 } 16920 } 16921 16922 // Deal with alpha if it is or used to be <1 16923 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16924 if (alpha < 1) { 16925 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16926 } else { 16927 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16928 } 16929 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16930 if (!drawingWithDrawingCache) { 16931 final int multipliedAlpha = (int) (255 * alpha); 16932 if (!onSetAlpha(multipliedAlpha)) { 16933 if (drawingWithRenderNode) { 16934 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 16935 } else if (layerType == LAYER_TYPE_NONE) { 16936 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 16937 multipliedAlpha); 16938 } 16939 } else { 16940 // Alpha is handled by the child directly, clobber the layer's alpha 16941 mPrivateFlags |= PFLAG_ALPHA_SET; 16942 } 16943 } 16944 } 16945 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16946 onSetAlpha(255); 16947 mPrivateFlags &= ~PFLAG_ALPHA_SET; 16948 } 16949 16950 if (!drawingWithRenderNode) { 16951 // apply clips directly, since RenderNode won't do it for this draw 16952 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 16953 if (offsetForScroll) { 16954 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 16955 } else { 16956 if (!scalingRequired || cache == null) { 16957 canvas.clipRect(0, 0, getWidth(), getHeight()); 16958 } else { 16959 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 16960 } 16961 } 16962 } 16963 16964 if (mClipBounds != null) { 16965 // clip bounds ignore scroll 16966 canvas.clipRect(mClipBounds); 16967 } 16968 } 16969 16970 if (!drawingWithDrawingCache) { 16971 if (drawingWithRenderNode) { 16972 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16973 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 16974 } else { 16975 // Fast path for layouts with no backgrounds 16976 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16977 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16978 dispatchDraw(canvas); 16979 } else { 16980 draw(canvas); 16981 } 16982 } 16983 } else if (cache != null) { 16984 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16985 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 16986 // no layer paint, use temporary paint to draw bitmap 16987 Paint cachePaint = parent.mCachePaint; 16988 if (cachePaint == null) { 16989 cachePaint = new Paint(); 16990 cachePaint.setDither(false); 16991 parent.mCachePaint = cachePaint; 16992 } 16993 cachePaint.setAlpha((int) (alpha * 255)); 16994 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 16995 } else { 16996 // use layer paint to draw the bitmap, merging the two alphas, but also restore 16997 int layerPaintAlpha = mLayerPaint.getAlpha(); 16998 if (alpha < 1) { 16999 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 17000 } 17001 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 17002 if (alpha < 1) { 17003 mLayerPaint.setAlpha(layerPaintAlpha); 17004 } 17005 } 17006 } 17007 17008 if (restoreTo >= 0) { 17009 canvas.restoreToCount(restoreTo); 17010 } 17011 17012 if (a != null && !more) { 17013 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 17014 onSetAlpha(255); 17015 } 17016 parent.finishAnimatingView(this, a); 17017 } 17018 17019 if (more && hardwareAcceleratedCanvas) { 17020 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17021 // alpha animations should cause the child to recreate its display list 17022 invalidate(true); 17023 } 17024 } 17025 17026 mRecreateDisplayList = false; 17027 17028 return more; 17029 } 17030 17031 /** 17032 * Manually render this view (and all of its children) to the given Canvas. 17033 * The view must have already done a full layout before this function is 17034 * called. When implementing a view, implement 17035 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 17036 * If you do need to override this method, call the superclass version. 17037 * 17038 * @param canvas The Canvas to which the View is rendered. 17039 */ 17040 @CallSuper 17041 public void draw(Canvas canvas) { 17042 final int privateFlags = mPrivateFlags; 17043 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 17044 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 17045 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 17046 17047 /* 17048 * Draw traversal performs several drawing steps which must be executed 17049 * in the appropriate order: 17050 * 17051 * 1. Draw the background 17052 * 2. If necessary, save the canvas' layers to prepare for fading 17053 * 3. Draw view's content 17054 * 4. Draw children 17055 * 5. If necessary, draw the fading edges and restore layers 17056 * 6. Draw decorations (scrollbars for instance) 17057 */ 17058 17059 // Step 1, draw the background, if needed 17060 int saveCount; 17061 17062 if (!dirtyOpaque) { 17063 drawBackground(canvas); 17064 } 17065 17066 // skip step 2 & 5 if possible (common case) 17067 final int viewFlags = mViewFlags; 17068 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 17069 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 17070 if (!verticalEdges && !horizontalEdges) { 17071 // Step 3, draw the content 17072 if (!dirtyOpaque) onDraw(canvas); 17073 17074 // Step 4, draw the children 17075 dispatchDraw(canvas); 17076 17077 // Overlay is part of the content and draws beneath Foreground 17078 if (mOverlay != null && !mOverlay.isEmpty()) { 17079 mOverlay.getOverlayView().dispatchDraw(canvas); 17080 } 17081 17082 // Step 6, draw decorations (foreground, scrollbars) 17083 onDrawForeground(canvas); 17084 17085 // we're done... 17086 return; 17087 } 17088 17089 /* 17090 * Here we do the full fledged routine... 17091 * (this is an uncommon case where speed matters less, 17092 * this is why we repeat some of the tests that have been 17093 * done above) 17094 */ 17095 17096 boolean drawTop = false; 17097 boolean drawBottom = false; 17098 boolean drawLeft = false; 17099 boolean drawRight = false; 17100 17101 float topFadeStrength = 0.0f; 17102 float bottomFadeStrength = 0.0f; 17103 float leftFadeStrength = 0.0f; 17104 float rightFadeStrength = 0.0f; 17105 17106 // Step 2, save the canvas' layers 17107 int paddingLeft = mPaddingLeft; 17108 17109 final boolean offsetRequired = isPaddingOffsetRequired(); 17110 if (offsetRequired) { 17111 paddingLeft += getLeftPaddingOffset(); 17112 } 17113 17114 int left = mScrollX + paddingLeft; 17115 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 17116 int top = mScrollY + getFadeTop(offsetRequired); 17117 int bottom = top + getFadeHeight(offsetRequired); 17118 17119 if (offsetRequired) { 17120 right += getRightPaddingOffset(); 17121 bottom += getBottomPaddingOffset(); 17122 } 17123 17124 final ScrollabilityCache scrollabilityCache = mScrollCache; 17125 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 17126 int length = (int) fadeHeight; 17127 17128 // clip the fade length if top and bottom fades overlap 17129 // overlapping fades produce odd-looking artifacts 17130 if (verticalEdges && (top + length > bottom - length)) { 17131 length = (bottom - top) / 2; 17132 } 17133 17134 // also clip horizontal fades if necessary 17135 if (horizontalEdges && (left + length > right - length)) { 17136 length = (right - left) / 2; 17137 } 17138 17139 if (verticalEdges) { 17140 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 17141 drawTop = topFadeStrength * fadeHeight > 1.0f; 17142 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 17143 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 17144 } 17145 17146 if (horizontalEdges) { 17147 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 17148 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 17149 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 17150 drawRight = rightFadeStrength * fadeHeight > 1.0f; 17151 } 17152 17153 saveCount = canvas.getSaveCount(); 17154 17155 int solidColor = getSolidColor(); 17156 if (solidColor == 0) { 17157 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 17158 17159 if (drawTop) { 17160 canvas.saveLayer(left, top, right, top + length, null, flags); 17161 } 17162 17163 if (drawBottom) { 17164 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 17165 } 17166 17167 if (drawLeft) { 17168 canvas.saveLayer(left, top, left + length, bottom, null, flags); 17169 } 17170 17171 if (drawRight) { 17172 canvas.saveLayer(right - length, top, right, bottom, null, flags); 17173 } 17174 } else { 17175 scrollabilityCache.setFadeColor(solidColor); 17176 } 17177 17178 // Step 3, draw the content 17179 if (!dirtyOpaque) onDraw(canvas); 17180 17181 // Step 4, draw the children 17182 dispatchDraw(canvas); 17183 17184 // Step 5, draw the fade effect and restore layers 17185 final Paint p = scrollabilityCache.paint; 17186 final Matrix matrix = scrollabilityCache.matrix; 17187 final Shader fade = scrollabilityCache.shader; 17188 17189 if (drawTop) { 17190 matrix.setScale(1, fadeHeight * topFadeStrength); 17191 matrix.postTranslate(left, top); 17192 fade.setLocalMatrix(matrix); 17193 p.setShader(fade); 17194 canvas.drawRect(left, top, right, top + length, p); 17195 } 17196 17197 if (drawBottom) { 17198 matrix.setScale(1, fadeHeight * bottomFadeStrength); 17199 matrix.postRotate(180); 17200 matrix.postTranslate(left, bottom); 17201 fade.setLocalMatrix(matrix); 17202 p.setShader(fade); 17203 canvas.drawRect(left, bottom - length, right, bottom, p); 17204 } 17205 17206 if (drawLeft) { 17207 matrix.setScale(1, fadeHeight * leftFadeStrength); 17208 matrix.postRotate(-90); 17209 matrix.postTranslate(left, top); 17210 fade.setLocalMatrix(matrix); 17211 p.setShader(fade); 17212 canvas.drawRect(left, top, left + length, bottom, p); 17213 } 17214 17215 if (drawRight) { 17216 matrix.setScale(1, fadeHeight * rightFadeStrength); 17217 matrix.postRotate(90); 17218 matrix.postTranslate(right, top); 17219 fade.setLocalMatrix(matrix); 17220 p.setShader(fade); 17221 canvas.drawRect(right - length, top, right, bottom, p); 17222 } 17223 17224 canvas.restoreToCount(saveCount); 17225 17226 // Overlay is part of the content and draws beneath Foreground 17227 if (mOverlay != null && !mOverlay.isEmpty()) { 17228 mOverlay.getOverlayView().dispatchDraw(canvas); 17229 } 17230 17231 // Step 6, draw decorations (foreground, scrollbars) 17232 onDrawForeground(canvas); 17233 } 17234 17235 /** 17236 * Draws the background onto the specified canvas. 17237 * 17238 * @param canvas Canvas on which to draw the background 17239 */ 17240 private void drawBackground(Canvas canvas) { 17241 final Drawable background = mBackground; 17242 if (background == null) { 17243 return; 17244 } 17245 17246 setBackgroundBounds(); 17247 17248 // Attempt to use a display list if requested. 17249 if (canvas.isHardwareAccelerated() && mAttachInfo != null 17250 && mAttachInfo.mHardwareRenderer != null) { 17251 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 17252 17253 final RenderNode renderNode = mBackgroundRenderNode; 17254 if (renderNode != null && renderNode.isValid()) { 17255 setBackgroundRenderNodeProperties(renderNode); 17256 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17257 return; 17258 } 17259 } 17260 17261 final int scrollX = mScrollX; 17262 final int scrollY = mScrollY; 17263 if ((scrollX | scrollY) == 0) { 17264 background.draw(canvas); 17265 } else { 17266 canvas.translate(scrollX, scrollY); 17267 background.draw(canvas); 17268 canvas.translate(-scrollX, -scrollY); 17269 } 17270 } 17271 17272 /** 17273 * Sets the correct background bounds and rebuilds the outline, if needed. 17274 * <p/> 17275 * This is called by LayoutLib. 17276 */ 17277 void setBackgroundBounds() { 17278 if (mBackgroundSizeChanged && mBackground != null) { 17279 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 17280 mBackgroundSizeChanged = false; 17281 rebuildOutline(); 17282 } 17283 } 17284 17285 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 17286 renderNode.setTranslationX(mScrollX); 17287 renderNode.setTranslationY(mScrollY); 17288 } 17289 17290 /** 17291 * Creates a new display list or updates the existing display list for the 17292 * specified Drawable. 17293 * 17294 * @param drawable Drawable for which to create a display list 17295 * @param renderNode Existing RenderNode, or {@code null} 17296 * @return A valid display list for the specified drawable 17297 */ 17298 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 17299 if (renderNode == null) { 17300 renderNode = RenderNode.create(drawable.getClass().getName(), this); 17301 } 17302 17303 final Rect bounds = drawable.getBounds(); 17304 final int width = bounds.width(); 17305 final int height = bounds.height(); 17306 final DisplayListCanvas canvas = renderNode.start(width, height); 17307 17308 // Reverse left/top translation done by drawable canvas, which will 17309 // instead be applied by rendernode's LTRB bounds below. This way, the 17310 // drawable's bounds match with its rendernode bounds and its content 17311 // will lie within those bounds in the rendernode tree. 17312 canvas.translate(-bounds.left, -bounds.top); 17313 17314 try { 17315 drawable.draw(canvas); 17316 } finally { 17317 renderNode.end(canvas); 17318 } 17319 17320 // Set up drawable properties that are view-independent. 17321 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 17322 renderNode.setProjectBackwards(drawable.isProjected()); 17323 renderNode.setProjectionReceiver(true); 17324 renderNode.setClipToBounds(false); 17325 return renderNode; 17326 } 17327 17328 /** 17329 * Returns the overlay for this view, creating it if it does not yet exist. 17330 * Adding drawables to the overlay will cause them to be displayed whenever 17331 * the view itself is redrawn. Objects in the overlay should be actively 17332 * managed: remove them when they should not be displayed anymore. The 17333 * overlay will always have the same size as its host view. 17334 * 17335 * <p>Note: Overlays do not currently work correctly with {@link 17336 * SurfaceView} or {@link TextureView}; contents in overlays for these 17337 * types of views may not display correctly.</p> 17338 * 17339 * @return The ViewOverlay object for this view. 17340 * @see ViewOverlay 17341 */ 17342 public ViewOverlay getOverlay() { 17343 if (mOverlay == null) { 17344 mOverlay = new ViewOverlay(mContext, this); 17345 } 17346 return mOverlay; 17347 } 17348 17349 /** 17350 * Override this if your view is known to always be drawn on top of a solid color background, 17351 * and needs to draw fading edges. Returning a non-zero color enables the view system to 17352 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 17353 * should be set to 0xFF. 17354 * 17355 * @see #setVerticalFadingEdgeEnabled(boolean) 17356 * @see #setHorizontalFadingEdgeEnabled(boolean) 17357 * 17358 * @return The known solid color background for this view, or 0 if the color may vary 17359 */ 17360 @ViewDebug.ExportedProperty(category = "drawing") 17361 @ColorInt 17362 public int getSolidColor() { 17363 return 0; 17364 } 17365 17366 /** 17367 * Build a human readable string representation of the specified view flags. 17368 * 17369 * @param flags the view flags to convert to a string 17370 * @return a String representing the supplied flags 17371 */ 17372 private static String printFlags(int flags) { 17373 String output = ""; 17374 int numFlags = 0; 17375 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 17376 output += "TAKES_FOCUS"; 17377 numFlags++; 17378 } 17379 17380 switch (flags & VISIBILITY_MASK) { 17381 case INVISIBLE: 17382 if (numFlags > 0) { 17383 output += " "; 17384 } 17385 output += "INVISIBLE"; 17386 // USELESS HERE numFlags++; 17387 break; 17388 case GONE: 17389 if (numFlags > 0) { 17390 output += " "; 17391 } 17392 output += "GONE"; 17393 // USELESS HERE numFlags++; 17394 break; 17395 default: 17396 break; 17397 } 17398 return output; 17399 } 17400 17401 /** 17402 * Build a human readable string representation of the specified private 17403 * view flags. 17404 * 17405 * @param privateFlags the private view flags to convert to a string 17406 * @return a String representing the supplied flags 17407 */ 17408 private static String printPrivateFlags(int privateFlags) { 17409 String output = ""; 17410 int numFlags = 0; 17411 17412 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 17413 output += "WANTS_FOCUS"; 17414 numFlags++; 17415 } 17416 17417 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 17418 if (numFlags > 0) { 17419 output += " "; 17420 } 17421 output += "FOCUSED"; 17422 numFlags++; 17423 } 17424 17425 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 17426 if (numFlags > 0) { 17427 output += " "; 17428 } 17429 output += "SELECTED"; 17430 numFlags++; 17431 } 17432 17433 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 17434 if (numFlags > 0) { 17435 output += " "; 17436 } 17437 output += "IS_ROOT_NAMESPACE"; 17438 numFlags++; 17439 } 17440 17441 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 17442 if (numFlags > 0) { 17443 output += " "; 17444 } 17445 output += "HAS_BOUNDS"; 17446 numFlags++; 17447 } 17448 17449 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 17450 if (numFlags > 0) { 17451 output += " "; 17452 } 17453 output += "DRAWN"; 17454 // USELESS HERE numFlags++; 17455 } 17456 return output; 17457 } 17458 17459 /** 17460 * <p>Indicates whether or not this view's layout will be requested during 17461 * the next hierarchy layout pass.</p> 17462 * 17463 * @return true if the layout will be forced during next layout pass 17464 */ 17465 public boolean isLayoutRequested() { 17466 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17467 } 17468 17469 /** 17470 * Return true if o is a ViewGroup that is laying out using optical bounds. 17471 * @hide 17472 */ 17473 public static boolean isLayoutModeOptical(Object o) { 17474 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 17475 } 17476 17477 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 17478 Insets parentInsets = mParent instanceof View ? 17479 ((View) mParent).getOpticalInsets() : Insets.NONE; 17480 Insets childInsets = getOpticalInsets(); 17481 return setFrame( 17482 left + parentInsets.left - childInsets.left, 17483 top + parentInsets.top - childInsets.top, 17484 right + parentInsets.left + childInsets.right, 17485 bottom + parentInsets.top + childInsets.bottom); 17486 } 17487 17488 /** 17489 * Assign a size and position to a view and all of its 17490 * descendants 17491 * 17492 * <p>This is the second phase of the layout mechanism. 17493 * (The first is measuring). In this phase, each parent calls 17494 * layout on all of its children to position them. 17495 * This is typically done using the child measurements 17496 * that were stored in the measure pass().</p> 17497 * 17498 * <p>Derived classes should not override this method. 17499 * Derived classes with children should override 17500 * onLayout. In that method, they should 17501 * call layout on each of their children.</p> 17502 * 17503 * @param l Left position, relative to parent 17504 * @param t Top position, relative to parent 17505 * @param r Right position, relative to parent 17506 * @param b Bottom position, relative to parent 17507 */ 17508 @SuppressWarnings({"unchecked"}) 17509 public void layout(int l, int t, int r, int b) { 17510 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 17511 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 17512 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17513 } 17514 17515 int oldL = mLeft; 17516 int oldT = mTop; 17517 int oldB = mBottom; 17518 int oldR = mRight; 17519 17520 boolean changed = isLayoutModeOptical(mParent) ? 17521 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 17522 17523 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 17524 onLayout(changed, l, t, r, b); 17525 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 17526 17527 ListenerInfo li = mListenerInfo; 17528 if (li != null && li.mOnLayoutChangeListeners != null) { 17529 ArrayList<OnLayoutChangeListener> listenersCopy = 17530 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 17531 int numListeners = listenersCopy.size(); 17532 for (int i = 0; i < numListeners; ++i) { 17533 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 17534 } 17535 } 17536 } 17537 17538 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 17539 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 17540 } 17541 17542 /** 17543 * Called from layout when this view should 17544 * assign a size and position to each of its children. 17545 * 17546 * Derived classes with children should override 17547 * this method and call layout on each of 17548 * their children. 17549 * @param changed This is a new size or position for this view 17550 * @param left Left position, relative to parent 17551 * @param top Top position, relative to parent 17552 * @param right Right position, relative to parent 17553 * @param bottom Bottom position, relative to parent 17554 */ 17555 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 17556 } 17557 17558 /** 17559 * Assign a size and position to this view. 17560 * 17561 * This is called from layout. 17562 * 17563 * @param left Left position, relative to parent 17564 * @param top Top position, relative to parent 17565 * @param right Right position, relative to parent 17566 * @param bottom Bottom position, relative to parent 17567 * @return true if the new size and position are different than the 17568 * previous ones 17569 * {@hide} 17570 */ 17571 protected boolean setFrame(int left, int top, int right, int bottom) { 17572 boolean changed = false; 17573 17574 if (DBG) { 17575 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 17576 + right + "," + bottom + ")"); 17577 } 17578 17579 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 17580 changed = true; 17581 17582 // Remember our drawn bit 17583 int drawn = mPrivateFlags & PFLAG_DRAWN; 17584 17585 int oldWidth = mRight - mLeft; 17586 int oldHeight = mBottom - mTop; 17587 int newWidth = right - left; 17588 int newHeight = bottom - top; 17589 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 17590 17591 // Invalidate our old position 17592 invalidate(sizeChanged); 17593 17594 mLeft = left; 17595 mTop = top; 17596 mRight = right; 17597 mBottom = bottom; 17598 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 17599 17600 mPrivateFlags |= PFLAG_HAS_BOUNDS; 17601 17602 17603 if (sizeChanged) { 17604 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 17605 } 17606 17607 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 17608 // If we are visible, force the DRAWN bit to on so that 17609 // this invalidate will go through (at least to our parent). 17610 // This is because someone may have invalidated this view 17611 // before this call to setFrame came in, thereby clearing 17612 // the DRAWN bit. 17613 mPrivateFlags |= PFLAG_DRAWN; 17614 invalidate(sizeChanged); 17615 // parent display list may need to be recreated based on a change in the bounds 17616 // of any child 17617 invalidateParentCaches(); 17618 } 17619 17620 // Reset drawn bit to original value (invalidate turns it off) 17621 mPrivateFlags |= drawn; 17622 17623 mBackgroundSizeChanged = true; 17624 if (mForegroundInfo != null) { 17625 mForegroundInfo.mBoundsChanged = true; 17626 } 17627 17628 notifySubtreeAccessibilityStateChangedIfNeeded(); 17629 } 17630 return changed; 17631 } 17632 17633 /** 17634 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 17635 * @hide 17636 */ 17637 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 17638 setFrame(left, top, right, bottom); 17639 } 17640 17641 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 17642 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 17643 if (mOverlay != null) { 17644 mOverlay.getOverlayView().setRight(newWidth); 17645 mOverlay.getOverlayView().setBottom(newHeight); 17646 } 17647 rebuildOutline(); 17648 } 17649 17650 /** 17651 * Finalize inflating a view from XML. This is called as the last phase 17652 * of inflation, after all child views have been added. 17653 * 17654 * <p>Even if the subclass overrides onFinishInflate, they should always be 17655 * sure to call the super method, so that we get called. 17656 */ 17657 @CallSuper 17658 protected void onFinishInflate() { 17659 } 17660 17661 /** 17662 * Returns the resources associated with this view. 17663 * 17664 * @return Resources object. 17665 */ 17666 public Resources getResources() { 17667 return mResources; 17668 } 17669 17670 /** 17671 * Invalidates the specified Drawable. 17672 * 17673 * @param drawable the drawable to invalidate 17674 */ 17675 @Override 17676 public void invalidateDrawable(@NonNull Drawable drawable) { 17677 if (verifyDrawable(drawable)) { 17678 final Rect dirty = drawable.getDirtyBounds(); 17679 final int scrollX = mScrollX; 17680 final int scrollY = mScrollY; 17681 17682 invalidate(dirty.left + scrollX, dirty.top + scrollY, 17683 dirty.right + scrollX, dirty.bottom + scrollY); 17684 rebuildOutline(); 17685 } 17686 } 17687 17688 /** 17689 * Schedules an action on a drawable to occur at a specified time. 17690 * 17691 * @param who the recipient of the action 17692 * @param what the action to run on the drawable 17693 * @param when the time at which the action must occur. Uses the 17694 * {@link SystemClock#uptimeMillis} timebase. 17695 */ 17696 @Override 17697 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 17698 if (verifyDrawable(who) && what != null) { 17699 final long delay = when - SystemClock.uptimeMillis(); 17700 if (mAttachInfo != null) { 17701 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 17702 Choreographer.CALLBACK_ANIMATION, what, who, 17703 Choreographer.subtractFrameDelay(delay)); 17704 } else { 17705 // Postpone the runnable until we know 17706 // on which thread it needs to run. 17707 getRunQueue().postDelayed(what, delay); 17708 } 17709 } 17710 } 17711 17712 /** 17713 * Cancels a scheduled action on a drawable. 17714 * 17715 * @param who the recipient of the action 17716 * @param what the action to cancel 17717 */ 17718 @Override 17719 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 17720 if (verifyDrawable(who) && what != null) { 17721 if (mAttachInfo != null) { 17722 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17723 Choreographer.CALLBACK_ANIMATION, what, who); 17724 } 17725 getRunQueue().removeCallbacks(what); 17726 } 17727 } 17728 17729 /** 17730 * Unschedule any events associated with the given Drawable. This can be 17731 * used when selecting a new Drawable into a view, so that the previous 17732 * one is completely unscheduled. 17733 * 17734 * @param who The Drawable to unschedule. 17735 * 17736 * @see #drawableStateChanged 17737 */ 17738 public void unscheduleDrawable(Drawable who) { 17739 if (mAttachInfo != null && who != null) { 17740 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17741 Choreographer.CALLBACK_ANIMATION, null, who); 17742 } 17743 } 17744 17745 /** 17746 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 17747 * that the View directionality can and will be resolved before its Drawables. 17748 * 17749 * Will call {@link View#onResolveDrawables} when resolution is done. 17750 * 17751 * @hide 17752 */ 17753 protected void resolveDrawables() { 17754 // Drawables resolution may need to happen before resolving the layout direction (which is 17755 // done only during the measure() call). 17756 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 17757 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 17758 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 17759 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 17760 // direction to be resolved as its resolved value will be the same as its raw value. 17761 if (!isLayoutDirectionResolved() && 17762 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 17763 return; 17764 } 17765 17766 final int layoutDirection = isLayoutDirectionResolved() ? 17767 getLayoutDirection() : getRawLayoutDirection(); 17768 17769 if (mBackground != null) { 17770 mBackground.setLayoutDirection(layoutDirection); 17771 } 17772 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17773 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 17774 } 17775 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 17776 onResolveDrawables(layoutDirection); 17777 } 17778 17779 boolean areDrawablesResolved() { 17780 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 17781 } 17782 17783 /** 17784 * Called when layout direction has been resolved. 17785 * 17786 * The default implementation does nothing. 17787 * 17788 * @param layoutDirection The resolved layout direction. 17789 * 17790 * @see #LAYOUT_DIRECTION_LTR 17791 * @see #LAYOUT_DIRECTION_RTL 17792 * 17793 * @hide 17794 */ 17795 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 17796 } 17797 17798 /** 17799 * @hide 17800 */ 17801 protected void resetResolvedDrawables() { 17802 resetResolvedDrawablesInternal(); 17803 } 17804 17805 void resetResolvedDrawablesInternal() { 17806 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 17807 } 17808 17809 /** 17810 * If your view subclass is displaying its own Drawable objects, it should 17811 * override this function and return true for any Drawable it is 17812 * displaying. This allows animations for those drawables to be 17813 * scheduled. 17814 * 17815 * <p>Be sure to call through to the super class when overriding this 17816 * function. 17817 * 17818 * @param who The Drawable to verify. Return true if it is one you are 17819 * displaying, else return the result of calling through to the 17820 * super class. 17821 * 17822 * @return boolean If true than the Drawable is being displayed in the 17823 * view; else false and it is not allowed to animate. 17824 * 17825 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 17826 * @see #drawableStateChanged() 17827 */ 17828 @CallSuper 17829 protected boolean verifyDrawable(@NonNull Drawable who) { 17830 // Avoid verifying the scroll bar drawable so that we don't end up in 17831 // an invalidation loop. This effectively prevents the scroll bar 17832 // drawable from triggering invalidations and scheduling runnables. 17833 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 17834 } 17835 17836 /** 17837 * This function is called whenever the state of the view changes in such 17838 * a way that it impacts the state of drawables being shown. 17839 * <p> 17840 * If the View has a StateListAnimator, it will also be called to run necessary state 17841 * change animations. 17842 * <p> 17843 * Be sure to call through to the superclass when overriding this function. 17844 * 17845 * @see Drawable#setState(int[]) 17846 */ 17847 @CallSuper 17848 protected void drawableStateChanged() { 17849 final int[] state = getDrawableState(); 17850 boolean changed = false; 17851 17852 final Drawable bg = mBackground; 17853 if (bg != null && bg.isStateful()) { 17854 changed |= bg.setState(state); 17855 } 17856 17857 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17858 if (fg != null && fg.isStateful()) { 17859 changed |= fg.setState(state); 17860 } 17861 17862 if (mScrollCache != null) { 17863 final Drawable scrollBar = mScrollCache.scrollBar; 17864 if (scrollBar != null && scrollBar.isStateful()) { 17865 changed |= scrollBar.setState(state) 17866 && mScrollCache.state != ScrollabilityCache.OFF; 17867 } 17868 } 17869 17870 if (mStateListAnimator != null) { 17871 mStateListAnimator.setState(state); 17872 } 17873 17874 if (changed) { 17875 invalidate(); 17876 } 17877 } 17878 17879 /** 17880 * This function is called whenever the view hotspot changes and needs to 17881 * be propagated to drawables or child views managed by the view. 17882 * <p> 17883 * Dispatching to child views is handled by 17884 * {@link #dispatchDrawableHotspotChanged(float, float)}. 17885 * <p> 17886 * Be sure to call through to the superclass when overriding this function. 17887 * 17888 * @param x hotspot x coordinate 17889 * @param y hotspot y coordinate 17890 */ 17891 @CallSuper 17892 public void drawableHotspotChanged(float x, float y) { 17893 if (mBackground != null) { 17894 mBackground.setHotspot(x, y); 17895 } 17896 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17897 mForegroundInfo.mDrawable.setHotspot(x, y); 17898 } 17899 17900 dispatchDrawableHotspotChanged(x, y); 17901 } 17902 17903 /** 17904 * Dispatches drawableHotspotChanged to all of this View's children. 17905 * 17906 * @param x hotspot x coordinate 17907 * @param y hotspot y coordinate 17908 * @see #drawableHotspotChanged(float, float) 17909 */ 17910 public void dispatchDrawableHotspotChanged(float x, float y) { 17911 } 17912 17913 /** 17914 * Call this to force a view to update its drawable state. This will cause 17915 * drawableStateChanged to be called on this view. Views that are interested 17916 * in the new state should call getDrawableState. 17917 * 17918 * @see #drawableStateChanged 17919 * @see #getDrawableState 17920 */ 17921 public void refreshDrawableState() { 17922 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 17923 drawableStateChanged(); 17924 17925 ViewParent parent = mParent; 17926 if (parent != null) { 17927 parent.childDrawableStateChanged(this); 17928 } 17929 } 17930 17931 /** 17932 * Return an array of resource IDs of the drawable states representing the 17933 * current state of the view. 17934 * 17935 * @return The current drawable state 17936 * 17937 * @see Drawable#setState(int[]) 17938 * @see #drawableStateChanged() 17939 * @see #onCreateDrawableState(int) 17940 */ 17941 public final int[] getDrawableState() { 17942 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 17943 return mDrawableState; 17944 } else { 17945 mDrawableState = onCreateDrawableState(0); 17946 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 17947 return mDrawableState; 17948 } 17949 } 17950 17951 /** 17952 * Generate the new {@link android.graphics.drawable.Drawable} state for 17953 * this view. This is called by the view 17954 * system when the cached Drawable state is determined to be invalid. To 17955 * retrieve the current state, you should use {@link #getDrawableState}. 17956 * 17957 * @param extraSpace if non-zero, this is the number of extra entries you 17958 * would like in the returned array in which you can place your own 17959 * states. 17960 * 17961 * @return Returns an array holding the current {@link Drawable} state of 17962 * the view. 17963 * 17964 * @see #mergeDrawableStates(int[], int[]) 17965 */ 17966 protected int[] onCreateDrawableState(int extraSpace) { 17967 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 17968 mParent instanceof View) { 17969 return ((View) mParent).onCreateDrawableState(extraSpace); 17970 } 17971 17972 int[] drawableState; 17973 17974 int privateFlags = mPrivateFlags; 17975 17976 int viewStateIndex = 0; 17977 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 17978 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 17979 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 17980 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 17981 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 17982 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 17983 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 17984 ThreadedRenderer.isAvailable()) { 17985 // This is set if HW acceleration is requested, even if the current 17986 // process doesn't allow it. This is just to allow app preview 17987 // windows to better match their app. 17988 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 17989 } 17990 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 17991 17992 final int privateFlags2 = mPrivateFlags2; 17993 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 17994 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 17995 } 17996 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 17997 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 17998 } 17999 18000 drawableState = StateSet.get(viewStateIndex); 18001 18002 //noinspection ConstantIfStatement 18003 if (false) { 18004 Log.i("View", "drawableStateIndex=" + viewStateIndex); 18005 Log.i("View", toString() 18006 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 18007 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 18008 + " fo=" + hasFocus() 18009 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 18010 + " wf=" + hasWindowFocus() 18011 + ": " + Arrays.toString(drawableState)); 18012 } 18013 18014 if (extraSpace == 0) { 18015 return drawableState; 18016 } 18017 18018 final int[] fullState; 18019 if (drawableState != null) { 18020 fullState = new int[drawableState.length + extraSpace]; 18021 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 18022 } else { 18023 fullState = new int[extraSpace]; 18024 } 18025 18026 return fullState; 18027 } 18028 18029 /** 18030 * Merge your own state values in <var>additionalState</var> into the base 18031 * state values <var>baseState</var> that were returned by 18032 * {@link #onCreateDrawableState(int)}. 18033 * 18034 * @param baseState The base state values returned by 18035 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 18036 * own additional state values. 18037 * 18038 * @param additionalState The additional state values you would like 18039 * added to <var>baseState</var>; this array is not modified. 18040 * 18041 * @return As a convenience, the <var>baseState</var> array you originally 18042 * passed into the function is returned. 18043 * 18044 * @see #onCreateDrawableState(int) 18045 */ 18046 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 18047 final int N = baseState.length; 18048 int i = N - 1; 18049 while (i >= 0 && baseState[i] == 0) { 18050 i--; 18051 } 18052 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 18053 return baseState; 18054 } 18055 18056 /** 18057 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 18058 * on all Drawable objects associated with this view. 18059 * <p> 18060 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 18061 * attached to this view. 18062 */ 18063 @CallSuper 18064 public void jumpDrawablesToCurrentState() { 18065 if (mBackground != null) { 18066 mBackground.jumpToCurrentState(); 18067 } 18068 if (mStateListAnimator != null) { 18069 mStateListAnimator.jumpToCurrentState(); 18070 } 18071 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18072 mForegroundInfo.mDrawable.jumpToCurrentState(); 18073 } 18074 } 18075 18076 /** 18077 * Sets the background color for this view. 18078 * @param color the color of the background 18079 */ 18080 @RemotableViewMethod 18081 public void setBackgroundColor(@ColorInt int color) { 18082 if (mBackground instanceof ColorDrawable) { 18083 ((ColorDrawable) mBackground.mutate()).setColor(color); 18084 computeOpaqueFlags(); 18085 mBackgroundResource = 0; 18086 } else { 18087 setBackground(new ColorDrawable(color)); 18088 } 18089 } 18090 18091 /** 18092 * Set the background to a given resource. The resource should refer to 18093 * a Drawable object or 0 to remove the background. 18094 * @param resid The identifier of the resource. 18095 * 18096 * @attr ref android.R.styleable#View_background 18097 */ 18098 @RemotableViewMethod 18099 public void setBackgroundResource(@DrawableRes int resid) { 18100 if (resid != 0 && resid == mBackgroundResource) { 18101 return; 18102 } 18103 18104 Drawable d = null; 18105 if (resid != 0) { 18106 d = mContext.getDrawable(resid); 18107 } 18108 setBackground(d); 18109 18110 mBackgroundResource = resid; 18111 } 18112 18113 /** 18114 * Set the background to a given Drawable, or remove the background. If the 18115 * background has padding, this View's padding is set to the background's 18116 * padding. However, when a background is removed, this View's padding isn't 18117 * touched. If setting the padding is desired, please use 18118 * {@link #setPadding(int, int, int, int)}. 18119 * 18120 * @param background The Drawable to use as the background, or null to remove the 18121 * background 18122 */ 18123 public void setBackground(Drawable background) { 18124 //noinspection deprecation 18125 setBackgroundDrawable(background); 18126 } 18127 18128 /** 18129 * @deprecated use {@link #setBackground(Drawable)} instead 18130 */ 18131 @Deprecated 18132 public void setBackgroundDrawable(Drawable background) { 18133 computeOpaqueFlags(); 18134 18135 if (background == mBackground) { 18136 return; 18137 } 18138 18139 boolean requestLayout = false; 18140 18141 mBackgroundResource = 0; 18142 18143 /* 18144 * Regardless of whether we're setting a new background or not, we want 18145 * to clear the previous drawable. setVisible first while we still have the callback set. 18146 */ 18147 if (mBackground != null) { 18148 if (isAttachedToWindow()) { 18149 mBackground.setVisible(false, false); 18150 } 18151 mBackground.setCallback(null); 18152 unscheduleDrawable(mBackground); 18153 } 18154 18155 if (background != null) { 18156 Rect padding = sThreadLocal.get(); 18157 if (padding == null) { 18158 padding = new Rect(); 18159 sThreadLocal.set(padding); 18160 } 18161 resetResolvedDrawablesInternal(); 18162 background.setLayoutDirection(getLayoutDirection()); 18163 if (background.getPadding(padding)) { 18164 resetResolvedPaddingInternal(); 18165 switch (background.getLayoutDirection()) { 18166 case LAYOUT_DIRECTION_RTL: 18167 mUserPaddingLeftInitial = padding.right; 18168 mUserPaddingRightInitial = padding.left; 18169 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 18170 break; 18171 case LAYOUT_DIRECTION_LTR: 18172 default: 18173 mUserPaddingLeftInitial = padding.left; 18174 mUserPaddingRightInitial = padding.right; 18175 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 18176 } 18177 mLeftPaddingDefined = false; 18178 mRightPaddingDefined = false; 18179 } 18180 18181 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 18182 // if it has a different minimum size, we should layout again 18183 if (mBackground == null 18184 || mBackground.getMinimumHeight() != background.getMinimumHeight() 18185 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 18186 requestLayout = true; 18187 } 18188 18189 // Set mBackground before we set this as the callback and start making other 18190 // background drawable state change calls. In particular, the setVisible call below 18191 // can result in drawables attempting to start animations or otherwise invalidate, 18192 // which requires the view set as the callback (us) to recognize the drawable as 18193 // belonging to it as per verifyDrawable. 18194 mBackground = background; 18195 if (background.isStateful()) { 18196 background.setState(getDrawableState()); 18197 } 18198 if (isAttachedToWindow()) { 18199 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18200 } 18201 18202 applyBackgroundTint(); 18203 18204 // Set callback last, since the view may still be initializing. 18205 background.setCallback(this); 18206 18207 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18208 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18209 requestLayout = true; 18210 } 18211 } else { 18212 /* Remove the background */ 18213 mBackground = null; 18214 if ((mViewFlags & WILL_NOT_DRAW) != 0 18215 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 18216 mPrivateFlags |= PFLAG_SKIP_DRAW; 18217 } 18218 18219 /* 18220 * When the background is set, we try to apply its padding to this 18221 * View. When the background is removed, we don't touch this View's 18222 * padding. This is noted in the Javadocs. Hence, we don't need to 18223 * requestLayout(), the invalidate() below is sufficient. 18224 */ 18225 18226 // The old background's minimum size could have affected this 18227 // View's layout, so let's requestLayout 18228 requestLayout = true; 18229 } 18230 18231 computeOpaqueFlags(); 18232 18233 if (requestLayout) { 18234 requestLayout(); 18235 } 18236 18237 mBackgroundSizeChanged = true; 18238 invalidate(true); 18239 invalidateOutline(); 18240 } 18241 18242 /** 18243 * Gets the background drawable 18244 * 18245 * @return The drawable used as the background for this view, if any. 18246 * 18247 * @see #setBackground(Drawable) 18248 * 18249 * @attr ref android.R.styleable#View_background 18250 */ 18251 public Drawable getBackground() { 18252 return mBackground; 18253 } 18254 18255 /** 18256 * Applies a tint to the background drawable. Does not modify the current tint 18257 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18258 * <p> 18259 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 18260 * mutate the drawable and apply the specified tint and tint mode using 18261 * {@link Drawable#setTintList(ColorStateList)}. 18262 * 18263 * @param tint the tint to apply, may be {@code null} to clear tint 18264 * 18265 * @attr ref android.R.styleable#View_backgroundTint 18266 * @see #getBackgroundTintList() 18267 * @see Drawable#setTintList(ColorStateList) 18268 */ 18269 public void setBackgroundTintList(@Nullable ColorStateList tint) { 18270 if (mBackgroundTint == null) { 18271 mBackgroundTint = new TintInfo(); 18272 } 18273 mBackgroundTint.mTintList = tint; 18274 mBackgroundTint.mHasTintList = true; 18275 18276 applyBackgroundTint(); 18277 } 18278 18279 /** 18280 * Return the tint applied to the background drawable, if specified. 18281 * 18282 * @return the tint applied to the background drawable 18283 * @attr ref android.R.styleable#View_backgroundTint 18284 * @see #setBackgroundTintList(ColorStateList) 18285 */ 18286 @Nullable 18287 public ColorStateList getBackgroundTintList() { 18288 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 18289 } 18290 18291 /** 18292 * Specifies the blending mode used to apply the tint specified by 18293 * {@link #setBackgroundTintList(ColorStateList)}} to the background 18294 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18295 * 18296 * @param tintMode the blending mode used to apply the tint, may be 18297 * {@code null} to clear tint 18298 * @attr ref android.R.styleable#View_backgroundTintMode 18299 * @see #getBackgroundTintMode() 18300 * @see Drawable#setTintMode(PorterDuff.Mode) 18301 */ 18302 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18303 if (mBackgroundTint == null) { 18304 mBackgroundTint = new TintInfo(); 18305 } 18306 mBackgroundTint.mTintMode = tintMode; 18307 mBackgroundTint.mHasTintMode = true; 18308 18309 applyBackgroundTint(); 18310 } 18311 18312 /** 18313 * Return the blending mode used to apply the tint to the background 18314 * drawable, if specified. 18315 * 18316 * @return the blending mode used to apply the tint to the background 18317 * drawable 18318 * @attr ref android.R.styleable#View_backgroundTintMode 18319 * @see #setBackgroundTintMode(PorterDuff.Mode) 18320 */ 18321 @Nullable 18322 public PorterDuff.Mode getBackgroundTintMode() { 18323 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 18324 } 18325 18326 private void applyBackgroundTint() { 18327 if (mBackground != null && mBackgroundTint != null) { 18328 final TintInfo tintInfo = mBackgroundTint; 18329 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18330 mBackground = mBackground.mutate(); 18331 18332 if (tintInfo.mHasTintList) { 18333 mBackground.setTintList(tintInfo.mTintList); 18334 } 18335 18336 if (tintInfo.mHasTintMode) { 18337 mBackground.setTintMode(tintInfo.mTintMode); 18338 } 18339 18340 // The drawable (or one of its children) may not have been 18341 // stateful before applying the tint, so let's try again. 18342 if (mBackground.isStateful()) { 18343 mBackground.setState(getDrawableState()); 18344 } 18345 } 18346 } 18347 } 18348 18349 /** 18350 * Returns the drawable used as the foreground of this View. The 18351 * foreground drawable, if non-null, is always drawn on top of the view's content. 18352 * 18353 * @return a Drawable or null if no foreground was set 18354 * 18355 * @see #onDrawForeground(Canvas) 18356 */ 18357 public Drawable getForeground() { 18358 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18359 } 18360 18361 /** 18362 * Supply a Drawable that is to be rendered on top of all of the content in the view. 18363 * 18364 * @param foreground the Drawable to be drawn on top of the children 18365 * 18366 * @attr ref android.R.styleable#View_foreground 18367 */ 18368 public void setForeground(Drawable foreground) { 18369 if (mForegroundInfo == null) { 18370 if (foreground == null) { 18371 // Nothing to do. 18372 return; 18373 } 18374 mForegroundInfo = new ForegroundInfo(); 18375 } 18376 18377 if (foreground == mForegroundInfo.mDrawable) { 18378 // Nothing to do 18379 return; 18380 } 18381 18382 if (mForegroundInfo.mDrawable != null) { 18383 if (isAttachedToWindow()) { 18384 mForegroundInfo.mDrawable.setVisible(false, false); 18385 } 18386 mForegroundInfo.mDrawable.setCallback(null); 18387 unscheduleDrawable(mForegroundInfo.mDrawable); 18388 } 18389 18390 mForegroundInfo.mDrawable = foreground; 18391 mForegroundInfo.mBoundsChanged = true; 18392 if (foreground != null) { 18393 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18394 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18395 } 18396 foreground.setLayoutDirection(getLayoutDirection()); 18397 if (foreground.isStateful()) { 18398 foreground.setState(getDrawableState()); 18399 } 18400 applyForegroundTint(); 18401 if (isAttachedToWindow()) { 18402 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18403 } 18404 // Set callback last, since the view may still be initializing. 18405 foreground.setCallback(this); 18406 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 18407 mPrivateFlags |= PFLAG_SKIP_DRAW; 18408 } 18409 requestLayout(); 18410 invalidate(); 18411 } 18412 18413 /** 18414 * Magic bit used to support features of framework-internal window decor implementation details. 18415 * This used to live exclusively in FrameLayout. 18416 * 18417 * @return true if the foreground should draw inside the padding region or false 18418 * if it should draw inset by the view's padding 18419 * @hide internal use only; only used by FrameLayout and internal screen layouts. 18420 */ 18421 public boolean isForegroundInsidePadding() { 18422 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 18423 } 18424 18425 /** 18426 * Describes how the foreground is positioned. 18427 * 18428 * @return foreground gravity. 18429 * 18430 * @see #setForegroundGravity(int) 18431 * 18432 * @attr ref android.R.styleable#View_foregroundGravity 18433 */ 18434 public int getForegroundGravity() { 18435 return mForegroundInfo != null ? mForegroundInfo.mGravity 18436 : Gravity.START | Gravity.TOP; 18437 } 18438 18439 /** 18440 * Describes how the foreground is positioned. Defaults to START and TOP. 18441 * 18442 * @param gravity see {@link android.view.Gravity} 18443 * 18444 * @see #getForegroundGravity() 18445 * 18446 * @attr ref android.R.styleable#View_foregroundGravity 18447 */ 18448 public void setForegroundGravity(int gravity) { 18449 if (mForegroundInfo == null) { 18450 mForegroundInfo = new ForegroundInfo(); 18451 } 18452 18453 if (mForegroundInfo.mGravity != gravity) { 18454 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 18455 gravity |= Gravity.START; 18456 } 18457 18458 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 18459 gravity |= Gravity.TOP; 18460 } 18461 18462 mForegroundInfo.mGravity = gravity; 18463 requestLayout(); 18464 } 18465 } 18466 18467 /** 18468 * Applies a tint to the foreground drawable. Does not modify the current tint 18469 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18470 * <p> 18471 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 18472 * mutate the drawable and apply the specified tint and tint mode using 18473 * {@link Drawable#setTintList(ColorStateList)}. 18474 * 18475 * @param tint the tint to apply, may be {@code null} to clear tint 18476 * 18477 * @attr ref android.R.styleable#View_foregroundTint 18478 * @see #getForegroundTintList() 18479 * @see Drawable#setTintList(ColorStateList) 18480 */ 18481 public void setForegroundTintList(@Nullable ColorStateList tint) { 18482 if (mForegroundInfo == null) { 18483 mForegroundInfo = new ForegroundInfo(); 18484 } 18485 if (mForegroundInfo.mTintInfo == null) { 18486 mForegroundInfo.mTintInfo = new TintInfo(); 18487 } 18488 mForegroundInfo.mTintInfo.mTintList = tint; 18489 mForegroundInfo.mTintInfo.mHasTintList = true; 18490 18491 applyForegroundTint(); 18492 } 18493 18494 /** 18495 * Return the tint applied to the foreground drawable, if specified. 18496 * 18497 * @return the tint applied to the foreground drawable 18498 * @attr ref android.R.styleable#View_foregroundTint 18499 * @see #setForegroundTintList(ColorStateList) 18500 */ 18501 @Nullable 18502 public ColorStateList getForegroundTintList() { 18503 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18504 ? mForegroundInfo.mTintInfo.mTintList : null; 18505 } 18506 18507 /** 18508 * Specifies the blending mode used to apply the tint specified by 18509 * {@link #setForegroundTintList(ColorStateList)}} to the background 18510 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18511 * 18512 * @param tintMode the blending mode used to apply the tint, may be 18513 * {@code null} to clear tint 18514 * @attr ref android.R.styleable#View_foregroundTintMode 18515 * @see #getForegroundTintMode() 18516 * @see Drawable#setTintMode(PorterDuff.Mode) 18517 */ 18518 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18519 if (mForegroundInfo == null) { 18520 mForegroundInfo = new ForegroundInfo(); 18521 } 18522 if (mForegroundInfo.mTintInfo == null) { 18523 mForegroundInfo.mTintInfo = new TintInfo(); 18524 } 18525 mForegroundInfo.mTintInfo.mTintMode = tintMode; 18526 mForegroundInfo.mTintInfo.mHasTintMode = true; 18527 18528 applyForegroundTint(); 18529 } 18530 18531 /** 18532 * Return the blending mode used to apply the tint to the foreground 18533 * drawable, if specified. 18534 * 18535 * @return the blending mode used to apply the tint to the foreground 18536 * drawable 18537 * @attr ref android.R.styleable#View_foregroundTintMode 18538 * @see #setForegroundTintMode(PorterDuff.Mode) 18539 */ 18540 @Nullable 18541 public PorterDuff.Mode getForegroundTintMode() { 18542 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18543 ? mForegroundInfo.mTintInfo.mTintMode : null; 18544 } 18545 18546 private void applyForegroundTint() { 18547 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 18548 && mForegroundInfo.mTintInfo != null) { 18549 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 18550 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18551 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 18552 18553 if (tintInfo.mHasTintList) { 18554 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 18555 } 18556 18557 if (tintInfo.mHasTintMode) { 18558 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 18559 } 18560 18561 // The drawable (or one of its children) may not have been 18562 // stateful before applying the tint, so let's try again. 18563 if (mForegroundInfo.mDrawable.isStateful()) { 18564 mForegroundInfo.mDrawable.setState(getDrawableState()); 18565 } 18566 } 18567 } 18568 } 18569 18570 /** 18571 * Draw any foreground content for this view. 18572 * 18573 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 18574 * drawable or other view-specific decorations. The foreground is drawn on top of the 18575 * primary view content.</p> 18576 * 18577 * @param canvas canvas to draw into 18578 */ 18579 public void onDrawForeground(Canvas canvas) { 18580 onDrawScrollIndicators(canvas); 18581 onDrawScrollBars(canvas); 18582 18583 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18584 if (foreground != null) { 18585 if (mForegroundInfo.mBoundsChanged) { 18586 mForegroundInfo.mBoundsChanged = false; 18587 final Rect selfBounds = mForegroundInfo.mSelfBounds; 18588 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 18589 18590 if (mForegroundInfo.mInsidePadding) { 18591 selfBounds.set(0, 0, getWidth(), getHeight()); 18592 } else { 18593 selfBounds.set(getPaddingLeft(), getPaddingTop(), 18594 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 18595 } 18596 18597 final int ld = getLayoutDirection(); 18598 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 18599 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 18600 foreground.setBounds(overlayBounds); 18601 } 18602 18603 foreground.draw(canvas); 18604 } 18605 } 18606 18607 /** 18608 * Sets the padding. The view may add on the space required to display 18609 * the scrollbars, depending on the style and visibility of the scrollbars. 18610 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 18611 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 18612 * from the values set in this call. 18613 * 18614 * @attr ref android.R.styleable#View_padding 18615 * @attr ref android.R.styleable#View_paddingBottom 18616 * @attr ref android.R.styleable#View_paddingLeft 18617 * @attr ref android.R.styleable#View_paddingRight 18618 * @attr ref android.R.styleable#View_paddingTop 18619 * @param left the left padding in pixels 18620 * @param top the top padding in pixels 18621 * @param right the right padding in pixels 18622 * @param bottom the bottom padding in pixels 18623 */ 18624 public void setPadding(int left, int top, int right, int bottom) { 18625 resetResolvedPaddingInternal(); 18626 18627 mUserPaddingStart = UNDEFINED_PADDING; 18628 mUserPaddingEnd = UNDEFINED_PADDING; 18629 18630 mUserPaddingLeftInitial = left; 18631 mUserPaddingRightInitial = right; 18632 18633 mLeftPaddingDefined = true; 18634 mRightPaddingDefined = true; 18635 18636 internalSetPadding(left, top, right, bottom); 18637 } 18638 18639 /** 18640 * @hide 18641 */ 18642 protected void internalSetPadding(int left, int top, int right, int bottom) { 18643 mUserPaddingLeft = left; 18644 mUserPaddingRight = right; 18645 mUserPaddingBottom = bottom; 18646 18647 final int viewFlags = mViewFlags; 18648 boolean changed = false; 18649 18650 // Common case is there are no scroll bars. 18651 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 18652 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 18653 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 18654 ? 0 : getVerticalScrollbarWidth(); 18655 switch (mVerticalScrollbarPosition) { 18656 case SCROLLBAR_POSITION_DEFAULT: 18657 if (isLayoutRtl()) { 18658 left += offset; 18659 } else { 18660 right += offset; 18661 } 18662 break; 18663 case SCROLLBAR_POSITION_RIGHT: 18664 right += offset; 18665 break; 18666 case SCROLLBAR_POSITION_LEFT: 18667 left += offset; 18668 break; 18669 } 18670 } 18671 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 18672 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 18673 ? 0 : getHorizontalScrollbarHeight(); 18674 } 18675 } 18676 18677 if (mPaddingLeft != left) { 18678 changed = true; 18679 mPaddingLeft = left; 18680 } 18681 if (mPaddingTop != top) { 18682 changed = true; 18683 mPaddingTop = top; 18684 } 18685 if (mPaddingRight != right) { 18686 changed = true; 18687 mPaddingRight = right; 18688 } 18689 if (mPaddingBottom != bottom) { 18690 changed = true; 18691 mPaddingBottom = bottom; 18692 } 18693 18694 if (changed) { 18695 requestLayout(); 18696 invalidateOutline(); 18697 } 18698 } 18699 18700 /** 18701 * Sets the relative padding. The view may add on the space required to display 18702 * the scrollbars, depending on the style and visibility of the scrollbars. 18703 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 18704 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 18705 * from the values set in this call. 18706 * 18707 * @attr ref android.R.styleable#View_padding 18708 * @attr ref android.R.styleable#View_paddingBottom 18709 * @attr ref android.R.styleable#View_paddingStart 18710 * @attr ref android.R.styleable#View_paddingEnd 18711 * @attr ref android.R.styleable#View_paddingTop 18712 * @param start the start padding in pixels 18713 * @param top the top padding in pixels 18714 * @param end the end padding in pixels 18715 * @param bottom the bottom padding in pixels 18716 */ 18717 public void setPaddingRelative(int start, int top, int end, int bottom) { 18718 resetResolvedPaddingInternal(); 18719 18720 mUserPaddingStart = start; 18721 mUserPaddingEnd = end; 18722 mLeftPaddingDefined = true; 18723 mRightPaddingDefined = true; 18724 18725 switch(getLayoutDirection()) { 18726 case LAYOUT_DIRECTION_RTL: 18727 mUserPaddingLeftInitial = end; 18728 mUserPaddingRightInitial = start; 18729 internalSetPadding(end, top, start, bottom); 18730 break; 18731 case LAYOUT_DIRECTION_LTR: 18732 default: 18733 mUserPaddingLeftInitial = start; 18734 mUserPaddingRightInitial = end; 18735 internalSetPadding(start, top, end, bottom); 18736 } 18737 } 18738 18739 /** 18740 * Returns the top padding of this view. 18741 * 18742 * @return the top padding in pixels 18743 */ 18744 public int getPaddingTop() { 18745 return mPaddingTop; 18746 } 18747 18748 /** 18749 * Returns the bottom padding of this view. If there are inset and enabled 18750 * scrollbars, this value may include the space required to display the 18751 * scrollbars as well. 18752 * 18753 * @return the bottom padding in pixels 18754 */ 18755 public int getPaddingBottom() { 18756 return mPaddingBottom; 18757 } 18758 18759 /** 18760 * Returns the left padding of this view. If there are inset and enabled 18761 * scrollbars, this value may include the space required to display the 18762 * scrollbars as well. 18763 * 18764 * @return the left padding in pixels 18765 */ 18766 public int getPaddingLeft() { 18767 if (!isPaddingResolved()) { 18768 resolvePadding(); 18769 } 18770 return mPaddingLeft; 18771 } 18772 18773 /** 18774 * Returns the start padding of this view depending on its resolved layout direction. 18775 * If there are inset and enabled scrollbars, this value may include the space 18776 * required to display the scrollbars as well. 18777 * 18778 * @return the start padding in pixels 18779 */ 18780 public int getPaddingStart() { 18781 if (!isPaddingResolved()) { 18782 resolvePadding(); 18783 } 18784 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18785 mPaddingRight : mPaddingLeft; 18786 } 18787 18788 /** 18789 * Returns the right padding of this view. If there are inset and enabled 18790 * scrollbars, this value may include the space required to display the 18791 * scrollbars as well. 18792 * 18793 * @return the right padding in pixels 18794 */ 18795 public int getPaddingRight() { 18796 if (!isPaddingResolved()) { 18797 resolvePadding(); 18798 } 18799 return mPaddingRight; 18800 } 18801 18802 /** 18803 * Returns the end padding of this view depending on its resolved layout direction. 18804 * If there are inset and enabled scrollbars, this value may include the space 18805 * required to display the scrollbars as well. 18806 * 18807 * @return the end padding in pixels 18808 */ 18809 public int getPaddingEnd() { 18810 if (!isPaddingResolved()) { 18811 resolvePadding(); 18812 } 18813 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18814 mPaddingLeft : mPaddingRight; 18815 } 18816 18817 /** 18818 * Return if the padding has been set through relative values 18819 * {@link #setPaddingRelative(int, int, int, int)} or through 18820 * @attr ref android.R.styleable#View_paddingStart or 18821 * @attr ref android.R.styleable#View_paddingEnd 18822 * 18823 * @return true if the padding is relative or false if it is not. 18824 */ 18825 public boolean isPaddingRelative() { 18826 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 18827 } 18828 18829 Insets computeOpticalInsets() { 18830 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 18831 } 18832 18833 /** 18834 * @hide 18835 */ 18836 public void resetPaddingToInitialValues() { 18837 if (isRtlCompatibilityMode()) { 18838 mPaddingLeft = mUserPaddingLeftInitial; 18839 mPaddingRight = mUserPaddingRightInitial; 18840 return; 18841 } 18842 if (isLayoutRtl()) { 18843 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 18844 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 18845 } else { 18846 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 18847 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 18848 } 18849 } 18850 18851 /** 18852 * @hide 18853 */ 18854 public Insets getOpticalInsets() { 18855 if (mLayoutInsets == null) { 18856 mLayoutInsets = computeOpticalInsets(); 18857 } 18858 return mLayoutInsets; 18859 } 18860 18861 /** 18862 * Set this view's optical insets. 18863 * 18864 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 18865 * property. Views that compute their own optical insets should call it as part of measurement. 18866 * This method does not request layout. If you are setting optical insets outside of 18867 * measure/layout itself you will want to call requestLayout() yourself. 18868 * </p> 18869 * @hide 18870 */ 18871 public void setOpticalInsets(Insets insets) { 18872 mLayoutInsets = insets; 18873 } 18874 18875 /** 18876 * Changes the selection state of this view. A view can be selected or not. 18877 * Note that selection is not the same as focus. Views are typically 18878 * selected in the context of an AdapterView like ListView or GridView; 18879 * the selected view is the view that is highlighted. 18880 * 18881 * @param selected true if the view must be selected, false otherwise 18882 */ 18883 public void setSelected(boolean selected) { 18884 //noinspection DoubleNegation 18885 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 18886 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 18887 if (!selected) resetPressedState(); 18888 invalidate(true); 18889 refreshDrawableState(); 18890 dispatchSetSelected(selected); 18891 if (selected) { 18892 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 18893 } else { 18894 notifyViewAccessibilityStateChangedIfNeeded( 18895 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 18896 } 18897 } 18898 } 18899 18900 /** 18901 * Dispatch setSelected to all of this View's children. 18902 * 18903 * @see #setSelected(boolean) 18904 * 18905 * @param selected The new selected state 18906 */ 18907 protected void dispatchSetSelected(boolean selected) { 18908 } 18909 18910 /** 18911 * Indicates the selection state of this view. 18912 * 18913 * @return true if the view is selected, false otherwise 18914 */ 18915 @ViewDebug.ExportedProperty 18916 public boolean isSelected() { 18917 return (mPrivateFlags & PFLAG_SELECTED) != 0; 18918 } 18919 18920 /** 18921 * Changes the activated state of this view. A view can be activated or not. 18922 * Note that activation is not the same as selection. Selection is 18923 * a transient property, representing the view (hierarchy) the user is 18924 * currently interacting with. Activation is a longer-term state that the 18925 * user can move views in and out of. For example, in a list view with 18926 * single or multiple selection enabled, the views in the current selection 18927 * set are activated. (Um, yeah, we are deeply sorry about the terminology 18928 * here.) The activated state is propagated down to children of the view it 18929 * is set on. 18930 * 18931 * @param activated true if the view must be activated, false otherwise 18932 */ 18933 public void setActivated(boolean activated) { 18934 //noinspection DoubleNegation 18935 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 18936 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 18937 invalidate(true); 18938 refreshDrawableState(); 18939 dispatchSetActivated(activated); 18940 } 18941 } 18942 18943 /** 18944 * Dispatch setActivated to all of this View's children. 18945 * 18946 * @see #setActivated(boolean) 18947 * 18948 * @param activated The new activated state 18949 */ 18950 protected void dispatchSetActivated(boolean activated) { 18951 } 18952 18953 /** 18954 * Indicates the activation state of this view. 18955 * 18956 * @return true if the view is activated, false otherwise 18957 */ 18958 @ViewDebug.ExportedProperty 18959 public boolean isActivated() { 18960 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 18961 } 18962 18963 /** 18964 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 18965 * observer can be used to get notifications when global events, like 18966 * layout, happen. 18967 * 18968 * The returned ViewTreeObserver observer is not guaranteed to remain 18969 * valid for the lifetime of this View. If the caller of this method keeps 18970 * a long-lived reference to ViewTreeObserver, it should always check for 18971 * the return value of {@link ViewTreeObserver#isAlive()}. 18972 * 18973 * @return The ViewTreeObserver for this view's hierarchy. 18974 */ 18975 public ViewTreeObserver getViewTreeObserver() { 18976 if (mAttachInfo != null) { 18977 return mAttachInfo.mTreeObserver; 18978 } 18979 if (mFloatingTreeObserver == null) { 18980 mFloatingTreeObserver = new ViewTreeObserver(); 18981 } 18982 return mFloatingTreeObserver; 18983 } 18984 18985 /** 18986 * <p>Finds the topmost view in the current view hierarchy.</p> 18987 * 18988 * @return the topmost view containing this view 18989 */ 18990 public View getRootView() { 18991 if (mAttachInfo != null) { 18992 final View v = mAttachInfo.mRootView; 18993 if (v != null) { 18994 return v; 18995 } 18996 } 18997 18998 View parent = this; 18999 19000 while (parent.mParent != null && parent.mParent instanceof View) { 19001 parent = (View) parent.mParent; 19002 } 19003 19004 return parent; 19005 } 19006 19007 /** 19008 * Transforms a motion event from view-local coordinates to on-screen 19009 * coordinates. 19010 * 19011 * @param ev the view-local motion event 19012 * @return false if the transformation could not be applied 19013 * @hide 19014 */ 19015 public boolean toGlobalMotionEvent(MotionEvent ev) { 19016 final AttachInfo info = mAttachInfo; 19017 if (info == null) { 19018 return false; 19019 } 19020 19021 final Matrix m = info.mTmpMatrix; 19022 m.set(Matrix.IDENTITY_MATRIX); 19023 transformMatrixToGlobal(m); 19024 ev.transform(m); 19025 return true; 19026 } 19027 19028 /** 19029 * Transforms a motion event from on-screen coordinates to view-local 19030 * coordinates. 19031 * 19032 * @param ev the on-screen motion event 19033 * @return false if the transformation could not be applied 19034 * @hide 19035 */ 19036 public boolean toLocalMotionEvent(MotionEvent ev) { 19037 final AttachInfo info = mAttachInfo; 19038 if (info == null) { 19039 return false; 19040 } 19041 19042 final Matrix m = info.mTmpMatrix; 19043 m.set(Matrix.IDENTITY_MATRIX); 19044 transformMatrixToLocal(m); 19045 ev.transform(m); 19046 return true; 19047 } 19048 19049 /** 19050 * Modifies the input matrix such that it maps view-local coordinates to 19051 * on-screen coordinates. 19052 * 19053 * @param m input matrix to modify 19054 * @hide 19055 */ 19056 public void transformMatrixToGlobal(Matrix m) { 19057 final ViewParent parent = mParent; 19058 if (parent instanceof View) { 19059 final View vp = (View) parent; 19060 vp.transformMatrixToGlobal(m); 19061 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 19062 } else if (parent instanceof ViewRootImpl) { 19063 final ViewRootImpl vr = (ViewRootImpl) parent; 19064 vr.transformMatrixToGlobal(m); 19065 m.preTranslate(0, -vr.mCurScrollY); 19066 } 19067 19068 m.preTranslate(mLeft, mTop); 19069 19070 if (!hasIdentityMatrix()) { 19071 m.preConcat(getMatrix()); 19072 } 19073 } 19074 19075 /** 19076 * Modifies the input matrix such that it maps on-screen coordinates to 19077 * view-local coordinates. 19078 * 19079 * @param m input matrix to modify 19080 * @hide 19081 */ 19082 public void transformMatrixToLocal(Matrix m) { 19083 final ViewParent parent = mParent; 19084 if (parent instanceof View) { 19085 final View vp = (View) parent; 19086 vp.transformMatrixToLocal(m); 19087 m.postTranslate(vp.mScrollX, vp.mScrollY); 19088 } else if (parent instanceof ViewRootImpl) { 19089 final ViewRootImpl vr = (ViewRootImpl) parent; 19090 vr.transformMatrixToLocal(m); 19091 m.postTranslate(0, vr.mCurScrollY); 19092 } 19093 19094 m.postTranslate(-mLeft, -mTop); 19095 19096 if (!hasIdentityMatrix()) { 19097 m.postConcat(getInverseMatrix()); 19098 } 19099 } 19100 19101 /** 19102 * @hide 19103 */ 19104 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 19105 @ViewDebug.IntToString(from = 0, to = "x"), 19106 @ViewDebug.IntToString(from = 1, to = "y") 19107 }) 19108 public int[] getLocationOnScreen() { 19109 int[] location = new int[2]; 19110 getLocationOnScreen(location); 19111 return location; 19112 } 19113 19114 /** 19115 * <p>Computes the coordinates of this view on the screen. The argument 19116 * must be an array of two integers. After the method returns, the array 19117 * contains the x and y location in that order.</p> 19118 * 19119 * @param outLocation an array of two integers in which to hold the coordinates 19120 */ 19121 public void getLocationOnScreen(@Size(2) int[] outLocation) { 19122 getLocationInWindow(outLocation); 19123 19124 final AttachInfo info = mAttachInfo; 19125 if (info != null) { 19126 outLocation[0] += info.mWindowLeft; 19127 outLocation[1] += info.mWindowTop; 19128 } 19129 } 19130 19131 /** 19132 * <p>Computes the coordinates of this view in its window. The argument 19133 * must be an array of two integers. After the method returns, the array 19134 * contains the x and y location in that order.</p> 19135 * 19136 * @param outLocation an array of two integers in which to hold the coordinates 19137 */ 19138 public void getLocationInWindow(@Size(2) int[] outLocation) { 19139 if (outLocation == null || outLocation.length < 2) { 19140 throw new IllegalArgumentException("outLocation must be an array of two integers"); 19141 } 19142 19143 outLocation[0] = 0; 19144 outLocation[1] = 0; 19145 19146 transformFromViewToWindowSpace(outLocation); 19147 } 19148 19149 /** @hide */ 19150 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 19151 if (inOutLocation == null || inOutLocation.length < 2) { 19152 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 19153 } 19154 19155 if (mAttachInfo == null) { 19156 // When the view is not attached to a window, this method does not make sense 19157 inOutLocation[0] = inOutLocation[1] = 0; 19158 return; 19159 } 19160 19161 float position[] = mAttachInfo.mTmpTransformLocation; 19162 position[0] = inOutLocation[0]; 19163 position[1] = inOutLocation[1]; 19164 19165 if (!hasIdentityMatrix()) { 19166 getMatrix().mapPoints(position); 19167 } 19168 19169 position[0] += mLeft; 19170 position[1] += mTop; 19171 19172 ViewParent viewParent = mParent; 19173 while (viewParent instanceof View) { 19174 final View view = (View) viewParent; 19175 19176 position[0] -= view.mScrollX; 19177 position[1] -= view.mScrollY; 19178 19179 if (!view.hasIdentityMatrix()) { 19180 view.getMatrix().mapPoints(position); 19181 } 19182 19183 position[0] += view.mLeft; 19184 position[1] += view.mTop; 19185 19186 viewParent = view.mParent; 19187 } 19188 19189 if (viewParent instanceof ViewRootImpl) { 19190 // *cough* 19191 final ViewRootImpl vr = (ViewRootImpl) viewParent; 19192 position[1] -= vr.mCurScrollY; 19193 } 19194 19195 inOutLocation[0] = Math.round(position[0]); 19196 inOutLocation[1] = Math.round(position[1]); 19197 } 19198 19199 /** 19200 * {@hide} 19201 * @param id the id of the view to be found 19202 * @return the view of the specified id, null if cannot be found 19203 */ 19204 protected View findViewTraversal(@IdRes int id) { 19205 if (id == mID) { 19206 return this; 19207 } 19208 return null; 19209 } 19210 19211 /** 19212 * {@hide} 19213 * @param tag the tag of the view to be found 19214 * @return the view of specified tag, null if cannot be found 19215 */ 19216 protected View findViewWithTagTraversal(Object tag) { 19217 if (tag != null && tag.equals(mTag)) { 19218 return this; 19219 } 19220 return null; 19221 } 19222 19223 /** 19224 * {@hide} 19225 * @param predicate The predicate to evaluate. 19226 * @param childToSkip If not null, ignores this child during the recursive traversal. 19227 * @return The first view that matches the predicate or null. 19228 */ 19229 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 19230 if (predicate.apply(this)) { 19231 return this; 19232 } 19233 return null; 19234 } 19235 19236 /** 19237 * Look for a child view with the given id. If this view has the given 19238 * id, return this view. 19239 * 19240 * @param id The id to search for. 19241 * @return The view that has the given id in the hierarchy or null 19242 */ 19243 @Nullable 19244 public final View findViewById(@IdRes int id) { 19245 if (id < 0) { 19246 return null; 19247 } 19248 return findViewTraversal(id); 19249 } 19250 19251 /** 19252 * Finds a view by its unuque and stable accessibility id. 19253 * 19254 * @param accessibilityId The searched accessibility id. 19255 * @return The found view. 19256 */ 19257 final View findViewByAccessibilityId(int accessibilityId) { 19258 if (accessibilityId < 0) { 19259 return null; 19260 } 19261 View view = findViewByAccessibilityIdTraversal(accessibilityId); 19262 if (view != null) { 19263 return view.includeForAccessibility() ? view : null; 19264 } 19265 return null; 19266 } 19267 19268 /** 19269 * Performs the traversal to find a view by its unuque and stable accessibility id. 19270 * 19271 * <strong>Note:</strong>This method does not stop at the root namespace 19272 * boundary since the user can touch the screen at an arbitrary location 19273 * potentially crossing the root namespace bounday which will send an 19274 * accessibility event to accessibility services and they should be able 19275 * to obtain the event source. Also accessibility ids are guaranteed to be 19276 * unique in the window. 19277 * 19278 * @param accessibilityId The accessibility id. 19279 * @return The found view. 19280 * 19281 * @hide 19282 */ 19283 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 19284 if (getAccessibilityViewId() == accessibilityId) { 19285 return this; 19286 } 19287 return null; 19288 } 19289 19290 /** 19291 * Look for a child view with the given tag. If this view has the given 19292 * tag, return this view. 19293 * 19294 * @param tag The tag to search for, using "tag.equals(getTag())". 19295 * @return The View that has the given tag in the hierarchy or null 19296 */ 19297 public final View findViewWithTag(Object tag) { 19298 if (tag == null) { 19299 return null; 19300 } 19301 return findViewWithTagTraversal(tag); 19302 } 19303 19304 /** 19305 * {@hide} 19306 * Look for a child view that matches the specified predicate. 19307 * If this view matches the predicate, return this view. 19308 * 19309 * @param predicate The predicate to evaluate. 19310 * @return The first view that matches the predicate or null. 19311 */ 19312 public final View findViewByPredicate(Predicate<View> predicate) { 19313 return findViewByPredicateTraversal(predicate, null); 19314 } 19315 19316 /** 19317 * {@hide} 19318 * Look for a child view that matches the specified predicate, 19319 * starting with the specified view and its descendents and then 19320 * recusively searching the ancestors and siblings of that view 19321 * until this view is reached. 19322 * 19323 * This method is useful in cases where the predicate does not match 19324 * a single unique view (perhaps multiple views use the same id) 19325 * and we are trying to find the view that is "closest" in scope to the 19326 * starting view. 19327 * 19328 * @param start The view to start from. 19329 * @param predicate The predicate to evaluate. 19330 * @return The first view that matches the predicate or null. 19331 */ 19332 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 19333 View childToSkip = null; 19334 for (;;) { 19335 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 19336 if (view != null || start == this) { 19337 return view; 19338 } 19339 19340 ViewParent parent = start.getParent(); 19341 if (parent == null || !(parent instanceof View)) { 19342 return null; 19343 } 19344 19345 childToSkip = start; 19346 start = (View) parent; 19347 } 19348 } 19349 19350 /** 19351 * Sets the identifier for this view. The identifier does not have to be 19352 * unique in this view's hierarchy. The identifier should be a positive 19353 * number. 19354 * 19355 * @see #NO_ID 19356 * @see #getId() 19357 * @see #findViewById(int) 19358 * 19359 * @param id a number used to identify the view 19360 * 19361 * @attr ref android.R.styleable#View_id 19362 */ 19363 public void setId(@IdRes int id) { 19364 mID = id; 19365 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 19366 mID = generateViewId(); 19367 } 19368 } 19369 19370 /** 19371 * {@hide} 19372 * 19373 * @param isRoot true if the view belongs to the root namespace, false 19374 * otherwise 19375 */ 19376 public void setIsRootNamespace(boolean isRoot) { 19377 if (isRoot) { 19378 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 19379 } else { 19380 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 19381 } 19382 } 19383 19384 /** 19385 * {@hide} 19386 * 19387 * @return true if the view belongs to the root namespace, false otherwise 19388 */ 19389 public boolean isRootNamespace() { 19390 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 19391 } 19392 19393 /** 19394 * Returns this view's identifier. 19395 * 19396 * @return a positive integer used to identify the view or {@link #NO_ID} 19397 * if the view has no ID 19398 * 19399 * @see #setId(int) 19400 * @see #findViewById(int) 19401 * @attr ref android.R.styleable#View_id 19402 */ 19403 @IdRes 19404 @ViewDebug.CapturedViewProperty 19405 public int getId() { 19406 return mID; 19407 } 19408 19409 /** 19410 * Returns this view's tag. 19411 * 19412 * @return the Object stored in this view as a tag, or {@code null} if not 19413 * set 19414 * 19415 * @see #setTag(Object) 19416 * @see #getTag(int) 19417 */ 19418 @ViewDebug.ExportedProperty 19419 public Object getTag() { 19420 return mTag; 19421 } 19422 19423 /** 19424 * Sets the tag associated with this view. A tag can be used to mark 19425 * a view in its hierarchy and does not have to be unique within the 19426 * hierarchy. Tags can also be used to store data within a view without 19427 * resorting to another data structure. 19428 * 19429 * @param tag an Object to tag the view with 19430 * 19431 * @see #getTag() 19432 * @see #setTag(int, Object) 19433 */ 19434 public void setTag(final Object tag) { 19435 mTag = tag; 19436 } 19437 19438 /** 19439 * Returns the tag associated with this view and the specified key. 19440 * 19441 * @param key The key identifying the tag 19442 * 19443 * @return the Object stored in this view as a tag, or {@code null} if not 19444 * set 19445 * 19446 * @see #setTag(int, Object) 19447 * @see #getTag() 19448 */ 19449 public Object getTag(int key) { 19450 if (mKeyedTags != null) return mKeyedTags.get(key); 19451 return null; 19452 } 19453 19454 /** 19455 * Sets a tag associated with this view and a key. A tag can be used 19456 * to mark a view in its hierarchy and does not have to be unique within 19457 * the hierarchy. Tags can also be used to store data within a view 19458 * without resorting to another data structure. 19459 * 19460 * The specified key should be an id declared in the resources of the 19461 * application to ensure it is unique (see the <a 19462 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 19463 * Keys identified as belonging to 19464 * the Android framework or not associated with any package will cause 19465 * an {@link IllegalArgumentException} to be thrown. 19466 * 19467 * @param key The key identifying the tag 19468 * @param tag An Object to tag the view with 19469 * 19470 * @throws IllegalArgumentException If they specified key is not valid 19471 * 19472 * @see #setTag(Object) 19473 * @see #getTag(int) 19474 */ 19475 public void setTag(int key, final Object tag) { 19476 // If the package id is 0x00 or 0x01, it's either an undefined package 19477 // or a framework id 19478 if ((key >>> 24) < 2) { 19479 throw new IllegalArgumentException("The key must be an application-specific " 19480 + "resource id."); 19481 } 19482 19483 setKeyedTag(key, tag); 19484 } 19485 19486 /** 19487 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 19488 * framework id. 19489 * 19490 * @hide 19491 */ 19492 public void setTagInternal(int key, Object tag) { 19493 if ((key >>> 24) != 0x1) { 19494 throw new IllegalArgumentException("The key must be a framework-specific " 19495 + "resource id."); 19496 } 19497 19498 setKeyedTag(key, tag); 19499 } 19500 19501 private void setKeyedTag(int key, Object tag) { 19502 if (mKeyedTags == null) { 19503 mKeyedTags = new SparseArray<Object>(2); 19504 } 19505 19506 mKeyedTags.put(key, tag); 19507 } 19508 19509 /** 19510 * Prints information about this view in the log output, with the tag 19511 * {@link #VIEW_LOG_TAG}. 19512 * 19513 * @hide 19514 */ 19515 public void debug() { 19516 debug(0); 19517 } 19518 19519 /** 19520 * Prints information about this view in the log output, with the tag 19521 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 19522 * indentation defined by the <code>depth</code>. 19523 * 19524 * @param depth the indentation level 19525 * 19526 * @hide 19527 */ 19528 protected void debug(int depth) { 19529 String output = debugIndent(depth - 1); 19530 19531 output += "+ " + this; 19532 int id = getId(); 19533 if (id != -1) { 19534 output += " (id=" + id + ")"; 19535 } 19536 Object tag = getTag(); 19537 if (tag != null) { 19538 output += " (tag=" + tag + ")"; 19539 } 19540 Log.d(VIEW_LOG_TAG, output); 19541 19542 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 19543 output = debugIndent(depth) + " FOCUSED"; 19544 Log.d(VIEW_LOG_TAG, output); 19545 } 19546 19547 output = debugIndent(depth); 19548 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 19549 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 19550 + "} "; 19551 Log.d(VIEW_LOG_TAG, output); 19552 19553 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 19554 || mPaddingBottom != 0) { 19555 output = debugIndent(depth); 19556 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 19557 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 19558 Log.d(VIEW_LOG_TAG, output); 19559 } 19560 19561 output = debugIndent(depth); 19562 output += "mMeasureWidth=" + mMeasuredWidth + 19563 " mMeasureHeight=" + mMeasuredHeight; 19564 Log.d(VIEW_LOG_TAG, output); 19565 19566 output = debugIndent(depth); 19567 if (mLayoutParams == null) { 19568 output += "BAD! no layout params"; 19569 } else { 19570 output = mLayoutParams.debug(output); 19571 } 19572 Log.d(VIEW_LOG_TAG, output); 19573 19574 output = debugIndent(depth); 19575 output += "flags={"; 19576 output += View.printFlags(mViewFlags); 19577 output += "}"; 19578 Log.d(VIEW_LOG_TAG, output); 19579 19580 output = debugIndent(depth); 19581 output += "privateFlags={"; 19582 output += View.printPrivateFlags(mPrivateFlags); 19583 output += "}"; 19584 Log.d(VIEW_LOG_TAG, output); 19585 } 19586 19587 /** 19588 * Creates a string of whitespaces used for indentation. 19589 * 19590 * @param depth the indentation level 19591 * @return a String containing (depth * 2 + 3) * 2 white spaces 19592 * 19593 * @hide 19594 */ 19595 protected static String debugIndent(int depth) { 19596 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 19597 for (int i = 0; i < (depth * 2) + 3; i++) { 19598 spaces.append(' ').append(' '); 19599 } 19600 return spaces.toString(); 19601 } 19602 19603 /** 19604 * <p>Return the offset of the widget's text baseline from the widget's top 19605 * boundary. If this widget does not support baseline alignment, this 19606 * method returns -1. </p> 19607 * 19608 * @return the offset of the baseline within the widget's bounds or -1 19609 * if baseline alignment is not supported 19610 */ 19611 @ViewDebug.ExportedProperty(category = "layout") 19612 public int getBaseline() { 19613 return -1; 19614 } 19615 19616 /** 19617 * Returns whether the view hierarchy is currently undergoing a layout pass. This 19618 * information is useful to avoid situations such as calling {@link #requestLayout()} during 19619 * a layout pass. 19620 * 19621 * @return whether the view hierarchy is currently undergoing a layout pass 19622 */ 19623 public boolean isInLayout() { 19624 ViewRootImpl viewRoot = getViewRootImpl(); 19625 return (viewRoot != null && viewRoot.isInLayout()); 19626 } 19627 19628 /** 19629 * Call this when something has changed which has invalidated the 19630 * layout of this view. This will schedule a layout pass of the view 19631 * tree. This should not be called while the view hierarchy is currently in a layout 19632 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 19633 * end of the current layout pass (and then layout will run again) or after the current 19634 * frame is drawn and the next layout occurs. 19635 * 19636 * <p>Subclasses which override this method should call the superclass method to 19637 * handle possible request-during-layout errors correctly.</p> 19638 */ 19639 @CallSuper 19640 public void requestLayout() { 19641 if (mMeasureCache != null) mMeasureCache.clear(); 19642 19643 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 19644 // Only trigger request-during-layout logic if this is the view requesting it, 19645 // not the views in its parent hierarchy 19646 ViewRootImpl viewRoot = getViewRootImpl(); 19647 if (viewRoot != null && viewRoot.isInLayout()) { 19648 if (!viewRoot.requestLayoutDuringLayout(this)) { 19649 return; 19650 } 19651 } 19652 mAttachInfo.mViewRequestingLayout = this; 19653 } 19654 19655 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19656 mPrivateFlags |= PFLAG_INVALIDATED; 19657 19658 if (mParent != null && !mParent.isLayoutRequested()) { 19659 mParent.requestLayout(); 19660 } 19661 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 19662 mAttachInfo.mViewRequestingLayout = null; 19663 } 19664 } 19665 19666 /** 19667 * Forces this view to be laid out during the next layout pass. 19668 * This method does not call requestLayout() or forceLayout() 19669 * on the parent. 19670 */ 19671 public void forceLayout() { 19672 if (mMeasureCache != null) mMeasureCache.clear(); 19673 19674 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19675 mPrivateFlags |= PFLAG_INVALIDATED; 19676 } 19677 19678 /** 19679 * <p> 19680 * This is called to find out how big a view should be. The parent 19681 * supplies constraint information in the width and height parameters. 19682 * </p> 19683 * 19684 * <p> 19685 * The actual measurement work of a view is performed in 19686 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 19687 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 19688 * </p> 19689 * 19690 * 19691 * @param widthMeasureSpec Horizontal space requirements as imposed by the 19692 * parent 19693 * @param heightMeasureSpec Vertical space requirements as imposed by the 19694 * parent 19695 * 19696 * @see #onMeasure(int, int) 19697 */ 19698 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 19699 boolean optical = isLayoutModeOptical(this); 19700 if (optical != isLayoutModeOptical(mParent)) { 19701 Insets insets = getOpticalInsets(); 19702 int oWidth = insets.left + insets.right; 19703 int oHeight = insets.top + insets.bottom; 19704 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 19705 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 19706 } 19707 19708 // Suppress sign extension for the low bytes 19709 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 19710 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 19711 19712 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19713 19714 // Optimize layout by avoiding an extra EXACTLY pass when the view is 19715 // already measured as the correct size. In API 23 and below, this 19716 // extra pass is required to make LinearLayout re-distribute weight. 19717 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 19718 || heightMeasureSpec != mOldHeightMeasureSpec; 19719 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 19720 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 19721 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 19722 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 19723 final boolean needsLayout = specChanged 19724 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 19725 19726 if (forceLayout || needsLayout) { 19727 // first clears the measured dimension flag 19728 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 19729 19730 resolveRtlPropertiesIfNeeded(); 19731 19732 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 19733 if (cacheIndex < 0 || sIgnoreMeasureCache) { 19734 // measure ourselves, this should set the measured dimension flag back 19735 onMeasure(widthMeasureSpec, heightMeasureSpec); 19736 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19737 } else { 19738 long value = mMeasureCache.valueAt(cacheIndex); 19739 // Casting a long to int drops the high 32 bits, no mask needed 19740 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 19741 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19742 } 19743 19744 // flag not set, setMeasuredDimension() was not invoked, we raise 19745 // an exception to warn the developer 19746 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 19747 throw new IllegalStateException("View with id " + getId() + ": " 19748 + getClass().getName() + "#onMeasure() did not set the" 19749 + " measured dimension by calling" 19750 + " setMeasuredDimension()"); 19751 } 19752 19753 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 19754 } 19755 19756 mOldWidthMeasureSpec = widthMeasureSpec; 19757 mOldHeightMeasureSpec = heightMeasureSpec; 19758 19759 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 19760 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 19761 } 19762 19763 /** 19764 * <p> 19765 * Measure the view and its content to determine the measured width and the 19766 * measured height. This method is invoked by {@link #measure(int, int)} and 19767 * should be overridden by subclasses to provide accurate and efficient 19768 * measurement of their contents. 19769 * </p> 19770 * 19771 * <p> 19772 * <strong>CONTRACT:</strong> When overriding this method, you 19773 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 19774 * measured width and height of this view. Failure to do so will trigger an 19775 * <code>IllegalStateException</code>, thrown by 19776 * {@link #measure(int, int)}. Calling the superclass' 19777 * {@link #onMeasure(int, int)} is a valid use. 19778 * </p> 19779 * 19780 * <p> 19781 * The base class implementation of measure defaults to the background size, 19782 * unless a larger size is allowed by the MeasureSpec. Subclasses should 19783 * override {@link #onMeasure(int, int)} to provide better measurements of 19784 * their content. 19785 * </p> 19786 * 19787 * <p> 19788 * If this method is overridden, it is the subclass's responsibility to make 19789 * sure the measured height and width are at least the view's minimum height 19790 * and width ({@link #getSuggestedMinimumHeight()} and 19791 * {@link #getSuggestedMinimumWidth()}). 19792 * </p> 19793 * 19794 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 19795 * The requirements are encoded with 19796 * {@link android.view.View.MeasureSpec}. 19797 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 19798 * The requirements are encoded with 19799 * {@link android.view.View.MeasureSpec}. 19800 * 19801 * @see #getMeasuredWidth() 19802 * @see #getMeasuredHeight() 19803 * @see #setMeasuredDimension(int, int) 19804 * @see #getSuggestedMinimumHeight() 19805 * @see #getSuggestedMinimumWidth() 19806 * @see android.view.View.MeasureSpec#getMode(int) 19807 * @see android.view.View.MeasureSpec#getSize(int) 19808 */ 19809 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 19810 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 19811 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 19812 } 19813 19814 /** 19815 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 19816 * measured width and measured height. Failing to do so will trigger an 19817 * exception at measurement time.</p> 19818 * 19819 * @param measuredWidth The measured width of this view. May be a complex 19820 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19821 * {@link #MEASURED_STATE_TOO_SMALL}. 19822 * @param measuredHeight The measured height of this view. May be a complex 19823 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19824 * {@link #MEASURED_STATE_TOO_SMALL}. 19825 */ 19826 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 19827 boolean optical = isLayoutModeOptical(this); 19828 if (optical != isLayoutModeOptical(mParent)) { 19829 Insets insets = getOpticalInsets(); 19830 int opticalWidth = insets.left + insets.right; 19831 int opticalHeight = insets.top + insets.bottom; 19832 19833 measuredWidth += optical ? opticalWidth : -opticalWidth; 19834 measuredHeight += optical ? opticalHeight : -opticalHeight; 19835 } 19836 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 19837 } 19838 19839 /** 19840 * Sets the measured dimension without extra processing for things like optical bounds. 19841 * Useful for reapplying consistent values that have already been cooked with adjustments 19842 * for optical bounds, etc. such as those from the measurement cache. 19843 * 19844 * @param measuredWidth The measured width of this view. May be a complex 19845 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19846 * {@link #MEASURED_STATE_TOO_SMALL}. 19847 * @param measuredHeight The measured height of this view. May be a complex 19848 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19849 * {@link #MEASURED_STATE_TOO_SMALL}. 19850 */ 19851 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 19852 mMeasuredWidth = measuredWidth; 19853 mMeasuredHeight = measuredHeight; 19854 19855 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 19856 } 19857 19858 /** 19859 * Merge two states as returned by {@link #getMeasuredState()}. 19860 * @param curState The current state as returned from a view or the result 19861 * of combining multiple views. 19862 * @param newState The new view state to combine. 19863 * @return Returns a new integer reflecting the combination of the two 19864 * states. 19865 */ 19866 public static int combineMeasuredStates(int curState, int newState) { 19867 return curState | newState; 19868 } 19869 19870 /** 19871 * Version of {@link #resolveSizeAndState(int, int, int)} 19872 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 19873 */ 19874 public static int resolveSize(int size, int measureSpec) { 19875 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 19876 } 19877 19878 /** 19879 * Utility to reconcile a desired size and state, with constraints imposed 19880 * by a MeasureSpec. Will take the desired size, unless a different size 19881 * is imposed by the constraints. The returned value is a compound integer, 19882 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 19883 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 19884 * resulting size is smaller than the size the view wants to be. 19885 * 19886 * @param size How big the view wants to be. 19887 * @param measureSpec Constraints imposed by the parent. 19888 * @param childMeasuredState Size information bit mask for the view's 19889 * children. 19890 * @return Size information bit mask as defined by 19891 * {@link #MEASURED_SIZE_MASK} and 19892 * {@link #MEASURED_STATE_TOO_SMALL}. 19893 */ 19894 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 19895 final int specMode = MeasureSpec.getMode(measureSpec); 19896 final int specSize = MeasureSpec.getSize(measureSpec); 19897 final int result; 19898 switch (specMode) { 19899 case MeasureSpec.AT_MOST: 19900 if (specSize < size) { 19901 result = specSize | MEASURED_STATE_TOO_SMALL; 19902 } else { 19903 result = size; 19904 } 19905 break; 19906 case MeasureSpec.EXACTLY: 19907 result = specSize; 19908 break; 19909 case MeasureSpec.UNSPECIFIED: 19910 default: 19911 result = size; 19912 } 19913 return result | (childMeasuredState & MEASURED_STATE_MASK); 19914 } 19915 19916 /** 19917 * Utility to return a default size. Uses the supplied size if the 19918 * MeasureSpec imposed no constraints. Will get larger if allowed 19919 * by the MeasureSpec. 19920 * 19921 * @param size Default size for this view 19922 * @param measureSpec Constraints imposed by the parent 19923 * @return The size this view should be. 19924 */ 19925 public static int getDefaultSize(int size, int measureSpec) { 19926 int result = size; 19927 int specMode = MeasureSpec.getMode(measureSpec); 19928 int specSize = MeasureSpec.getSize(measureSpec); 19929 19930 switch (specMode) { 19931 case MeasureSpec.UNSPECIFIED: 19932 result = size; 19933 break; 19934 case MeasureSpec.AT_MOST: 19935 case MeasureSpec.EXACTLY: 19936 result = specSize; 19937 break; 19938 } 19939 return result; 19940 } 19941 19942 /** 19943 * Returns the suggested minimum height that the view should use. This 19944 * returns the maximum of the view's minimum height 19945 * and the background's minimum height 19946 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 19947 * <p> 19948 * When being used in {@link #onMeasure(int, int)}, the caller should still 19949 * ensure the returned height is within the requirements of the parent. 19950 * 19951 * @return The suggested minimum height of the view. 19952 */ 19953 protected int getSuggestedMinimumHeight() { 19954 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 19955 19956 } 19957 19958 /** 19959 * Returns the suggested minimum width that the view should use. This 19960 * returns the maximum of the view's minimum width 19961 * and the background's minimum width 19962 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 19963 * <p> 19964 * When being used in {@link #onMeasure(int, int)}, the caller should still 19965 * ensure the returned width is within the requirements of the parent. 19966 * 19967 * @return The suggested minimum width of the view. 19968 */ 19969 protected int getSuggestedMinimumWidth() { 19970 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 19971 } 19972 19973 /** 19974 * Returns the minimum height of the view. 19975 * 19976 * @return the minimum height the view will try to be. 19977 * 19978 * @see #setMinimumHeight(int) 19979 * 19980 * @attr ref android.R.styleable#View_minHeight 19981 */ 19982 public int getMinimumHeight() { 19983 return mMinHeight; 19984 } 19985 19986 /** 19987 * Sets the minimum height of the view. It is not guaranteed the view will 19988 * be able to achieve this minimum height (for example, if its parent layout 19989 * constrains it with less available height). 19990 * 19991 * @param minHeight The minimum height the view will try to be. 19992 * 19993 * @see #getMinimumHeight() 19994 * 19995 * @attr ref android.R.styleable#View_minHeight 19996 */ 19997 @RemotableViewMethod 19998 public void setMinimumHeight(int minHeight) { 19999 mMinHeight = minHeight; 20000 requestLayout(); 20001 } 20002 20003 /** 20004 * Returns the minimum width of the view. 20005 * 20006 * @return the minimum width the view will try to be. 20007 * 20008 * @see #setMinimumWidth(int) 20009 * 20010 * @attr ref android.R.styleable#View_minWidth 20011 */ 20012 public int getMinimumWidth() { 20013 return mMinWidth; 20014 } 20015 20016 /** 20017 * Sets the minimum width of the view. It is not guaranteed the view will 20018 * be able to achieve this minimum width (for example, if its parent layout 20019 * constrains it with less available width). 20020 * 20021 * @param minWidth The minimum width the view will try to be. 20022 * 20023 * @see #getMinimumWidth() 20024 * 20025 * @attr ref android.R.styleable#View_minWidth 20026 */ 20027 public void setMinimumWidth(int minWidth) { 20028 mMinWidth = minWidth; 20029 requestLayout(); 20030 20031 } 20032 20033 /** 20034 * Get the animation currently associated with this view. 20035 * 20036 * @return The animation that is currently playing or 20037 * scheduled to play for this view. 20038 */ 20039 public Animation getAnimation() { 20040 return mCurrentAnimation; 20041 } 20042 20043 /** 20044 * Start the specified animation now. 20045 * 20046 * @param animation the animation to start now 20047 */ 20048 public void startAnimation(Animation animation) { 20049 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 20050 setAnimation(animation); 20051 invalidateParentCaches(); 20052 invalidate(true); 20053 } 20054 20055 /** 20056 * Cancels any animations for this view. 20057 */ 20058 public void clearAnimation() { 20059 if (mCurrentAnimation != null) { 20060 mCurrentAnimation.detach(); 20061 } 20062 mCurrentAnimation = null; 20063 invalidateParentIfNeeded(); 20064 } 20065 20066 /** 20067 * Sets the next animation to play for this view. 20068 * If you want the animation to play immediately, use 20069 * {@link #startAnimation(android.view.animation.Animation)} instead. 20070 * This method provides allows fine-grained 20071 * control over the start time and invalidation, but you 20072 * must make sure that 1) the animation has a start time set, and 20073 * 2) the view's parent (which controls animations on its children) 20074 * will be invalidated when the animation is supposed to 20075 * start. 20076 * 20077 * @param animation The next animation, or null. 20078 */ 20079 public void setAnimation(Animation animation) { 20080 mCurrentAnimation = animation; 20081 20082 if (animation != null) { 20083 // If the screen is off assume the animation start time is now instead of 20084 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 20085 // would cause the animation to start when the screen turns back on 20086 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 20087 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 20088 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 20089 } 20090 animation.reset(); 20091 } 20092 } 20093 20094 /** 20095 * Invoked by a parent ViewGroup to notify the start of the animation 20096 * currently associated with this view. If you override this method, 20097 * always call super.onAnimationStart(); 20098 * 20099 * @see #setAnimation(android.view.animation.Animation) 20100 * @see #getAnimation() 20101 */ 20102 @CallSuper 20103 protected void onAnimationStart() { 20104 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 20105 } 20106 20107 /** 20108 * Invoked by a parent ViewGroup to notify the end of the animation 20109 * currently associated with this view. If you override this method, 20110 * always call super.onAnimationEnd(); 20111 * 20112 * @see #setAnimation(android.view.animation.Animation) 20113 * @see #getAnimation() 20114 */ 20115 @CallSuper 20116 protected void onAnimationEnd() { 20117 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 20118 } 20119 20120 /** 20121 * Invoked if there is a Transform that involves alpha. Subclass that can 20122 * draw themselves with the specified alpha should return true, and then 20123 * respect that alpha when their onDraw() is called. If this returns false 20124 * then the view may be redirected to draw into an offscreen buffer to 20125 * fulfill the request, which will look fine, but may be slower than if the 20126 * subclass handles it internally. The default implementation returns false. 20127 * 20128 * @param alpha The alpha (0..255) to apply to the view's drawing 20129 * @return true if the view can draw with the specified alpha. 20130 */ 20131 protected boolean onSetAlpha(int alpha) { 20132 return false; 20133 } 20134 20135 /** 20136 * This is used by the RootView to perform an optimization when 20137 * the view hierarchy contains one or several SurfaceView. 20138 * SurfaceView is always considered transparent, but its children are not, 20139 * therefore all View objects remove themselves from the global transparent 20140 * region (passed as a parameter to this function). 20141 * 20142 * @param region The transparent region for this ViewAncestor (window). 20143 * 20144 * @return Returns true if the effective visibility of the view at this 20145 * point is opaque, regardless of the transparent region; returns false 20146 * if it is possible for underlying windows to be seen behind the view. 20147 * 20148 * {@hide} 20149 */ 20150 public boolean gatherTransparentRegion(Region region) { 20151 final AttachInfo attachInfo = mAttachInfo; 20152 if (region != null && attachInfo != null) { 20153 final int pflags = mPrivateFlags; 20154 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 20155 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 20156 // remove it from the transparent region. 20157 final int[] location = attachInfo.mTransparentLocation; 20158 getLocationInWindow(location); 20159 region.op(location[0], location[1], location[0] + mRight - mLeft, 20160 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 20161 } else { 20162 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 20163 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 20164 // the background drawable's non-transparent parts from this transparent region. 20165 applyDrawableToTransparentRegion(mBackground, region); 20166 } 20167 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20168 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 20169 // Similarly, we remove the foreground drawable's non-transparent parts. 20170 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 20171 } 20172 } 20173 } 20174 return true; 20175 } 20176 20177 /** 20178 * Play a sound effect for this view. 20179 * 20180 * <p>The framework will play sound effects for some built in actions, such as 20181 * clicking, but you may wish to play these effects in your widget, 20182 * for instance, for internal navigation. 20183 * 20184 * <p>The sound effect will only be played if sound effects are enabled by the user, and 20185 * {@link #isSoundEffectsEnabled()} is true. 20186 * 20187 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 20188 */ 20189 public void playSoundEffect(int soundConstant) { 20190 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 20191 return; 20192 } 20193 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 20194 } 20195 20196 /** 20197 * BZZZTT!!1! 20198 * 20199 * <p>Provide haptic feedback to the user for this view. 20200 * 20201 * <p>The framework will provide haptic feedback for some built in actions, 20202 * such as long presses, but you may wish to provide feedback for your 20203 * own widget. 20204 * 20205 * <p>The feedback will only be performed if 20206 * {@link #isHapticFeedbackEnabled()} is true. 20207 * 20208 * @param feedbackConstant One of the constants defined in 20209 * {@link HapticFeedbackConstants} 20210 */ 20211 public boolean performHapticFeedback(int feedbackConstant) { 20212 return performHapticFeedback(feedbackConstant, 0); 20213 } 20214 20215 /** 20216 * BZZZTT!!1! 20217 * 20218 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 20219 * 20220 * @param feedbackConstant One of the constants defined in 20221 * {@link HapticFeedbackConstants} 20222 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 20223 */ 20224 public boolean performHapticFeedback(int feedbackConstant, int flags) { 20225 if (mAttachInfo == null) { 20226 return false; 20227 } 20228 //noinspection SimplifiableIfStatement 20229 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 20230 && !isHapticFeedbackEnabled()) { 20231 return false; 20232 } 20233 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 20234 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 20235 } 20236 20237 /** 20238 * Request that the visibility of the status bar or other screen/window 20239 * decorations be changed. 20240 * 20241 * <p>This method is used to put the over device UI into temporary modes 20242 * where the user's attention is focused more on the application content, 20243 * by dimming or hiding surrounding system affordances. This is typically 20244 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 20245 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 20246 * to be placed behind the action bar (and with these flags other system 20247 * affordances) so that smooth transitions between hiding and showing them 20248 * can be done. 20249 * 20250 * <p>Two representative examples of the use of system UI visibility is 20251 * implementing a content browsing application (like a magazine reader) 20252 * and a video playing application. 20253 * 20254 * <p>The first code shows a typical implementation of a View in a content 20255 * browsing application. In this implementation, the application goes 20256 * into a content-oriented mode by hiding the status bar and action bar, 20257 * and putting the navigation elements into lights out mode. The user can 20258 * then interact with content while in this mode. Such an application should 20259 * provide an easy way for the user to toggle out of the mode (such as to 20260 * check information in the status bar or access notifications). In the 20261 * implementation here, this is done simply by tapping on the content. 20262 * 20263 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 20264 * content} 20265 * 20266 * <p>This second code sample shows a typical implementation of a View 20267 * in a video playing application. In this situation, while the video is 20268 * playing the application would like to go into a complete full-screen mode, 20269 * to use as much of the display as possible for the video. When in this state 20270 * the user can not interact with the application; the system intercepts 20271 * touching on the screen to pop the UI out of full screen mode. See 20272 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 20273 * 20274 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 20275 * content} 20276 * 20277 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20278 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20279 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20280 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20281 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20282 */ 20283 public void setSystemUiVisibility(int visibility) { 20284 if (visibility != mSystemUiVisibility) { 20285 mSystemUiVisibility = visibility; 20286 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20287 mParent.recomputeViewAttributes(this); 20288 } 20289 } 20290 } 20291 20292 /** 20293 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 20294 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20295 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20296 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20297 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20298 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20299 */ 20300 public int getSystemUiVisibility() { 20301 return mSystemUiVisibility; 20302 } 20303 20304 /** 20305 * Returns the current system UI visibility that is currently set for 20306 * the entire window. This is the combination of the 20307 * {@link #setSystemUiVisibility(int)} values supplied by all of the 20308 * views in the window. 20309 */ 20310 public int getWindowSystemUiVisibility() { 20311 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 20312 } 20313 20314 /** 20315 * Override to find out when the window's requested system UI visibility 20316 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 20317 * This is different from the callbacks received through 20318 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 20319 * in that this is only telling you about the local request of the window, 20320 * not the actual values applied by the system. 20321 */ 20322 public void onWindowSystemUiVisibilityChanged(int visible) { 20323 } 20324 20325 /** 20326 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 20327 * the view hierarchy. 20328 */ 20329 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 20330 onWindowSystemUiVisibilityChanged(visible); 20331 } 20332 20333 /** 20334 * Set a listener to receive callbacks when the visibility of the system bar changes. 20335 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 20336 */ 20337 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 20338 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 20339 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20340 mParent.recomputeViewAttributes(this); 20341 } 20342 } 20343 20344 /** 20345 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 20346 * the view hierarchy. 20347 */ 20348 public void dispatchSystemUiVisibilityChanged(int visibility) { 20349 ListenerInfo li = mListenerInfo; 20350 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 20351 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 20352 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 20353 } 20354 } 20355 20356 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 20357 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 20358 if (val != mSystemUiVisibility) { 20359 setSystemUiVisibility(val); 20360 return true; 20361 } 20362 return false; 20363 } 20364 20365 /** @hide */ 20366 public void setDisabledSystemUiVisibility(int flags) { 20367 if (mAttachInfo != null) { 20368 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 20369 mAttachInfo.mDisabledSystemUiVisibility = flags; 20370 if (mParent != null) { 20371 mParent.recomputeViewAttributes(this); 20372 } 20373 } 20374 } 20375 } 20376 20377 /** 20378 * Creates an image that the system displays during the drag and drop 20379 * operation. This is called a "drag shadow". The default implementation 20380 * for a DragShadowBuilder based on a View returns an image that has exactly the same 20381 * appearance as the given View. The default also positions the center of the drag shadow 20382 * directly under the touch point. If no View is provided (the constructor with no parameters 20383 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 20384 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 20385 * default is an invisible drag shadow. 20386 * <p> 20387 * You are not required to use the View you provide to the constructor as the basis of the 20388 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 20389 * anything you want as the drag shadow. 20390 * </p> 20391 * <p> 20392 * You pass a DragShadowBuilder object to the system when you start the drag. The system 20393 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 20394 * size and position of the drag shadow. It uses this data to construct a 20395 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 20396 * so that your application can draw the shadow image in the Canvas. 20397 * </p> 20398 * 20399 * <div class="special reference"> 20400 * <h3>Developer Guides</h3> 20401 * <p>For a guide to implementing drag and drop features, read the 20402 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20403 * </div> 20404 */ 20405 public static class DragShadowBuilder { 20406 private final WeakReference<View> mView; 20407 20408 /** 20409 * Constructs a shadow image builder based on a View. By default, the resulting drag 20410 * shadow will have the same appearance and dimensions as the View, with the touch point 20411 * over the center of the View. 20412 * @param view A View. Any View in scope can be used. 20413 */ 20414 public DragShadowBuilder(View view) { 20415 mView = new WeakReference<View>(view); 20416 } 20417 20418 /** 20419 * Construct a shadow builder object with no associated View. This 20420 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 20421 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 20422 * to supply the drag shadow's dimensions and appearance without 20423 * reference to any View object. If they are not overridden, then the result is an 20424 * invisible drag shadow. 20425 */ 20426 public DragShadowBuilder() { 20427 mView = new WeakReference<View>(null); 20428 } 20429 20430 /** 20431 * Returns the View object that had been passed to the 20432 * {@link #View.DragShadowBuilder(View)} 20433 * constructor. If that View parameter was {@code null} or if the 20434 * {@link #View.DragShadowBuilder()} 20435 * constructor was used to instantiate the builder object, this method will return 20436 * null. 20437 * 20438 * @return The View object associate with this builder object. 20439 */ 20440 @SuppressWarnings({"JavadocReference"}) 20441 final public View getView() { 20442 return mView.get(); 20443 } 20444 20445 /** 20446 * Provides the metrics for the shadow image. These include the dimensions of 20447 * the shadow image, and the point within that shadow that should 20448 * be centered under the touch location while dragging. 20449 * <p> 20450 * The default implementation sets the dimensions of the shadow to be the 20451 * same as the dimensions of the View itself and centers the shadow under 20452 * the touch point. 20453 * </p> 20454 * 20455 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 20456 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 20457 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 20458 * image. 20459 * 20460 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 20461 * shadow image that should be underneath the touch point during the drag and drop 20462 * operation. Your application must set {@link android.graphics.Point#x} to the 20463 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 20464 */ 20465 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 20466 final View view = mView.get(); 20467 if (view != null) { 20468 outShadowSize.set(view.getWidth(), view.getHeight()); 20469 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 20470 } else { 20471 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 20472 } 20473 } 20474 20475 /** 20476 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 20477 * based on the dimensions it received from the 20478 * {@link #onProvideShadowMetrics(Point, Point)} callback. 20479 * 20480 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 20481 */ 20482 public void onDrawShadow(Canvas canvas) { 20483 final View view = mView.get(); 20484 if (view != null) { 20485 view.draw(canvas); 20486 } else { 20487 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 20488 } 20489 } 20490 } 20491 20492 /** 20493 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 20494 * startDragAndDrop()} for newer platform versions. 20495 */ 20496 @Deprecated 20497 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 20498 Object myLocalState, int flags) { 20499 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 20500 } 20501 20502 /** 20503 * Starts a drag and drop operation. When your application calls this method, it passes a 20504 * {@link android.view.View.DragShadowBuilder} object to the system. The 20505 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 20506 * to get metrics for the drag shadow, and then calls the object's 20507 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 20508 * <p> 20509 * Once the system has the drag shadow, it begins the drag and drop operation by sending 20510 * drag events to all the View objects in your application that are currently visible. It does 20511 * this either by calling the View object's drag listener (an implementation of 20512 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 20513 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 20514 * Both are passed a {@link android.view.DragEvent} object that has a 20515 * {@link android.view.DragEvent#getAction()} value of 20516 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 20517 * </p> 20518 * <p> 20519 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 20520 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 20521 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 20522 * to the View the user selected for dragging. 20523 * </p> 20524 * @param data A {@link android.content.ClipData} object pointing to the data to be 20525 * transferred by the drag and drop operation. 20526 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20527 * drag shadow. 20528 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 20529 * drop operation. This Object is put into every DragEvent object sent by the system during the 20530 * current drag. 20531 * <p> 20532 * myLocalState is a lightweight mechanism for the sending information from the dragged View 20533 * to the target Views. For example, it can contain flags that differentiate between a 20534 * a copy operation and a move operation. 20535 * </p> 20536 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 20537 * so the parameter should be set to 0. 20538 * @return {@code true} if the method completes successfully, or 20539 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 20540 * do a drag, and so no drag operation is in progress. 20541 */ 20542 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 20543 Object myLocalState, int flags) { 20544 if (ViewDebug.DEBUG_DRAG) { 20545 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 20546 } 20547 boolean okay = false; 20548 20549 Point shadowSize = new Point(); 20550 Point shadowTouchPoint = new Point(); 20551 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 20552 20553 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 20554 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 20555 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 20556 } 20557 20558 if (ViewDebug.DEBUG_DRAG) { 20559 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 20560 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 20561 } 20562 if (mAttachInfo.mDragSurface != null) { 20563 mAttachInfo.mDragSurface.release(); 20564 } 20565 mAttachInfo.mDragSurface = new Surface(); 20566 try { 20567 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 20568 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 20569 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 20570 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 20571 if (mAttachInfo.mDragToken != null) { 20572 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20573 try { 20574 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20575 shadowBuilder.onDrawShadow(canvas); 20576 } finally { 20577 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20578 } 20579 20580 final ViewRootImpl root = getViewRootImpl(); 20581 20582 // Cache the local state object for delivery with DragEvents 20583 root.setLocalDragState(myLocalState); 20584 20585 // repurpose 'shadowSize' for the last touch point 20586 root.getLastTouchPoint(shadowSize); 20587 20588 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 20589 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 20590 shadowTouchPoint.x, shadowTouchPoint.y, data); 20591 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 20592 } 20593 } catch (Exception e) { 20594 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 20595 mAttachInfo.mDragSurface.destroy(); 20596 mAttachInfo.mDragSurface = null; 20597 } 20598 20599 return okay; 20600 } 20601 20602 /** 20603 * Cancels an ongoing drag and drop operation. 20604 * <p> 20605 * A {@link android.view.DragEvent} object with 20606 * {@link android.view.DragEvent#getAction()} value of 20607 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 20608 * {@link android.view.DragEvent#getResult()} value of {@code false} 20609 * will be sent to every 20610 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 20611 * even if they are not currently visible. 20612 * </p> 20613 * <p> 20614 * This method can be called on any View in the same window as the View on which 20615 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 20616 * was called. 20617 * </p> 20618 */ 20619 public final void cancelDragAndDrop() { 20620 if (ViewDebug.DEBUG_DRAG) { 20621 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 20622 } 20623 if (mAttachInfo.mDragToken != null) { 20624 try { 20625 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 20626 } catch (Exception e) { 20627 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 20628 } 20629 mAttachInfo.mDragToken = null; 20630 } else { 20631 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 20632 } 20633 } 20634 20635 /** 20636 * Updates the drag shadow for the ongoing drag and drop operation. 20637 * 20638 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20639 * new drag shadow. 20640 */ 20641 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 20642 if (ViewDebug.DEBUG_DRAG) { 20643 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 20644 } 20645 if (mAttachInfo.mDragToken != null) { 20646 try { 20647 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20648 try { 20649 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20650 shadowBuilder.onDrawShadow(canvas); 20651 } finally { 20652 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20653 } 20654 } catch (Exception e) { 20655 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 20656 } 20657 } else { 20658 Log.e(VIEW_LOG_TAG, "No active drag"); 20659 } 20660 } 20661 20662 /** 20663 * Starts a move from {startX, startY}, the amount of the movement will be the offset 20664 * between {startX, startY} and the new cursor positon. 20665 * @param startX horizontal coordinate where the move started. 20666 * @param startY vertical coordinate where the move started. 20667 * @return whether moving was started successfully. 20668 * @hide 20669 */ 20670 public final boolean startMovingTask(float startX, float startY) { 20671 if (ViewDebug.DEBUG_POSITIONING) { 20672 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 20673 } 20674 try { 20675 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 20676 } catch (RemoteException e) { 20677 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 20678 } 20679 return false; 20680 } 20681 20682 /** 20683 * Handles drag events sent by the system following a call to 20684 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 20685 * startDragAndDrop()}. 20686 *<p> 20687 * When the system calls this method, it passes a 20688 * {@link android.view.DragEvent} object. A call to 20689 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 20690 * in DragEvent. The method uses these to determine what is happening in the drag and drop 20691 * operation. 20692 * @param event The {@link android.view.DragEvent} sent by the system. 20693 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 20694 * in DragEvent, indicating the type of drag event represented by this object. 20695 * @return {@code true} if the method was successful, otherwise {@code false}. 20696 * <p> 20697 * The method should return {@code true} in response to an action type of 20698 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 20699 * operation. 20700 * </p> 20701 * <p> 20702 * The method should also return {@code true} in response to an action type of 20703 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 20704 * {@code false} if it didn't. 20705 * </p> 20706 */ 20707 public boolean onDragEvent(DragEvent event) { 20708 return false; 20709 } 20710 20711 /** 20712 * Detects if this View is enabled and has a drag event listener. 20713 * If both are true, then it calls the drag event listener with the 20714 * {@link android.view.DragEvent} it received. If the drag event listener returns 20715 * {@code true}, then dispatchDragEvent() returns {@code true}. 20716 * <p> 20717 * For all other cases, the method calls the 20718 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 20719 * method and returns its result. 20720 * </p> 20721 * <p> 20722 * This ensures that a drag event is always consumed, even if the View does not have a drag 20723 * event listener. However, if the View has a listener and the listener returns true, then 20724 * onDragEvent() is not called. 20725 * </p> 20726 */ 20727 public boolean dispatchDragEvent(DragEvent event) { 20728 ListenerInfo li = mListenerInfo; 20729 //noinspection SimplifiableIfStatement 20730 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 20731 && li.mOnDragListener.onDrag(this, event)) { 20732 return true; 20733 } 20734 return onDragEvent(event); 20735 } 20736 20737 boolean canAcceptDrag() { 20738 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 20739 } 20740 20741 /** 20742 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 20743 * it is ever exposed at all. 20744 * @hide 20745 */ 20746 public void onCloseSystemDialogs(String reason) { 20747 } 20748 20749 /** 20750 * Given a Drawable whose bounds have been set to draw into this view, 20751 * update a Region being computed for 20752 * {@link #gatherTransparentRegion(android.graphics.Region)} so 20753 * that any non-transparent parts of the Drawable are removed from the 20754 * given transparent region. 20755 * 20756 * @param dr The Drawable whose transparency is to be applied to the region. 20757 * @param region A Region holding the current transparency information, 20758 * where any parts of the region that are set are considered to be 20759 * transparent. On return, this region will be modified to have the 20760 * transparency information reduced by the corresponding parts of the 20761 * Drawable that are not transparent. 20762 * {@hide} 20763 */ 20764 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 20765 if (DBG) { 20766 Log.i("View", "Getting transparent region for: " + this); 20767 } 20768 final Region r = dr.getTransparentRegion(); 20769 final Rect db = dr.getBounds(); 20770 final AttachInfo attachInfo = mAttachInfo; 20771 if (r != null && attachInfo != null) { 20772 final int w = getRight()-getLeft(); 20773 final int h = getBottom()-getTop(); 20774 if (db.left > 0) { 20775 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 20776 r.op(0, 0, db.left, h, Region.Op.UNION); 20777 } 20778 if (db.right < w) { 20779 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 20780 r.op(db.right, 0, w, h, Region.Op.UNION); 20781 } 20782 if (db.top > 0) { 20783 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 20784 r.op(0, 0, w, db.top, Region.Op.UNION); 20785 } 20786 if (db.bottom < h) { 20787 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 20788 r.op(0, db.bottom, w, h, Region.Op.UNION); 20789 } 20790 final int[] location = attachInfo.mTransparentLocation; 20791 getLocationInWindow(location); 20792 r.translate(location[0], location[1]); 20793 region.op(r, Region.Op.INTERSECT); 20794 } else { 20795 region.op(db, Region.Op.DIFFERENCE); 20796 } 20797 } 20798 20799 private void checkForLongClick(int delayOffset, float x, float y) { 20800 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 20801 mHasPerformedLongPress = false; 20802 20803 if (mPendingCheckForLongPress == null) { 20804 mPendingCheckForLongPress = new CheckForLongPress(); 20805 } 20806 mPendingCheckForLongPress.setAnchor(x, y); 20807 mPendingCheckForLongPress.rememberWindowAttachCount(); 20808 postDelayed(mPendingCheckForLongPress, 20809 ViewConfiguration.getLongPressTimeout() - delayOffset); 20810 } 20811 } 20812 20813 /** 20814 * Inflate a view from an XML resource. This convenience method wraps the {@link 20815 * LayoutInflater} class, which provides a full range of options for view inflation. 20816 * 20817 * @param context The Context object for your activity or application. 20818 * @param resource The resource ID to inflate 20819 * @param root A view group that will be the parent. Used to properly inflate the 20820 * layout_* parameters. 20821 * @see LayoutInflater 20822 */ 20823 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 20824 LayoutInflater factory = LayoutInflater.from(context); 20825 return factory.inflate(resource, root); 20826 } 20827 20828 /** 20829 * Scroll the view with standard behavior for scrolling beyond the normal 20830 * content boundaries. Views that call this method should override 20831 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 20832 * results of an over-scroll operation. 20833 * 20834 * Views can use this method to handle any touch or fling-based scrolling. 20835 * 20836 * @param deltaX Change in X in pixels 20837 * @param deltaY Change in Y in pixels 20838 * @param scrollX Current X scroll value in pixels before applying deltaX 20839 * @param scrollY Current Y scroll value in pixels before applying deltaY 20840 * @param scrollRangeX Maximum content scroll range along the X axis 20841 * @param scrollRangeY Maximum content scroll range along the Y axis 20842 * @param maxOverScrollX Number of pixels to overscroll by in either direction 20843 * along the X axis. 20844 * @param maxOverScrollY Number of pixels to overscroll by in either direction 20845 * along the Y axis. 20846 * @param isTouchEvent true if this scroll operation is the result of a touch event. 20847 * @return true if scrolling was clamped to an over-scroll boundary along either 20848 * axis, false otherwise. 20849 */ 20850 @SuppressWarnings({"UnusedParameters"}) 20851 protected boolean overScrollBy(int deltaX, int deltaY, 20852 int scrollX, int scrollY, 20853 int scrollRangeX, int scrollRangeY, 20854 int maxOverScrollX, int maxOverScrollY, 20855 boolean isTouchEvent) { 20856 final int overScrollMode = mOverScrollMode; 20857 final boolean canScrollHorizontal = 20858 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 20859 final boolean canScrollVertical = 20860 computeVerticalScrollRange() > computeVerticalScrollExtent(); 20861 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 20862 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 20863 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 20864 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 20865 20866 int newScrollX = scrollX + deltaX; 20867 if (!overScrollHorizontal) { 20868 maxOverScrollX = 0; 20869 } 20870 20871 int newScrollY = scrollY + deltaY; 20872 if (!overScrollVertical) { 20873 maxOverScrollY = 0; 20874 } 20875 20876 // Clamp values if at the limits and record 20877 final int left = -maxOverScrollX; 20878 final int right = maxOverScrollX + scrollRangeX; 20879 final int top = -maxOverScrollY; 20880 final int bottom = maxOverScrollY + scrollRangeY; 20881 20882 boolean clampedX = false; 20883 if (newScrollX > right) { 20884 newScrollX = right; 20885 clampedX = true; 20886 } else if (newScrollX < left) { 20887 newScrollX = left; 20888 clampedX = true; 20889 } 20890 20891 boolean clampedY = false; 20892 if (newScrollY > bottom) { 20893 newScrollY = bottom; 20894 clampedY = true; 20895 } else if (newScrollY < top) { 20896 newScrollY = top; 20897 clampedY = true; 20898 } 20899 20900 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 20901 20902 return clampedX || clampedY; 20903 } 20904 20905 /** 20906 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 20907 * respond to the results of an over-scroll operation. 20908 * 20909 * @param scrollX New X scroll value in pixels 20910 * @param scrollY New Y scroll value in pixels 20911 * @param clampedX True if scrollX was clamped to an over-scroll boundary 20912 * @param clampedY True if scrollY was clamped to an over-scroll boundary 20913 */ 20914 protected void onOverScrolled(int scrollX, int scrollY, 20915 boolean clampedX, boolean clampedY) { 20916 // Intentionally empty. 20917 } 20918 20919 /** 20920 * Returns the over-scroll mode for this view. The result will be 20921 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20922 * (allow over-scrolling only if the view content is larger than the container), 20923 * or {@link #OVER_SCROLL_NEVER}. 20924 * 20925 * @return This view's over-scroll mode. 20926 */ 20927 public int getOverScrollMode() { 20928 return mOverScrollMode; 20929 } 20930 20931 /** 20932 * Set the over-scroll mode for this view. Valid over-scroll modes are 20933 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20934 * (allow over-scrolling only if the view content is larger than the container), 20935 * or {@link #OVER_SCROLL_NEVER}. 20936 * 20937 * Setting the over-scroll mode of a view will have an effect only if the 20938 * view is capable of scrolling. 20939 * 20940 * @param overScrollMode The new over-scroll mode for this view. 20941 */ 20942 public void setOverScrollMode(int overScrollMode) { 20943 if (overScrollMode != OVER_SCROLL_ALWAYS && 20944 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 20945 overScrollMode != OVER_SCROLL_NEVER) { 20946 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 20947 } 20948 mOverScrollMode = overScrollMode; 20949 } 20950 20951 /** 20952 * Enable or disable nested scrolling for this view. 20953 * 20954 * <p>If this property is set to true the view will be permitted to initiate nested 20955 * scrolling operations with a compatible parent view in the current hierarchy. If this 20956 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 20957 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 20958 * the nested scroll.</p> 20959 * 20960 * @param enabled true to enable nested scrolling, false to disable 20961 * 20962 * @see #isNestedScrollingEnabled() 20963 */ 20964 public void setNestedScrollingEnabled(boolean enabled) { 20965 if (enabled) { 20966 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 20967 } else { 20968 stopNestedScroll(); 20969 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 20970 } 20971 } 20972 20973 /** 20974 * Returns true if nested scrolling is enabled for this view. 20975 * 20976 * <p>If nested scrolling is enabled and this View class implementation supports it, 20977 * this view will act as a nested scrolling child view when applicable, forwarding data 20978 * about the scroll operation in progress to a compatible and cooperating nested scrolling 20979 * parent.</p> 20980 * 20981 * @return true if nested scrolling is enabled 20982 * 20983 * @see #setNestedScrollingEnabled(boolean) 20984 */ 20985 public boolean isNestedScrollingEnabled() { 20986 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 20987 PFLAG3_NESTED_SCROLLING_ENABLED; 20988 } 20989 20990 /** 20991 * Begin a nestable scroll operation along the given axes. 20992 * 20993 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 20994 * 20995 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 20996 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 20997 * In the case of touch scrolling the nested scroll will be terminated automatically in 20998 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 20999 * In the event of programmatic scrolling the caller must explicitly call 21000 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 21001 * 21002 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 21003 * If it returns false the caller may ignore the rest of this contract until the next scroll. 21004 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 21005 * 21006 * <p>At each incremental step of the scroll the caller should invoke 21007 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 21008 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 21009 * parent at least partially consumed the scroll and the caller should adjust the amount it 21010 * scrolls by.</p> 21011 * 21012 * <p>After applying the remainder of the scroll delta the caller should invoke 21013 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 21014 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 21015 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 21016 * </p> 21017 * 21018 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 21019 * {@link #SCROLL_AXIS_VERTICAL}. 21020 * @return true if a cooperative parent was found and nested scrolling has been enabled for 21021 * the current gesture. 21022 * 21023 * @see #stopNestedScroll() 21024 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21025 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21026 */ 21027 public boolean startNestedScroll(int axes) { 21028 if (hasNestedScrollingParent()) { 21029 // Already in progress 21030 return true; 21031 } 21032 if (isNestedScrollingEnabled()) { 21033 ViewParent p = getParent(); 21034 View child = this; 21035 while (p != null) { 21036 try { 21037 if (p.onStartNestedScroll(child, this, axes)) { 21038 mNestedScrollingParent = p; 21039 p.onNestedScrollAccepted(child, this, axes); 21040 return true; 21041 } 21042 } catch (AbstractMethodError e) { 21043 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 21044 "method onStartNestedScroll", e); 21045 // Allow the search upward to continue 21046 } 21047 if (p instanceof View) { 21048 child = (View) p; 21049 } 21050 p = p.getParent(); 21051 } 21052 } 21053 return false; 21054 } 21055 21056 /** 21057 * Stop a nested scroll in progress. 21058 * 21059 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 21060 * 21061 * @see #startNestedScroll(int) 21062 */ 21063 public void stopNestedScroll() { 21064 if (mNestedScrollingParent != null) { 21065 mNestedScrollingParent.onStopNestedScroll(this); 21066 mNestedScrollingParent = null; 21067 } 21068 } 21069 21070 /** 21071 * Returns true if this view has a nested scrolling parent. 21072 * 21073 * <p>The presence of a nested scrolling parent indicates that this view has initiated 21074 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 21075 * 21076 * @return whether this view has a nested scrolling parent 21077 */ 21078 public boolean hasNestedScrollingParent() { 21079 return mNestedScrollingParent != null; 21080 } 21081 21082 /** 21083 * Dispatch one step of a nested scroll in progress. 21084 * 21085 * <p>Implementations of views that support nested scrolling should call this to report 21086 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 21087 * is not currently in progress or nested scrolling is not 21088 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 21089 * 21090 * <p>Compatible View implementations should also call 21091 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 21092 * consuming a component of the scroll event themselves.</p> 21093 * 21094 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 21095 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 21096 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 21097 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 21098 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21099 * in local view coordinates of this view from before this operation 21100 * to after it completes. View implementations may use this to adjust 21101 * expected input coordinate tracking. 21102 * @return true if the event was dispatched, false if it could not be dispatched. 21103 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21104 */ 21105 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 21106 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 21107 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21108 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 21109 int startX = 0; 21110 int startY = 0; 21111 if (offsetInWindow != null) { 21112 getLocationInWindow(offsetInWindow); 21113 startX = offsetInWindow[0]; 21114 startY = offsetInWindow[1]; 21115 } 21116 21117 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 21118 dxUnconsumed, dyUnconsumed); 21119 21120 if (offsetInWindow != null) { 21121 getLocationInWindow(offsetInWindow); 21122 offsetInWindow[0] -= startX; 21123 offsetInWindow[1] -= startY; 21124 } 21125 return true; 21126 } else if (offsetInWindow != null) { 21127 // No motion, no dispatch. Keep offsetInWindow up to date. 21128 offsetInWindow[0] = 0; 21129 offsetInWindow[1] = 0; 21130 } 21131 } 21132 return false; 21133 } 21134 21135 /** 21136 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 21137 * 21138 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 21139 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 21140 * scrolling operation to consume some or all of the scroll operation before the child view 21141 * consumes it.</p> 21142 * 21143 * @param dx Horizontal scroll distance in pixels 21144 * @param dy Vertical scroll distance in pixels 21145 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 21146 * and consumed[1] the consumed dy. 21147 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21148 * in local view coordinates of this view from before this operation 21149 * to after it completes. View implementations may use this to adjust 21150 * expected input coordinate tracking. 21151 * @return true if the parent consumed some or all of the scroll delta 21152 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21153 */ 21154 public boolean dispatchNestedPreScroll(int dx, int dy, 21155 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 21156 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21157 if (dx != 0 || dy != 0) { 21158 int startX = 0; 21159 int startY = 0; 21160 if (offsetInWindow != null) { 21161 getLocationInWindow(offsetInWindow); 21162 startX = offsetInWindow[0]; 21163 startY = offsetInWindow[1]; 21164 } 21165 21166 if (consumed == null) { 21167 if (mTempNestedScrollConsumed == null) { 21168 mTempNestedScrollConsumed = new int[2]; 21169 } 21170 consumed = mTempNestedScrollConsumed; 21171 } 21172 consumed[0] = 0; 21173 consumed[1] = 0; 21174 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 21175 21176 if (offsetInWindow != null) { 21177 getLocationInWindow(offsetInWindow); 21178 offsetInWindow[0] -= startX; 21179 offsetInWindow[1] -= startY; 21180 } 21181 return consumed[0] != 0 || consumed[1] != 0; 21182 } else if (offsetInWindow != null) { 21183 offsetInWindow[0] = 0; 21184 offsetInWindow[1] = 0; 21185 } 21186 } 21187 return false; 21188 } 21189 21190 /** 21191 * Dispatch a fling to a nested scrolling parent. 21192 * 21193 * <p>This method should be used to indicate that a nested scrolling child has detected 21194 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 21195 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 21196 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 21197 * along a scrollable axis.</p> 21198 * 21199 * <p>If a nested scrolling child view would normally fling but it is at the edge of 21200 * its own content, it can use this method to delegate the fling to its nested scrolling 21201 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 21202 * 21203 * @param velocityX Horizontal fling velocity in pixels per second 21204 * @param velocityY Vertical fling velocity in pixels per second 21205 * @param consumed true if the child consumed the fling, false otherwise 21206 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 21207 */ 21208 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 21209 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21210 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 21211 } 21212 return false; 21213 } 21214 21215 /** 21216 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 21217 * 21218 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 21219 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 21220 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 21221 * before the child view consumes it. If this method returns <code>true</code>, a nested 21222 * parent view consumed the fling and this view should not scroll as a result.</p> 21223 * 21224 * <p>For a better user experience, only one view in a nested scrolling chain should consume 21225 * the fling at a time. If a parent view consumed the fling this method will return false. 21226 * Custom view implementations should account for this in two ways:</p> 21227 * 21228 * <ul> 21229 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 21230 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 21231 * position regardless.</li> 21232 * <li>If a nested parent does consume the fling, this view should not scroll at all, 21233 * even to settle back to a valid idle position.</li> 21234 * </ul> 21235 * 21236 * <p>Views should also not offer fling velocities to nested parent views along an axis 21237 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 21238 * should not offer a horizontal fling velocity to its parents since scrolling along that 21239 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 21240 * 21241 * @param velocityX Horizontal fling velocity in pixels per second 21242 * @param velocityY Vertical fling velocity in pixels per second 21243 * @return true if a nested scrolling parent consumed the fling 21244 */ 21245 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 21246 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21247 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 21248 } 21249 return false; 21250 } 21251 21252 /** 21253 * Gets a scale factor that determines the distance the view should scroll 21254 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 21255 * @return The vertical scroll scale factor. 21256 * @hide 21257 */ 21258 protected float getVerticalScrollFactor() { 21259 if (mVerticalScrollFactor == 0) { 21260 TypedValue outValue = new TypedValue(); 21261 if (!mContext.getTheme().resolveAttribute( 21262 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 21263 throw new IllegalStateException( 21264 "Expected theme to define listPreferredItemHeight."); 21265 } 21266 mVerticalScrollFactor = outValue.getDimension( 21267 mContext.getResources().getDisplayMetrics()); 21268 } 21269 return mVerticalScrollFactor; 21270 } 21271 21272 /** 21273 * Gets a scale factor that determines the distance the view should scroll 21274 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 21275 * @return The horizontal scroll scale factor. 21276 * @hide 21277 */ 21278 protected float getHorizontalScrollFactor() { 21279 // TODO: Should use something else. 21280 return getVerticalScrollFactor(); 21281 } 21282 21283 /** 21284 * Return the value specifying the text direction or policy that was set with 21285 * {@link #setTextDirection(int)}. 21286 * 21287 * @return the defined text direction. It can be one of: 21288 * 21289 * {@link #TEXT_DIRECTION_INHERIT}, 21290 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21291 * {@link #TEXT_DIRECTION_ANY_RTL}, 21292 * {@link #TEXT_DIRECTION_LTR}, 21293 * {@link #TEXT_DIRECTION_RTL}, 21294 * {@link #TEXT_DIRECTION_LOCALE}, 21295 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21296 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21297 * 21298 * @attr ref android.R.styleable#View_textDirection 21299 * 21300 * @hide 21301 */ 21302 @ViewDebug.ExportedProperty(category = "text", mapping = { 21303 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21304 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21305 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21306 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21307 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21308 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21309 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21310 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21311 }) 21312 public int getRawTextDirection() { 21313 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 21314 } 21315 21316 /** 21317 * Set the text direction. 21318 * 21319 * @param textDirection the direction to set. Should be one of: 21320 * 21321 * {@link #TEXT_DIRECTION_INHERIT}, 21322 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21323 * {@link #TEXT_DIRECTION_ANY_RTL}, 21324 * {@link #TEXT_DIRECTION_LTR}, 21325 * {@link #TEXT_DIRECTION_RTL}, 21326 * {@link #TEXT_DIRECTION_LOCALE} 21327 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21328 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 21329 * 21330 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 21331 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 21332 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 21333 * 21334 * @attr ref android.R.styleable#View_textDirection 21335 */ 21336 public void setTextDirection(int textDirection) { 21337 if (getRawTextDirection() != textDirection) { 21338 // Reset the current text direction and the resolved one 21339 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 21340 resetResolvedTextDirection(); 21341 // Set the new text direction 21342 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 21343 // Do resolution 21344 resolveTextDirection(); 21345 // Notify change 21346 onRtlPropertiesChanged(getLayoutDirection()); 21347 // Refresh 21348 requestLayout(); 21349 invalidate(true); 21350 } 21351 } 21352 21353 /** 21354 * Return the resolved text direction. 21355 * 21356 * @return the resolved text direction. Returns one of: 21357 * 21358 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21359 * {@link #TEXT_DIRECTION_ANY_RTL}, 21360 * {@link #TEXT_DIRECTION_LTR}, 21361 * {@link #TEXT_DIRECTION_RTL}, 21362 * {@link #TEXT_DIRECTION_LOCALE}, 21363 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21364 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21365 * 21366 * @attr ref android.R.styleable#View_textDirection 21367 */ 21368 @ViewDebug.ExportedProperty(category = "text", mapping = { 21369 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21370 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21371 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21372 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21373 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21374 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21375 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21376 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21377 }) 21378 public int getTextDirection() { 21379 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 21380 } 21381 21382 /** 21383 * Resolve the text direction. 21384 * 21385 * @return true if resolution has been done, false otherwise. 21386 * 21387 * @hide 21388 */ 21389 public boolean resolveTextDirection() { 21390 // Reset any previous text direction resolution 21391 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21392 21393 if (hasRtlSupport()) { 21394 // Set resolved text direction flag depending on text direction flag 21395 final int textDirection = getRawTextDirection(); 21396 switch(textDirection) { 21397 case TEXT_DIRECTION_INHERIT: 21398 if (!canResolveTextDirection()) { 21399 // We cannot do the resolution if there is no parent, so use the default one 21400 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21401 // Resolution will need to happen again later 21402 return false; 21403 } 21404 21405 // Parent has not yet resolved, so we still return the default 21406 try { 21407 if (!mParent.isTextDirectionResolved()) { 21408 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21409 // Resolution will need to happen again later 21410 return false; 21411 } 21412 } catch (AbstractMethodError e) { 21413 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21414 " does not fully implement ViewParent", e); 21415 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 21416 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21417 return true; 21418 } 21419 21420 // Set current resolved direction to the same value as the parent's one 21421 int parentResolvedDirection; 21422 try { 21423 parentResolvedDirection = mParent.getTextDirection(); 21424 } catch (AbstractMethodError e) { 21425 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21426 " does not fully implement ViewParent", e); 21427 parentResolvedDirection = TEXT_DIRECTION_LTR; 21428 } 21429 switch (parentResolvedDirection) { 21430 case TEXT_DIRECTION_FIRST_STRONG: 21431 case TEXT_DIRECTION_ANY_RTL: 21432 case TEXT_DIRECTION_LTR: 21433 case TEXT_DIRECTION_RTL: 21434 case TEXT_DIRECTION_LOCALE: 21435 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21436 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21437 mPrivateFlags2 |= 21438 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21439 break; 21440 default: 21441 // Default resolved direction is "first strong" heuristic 21442 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21443 } 21444 break; 21445 case TEXT_DIRECTION_FIRST_STRONG: 21446 case TEXT_DIRECTION_ANY_RTL: 21447 case TEXT_DIRECTION_LTR: 21448 case TEXT_DIRECTION_RTL: 21449 case TEXT_DIRECTION_LOCALE: 21450 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21451 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21452 // Resolved direction is the same as text direction 21453 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21454 break; 21455 default: 21456 // Default resolved direction is "first strong" heuristic 21457 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21458 } 21459 } else { 21460 // Default resolved direction is "first strong" heuristic 21461 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21462 } 21463 21464 // Set to resolved 21465 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 21466 return true; 21467 } 21468 21469 /** 21470 * Check if text direction resolution can be done. 21471 * 21472 * @return true if text direction resolution can be done otherwise return false. 21473 */ 21474 public boolean canResolveTextDirection() { 21475 switch (getRawTextDirection()) { 21476 case TEXT_DIRECTION_INHERIT: 21477 if (mParent != null) { 21478 try { 21479 return mParent.canResolveTextDirection(); 21480 } catch (AbstractMethodError e) { 21481 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21482 " does not fully implement ViewParent", e); 21483 } 21484 } 21485 return false; 21486 21487 default: 21488 return true; 21489 } 21490 } 21491 21492 /** 21493 * Reset resolved text direction. Text direction will be resolved during a call to 21494 * {@link #onMeasure(int, int)}. 21495 * 21496 * @hide 21497 */ 21498 public void resetResolvedTextDirection() { 21499 // Reset any previous text direction resolution 21500 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21501 // Set to default value 21502 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21503 } 21504 21505 /** 21506 * @return true if text direction is inherited. 21507 * 21508 * @hide 21509 */ 21510 public boolean isTextDirectionInherited() { 21511 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 21512 } 21513 21514 /** 21515 * @return true if text direction is resolved. 21516 */ 21517 public boolean isTextDirectionResolved() { 21518 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 21519 } 21520 21521 /** 21522 * Return the value specifying the text alignment or policy that was set with 21523 * {@link #setTextAlignment(int)}. 21524 * 21525 * @return the defined text alignment. It can be one of: 21526 * 21527 * {@link #TEXT_ALIGNMENT_INHERIT}, 21528 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21529 * {@link #TEXT_ALIGNMENT_CENTER}, 21530 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21531 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21532 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21533 * {@link #TEXT_ALIGNMENT_VIEW_END} 21534 * 21535 * @attr ref android.R.styleable#View_textAlignment 21536 * 21537 * @hide 21538 */ 21539 @ViewDebug.ExportedProperty(category = "text", mapping = { 21540 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21541 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21542 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21543 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21544 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21545 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21546 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21547 }) 21548 @TextAlignment 21549 public int getRawTextAlignment() { 21550 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 21551 } 21552 21553 /** 21554 * Set the text alignment. 21555 * 21556 * @param textAlignment The text alignment to set. Should be one of 21557 * 21558 * {@link #TEXT_ALIGNMENT_INHERIT}, 21559 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21560 * {@link #TEXT_ALIGNMENT_CENTER}, 21561 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21562 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21563 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21564 * {@link #TEXT_ALIGNMENT_VIEW_END} 21565 * 21566 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 21567 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 21568 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 21569 * 21570 * @attr ref android.R.styleable#View_textAlignment 21571 */ 21572 public void setTextAlignment(@TextAlignment int textAlignment) { 21573 if (textAlignment != getRawTextAlignment()) { 21574 // Reset the current and resolved text alignment 21575 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 21576 resetResolvedTextAlignment(); 21577 // Set the new text alignment 21578 mPrivateFlags2 |= 21579 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 21580 // Do resolution 21581 resolveTextAlignment(); 21582 // Notify change 21583 onRtlPropertiesChanged(getLayoutDirection()); 21584 // Refresh 21585 requestLayout(); 21586 invalidate(true); 21587 } 21588 } 21589 21590 /** 21591 * Return the resolved text alignment. 21592 * 21593 * @return the resolved text alignment. Returns one of: 21594 * 21595 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21596 * {@link #TEXT_ALIGNMENT_CENTER}, 21597 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21598 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21599 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21600 * {@link #TEXT_ALIGNMENT_VIEW_END} 21601 * 21602 * @attr ref android.R.styleable#View_textAlignment 21603 */ 21604 @ViewDebug.ExportedProperty(category = "text", mapping = { 21605 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21606 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21607 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21608 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21609 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21610 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21611 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21612 }) 21613 @TextAlignment 21614 public int getTextAlignment() { 21615 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 21616 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 21617 } 21618 21619 /** 21620 * Resolve the text alignment. 21621 * 21622 * @return true if resolution has been done, false otherwise. 21623 * 21624 * @hide 21625 */ 21626 public boolean resolveTextAlignment() { 21627 // Reset any previous text alignment resolution 21628 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21629 21630 if (hasRtlSupport()) { 21631 // Set resolved text alignment flag depending on text alignment flag 21632 final int textAlignment = getRawTextAlignment(); 21633 switch (textAlignment) { 21634 case TEXT_ALIGNMENT_INHERIT: 21635 // Check if we can resolve the text alignment 21636 if (!canResolveTextAlignment()) { 21637 // We cannot do the resolution if there is no parent so use the default 21638 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21639 // Resolution will need to happen again later 21640 return false; 21641 } 21642 21643 // Parent has not yet resolved, so we still return the default 21644 try { 21645 if (!mParent.isTextAlignmentResolved()) { 21646 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21647 // Resolution will need to happen again later 21648 return false; 21649 } 21650 } catch (AbstractMethodError e) { 21651 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21652 " does not fully implement ViewParent", e); 21653 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 21654 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21655 return true; 21656 } 21657 21658 int parentResolvedTextAlignment; 21659 try { 21660 parentResolvedTextAlignment = mParent.getTextAlignment(); 21661 } catch (AbstractMethodError e) { 21662 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21663 " does not fully implement ViewParent", e); 21664 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 21665 } 21666 switch (parentResolvedTextAlignment) { 21667 case TEXT_ALIGNMENT_GRAVITY: 21668 case TEXT_ALIGNMENT_TEXT_START: 21669 case TEXT_ALIGNMENT_TEXT_END: 21670 case TEXT_ALIGNMENT_CENTER: 21671 case TEXT_ALIGNMENT_VIEW_START: 21672 case TEXT_ALIGNMENT_VIEW_END: 21673 // Resolved text alignment is the same as the parent resolved 21674 // text alignment 21675 mPrivateFlags2 |= 21676 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21677 break; 21678 default: 21679 // Use default resolved text alignment 21680 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21681 } 21682 break; 21683 case TEXT_ALIGNMENT_GRAVITY: 21684 case TEXT_ALIGNMENT_TEXT_START: 21685 case TEXT_ALIGNMENT_TEXT_END: 21686 case TEXT_ALIGNMENT_CENTER: 21687 case TEXT_ALIGNMENT_VIEW_START: 21688 case TEXT_ALIGNMENT_VIEW_END: 21689 // Resolved text alignment is the same as text alignment 21690 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21691 break; 21692 default: 21693 // Use default resolved text alignment 21694 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21695 } 21696 } else { 21697 // Use default resolved text alignment 21698 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21699 } 21700 21701 // Set the resolved 21702 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21703 return true; 21704 } 21705 21706 /** 21707 * Check if text alignment resolution can be done. 21708 * 21709 * @return true if text alignment resolution can be done otherwise return false. 21710 */ 21711 public boolean canResolveTextAlignment() { 21712 switch (getRawTextAlignment()) { 21713 case TEXT_DIRECTION_INHERIT: 21714 if (mParent != null) { 21715 try { 21716 return mParent.canResolveTextAlignment(); 21717 } catch (AbstractMethodError e) { 21718 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21719 " does not fully implement ViewParent", e); 21720 } 21721 } 21722 return false; 21723 21724 default: 21725 return true; 21726 } 21727 } 21728 21729 /** 21730 * Reset resolved text alignment. Text alignment will be resolved during a call to 21731 * {@link #onMeasure(int, int)}. 21732 * 21733 * @hide 21734 */ 21735 public void resetResolvedTextAlignment() { 21736 // Reset any previous text alignment resolution 21737 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21738 // Set to default 21739 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21740 } 21741 21742 /** 21743 * @return true if text alignment is inherited. 21744 * 21745 * @hide 21746 */ 21747 public boolean isTextAlignmentInherited() { 21748 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 21749 } 21750 21751 /** 21752 * @return true if text alignment is resolved. 21753 */ 21754 public boolean isTextAlignmentResolved() { 21755 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21756 } 21757 21758 /** 21759 * Generate a value suitable for use in {@link #setId(int)}. 21760 * This value will not collide with ID values generated at build time by aapt for R.id. 21761 * 21762 * @return a generated ID value 21763 */ 21764 public static int generateViewId() { 21765 for (;;) { 21766 final int result = sNextGeneratedId.get(); 21767 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 21768 int newValue = result + 1; 21769 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 21770 if (sNextGeneratedId.compareAndSet(result, newValue)) { 21771 return result; 21772 } 21773 } 21774 } 21775 21776 /** 21777 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 21778 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 21779 * a normal View or a ViewGroup with 21780 * {@link android.view.ViewGroup#isTransitionGroup()} true. 21781 * @hide 21782 */ 21783 public void captureTransitioningViews(List<View> transitioningViews) { 21784 if (getVisibility() == View.VISIBLE) { 21785 transitioningViews.add(this); 21786 } 21787 } 21788 21789 /** 21790 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 21791 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 21792 * @hide 21793 */ 21794 public void findNamedViews(Map<String, View> namedElements) { 21795 if (getVisibility() == VISIBLE || mGhostView != null) { 21796 String transitionName = getTransitionName(); 21797 if (transitionName != null) { 21798 namedElements.put(transitionName, this); 21799 } 21800 } 21801 } 21802 21803 /** 21804 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 21805 * The default implementation does not care the location or event types, but some subclasses 21806 * may use it (such as WebViews). 21807 * @param event The MotionEvent from a mouse 21808 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}. 21809 * This will be between 0 and {@link MotionEvent#getPointerCount()}. 21810 * @see PointerIcon 21811 */ 21812 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 21813 final float x = event.getX(pointerIndex); 21814 final float y = event.getY(pointerIndex); 21815 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 21816 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW); 21817 } 21818 return mPointerIcon; 21819 } 21820 21821 /** 21822 * Set the pointer icon for the current view. 21823 * Passing {@code null} will restore the pointer icon to its default value. 21824 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 21825 */ 21826 public void setPointerIcon(PointerIcon pointerIcon) { 21827 mPointerIcon = pointerIcon; 21828 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 21829 return; 21830 } 21831 try { 21832 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 21833 } catch (RemoteException e) { 21834 } 21835 } 21836 21837 /** 21838 * Gets the pointer icon for the current view. 21839 */ 21840 public PointerIcon getPointerIcon() { 21841 return mPointerIcon; 21842 } 21843 21844 21845 /** 21846 * Request capturing further mouse events. 21847 * 21848 * When the view captures, the pointer icon will disappear and will not change its 21849 * position. Further pointer events will come to the capturing view, and the pointer movements 21850 * will can be detected through {@link MotionEvent#AXIS_RELATIVE_X} and 21851 * {@link MotionEvent#AXIS_RELATIVE_Y}. Non-mouse events (touchscreens, or stylus) will not 21852 * be affected. 21853 * 21854 * The capture will be released through {@link #releasePointerCapture()}, or will be lost 21855 * automatically when the view or containing window disappear. 21856 * 21857 * @return true when succeeds. 21858 * @see #releasePointerCapture() 21859 * @see #hasPointerCapture() 21860 */ 21861 public void requestPointerCapture() { 21862 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21863 if (viewRootImpl != null) { 21864 viewRootImpl.requestPointerCapture(this); 21865 } 21866 } 21867 21868 21869 /** 21870 * Release the current capture of mouse events. 21871 * 21872 * If the view does not have the capture, it will do nothing. 21873 * @see #requestPointerCapture() 21874 * @see #hasPointerCapture() 21875 */ 21876 public void releasePointerCapture() { 21877 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21878 if (viewRootImpl != null) { 21879 viewRootImpl.releasePointerCapture(this); 21880 } 21881 } 21882 21883 /** 21884 * Checks the capture status of mouse events. 21885 * 21886 * @return true if the view has the capture. 21887 * @see #requestPointerCapture() 21888 * @see #hasPointerCapture() 21889 */ 21890 public boolean hasPointerCapture() { 21891 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21892 return (viewRootImpl != null) && viewRootImpl.hasPointerCapture(this); 21893 } 21894 21895 // 21896 // Properties 21897 // 21898 /** 21899 * A Property wrapper around the <code>alpha</code> functionality handled by the 21900 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 21901 */ 21902 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 21903 @Override 21904 public void setValue(View object, float value) { 21905 object.setAlpha(value); 21906 } 21907 21908 @Override 21909 public Float get(View object) { 21910 return object.getAlpha(); 21911 } 21912 }; 21913 21914 /** 21915 * A Property wrapper around the <code>translationX</code> functionality handled by the 21916 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 21917 */ 21918 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 21919 @Override 21920 public void setValue(View object, float value) { 21921 object.setTranslationX(value); 21922 } 21923 21924 @Override 21925 public Float get(View object) { 21926 return object.getTranslationX(); 21927 } 21928 }; 21929 21930 /** 21931 * A Property wrapper around the <code>translationY</code> functionality handled by the 21932 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 21933 */ 21934 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 21935 @Override 21936 public void setValue(View object, float value) { 21937 object.setTranslationY(value); 21938 } 21939 21940 @Override 21941 public Float get(View object) { 21942 return object.getTranslationY(); 21943 } 21944 }; 21945 21946 /** 21947 * A Property wrapper around the <code>translationZ</code> functionality handled by the 21948 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 21949 */ 21950 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 21951 @Override 21952 public void setValue(View object, float value) { 21953 object.setTranslationZ(value); 21954 } 21955 21956 @Override 21957 public Float get(View object) { 21958 return object.getTranslationZ(); 21959 } 21960 }; 21961 21962 /** 21963 * A Property wrapper around the <code>x</code> functionality handled by the 21964 * {@link View#setX(float)} and {@link View#getX()} methods. 21965 */ 21966 public static final Property<View, Float> X = new FloatProperty<View>("x") { 21967 @Override 21968 public void setValue(View object, float value) { 21969 object.setX(value); 21970 } 21971 21972 @Override 21973 public Float get(View object) { 21974 return object.getX(); 21975 } 21976 }; 21977 21978 /** 21979 * A Property wrapper around the <code>y</code> functionality handled by the 21980 * {@link View#setY(float)} and {@link View#getY()} methods. 21981 */ 21982 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 21983 @Override 21984 public void setValue(View object, float value) { 21985 object.setY(value); 21986 } 21987 21988 @Override 21989 public Float get(View object) { 21990 return object.getY(); 21991 } 21992 }; 21993 21994 /** 21995 * A Property wrapper around the <code>z</code> functionality handled by the 21996 * {@link View#setZ(float)} and {@link View#getZ()} methods. 21997 */ 21998 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 21999 @Override 22000 public void setValue(View object, float value) { 22001 object.setZ(value); 22002 } 22003 22004 @Override 22005 public Float get(View object) { 22006 return object.getZ(); 22007 } 22008 }; 22009 22010 /** 22011 * A Property wrapper around the <code>rotation</code> functionality handled by the 22012 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 22013 */ 22014 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 22015 @Override 22016 public void setValue(View object, float value) { 22017 object.setRotation(value); 22018 } 22019 22020 @Override 22021 public Float get(View object) { 22022 return object.getRotation(); 22023 } 22024 }; 22025 22026 /** 22027 * A Property wrapper around the <code>rotationX</code> functionality handled by the 22028 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 22029 */ 22030 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 22031 @Override 22032 public void setValue(View object, float value) { 22033 object.setRotationX(value); 22034 } 22035 22036 @Override 22037 public Float get(View object) { 22038 return object.getRotationX(); 22039 } 22040 }; 22041 22042 /** 22043 * A Property wrapper around the <code>rotationY</code> functionality handled by the 22044 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 22045 */ 22046 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 22047 @Override 22048 public void setValue(View object, float value) { 22049 object.setRotationY(value); 22050 } 22051 22052 @Override 22053 public Float get(View object) { 22054 return object.getRotationY(); 22055 } 22056 }; 22057 22058 /** 22059 * A Property wrapper around the <code>scaleX</code> functionality handled by the 22060 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 22061 */ 22062 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 22063 @Override 22064 public void setValue(View object, float value) { 22065 object.setScaleX(value); 22066 } 22067 22068 @Override 22069 public Float get(View object) { 22070 return object.getScaleX(); 22071 } 22072 }; 22073 22074 /** 22075 * A Property wrapper around the <code>scaleY</code> functionality handled by the 22076 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 22077 */ 22078 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 22079 @Override 22080 public void setValue(View object, float value) { 22081 object.setScaleY(value); 22082 } 22083 22084 @Override 22085 public Float get(View object) { 22086 return object.getScaleY(); 22087 } 22088 }; 22089 22090 /** 22091 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 22092 * Each MeasureSpec represents a requirement for either the width or the height. 22093 * A MeasureSpec is comprised of a size and a mode. There are three possible 22094 * modes: 22095 * <dl> 22096 * <dt>UNSPECIFIED</dt> 22097 * <dd> 22098 * The parent has not imposed any constraint on the child. It can be whatever size 22099 * it wants. 22100 * </dd> 22101 * 22102 * <dt>EXACTLY</dt> 22103 * <dd> 22104 * The parent has determined an exact size for the child. The child is going to be 22105 * given those bounds regardless of how big it wants to be. 22106 * </dd> 22107 * 22108 * <dt>AT_MOST</dt> 22109 * <dd> 22110 * The child can be as large as it wants up to the specified size. 22111 * </dd> 22112 * </dl> 22113 * 22114 * MeasureSpecs are implemented as ints to reduce object allocation. This class 22115 * is provided to pack and unpack the <size, mode> tuple into the int. 22116 */ 22117 public static class MeasureSpec { 22118 private static final int MODE_SHIFT = 30; 22119 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 22120 22121 /** @hide */ 22122 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 22123 @Retention(RetentionPolicy.SOURCE) 22124 public @interface MeasureSpecMode {} 22125 22126 /** 22127 * Measure specification mode: The parent has not imposed any constraint 22128 * on the child. It can be whatever size it wants. 22129 */ 22130 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 22131 22132 /** 22133 * Measure specification mode: The parent has determined an exact size 22134 * for the child. The child is going to be given those bounds regardless 22135 * of how big it wants to be. 22136 */ 22137 public static final int EXACTLY = 1 << MODE_SHIFT; 22138 22139 /** 22140 * Measure specification mode: The child can be as large as it wants up 22141 * to the specified size. 22142 */ 22143 public static final int AT_MOST = 2 << MODE_SHIFT; 22144 22145 /** 22146 * Creates a measure specification based on the supplied size and mode. 22147 * 22148 * The mode must always be one of the following: 22149 * <ul> 22150 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 22151 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 22152 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 22153 * </ul> 22154 * 22155 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 22156 * implementation was such that the order of arguments did not matter 22157 * and overflow in either value could impact the resulting MeasureSpec. 22158 * {@link android.widget.RelativeLayout} was affected by this bug. 22159 * Apps targeting API levels greater than 17 will get the fixed, more strict 22160 * behavior.</p> 22161 * 22162 * @param size the size of the measure specification 22163 * @param mode the mode of the measure specification 22164 * @return the measure specification based on size and mode 22165 */ 22166 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 22167 @MeasureSpecMode int mode) { 22168 if (sUseBrokenMakeMeasureSpec) { 22169 return size + mode; 22170 } else { 22171 return (size & ~MODE_MASK) | (mode & MODE_MASK); 22172 } 22173 } 22174 22175 /** 22176 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 22177 * will automatically get a size of 0. Older apps expect this. 22178 * 22179 * @hide internal use only for compatibility with system widgets and older apps 22180 */ 22181 public static int makeSafeMeasureSpec(int size, int mode) { 22182 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 22183 return 0; 22184 } 22185 return makeMeasureSpec(size, mode); 22186 } 22187 22188 /** 22189 * Extracts the mode from the supplied measure specification. 22190 * 22191 * @param measureSpec the measure specification to extract the mode from 22192 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 22193 * {@link android.view.View.MeasureSpec#AT_MOST} or 22194 * {@link android.view.View.MeasureSpec#EXACTLY} 22195 */ 22196 @MeasureSpecMode 22197 public static int getMode(int measureSpec) { 22198 //noinspection ResourceType 22199 return (measureSpec & MODE_MASK); 22200 } 22201 22202 /** 22203 * Extracts the size from the supplied measure specification. 22204 * 22205 * @param measureSpec the measure specification to extract the size from 22206 * @return the size in pixels defined in the supplied measure specification 22207 */ 22208 public static int getSize(int measureSpec) { 22209 return (measureSpec & ~MODE_MASK); 22210 } 22211 22212 static int adjust(int measureSpec, int delta) { 22213 final int mode = getMode(measureSpec); 22214 int size = getSize(measureSpec); 22215 if (mode == UNSPECIFIED) { 22216 // No need to adjust size for UNSPECIFIED mode. 22217 return makeMeasureSpec(size, UNSPECIFIED); 22218 } 22219 size += delta; 22220 if (size < 0) { 22221 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 22222 ") spec: " + toString(measureSpec) + " delta: " + delta); 22223 size = 0; 22224 } 22225 return makeMeasureSpec(size, mode); 22226 } 22227 22228 /** 22229 * Returns a String representation of the specified measure 22230 * specification. 22231 * 22232 * @param measureSpec the measure specification to convert to a String 22233 * @return a String with the following format: "MeasureSpec: MODE SIZE" 22234 */ 22235 public static String toString(int measureSpec) { 22236 int mode = getMode(measureSpec); 22237 int size = getSize(measureSpec); 22238 22239 StringBuilder sb = new StringBuilder("MeasureSpec: "); 22240 22241 if (mode == UNSPECIFIED) 22242 sb.append("UNSPECIFIED "); 22243 else if (mode == EXACTLY) 22244 sb.append("EXACTLY "); 22245 else if (mode == AT_MOST) 22246 sb.append("AT_MOST "); 22247 else 22248 sb.append(mode).append(" "); 22249 22250 sb.append(size); 22251 return sb.toString(); 22252 } 22253 } 22254 22255 private final class CheckForLongPress implements Runnable { 22256 private int mOriginalWindowAttachCount; 22257 private float mX; 22258 private float mY; 22259 22260 @Override 22261 public void run() { 22262 if (isPressed() && (mParent != null) 22263 && mOriginalWindowAttachCount == mWindowAttachCount) { 22264 if (performLongClick(mX, mY)) { 22265 mHasPerformedLongPress = true; 22266 } 22267 } 22268 } 22269 22270 public void setAnchor(float x, float y) { 22271 mX = x; 22272 mY = y; 22273 } 22274 22275 public void rememberWindowAttachCount() { 22276 mOriginalWindowAttachCount = mWindowAttachCount; 22277 } 22278 } 22279 22280 private final class CheckForTap implements Runnable { 22281 public float x; 22282 public float y; 22283 22284 @Override 22285 public void run() { 22286 mPrivateFlags &= ~PFLAG_PREPRESSED; 22287 setPressed(true, x, y); 22288 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 22289 } 22290 } 22291 22292 private final class PerformClick implements Runnable { 22293 @Override 22294 public void run() { 22295 performClick(); 22296 } 22297 } 22298 22299 /** 22300 * This method returns a ViewPropertyAnimator object, which can be used to animate 22301 * specific properties on this View. 22302 * 22303 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 22304 */ 22305 public ViewPropertyAnimator animate() { 22306 if (mAnimator == null) { 22307 mAnimator = new ViewPropertyAnimator(this); 22308 } 22309 return mAnimator; 22310 } 22311 22312 /** 22313 * Sets the name of the View to be used to identify Views in Transitions. 22314 * Names should be unique in the View hierarchy. 22315 * 22316 * @param transitionName The name of the View to uniquely identify it for Transitions. 22317 */ 22318 public final void setTransitionName(String transitionName) { 22319 mTransitionName = transitionName; 22320 } 22321 22322 /** 22323 * Returns the name of the View to be used to identify Views in Transitions. 22324 * Names should be unique in the View hierarchy. 22325 * 22326 * <p>This returns null if the View has not been given a name.</p> 22327 * 22328 * @return The name used of the View to be used to identify Views in Transitions or null 22329 * if no name has been given. 22330 */ 22331 @ViewDebug.ExportedProperty 22332 public String getTransitionName() { 22333 return mTransitionName; 22334 } 22335 22336 /** 22337 * @hide 22338 */ 22339 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 22340 // Do nothing. 22341 } 22342 22343 /** 22344 * Interface definition for a callback to be invoked when a hardware key event is 22345 * dispatched to this view. The callback will be invoked before the key event is 22346 * given to the view. This is only useful for hardware keyboards; a software input 22347 * method has no obligation to trigger this listener. 22348 */ 22349 public interface OnKeyListener { 22350 /** 22351 * Called when a hardware key is dispatched to a view. This allows listeners to 22352 * get a chance to respond before the target view. 22353 * <p>Key presses in software keyboards will generally NOT trigger this method, 22354 * although some may elect to do so in some situations. Do not assume a 22355 * software input method has to be key-based; even if it is, it may use key presses 22356 * in a different way than you expect, so there is no way to reliably catch soft 22357 * input key presses. 22358 * 22359 * @param v The view the key has been dispatched to. 22360 * @param keyCode The code for the physical key that was pressed 22361 * @param event The KeyEvent object containing full information about 22362 * the event. 22363 * @return True if the listener has consumed the event, false otherwise. 22364 */ 22365 boolean onKey(View v, int keyCode, KeyEvent event); 22366 } 22367 22368 /** 22369 * Interface definition for a callback to be invoked when a touch event is 22370 * dispatched to this view. The callback will be invoked before the touch 22371 * event is given to the view. 22372 */ 22373 public interface OnTouchListener { 22374 /** 22375 * Called when a touch event is dispatched to a view. This allows listeners to 22376 * get a chance to respond before the target view. 22377 * 22378 * @param v The view the touch event has been dispatched to. 22379 * @param event The MotionEvent object containing full information about 22380 * the event. 22381 * @return True if the listener has consumed the event, false otherwise. 22382 */ 22383 boolean onTouch(View v, MotionEvent event); 22384 } 22385 22386 /** 22387 * Interface definition for a callback to be invoked when a hover event is 22388 * dispatched to this view. The callback will be invoked before the hover 22389 * event is given to the view. 22390 */ 22391 public interface OnHoverListener { 22392 /** 22393 * Called when a hover event is dispatched to a view. This allows listeners to 22394 * get a chance to respond before the target view. 22395 * 22396 * @param v The view the hover event has been dispatched to. 22397 * @param event The MotionEvent object containing full information about 22398 * the event. 22399 * @return True if the listener has consumed the event, false otherwise. 22400 */ 22401 boolean onHover(View v, MotionEvent event); 22402 } 22403 22404 /** 22405 * Interface definition for a callback to be invoked when a generic motion event is 22406 * dispatched to this view. The callback will be invoked before the generic motion 22407 * event is given to the view. 22408 */ 22409 public interface OnGenericMotionListener { 22410 /** 22411 * Called when a generic motion event is dispatched to a view. This allows listeners to 22412 * get a chance to respond before the target view. 22413 * 22414 * @param v The view the generic motion event has been dispatched to. 22415 * @param event The MotionEvent object containing full information about 22416 * the event. 22417 * @return True if the listener has consumed the event, false otherwise. 22418 */ 22419 boolean onGenericMotion(View v, MotionEvent event); 22420 } 22421 22422 /** 22423 * Interface definition for a callback to be invoked when a view has been clicked and held. 22424 */ 22425 public interface OnLongClickListener { 22426 /** 22427 * Called when a view has been clicked and held. 22428 * 22429 * @param v The view that was clicked and held. 22430 * 22431 * @return true if the callback consumed the long click, false otherwise. 22432 */ 22433 boolean onLongClick(View v); 22434 } 22435 22436 /** 22437 * Interface definition for a callback to be invoked when a drag is being dispatched 22438 * to this view. The callback will be invoked before the hosting view's own 22439 * onDrag(event) method. If the listener wants to fall back to the hosting view's 22440 * onDrag(event) behavior, it should return 'false' from this callback. 22441 * 22442 * <div class="special reference"> 22443 * <h3>Developer Guides</h3> 22444 * <p>For a guide to implementing drag and drop features, read the 22445 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22446 * </div> 22447 */ 22448 public interface OnDragListener { 22449 /** 22450 * Called when a drag event is dispatched to a view. This allows listeners 22451 * to get a chance to override base View behavior. 22452 * 22453 * @param v The View that received the drag event. 22454 * @param event The {@link android.view.DragEvent} object for the drag event. 22455 * @return {@code true} if the drag event was handled successfully, or {@code false} 22456 * if the drag event was not handled. Note that {@code false} will trigger the View 22457 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 22458 */ 22459 boolean onDrag(View v, DragEvent event); 22460 } 22461 22462 /** 22463 * Interface definition for a callback to be invoked when the focus state of 22464 * a view changed. 22465 */ 22466 public interface OnFocusChangeListener { 22467 /** 22468 * Called when the focus state of a view has changed. 22469 * 22470 * @param v The view whose state has changed. 22471 * @param hasFocus The new focus state of v. 22472 */ 22473 void onFocusChange(View v, boolean hasFocus); 22474 } 22475 22476 /** 22477 * Interface definition for a callback to be invoked when a view is clicked. 22478 */ 22479 public interface OnClickListener { 22480 /** 22481 * Called when a view has been clicked. 22482 * 22483 * @param v The view that was clicked. 22484 */ 22485 void onClick(View v); 22486 } 22487 22488 /** 22489 * Interface definition for a callback to be invoked when a view is context clicked. 22490 */ 22491 public interface OnContextClickListener { 22492 /** 22493 * Called when a view is context clicked. 22494 * 22495 * @param v The view that has been context clicked. 22496 * @return true if the callback consumed the context click, false otherwise. 22497 */ 22498 boolean onContextClick(View v); 22499 } 22500 22501 /** 22502 * Interface definition for a callback to be invoked when the context menu 22503 * for this view is being built. 22504 */ 22505 public interface OnCreateContextMenuListener { 22506 /** 22507 * Called when the context menu for this view is being built. It is not 22508 * safe to hold onto the menu after this method returns. 22509 * 22510 * @param menu The context menu that is being built 22511 * @param v The view for which the context menu is being built 22512 * @param menuInfo Extra information about the item for which the 22513 * context menu should be shown. This information will vary 22514 * depending on the class of v. 22515 */ 22516 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 22517 } 22518 22519 /** 22520 * Interface definition for a callback to be invoked when the status bar changes 22521 * visibility. This reports <strong>global</strong> changes to the system UI 22522 * state, not what the application is requesting. 22523 * 22524 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 22525 */ 22526 public interface OnSystemUiVisibilityChangeListener { 22527 /** 22528 * Called when the status bar changes visibility because of a call to 22529 * {@link View#setSystemUiVisibility(int)}. 22530 * 22531 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22532 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 22533 * This tells you the <strong>global</strong> state of these UI visibility 22534 * flags, not what your app is currently applying. 22535 */ 22536 public void onSystemUiVisibilityChange(int visibility); 22537 } 22538 22539 /** 22540 * Interface definition for a callback to be invoked when this view is attached 22541 * or detached from its window. 22542 */ 22543 public interface OnAttachStateChangeListener { 22544 /** 22545 * Called when the view is attached to a window. 22546 * @param v The view that was attached 22547 */ 22548 public void onViewAttachedToWindow(View v); 22549 /** 22550 * Called when the view is detached from a window. 22551 * @param v The view that was detached 22552 */ 22553 public void onViewDetachedFromWindow(View v); 22554 } 22555 22556 /** 22557 * Listener for applying window insets on a view in a custom way. 22558 * 22559 * <p>Apps may choose to implement this interface if they want to apply custom policy 22560 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 22561 * is set, its 22562 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 22563 * method will be called instead of the View's own 22564 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 22565 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 22566 * the View's normal behavior as part of its own.</p> 22567 */ 22568 public interface OnApplyWindowInsetsListener { 22569 /** 22570 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 22571 * on a View, this listener method will be called instead of the view's own 22572 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 22573 * 22574 * @param v The view applying window insets 22575 * @param insets The insets to apply 22576 * @return The insets supplied, minus any insets that were consumed 22577 */ 22578 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 22579 } 22580 22581 private final class UnsetPressedState implements Runnable { 22582 @Override 22583 public void run() { 22584 setPressed(false); 22585 } 22586 } 22587 22588 /** 22589 * Base class for derived classes that want to save and restore their own 22590 * state in {@link android.view.View#onSaveInstanceState()}. 22591 */ 22592 public static class BaseSavedState extends AbsSavedState { 22593 String mStartActivityRequestWhoSaved; 22594 22595 /** 22596 * Constructor used when reading from a parcel. Reads the state of the superclass. 22597 * 22598 * @param source parcel to read from 22599 */ 22600 public BaseSavedState(Parcel source) { 22601 this(source, null); 22602 } 22603 22604 /** 22605 * Constructor used when reading from a parcel using a given class loader. 22606 * Reads the state of the superclass. 22607 * 22608 * @param source parcel to read from 22609 * @param loader ClassLoader to use for reading 22610 */ 22611 public BaseSavedState(Parcel source, ClassLoader loader) { 22612 super(source, loader); 22613 mStartActivityRequestWhoSaved = source.readString(); 22614 } 22615 22616 /** 22617 * Constructor called by derived classes when creating their SavedState objects 22618 * 22619 * @param superState The state of the superclass of this view 22620 */ 22621 public BaseSavedState(Parcelable superState) { 22622 super(superState); 22623 } 22624 22625 @Override 22626 public void writeToParcel(Parcel out, int flags) { 22627 super.writeToParcel(out, flags); 22628 out.writeString(mStartActivityRequestWhoSaved); 22629 } 22630 22631 public static final Parcelable.Creator<BaseSavedState> CREATOR 22632 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 22633 @Override 22634 public BaseSavedState createFromParcel(Parcel in) { 22635 return new BaseSavedState(in); 22636 } 22637 22638 @Override 22639 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 22640 return new BaseSavedState(in, loader); 22641 } 22642 22643 @Override 22644 public BaseSavedState[] newArray(int size) { 22645 return new BaseSavedState[size]; 22646 } 22647 }; 22648 } 22649 22650 /** 22651 * A set of information given to a view when it is attached to its parent 22652 * window. 22653 */ 22654 final static class AttachInfo { 22655 interface Callbacks { 22656 void playSoundEffect(int effectId); 22657 boolean performHapticFeedback(int effectId, boolean always); 22658 } 22659 22660 /** 22661 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 22662 * to a Handler. This class contains the target (View) to invalidate and 22663 * the coordinates of the dirty rectangle. 22664 * 22665 * For performance purposes, this class also implements a pool of up to 22666 * POOL_LIMIT objects that get reused. This reduces memory allocations 22667 * whenever possible. 22668 */ 22669 static class InvalidateInfo { 22670 private static final int POOL_LIMIT = 10; 22671 22672 private static final SynchronizedPool<InvalidateInfo> sPool = 22673 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 22674 22675 View target; 22676 22677 int left; 22678 int top; 22679 int right; 22680 int bottom; 22681 22682 public static InvalidateInfo obtain() { 22683 InvalidateInfo instance = sPool.acquire(); 22684 return (instance != null) ? instance : new InvalidateInfo(); 22685 } 22686 22687 public void recycle() { 22688 target = null; 22689 sPool.release(this); 22690 } 22691 } 22692 22693 final IWindowSession mSession; 22694 22695 final IWindow mWindow; 22696 22697 final IBinder mWindowToken; 22698 22699 final Display mDisplay; 22700 22701 final Callbacks mRootCallbacks; 22702 22703 IWindowId mIWindowId; 22704 WindowId mWindowId; 22705 22706 /** 22707 * The top view of the hierarchy. 22708 */ 22709 View mRootView; 22710 22711 IBinder mPanelParentWindowToken; 22712 22713 boolean mHardwareAccelerated; 22714 boolean mHardwareAccelerationRequested; 22715 ThreadedRenderer mHardwareRenderer; 22716 List<RenderNode> mPendingAnimatingRenderNodes; 22717 22718 /** 22719 * The state of the display to which the window is attached, as reported 22720 * by {@link Display#getState()}. Note that the display state constants 22721 * declared by {@link Display} do not exactly line up with the screen state 22722 * constants declared by {@link View} (there are more display states than 22723 * screen states). 22724 */ 22725 int mDisplayState = Display.STATE_UNKNOWN; 22726 22727 /** 22728 * Scale factor used by the compatibility mode 22729 */ 22730 float mApplicationScale; 22731 22732 /** 22733 * Indicates whether the application is in compatibility mode 22734 */ 22735 boolean mScalingRequired; 22736 22737 /** 22738 * Left position of this view's window 22739 */ 22740 int mWindowLeft; 22741 22742 /** 22743 * Top position of this view's window 22744 */ 22745 int mWindowTop; 22746 22747 /** 22748 * Indicates whether views need to use 32-bit drawing caches 22749 */ 22750 boolean mUse32BitDrawingCache; 22751 22752 /** 22753 * For windows that are full-screen but using insets to layout inside 22754 * of the screen areas, these are the current insets to appear inside 22755 * the overscan area of the display. 22756 */ 22757 final Rect mOverscanInsets = new Rect(); 22758 22759 /** 22760 * For windows that are full-screen but using insets to layout inside 22761 * of the screen decorations, these are the current insets for the 22762 * content of the window. 22763 */ 22764 final Rect mContentInsets = new Rect(); 22765 22766 /** 22767 * For windows that are full-screen but using insets to layout inside 22768 * of the screen decorations, these are the current insets for the 22769 * actual visible parts of the window. 22770 */ 22771 final Rect mVisibleInsets = new Rect(); 22772 22773 /** 22774 * For windows that are full-screen but using insets to layout inside 22775 * of the screen decorations, these are the current insets for the 22776 * stable system windows. 22777 */ 22778 final Rect mStableInsets = new Rect(); 22779 22780 /** 22781 * For windows that include areas that are not covered by real surface these are the outsets 22782 * for real surface. 22783 */ 22784 final Rect mOutsets = new Rect(); 22785 22786 /** 22787 * In multi-window we force show the navigation bar. Because we don't want that the surface 22788 * size changes in this mode, we instead have a flag whether the navigation bar size should 22789 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 22790 */ 22791 boolean mAlwaysConsumeNavBar; 22792 22793 /** 22794 * The internal insets given by this window. This value is 22795 * supplied by the client (through 22796 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 22797 * be given to the window manager when changed to be used in laying 22798 * out windows behind it. 22799 */ 22800 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 22801 = new ViewTreeObserver.InternalInsetsInfo(); 22802 22803 /** 22804 * Set to true when mGivenInternalInsets is non-empty. 22805 */ 22806 boolean mHasNonEmptyGivenInternalInsets; 22807 22808 /** 22809 * All views in the window's hierarchy that serve as scroll containers, 22810 * used to determine if the window can be resized or must be panned 22811 * to adjust for a soft input area. 22812 */ 22813 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 22814 22815 final KeyEvent.DispatcherState mKeyDispatchState 22816 = new KeyEvent.DispatcherState(); 22817 22818 /** 22819 * Indicates whether the view's window currently has the focus. 22820 */ 22821 boolean mHasWindowFocus; 22822 22823 /** 22824 * The current visibility of the window. 22825 */ 22826 int mWindowVisibility; 22827 22828 /** 22829 * Indicates the time at which drawing started to occur. 22830 */ 22831 long mDrawingTime; 22832 22833 /** 22834 * Indicates whether or not ignoring the DIRTY_MASK flags. 22835 */ 22836 boolean mIgnoreDirtyState; 22837 22838 /** 22839 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 22840 * to avoid clearing that flag prematurely. 22841 */ 22842 boolean mSetIgnoreDirtyState = false; 22843 22844 /** 22845 * Indicates whether the view's window is currently in touch mode. 22846 */ 22847 boolean mInTouchMode; 22848 22849 /** 22850 * Indicates whether the view has requested unbuffered input dispatching for the current 22851 * event stream. 22852 */ 22853 boolean mUnbufferedDispatchRequested; 22854 22855 /** 22856 * Indicates that ViewAncestor should trigger a global layout change 22857 * the next time it performs a traversal 22858 */ 22859 boolean mRecomputeGlobalAttributes; 22860 22861 /** 22862 * Always report new attributes at next traversal. 22863 */ 22864 boolean mForceReportNewAttributes; 22865 22866 /** 22867 * Set during a traveral if any views want to keep the screen on. 22868 */ 22869 boolean mKeepScreenOn; 22870 22871 /** 22872 * Set during a traveral if the light center needs to be updated. 22873 */ 22874 boolean mNeedsUpdateLightCenter; 22875 22876 /** 22877 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 22878 */ 22879 int mSystemUiVisibility; 22880 22881 /** 22882 * Hack to force certain system UI visibility flags to be cleared. 22883 */ 22884 int mDisabledSystemUiVisibility; 22885 22886 /** 22887 * Last global system UI visibility reported by the window manager. 22888 */ 22889 int mGlobalSystemUiVisibility; 22890 22891 /** 22892 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 22893 * attached. 22894 */ 22895 boolean mHasSystemUiListeners; 22896 22897 /** 22898 * Set if the window has requested to extend into the overscan region 22899 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 22900 */ 22901 boolean mOverscanRequested; 22902 22903 /** 22904 * Set if the visibility of any views has changed. 22905 */ 22906 boolean mViewVisibilityChanged; 22907 22908 /** 22909 * Set to true if a view has been scrolled. 22910 */ 22911 boolean mViewScrollChanged; 22912 22913 /** 22914 * Set to true if high contrast mode enabled 22915 */ 22916 boolean mHighContrastText; 22917 22918 /** 22919 * Set to true if a pointer event is currently being handled. 22920 */ 22921 boolean mHandlingPointerEvent; 22922 22923 /** 22924 * Global to the view hierarchy used as a temporary for dealing with 22925 * x/y points in the transparent region computations. 22926 */ 22927 final int[] mTransparentLocation = new int[2]; 22928 22929 /** 22930 * Global to the view hierarchy used as a temporary for dealing with 22931 * x/y points in the ViewGroup.invalidateChild implementation. 22932 */ 22933 final int[] mInvalidateChildLocation = new int[2]; 22934 22935 /** 22936 * Global to the view hierarchy used as a temporary for dealng with 22937 * computing absolute on-screen location. 22938 */ 22939 final int[] mTmpLocation = new int[2]; 22940 22941 /** 22942 * Global to the view hierarchy used as a temporary for dealing with 22943 * x/y location when view is transformed. 22944 */ 22945 final float[] mTmpTransformLocation = new float[2]; 22946 22947 /** 22948 * The view tree observer used to dispatch global events like 22949 * layout, pre-draw, touch mode change, etc. 22950 */ 22951 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 22952 22953 /** 22954 * A Canvas used by the view hierarchy to perform bitmap caching. 22955 */ 22956 Canvas mCanvas; 22957 22958 /** 22959 * The view root impl. 22960 */ 22961 final ViewRootImpl mViewRootImpl; 22962 22963 /** 22964 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 22965 * handler can be used to pump events in the UI events queue. 22966 */ 22967 final Handler mHandler; 22968 22969 /** 22970 * Temporary for use in computing invalidate rectangles while 22971 * calling up the hierarchy. 22972 */ 22973 final Rect mTmpInvalRect = new Rect(); 22974 22975 /** 22976 * Temporary for use in computing hit areas with transformed views 22977 */ 22978 final RectF mTmpTransformRect = new RectF(); 22979 22980 /** 22981 * Temporary for use in computing hit areas with transformed views 22982 */ 22983 final RectF mTmpTransformRect1 = new RectF(); 22984 22985 /** 22986 * Temporary list of rectanges. 22987 */ 22988 final List<RectF> mTmpRectList = new ArrayList<>(); 22989 22990 /** 22991 * Temporary for use in transforming invalidation rect 22992 */ 22993 final Matrix mTmpMatrix = new Matrix(); 22994 22995 /** 22996 * Temporary for use in transforming invalidation rect 22997 */ 22998 final Transformation mTmpTransformation = new Transformation(); 22999 23000 /** 23001 * Temporary for use in querying outlines from OutlineProviders 23002 */ 23003 final Outline mTmpOutline = new Outline(); 23004 23005 /** 23006 * Temporary list for use in collecting focusable descendents of a view. 23007 */ 23008 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 23009 23010 /** 23011 * The id of the window for accessibility purposes. 23012 */ 23013 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 23014 23015 /** 23016 * Flags related to accessibility processing. 23017 * 23018 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 23019 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 23020 */ 23021 int mAccessibilityFetchFlags; 23022 23023 /** 23024 * The drawable for highlighting accessibility focus. 23025 */ 23026 Drawable mAccessibilityFocusDrawable; 23027 23028 /** 23029 * Show where the margins, bounds and layout bounds are for each view. 23030 */ 23031 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 23032 23033 /** 23034 * Point used to compute visible regions. 23035 */ 23036 final Point mPoint = new Point(); 23037 23038 /** 23039 * Used to track which View originated a requestLayout() call, used when 23040 * requestLayout() is called during layout. 23041 */ 23042 View mViewRequestingLayout; 23043 23044 /** 23045 * Used to track views that need (at least) a partial relayout at their current size 23046 * during the next traversal. 23047 */ 23048 List<View> mPartialLayoutViews = new ArrayList<>(); 23049 23050 /** 23051 * Swapped with mPartialLayoutViews during layout to avoid concurrent 23052 * modification. Lazily assigned during ViewRootImpl layout. 23053 */ 23054 List<View> mEmptyPartialLayoutViews; 23055 23056 /** 23057 * Used to track the identity of the current drag operation. 23058 */ 23059 IBinder mDragToken; 23060 23061 /** 23062 * The drag shadow surface for the current drag operation. 23063 */ 23064 public Surface mDragSurface; 23065 23066 /** 23067 * Creates a new set of attachment information with the specified 23068 * events handler and thread. 23069 * 23070 * @param handler the events handler the view must use 23071 */ 23072 AttachInfo(IWindowSession session, IWindow window, Display display, 23073 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 23074 mSession = session; 23075 mWindow = window; 23076 mWindowToken = window.asBinder(); 23077 mDisplay = display; 23078 mViewRootImpl = viewRootImpl; 23079 mHandler = handler; 23080 mRootCallbacks = effectPlayer; 23081 } 23082 } 23083 23084 /** 23085 * <p>ScrollabilityCache holds various fields used by a View when scrolling 23086 * is supported. This avoids keeping too many unused fields in most 23087 * instances of View.</p> 23088 */ 23089 private static class ScrollabilityCache implements Runnable { 23090 23091 /** 23092 * Scrollbars are not visible 23093 */ 23094 public static final int OFF = 0; 23095 23096 /** 23097 * Scrollbars are visible 23098 */ 23099 public static final int ON = 1; 23100 23101 /** 23102 * Scrollbars are fading away 23103 */ 23104 public static final int FADING = 2; 23105 23106 public boolean fadeScrollBars; 23107 23108 public int fadingEdgeLength; 23109 public int scrollBarDefaultDelayBeforeFade; 23110 public int scrollBarFadeDuration; 23111 23112 public int scrollBarSize; 23113 public ScrollBarDrawable scrollBar; 23114 public float[] interpolatorValues; 23115 public View host; 23116 23117 public final Paint paint; 23118 public final Matrix matrix; 23119 public Shader shader; 23120 23121 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 23122 23123 private static final float[] OPAQUE = { 255 }; 23124 private static final float[] TRANSPARENT = { 0.0f }; 23125 23126 /** 23127 * When fading should start. This time moves into the future every time 23128 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 23129 */ 23130 public long fadeStartTime; 23131 23132 23133 /** 23134 * The current state of the scrollbars: ON, OFF, or FADING 23135 */ 23136 public int state = OFF; 23137 23138 private int mLastColor; 23139 23140 public final Rect mScrollBarBounds = new Rect(); 23141 23142 public static final int NOT_DRAGGING = 0; 23143 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 23144 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 23145 public int mScrollBarDraggingState = NOT_DRAGGING; 23146 23147 public float mScrollBarDraggingPos = 0; 23148 23149 public ScrollabilityCache(ViewConfiguration configuration, View host) { 23150 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 23151 scrollBarSize = configuration.getScaledScrollBarSize(); 23152 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 23153 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 23154 23155 paint = new Paint(); 23156 matrix = new Matrix(); 23157 // use use a height of 1, and then wack the matrix each time we 23158 // actually use it. 23159 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23160 paint.setShader(shader); 23161 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23162 23163 this.host = host; 23164 } 23165 23166 public void setFadeColor(int color) { 23167 if (color != mLastColor) { 23168 mLastColor = color; 23169 23170 if (color != 0) { 23171 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 23172 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 23173 paint.setShader(shader); 23174 // Restore the default transfer mode (src_over) 23175 paint.setXfermode(null); 23176 } else { 23177 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23178 paint.setShader(shader); 23179 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23180 } 23181 } 23182 } 23183 23184 public void run() { 23185 long now = AnimationUtils.currentAnimationTimeMillis(); 23186 if (now >= fadeStartTime) { 23187 23188 // the animation fades the scrollbars out by changing 23189 // the opacity (alpha) from fully opaque to fully 23190 // transparent 23191 int nextFrame = (int) now; 23192 int framesCount = 0; 23193 23194 Interpolator interpolator = scrollBarInterpolator; 23195 23196 // Start opaque 23197 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 23198 23199 // End transparent 23200 nextFrame += scrollBarFadeDuration; 23201 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 23202 23203 state = FADING; 23204 23205 // Kick off the fade animation 23206 host.invalidate(true); 23207 } 23208 } 23209 } 23210 23211 /** 23212 * Resuable callback for sending 23213 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 23214 */ 23215 private class SendViewScrolledAccessibilityEvent implements Runnable { 23216 public volatile boolean mIsPending; 23217 23218 public void run() { 23219 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 23220 mIsPending = false; 23221 } 23222 } 23223 23224 /** 23225 * <p> 23226 * This class represents a delegate that can be registered in a {@link View} 23227 * to enhance accessibility support via composition rather via inheritance. 23228 * It is specifically targeted to widget developers that extend basic View 23229 * classes i.e. classes in package android.view, that would like their 23230 * applications to be backwards compatible. 23231 * </p> 23232 * <div class="special reference"> 23233 * <h3>Developer Guides</h3> 23234 * <p>For more information about making applications accessible, read the 23235 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 23236 * developer guide.</p> 23237 * </div> 23238 * <p> 23239 * A scenario in which a developer would like to use an accessibility delegate 23240 * is overriding a method introduced in a later API version then the minimal API 23241 * version supported by the application. For example, the method 23242 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 23243 * in API version 4 when the accessibility APIs were first introduced. If a 23244 * developer would like his application to run on API version 4 devices (assuming 23245 * all other APIs used by the application are version 4 or lower) and take advantage 23246 * of this method, instead of overriding the method which would break the application's 23247 * backwards compatibility, he can override the corresponding method in this 23248 * delegate and register the delegate in the target View if the API version of 23249 * the system is high enough i.e. the API version is same or higher to the API 23250 * version that introduced 23251 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 23252 * </p> 23253 * <p> 23254 * Here is an example implementation: 23255 * </p> 23256 * <code><pre><p> 23257 * if (Build.VERSION.SDK_INT >= 14) { 23258 * // If the API version is equal of higher than the version in 23259 * // which onInitializeAccessibilityNodeInfo was introduced we 23260 * // register a delegate with a customized implementation. 23261 * View view = findViewById(R.id.view_id); 23262 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 23263 * public void onInitializeAccessibilityNodeInfo(View host, 23264 * AccessibilityNodeInfo info) { 23265 * // Let the default implementation populate the info. 23266 * super.onInitializeAccessibilityNodeInfo(host, info); 23267 * // Set some other information. 23268 * info.setEnabled(host.isEnabled()); 23269 * } 23270 * }); 23271 * } 23272 * </code></pre></p> 23273 * <p> 23274 * This delegate contains methods that correspond to the accessibility methods 23275 * in View. If a delegate has been specified the implementation in View hands 23276 * off handling to the corresponding method in this delegate. The default 23277 * implementation the delegate methods behaves exactly as the corresponding 23278 * method in View for the case of no accessibility delegate been set. Hence, 23279 * to customize the behavior of a View method, clients can override only the 23280 * corresponding delegate method without altering the behavior of the rest 23281 * accessibility related methods of the host view. 23282 * </p> 23283 * <p> 23284 * <strong>Note:</strong> On platform versions prior to 23285 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 23286 * views in the {@code android.widget.*} package are called <i>before</i> 23287 * host methods. This prevents certain properties such as class name from 23288 * being modified by overriding 23289 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 23290 * as any changes will be overwritten by the host class. 23291 * <p> 23292 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 23293 * methods are called <i>after</i> host methods, which all properties to be 23294 * modified without being overwritten by the host class. 23295 */ 23296 public static class AccessibilityDelegate { 23297 23298 /** 23299 * Sends an accessibility event of the given type. If accessibility is not 23300 * enabled this method has no effect. 23301 * <p> 23302 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 23303 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 23304 * been set. 23305 * </p> 23306 * 23307 * @param host The View hosting the delegate. 23308 * @param eventType The type of the event to send. 23309 * 23310 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 23311 */ 23312 public void sendAccessibilityEvent(View host, int eventType) { 23313 host.sendAccessibilityEventInternal(eventType); 23314 } 23315 23316 /** 23317 * Performs the specified accessibility action on the view. For 23318 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 23319 * <p> 23320 * The default implementation behaves as 23321 * {@link View#performAccessibilityAction(int, Bundle) 23322 * View#performAccessibilityAction(int, Bundle)} for the case of 23323 * no accessibility delegate been set. 23324 * </p> 23325 * 23326 * @param action The action to perform. 23327 * @return Whether the action was performed. 23328 * 23329 * @see View#performAccessibilityAction(int, Bundle) 23330 * View#performAccessibilityAction(int, Bundle) 23331 */ 23332 public boolean performAccessibilityAction(View host, int action, Bundle args) { 23333 return host.performAccessibilityActionInternal(action, args); 23334 } 23335 23336 /** 23337 * Sends an accessibility event. This method behaves exactly as 23338 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 23339 * empty {@link AccessibilityEvent} and does not perform a check whether 23340 * accessibility is enabled. 23341 * <p> 23342 * The default implementation behaves as 23343 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23344 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 23345 * the case of no accessibility delegate been set. 23346 * </p> 23347 * 23348 * @param host The View hosting the delegate. 23349 * @param event The event to send. 23350 * 23351 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23352 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23353 */ 23354 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 23355 host.sendAccessibilityEventUncheckedInternal(event); 23356 } 23357 23358 /** 23359 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 23360 * to its children for adding their text content to the event. 23361 * <p> 23362 * The default implementation behaves as 23363 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23364 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 23365 * the case of no accessibility delegate been set. 23366 * </p> 23367 * 23368 * @param host The View hosting the delegate. 23369 * @param event The event. 23370 * @return True if the event population was completed. 23371 * 23372 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23373 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23374 */ 23375 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23376 return host.dispatchPopulateAccessibilityEventInternal(event); 23377 } 23378 23379 /** 23380 * Gives a chance to the host View to populate the accessibility event with its 23381 * text content. 23382 * <p> 23383 * The default implementation behaves as 23384 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 23385 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 23386 * the case of no accessibility delegate been set. 23387 * </p> 23388 * 23389 * @param host The View hosting the delegate. 23390 * @param event The accessibility event which to populate. 23391 * 23392 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 23393 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 23394 */ 23395 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23396 host.onPopulateAccessibilityEventInternal(event); 23397 } 23398 23399 /** 23400 * Initializes an {@link AccessibilityEvent} with information about the 23401 * the host View which is the event source. 23402 * <p> 23403 * The default implementation behaves as 23404 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 23405 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 23406 * the case of no accessibility delegate been set. 23407 * </p> 23408 * 23409 * @param host The View hosting the delegate. 23410 * @param event The event to initialize. 23411 * 23412 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 23413 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 23414 */ 23415 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 23416 host.onInitializeAccessibilityEventInternal(event); 23417 } 23418 23419 /** 23420 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 23421 * <p> 23422 * The default implementation behaves as 23423 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23424 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 23425 * the case of no accessibility delegate been set. 23426 * </p> 23427 * 23428 * @param host The View hosting the delegate. 23429 * @param info The instance to initialize. 23430 * 23431 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23432 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23433 */ 23434 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 23435 host.onInitializeAccessibilityNodeInfoInternal(info); 23436 } 23437 23438 /** 23439 * Called when a child of the host View has requested sending an 23440 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 23441 * to augment the event. 23442 * <p> 23443 * The default implementation behaves as 23444 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23445 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 23446 * the case of no accessibility delegate been set. 23447 * </p> 23448 * 23449 * @param host The View hosting the delegate. 23450 * @param child The child which requests sending the event. 23451 * @param event The event to be sent. 23452 * @return True if the event should be sent 23453 * 23454 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23455 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23456 */ 23457 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 23458 AccessibilityEvent event) { 23459 return host.onRequestSendAccessibilityEventInternal(child, event); 23460 } 23461 23462 /** 23463 * Gets the provider for managing a virtual view hierarchy rooted at this View 23464 * and reported to {@link android.accessibilityservice.AccessibilityService}s 23465 * that explore the window content. 23466 * <p> 23467 * The default implementation behaves as 23468 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 23469 * the case of no accessibility delegate been set. 23470 * </p> 23471 * 23472 * @return The provider. 23473 * 23474 * @see AccessibilityNodeProvider 23475 */ 23476 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 23477 return null; 23478 } 23479 23480 /** 23481 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 23482 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 23483 * This method is responsible for obtaining an accessibility node info from a 23484 * pool of reusable instances and calling 23485 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 23486 * view to initialize the former. 23487 * <p> 23488 * <strong>Note:</strong> The client is responsible for recycling the obtained 23489 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 23490 * creation. 23491 * </p> 23492 * <p> 23493 * The default implementation behaves as 23494 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 23495 * the case of no accessibility delegate been set. 23496 * </p> 23497 * @return A populated {@link AccessibilityNodeInfo}. 23498 * 23499 * @see AccessibilityNodeInfo 23500 * 23501 * @hide 23502 */ 23503 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 23504 return host.createAccessibilityNodeInfoInternal(); 23505 } 23506 } 23507 23508 private class MatchIdPredicate implements Predicate<View> { 23509 public int mId; 23510 23511 @Override 23512 public boolean apply(View view) { 23513 return (view.mID == mId); 23514 } 23515 } 23516 23517 private class MatchLabelForPredicate implements Predicate<View> { 23518 private int mLabeledId; 23519 23520 @Override 23521 public boolean apply(View view) { 23522 return (view.mLabelForId == mLabeledId); 23523 } 23524 } 23525 23526 private class SendViewStateChangedAccessibilityEvent implements Runnable { 23527 private int mChangeTypes = 0; 23528 private boolean mPosted; 23529 private boolean mPostedWithDelay; 23530 private long mLastEventTimeMillis; 23531 23532 @Override 23533 public void run() { 23534 mPosted = false; 23535 mPostedWithDelay = false; 23536 mLastEventTimeMillis = SystemClock.uptimeMillis(); 23537 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 23538 final AccessibilityEvent event = AccessibilityEvent.obtain(); 23539 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 23540 event.setContentChangeTypes(mChangeTypes); 23541 sendAccessibilityEventUnchecked(event); 23542 } 23543 mChangeTypes = 0; 23544 } 23545 23546 public void runOrPost(int changeType) { 23547 mChangeTypes |= changeType; 23548 23549 // If this is a live region or the child of a live region, collect 23550 // all events from this frame and send them on the next frame. 23551 if (inLiveRegion()) { 23552 // If we're already posted with a delay, remove that. 23553 if (mPostedWithDelay) { 23554 removeCallbacks(this); 23555 mPostedWithDelay = false; 23556 } 23557 // Only post if we're not already posted. 23558 if (!mPosted) { 23559 post(this); 23560 mPosted = true; 23561 } 23562 return; 23563 } 23564 23565 if (mPosted) { 23566 return; 23567 } 23568 23569 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 23570 final long minEventIntevalMillis = 23571 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 23572 if (timeSinceLastMillis >= minEventIntevalMillis) { 23573 removeCallbacks(this); 23574 run(); 23575 } else { 23576 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 23577 mPostedWithDelay = true; 23578 } 23579 } 23580 } 23581 23582 private boolean inLiveRegion() { 23583 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23584 return true; 23585 } 23586 23587 ViewParent parent = getParent(); 23588 while (parent instanceof View) { 23589 if (((View) parent).getAccessibilityLiveRegion() 23590 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23591 return true; 23592 } 23593 parent = parent.getParent(); 23594 } 23595 23596 return false; 23597 } 23598 23599 /** 23600 * Dump all private flags in readable format, useful for documentation and 23601 * sanity checking. 23602 */ 23603 private static void dumpFlags() { 23604 final HashMap<String, String> found = Maps.newHashMap(); 23605 try { 23606 for (Field field : View.class.getDeclaredFields()) { 23607 final int modifiers = field.getModifiers(); 23608 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 23609 if (field.getType().equals(int.class)) { 23610 final int value = field.getInt(null); 23611 dumpFlag(found, field.getName(), value); 23612 } else if (field.getType().equals(int[].class)) { 23613 final int[] values = (int[]) field.get(null); 23614 for (int i = 0; i < values.length; i++) { 23615 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 23616 } 23617 } 23618 } 23619 } 23620 } catch (IllegalAccessException e) { 23621 throw new RuntimeException(e); 23622 } 23623 23624 final ArrayList<String> keys = Lists.newArrayList(); 23625 keys.addAll(found.keySet()); 23626 Collections.sort(keys); 23627 for (String key : keys) { 23628 Log.d(VIEW_LOG_TAG, found.get(key)); 23629 } 23630 } 23631 23632 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 23633 // Sort flags by prefix, then by bits, always keeping unique keys 23634 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 23635 final int prefix = name.indexOf('_'); 23636 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 23637 final String output = bits + " " + name; 23638 found.put(key, output); 23639 } 23640 23641 /** {@hide} */ 23642 public void encode(@NonNull ViewHierarchyEncoder stream) { 23643 stream.beginObject(this); 23644 encodeProperties(stream); 23645 stream.endObject(); 23646 } 23647 23648 /** {@hide} */ 23649 @CallSuper 23650 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 23651 Object resolveId = ViewDebug.resolveId(getContext(), mID); 23652 if (resolveId instanceof String) { 23653 stream.addProperty("id", (String) resolveId); 23654 } else { 23655 stream.addProperty("id", mID); 23656 } 23657 23658 stream.addProperty("misc:transformation.alpha", 23659 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 23660 stream.addProperty("misc:transitionName", getTransitionName()); 23661 23662 // layout 23663 stream.addProperty("layout:left", mLeft); 23664 stream.addProperty("layout:right", mRight); 23665 stream.addProperty("layout:top", mTop); 23666 stream.addProperty("layout:bottom", mBottom); 23667 stream.addProperty("layout:width", getWidth()); 23668 stream.addProperty("layout:height", getHeight()); 23669 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 23670 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 23671 stream.addProperty("layout:hasTransientState", hasTransientState()); 23672 stream.addProperty("layout:baseline", getBaseline()); 23673 23674 // layout params 23675 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 23676 if (layoutParams != null) { 23677 stream.addPropertyKey("layoutParams"); 23678 layoutParams.encode(stream); 23679 } 23680 23681 // scrolling 23682 stream.addProperty("scrolling:scrollX", mScrollX); 23683 stream.addProperty("scrolling:scrollY", mScrollY); 23684 23685 // padding 23686 stream.addProperty("padding:paddingLeft", mPaddingLeft); 23687 stream.addProperty("padding:paddingRight", mPaddingRight); 23688 stream.addProperty("padding:paddingTop", mPaddingTop); 23689 stream.addProperty("padding:paddingBottom", mPaddingBottom); 23690 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 23691 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 23692 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 23693 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 23694 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 23695 23696 // measurement 23697 stream.addProperty("measurement:minHeight", mMinHeight); 23698 stream.addProperty("measurement:minWidth", mMinWidth); 23699 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 23700 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 23701 23702 // drawing 23703 stream.addProperty("drawing:elevation", getElevation()); 23704 stream.addProperty("drawing:translationX", getTranslationX()); 23705 stream.addProperty("drawing:translationY", getTranslationY()); 23706 stream.addProperty("drawing:translationZ", getTranslationZ()); 23707 stream.addProperty("drawing:rotation", getRotation()); 23708 stream.addProperty("drawing:rotationX", getRotationX()); 23709 stream.addProperty("drawing:rotationY", getRotationY()); 23710 stream.addProperty("drawing:scaleX", getScaleX()); 23711 stream.addProperty("drawing:scaleY", getScaleY()); 23712 stream.addProperty("drawing:pivotX", getPivotX()); 23713 stream.addProperty("drawing:pivotY", getPivotY()); 23714 stream.addProperty("drawing:opaque", isOpaque()); 23715 stream.addProperty("drawing:alpha", getAlpha()); 23716 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 23717 stream.addProperty("drawing:shadow", hasShadow()); 23718 stream.addProperty("drawing:solidColor", getSolidColor()); 23719 stream.addProperty("drawing:layerType", mLayerType); 23720 stream.addProperty("drawing:willNotDraw", willNotDraw()); 23721 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 23722 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 23723 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 23724 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 23725 23726 // focus 23727 stream.addProperty("focus:hasFocus", hasFocus()); 23728 stream.addProperty("focus:isFocused", isFocused()); 23729 stream.addProperty("focus:isFocusable", isFocusable()); 23730 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 23731 23732 stream.addProperty("misc:clickable", isClickable()); 23733 stream.addProperty("misc:pressed", isPressed()); 23734 stream.addProperty("misc:selected", isSelected()); 23735 stream.addProperty("misc:touchMode", isInTouchMode()); 23736 stream.addProperty("misc:hovered", isHovered()); 23737 stream.addProperty("misc:activated", isActivated()); 23738 23739 stream.addProperty("misc:visibility", getVisibility()); 23740 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 23741 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 23742 23743 stream.addProperty("misc:enabled", isEnabled()); 23744 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 23745 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 23746 23747 // theme attributes 23748 Resources.Theme theme = getContext().getTheme(); 23749 if (theme != null) { 23750 stream.addPropertyKey("theme"); 23751 theme.encode(stream); 23752 } 23753 23754 // view attribute information 23755 int n = mAttributes != null ? mAttributes.length : 0; 23756 stream.addProperty("meta:__attrCount__", n/2); 23757 for (int i = 0; i < n; i += 2) { 23758 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 23759 } 23760 23761 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 23762 23763 // text 23764 stream.addProperty("text:textDirection", getTextDirection()); 23765 stream.addProperty("text:textAlignment", getTextAlignment()); 23766 23767 // accessibility 23768 CharSequence contentDescription = getContentDescription(); 23769 stream.addProperty("accessibility:contentDescription", 23770 contentDescription == null ? "" : contentDescription.toString()); 23771 stream.addProperty("accessibility:labelFor", getLabelFor()); 23772 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 23773 } 23774} 23775