View.java revision d58b65cd31531445dd2dd53ae3135a9a85149d8f
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 static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED; 20 21import static java.lang.Math.max; 22 23import android.animation.AnimatorInflater; 24import android.animation.StateListAnimator; 25import android.annotation.CallSuper; 26import android.annotation.ColorInt; 27import android.annotation.DrawableRes; 28import android.annotation.FloatRange; 29import android.annotation.IdRes; 30import android.annotation.IntDef; 31import android.annotation.IntRange; 32import android.annotation.LayoutRes; 33import android.annotation.NonNull; 34import android.annotation.Nullable; 35import android.annotation.Size; 36import android.annotation.TestApi; 37import android.annotation.UiThread; 38import android.content.ClipData; 39import android.content.Context; 40import android.content.ContextWrapper; 41import android.content.Intent; 42import android.content.res.ColorStateList; 43import android.content.res.Configuration; 44import android.content.res.Resources; 45import android.content.res.TypedArray; 46import android.graphics.Bitmap; 47import android.graphics.Canvas; 48import android.graphics.Color; 49import android.graphics.Insets; 50import android.graphics.Interpolator; 51import android.graphics.LinearGradient; 52import android.graphics.Matrix; 53import android.graphics.Outline; 54import android.graphics.Paint; 55import android.graphics.PixelFormat; 56import android.graphics.Point; 57import android.graphics.PorterDuff; 58import android.graphics.PorterDuffXfermode; 59import android.graphics.Rect; 60import android.graphics.RectF; 61import android.graphics.Region; 62import android.graphics.Shader; 63import android.graphics.drawable.ColorDrawable; 64import android.graphics.drawable.Drawable; 65import android.hardware.display.DisplayManagerGlobal; 66import android.net.Uri; 67import android.os.Build; 68import android.os.Bundle; 69import android.os.Handler; 70import android.os.IBinder; 71import android.os.Message; 72import android.os.Parcel; 73import android.os.Parcelable; 74import android.os.RemoteException; 75import android.os.SystemClock; 76import android.os.SystemProperties; 77import android.os.Trace; 78import android.text.InputType; 79import android.text.TextUtils; 80import android.util.AttributeSet; 81import android.util.FloatProperty; 82import android.util.LayoutDirection; 83import android.util.Log; 84import android.util.LongSparseLongArray; 85import android.util.Pools.SynchronizedPool; 86import android.util.Property; 87import android.util.SparseArray; 88import android.util.StateSet; 89import android.util.SuperNotCalledException; 90import android.util.TypedValue; 91import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 92import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 93import android.view.AccessibilityIterators.TextSegmentIterator; 94import android.view.AccessibilityIterators.WordTextSegmentIterator; 95import android.view.ContextMenu.ContextMenuInfo; 96import android.view.accessibility.AccessibilityEvent; 97import android.view.accessibility.AccessibilityEventSource; 98import android.view.accessibility.AccessibilityManager; 99import android.view.accessibility.AccessibilityNodeInfo; 100import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 101import android.view.accessibility.AccessibilityNodeProvider; 102import android.view.accessibility.AccessibilityWindowInfo; 103import android.view.animation.Animation; 104import android.view.animation.AnimationUtils; 105import android.view.animation.Transformation; 106import android.view.autofill.AutofillId; 107import android.view.autofill.AutofillManager; 108import android.view.autofill.AutofillValue; 109import android.view.inputmethod.EditorInfo; 110import android.view.inputmethod.InputConnection; 111import android.view.inputmethod.InputMethodManager; 112import android.widget.Checkable; 113import android.widget.FrameLayout; 114import android.widget.ScrollBarDrawable; 115 116import com.android.internal.R; 117import com.android.internal.view.TooltipPopup; 118import com.android.internal.view.menu.MenuBuilder; 119import com.android.internal.widget.ScrollBarUtils; 120 121import com.google.android.collect.Lists; 122import com.google.android.collect.Maps; 123 124import java.lang.annotation.Retention; 125import java.lang.annotation.RetentionPolicy; 126import java.lang.ref.WeakReference; 127import java.lang.reflect.Field; 128import java.lang.reflect.InvocationTargetException; 129import java.lang.reflect.Method; 130import java.lang.reflect.Modifier; 131import java.util.ArrayList; 132import java.util.Arrays; 133import java.util.Calendar; 134import java.util.Collection; 135import java.util.Collections; 136import java.util.HashMap; 137import java.util.List; 138import java.util.Locale; 139import java.util.Map; 140import java.util.concurrent.CopyOnWriteArrayList; 141import java.util.concurrent.atomic.AtomicInteger; 142import java.util.function.Predicate; 143 144/** 145 * <p> 146 * This class represents the basic building block for user interface components. A View 147 * occupies a rectangular area on the screen and is responsible for drawing and 148 * event handling. View is the base class for <em>widgets</em>, which are 149 * used to create interactive UI components (buttons, text fields, etc.). The 150 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 151 * are invisible containers that hold other Views (or other ViewGroups) and define 152 * their layout properties. 153 * </p> 154 * 155 * <div class="special reference"> 156 * <h3>Developer Guides</h3> 157 * <p>For information about using this class to develop your application's user interface, 158 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 159 * </div> 160 * 161 * <a name="Using"></a> 162 * <h3>Using Views</h3> 163 * <p> 164 * All of the views in a window are arranged in a single tree. You can add views 165 * either from code or by specifying a tree of views in one or more XML layout 166 * files. There are many specialized subclasses of views that act as controls or 167 * are capable of displaying text, images, or other content. 168 * </p> 169 * <p> 170 * Once you have created a tree of views, there are typically a few types of 171 * common operations you may wish to perform: 172 * <ul> 173 * <li><strong>Set properties:</strong> for example setting the text of a 174 * {@link android.widget.TextView}. The available properties and the methods 175 * that set them will vary among the different subclasses of views. Note that 176 * properties that are known at build time can be set in the XML layout 177 * files.</li> 178 * <li><strong>Set focus:</strong> The framework will handle moving focus in 179 * response to user input. To force focus to a specific view, call 180 * {@link #requestFocus}.</li> 181 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 182 * that will be notified when something interesting happens to the view. For 183 * example, all views will let you set a listener to be notified when the view 184 * gains or loses focus. You can register such a listener using 185 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 186 * Other view subclasses offer more specialized listeners. For example, a Button 187 * exposes a listener to notify clients when the button is clicked.</li> 188 * <li><strong>Set visibility:</strong> You can hide or show views using 189 * {@link #setVisibility(int)}.</li> 190 * </ul> 191 * </p> 192 * <p><em> 193 * Note: The Android framework is responsible for measuring, laying out and 194 * drawing views. You should not call methods that perform these actions on 195 * views yourself unless you are actually implementing a 196 * {@link android.view.ViewGroup}. 197 * </em></p> 198 * 199 * <a name="Lifecycle"></a> 200 * <h3>Implementing a Custom View</h3> 201 * 202 * <p> 203 * To implement a custom view, you will usually begin by providing overrides for 204 * some of the standard methods that the framework calls on all views. You do 205 * not need to override all of these methods. In fact, you can start by just 206 * overriding {@link #onDraw(android.graphics.Canvas)}. 207 * <table border="2" width="85%" align="center" cellpadding="5"> 208 * <thead> 209 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 210 * </thead> 211 * 212 * <tbody> 213 * <tr> 214 * <td rowspan="2">Creation</td> 215 * <td>Constructors</td> 216 * <td>There is a form of the constructor that are called when the view 217 * is created from code and a form that is called when the view is 218 * inflated from a layout file. The second form should parse and apply 219 * any attributes defined in the layout file. 220 * </td> 221 * </tr> 222 * <tr> 223 * <td><code>{@link #onFinishInflate()}</code></td> 224 * <td>Called after a view and all of its children has been inflated 225 * from XML.</td> 226 * </tr> 227 * 228 * <tr> 229 * <td rowspan="3">Layout</td> 230 * <td><code>{@link #onMeasure(int, int)}</code></td> 231 * <td>Called to determine the size requirements for this view and all 232 * of its children. 233 * </td> 234 * </tr> 235 * <tr> 236 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 237 * <td>Called when this view should assign a size and position to all 238 * of its children. 239 * </td> 240 * </tr> 241 * <tr> 242 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 243 * <td>Called when the size of this view has changed. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td>Drawing</td> 249 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 250 * <td>Called when the view should render its content. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td rowspan="4">Event processing</td> 256 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 257 * <td>Called when a new hardware key event occurs. 258 * </td> 259 * </tr> 260 * <tr> 261 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 262 * <td>Called when a hardware key up event occurs. 263 * </td> 264 * </tr> 265 * <tr> 266 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 267 * <td>Called when a trackball motion event occurs. 268 * </td> 269 * </tr> 270 * <tr> 271 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 272 * <td>Called when a touch screen motion event occurs. 273 * </td> 274 * </tr> 275 * 276 * <tr> 277 * <td rowspan="2">Focus</td> 278 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 279 * <td>Called when the view gains or loses focus. 280 * </td> 281 * </tr> 282 * 283 * <tr> 284 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 285 * <td>Called when the window containing the view gains or loses focus. 286 * </td> 287 * </tr> 288 * 289 * <tr> 290 * <td rowspan="3">Attaching</td> 291 * <td><code>{@link #onAttachedToWindow()}</code></td> 292 * <td>Called when the view is attached to a window. 293 * </td> 294 * </tr> 295 * 296 * <tr> 297 * <td><code>{@link #onDetachedFromWindow}</code></td> 298 * <td>Called when the view is detached from its window. 299 * </td> 300 * </tr> 301 * 302 * <tr> 303 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 304 * <td>Called when the visibility of the window containing the view 305 * has changed. 306 * </td> 307 * </tr> 308 * </tbody> 309 * 310 * </table> 311 * </p> 312 * 313 * <a name="IDs"></a> 314 * <h3>IDs</h3> 315 * Views may have an integer id associated with them. These ids are typically 316 * assigned in the layout XML files, and are used to find specific views within 317 * the view tree. A common pattern is to: 318 * <ul> 319 * <li>Define a Button in the layout file and assign it a unique ID. 320 * <pre> 321 * <Button 322 * android:id="@+id/my_button" 323 * android:layout_width="wrap_content" 324 * android:layout_height="wrap_content" 325 * android:text="@string/my_button_text"/> 326 * </pre></li> 327 * <li>From the onCreate method of an Activity, find the Button 328 * <pre class="prettyprint"> 329 * Button myButton = findViewById(R.id.my_button); 330 * </pre></li> 331 * </ul> 332 * <p> 333 * View IDs need not be unique throughout the tree, but it is good practice to 334 * ensure that they are at least unique within the part of the tree you are 335 * searching. 336 * </p> 337 * 338 * <a name="Position"></a> 339 * <h3>Position</h3> 340 * <p> 341 * The geometry of a view is that of a rectangle. A view has a location, 342 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 343 * two dimensions, expressed as a width and a height. The unit for location 344 * and dimensions is the pixel. 345 * </p> 346 * 347 * <p> 348 * It is possible to retrieve the location of a view by invoking the methods 349 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 350 * coordinate of the rectangle representing the view. The latter returns the 351 * top, or Y, coordinate of the rectangle representing the view. These methods 352 * both return the location of the view relative to its parent. For instance, 353 * when getLeft() returns 20, that means the view is located 20 pixels to the 354 * right of the left edge of its direct parent. 355 * </p> 356 * 357 * <p> 358 * In addition, several convenience methods are offered to avoid unnecessary 359 * computations, namely {@link #getRight()} and {@link #getBottom()}. 360 * These methods return the coordinates of the right and bottom edges of the 361 * rectangle representing the view. For instance, calling {@link #getRight()} 362 * is similar to the following computation: <code>getLeft() + getWidth()</code> 363 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 364 * </p> 365 * 366 * <a name="SizePaddingMargins"></a> 367 * <h3>Size, padding and margins</h3> 368 * <p> 369 * The size of a view is expressed with a width and a height. A view actually 370 * possess two pairs of width and height values. 371 * </p> 372 * 373 * <p> 374 * The first pair is known as <em>measured width</em> and 375 * <em>measured height</em>. These dimensions define how big a view wants to be 376 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 377 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 378 * and {@link #getMeasuredHeight()}. 379 * </p> 380 * 381 * <p> 382 * The second pair is simply known as <em>width</em> and <em>height</em>, or 383 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 384 * dimensions define the actual size of the view on screen, at drawing time and 385 * after layout. These values may, but do not have to, be different from the 386 * measured width and height. The width and height can be obtained by calling 387 * {@link #getWidth()} and {@link #getHeight()}. 388 * </p> 389 * 390 * <p> 391 * To measure its dimensions, a view takes into account its padding. The padding 392 * is expressed in pixels for the left, top, right and bottom parts of the view. 393 * Padding can be used to offset the content of the view by a specific amount of 394 * pixels. For instance, a left padding of 2 will push the view's content by 395 * 2 pixels to the right of the left edge. Padding can be set using the 396 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 397 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 398 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 399 * {@link #getPaddingEnd()}. 400 * </p> 401 * 402 * <p> 403 * Even though a view can define a padding, it does not provide any support for 404 * margins. However, view groups provide such a support. Refer to 405 * {@link android.view.ViewGroup} and 406 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 407 * </p> 408 * 409 * <a name="Layout"></a> 410 * <h3>Layout</h3> 411 * <p> 412 * Layout is a two pass process: a measure pass and a layout pass. The measuring 413 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 414 * of the view tree. Each view pushes dimension specifications down the tree 415 * during the recursion. At the end of the measure pass, every view has stored 416 * its measurements. The second pass happens in 417 * {@link #layout(int,int,int,int)} and is also top-down. During 418 * this pass each parent is responsible for positioning all of its children 419 * using the sizes computed in the measure pass. 420 * </p> 421 * 422 * <p> 423 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 424 * {@link #getMeasuredHeight()} values must be set, along with those for all of 425 * that view's descendants. A view's measured width and measured height values 426 * must respect the constraints imposed by the view's parents. This guarantees 427 * that at the end of the measure pass, all parents accept all of their 428 * children's measurements. A parent view may call measure() more than once on 429 * its children. For example, the parent may measure each child once with 430 * unspecified dimensions to find out how big they want to be, then call 431 * measure() on them again with actual numbers if the sum of all the children's 432 * unconstrained sizes is too big or too small. 433 * </p> 434 * 435 * <p> 436 * The measure pass uses two classes to communicate dimensions. The 437 * {@link MeasureSpec} class is used by views to tell their parents how they 438 * want to be measured and positioned. The base LayoutParams class just 439 * describes how big the view wants to be for both width and height. For each 440 * dimension, it can specify one of: 441 * <ul> 442 * <li> an exact number 443 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 444 * (minus padding) 445 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 446 * enclose its content (plus padding). 447 * </ul> 448 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 449 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 450 * an X and Y value. 451 * </p> 452 * 453 * <p> 454 * MeasureSpecs are used to push requirements down the tree from parent to 455 * child. A MeasureSpec can be in one of three modes: 456 * <ul> 457 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 458 * of a child view. For example, a LinearLayout may call measure() on its child 459 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 460 * tall the child view wants to be given a width of 240 pixels. 461 * <li>EXACTLY: This is used by the parent to impose an exact size on the 462 * child. The child must use this size, and guarantee that all of its 463 * descendants will fit within this size. 464 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 465 * child. The child must guarantee that it and all of its descendants will fit 466 * within this size. 467 * </ul> 468 * </p> 469 * 470 * <p> 471 * To initiate a layout, call {@link #requestLayout}. This method is typically 472 * called by a view on itself when it believes that is can no longer fit within 473 * its current bounds. 474 * </p> 475 * 476 * <a name="Drawing"></a> 477 * <h3>Drawing</h3> 478 * <p> 479 * Drawing is handled by walking the tree and recording the drawing commands of 480 * any View that needs to update. After this, the drawing commands of the 481 * entire tree are issued to screen, clipped to the newly damaged area. 482 * </p> 483 * 484 * <p> 485 * The tree is largely recorded and drawn in order, with parents drawn before 486 * (i.e., behind) their children, with siblings drawn in the order they appear 487 * in the tree. If you set a background drawable for a View, then the View will 488 * draw it before calling back to its <code>onDraw()</code> method. The child 489 * drawing order can be overridden with 490 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 491 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 492 * </p> 493 * 494 * <p> 495 * To force a view to draw, call {@link #invalidate()}. 496 * </p> 497 * 498 * <a name="EventHandlingThreading"></a> 499 * <h3>Event Handling and Threading</h3> 500 * <p> 501 * The basic cycle of a view is as follows: 502 * <ol> 503 * <li>An event comes in and is dispatched to the appropriate view. The view 504 * handles the event and notifies any listeners.</li> 505 * <li>If in the course of processing the event, the view's bounds may need 506 * to be changed, the view will call {@link #requestLayout()}.</li> 507 * <li>Similarly, if in the course of processing the event the view's appearance 508 * may need to be changed, the view will call {@link #invalidate()}.</li> 509 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 510 * the framework will take care of measuring, laying out, and drawing the tree 511 * as appropriate.</li> 512 * </ol> 513 * </p> 514 * 515 * <p><em>Note: The entire view tree is single threaded. You must always be on 516 * the UI thread when calling any method on any view.</em> 517 * If you are doing work on other threads and want to update the state of a view 518 * from that thread, you should use a {@link Handler}. 519 * </p> 520 * 521 * <a name="FocusHandling"></a> 522 * <h3>Focus Handling</h3> 523 * <p> 524 * The framework will handle routine focus movement in response to user input. 525 * This includes changing the focus as views are removed or hidden, or as new 526 * views become available. Views indicate their willingness to take focus 527 * through the {@link #isFocusable} method. To change whether a view can take 528 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 529 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 530 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 531 * </p> 532 * <p> 533 * Focus movement is based on an algorithm which finds the nearest neighbor in a 534 * given direction. In rare cases, the default algorithm may not match the 535 * intended behavior of the developer. In these situations, you can provide 536 * explicit overrides by using these XML attributes in the layout file: 537 * <pre> 538 * nextFocusDown 539 * nextFocusLeft 540 * nextFocusRight 541 * nextFocusUp 542 * </pre> 543 * </p> 544 * 545 * 546 * <p> 547 * To get a particular view to take focus, call {@link #requestFocus()}. 548 * </p> 549 * 550 * <a name="TouchMode"></a> 551 * <h3>Touch Mode</h3> 552 * <p> 553 * When a user is navigating a user interface via directional keys such as a D-pad, it is 554 * necessary to give focus to actionable items such as buttons so the user can see 555 * what will take input. If the device has touch capabilities, however, and the user 556 * begins interacting with the interface by touching it, it is no longer necessary to 557 * always highlight, or give focus to, a particular view. This motivates a mode 558 * for interaction named 'touch mode'. 559 * </p> 560 * <p> 561 * For a touch capable device, once the user touches the screen, the device 562 * will enter touch mode. From this point onward, only views for which 563 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 564 * Other views that are touchable, like buttons, will not take focus when touched; they will 565 * only fire the on click listeners. 566 * </p> 567 * <p> 568 * Any time a user hits a directional key, such as a D-pad direction, the view device will 569 * exit touch mode, and find a view to take focus, so that the user may resume interacting 570 * with the user interface without touching the screen again. 571 * </p> 572 * <p> 573 * The touch mode state is maintained across {@link android.app.Activity}s. Call 574 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 575 * </p> 576 * 577 * <a name="Scrolling"></a> 578 * <h3>Scrolling</h3> 579 * <p> 580 * The framework provides basic support for views that wish to internally 581 * scroll their content. This includes keeping track of the X and Y scroll 582 * offset as well as mechanisms for drawing scrollbars. See 583 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 584 * {@link #awakenScrollBars()} for more details. 585 * </p> 586 * 587 * <a name="Tags"></a> 588 * <h3>Tags</h3> 589 * <p> 590 * Unlike IDs, tags are not used to identify views. Tags are essentially an 591 * extra piece of information that can be associated with a view. They are most 592 * often used as a convenience to store data related to views in the views 593 * themselves rather than by putting them in a separate structure. 594 * </p> 595 * <p> 596 * Tags may be specified with character sequence values in layout XML as either 597 * a single tag using the {@link android.R.styleable#View_tag android:tag} 598 * attribute or multiple tags using the {@code <tag>} child element: 599 * <pre> 600 * <View ... 601 * android:tag="@string/mytag_value" /> 602 * <View ...> 603 * <tag android:id="@+id/mytag" 604 * android:value="@string/mytag_value" /> 605 * </View> 606 * </pre> 607 * </p> 608 * <p> 609 * Tags may also be specified with arbitrary objects from code using 610 * {@link #setTag(Object)} or {@link #setTag(int, Object)}. 611 * </p> 612 * 613 * <a name="Themes"></a> 614 * <h3>Themes</h3> 615 * <p> 616 * By default, Views are created using the theme of the Context object supplied 617 * to their constructor; however, a different theme may be specified by using 618 * the {@link android.R.styleable#View_theme android:theme} attribute in layout 619 * XML or by passing a {@link ContextThemeWrapper} to the constructor from 620 * code. 621 * </p> 622 * <p> 623 * When the {@link android.R.styleable#View_theme android:theme} attribute is 624 * used in XML, the specified theme is applied on top of the inflation 625 * context's theme (see {@link LayoutInflater}) and used for the view itself as 626 * well as any child elements. 627 * </p> 628 * <p> 629 * In the following example, both views will be created using the Material dark 630 * color scheme; however, because an overlay theme is used which only defines a 631 * subset of attributes, the value of 632 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on 633 * the inflation context's theme (e.g. the Activity theme) will be preserved. 634 * <pre> 635 * <LinearLayout 636 * ... 637 * android:theme="@android:theme/ThemeOverlay.Material.Dark"> 638 * <View ...> 639 * </LinearLayout> 640 * </pre> 641 * </p> 642 * 643 * <a name="Properties"></a> 644 * <h3>Properties</h3> 645 * <p> 646 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 647 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 648 * available both in the {@link Property} form as well as in similarly-named setter/getter 649 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 650 * be used to set persistent state associated with these rendering-related properties on the view. 651 * The properties and methods can also be used in conjunction with 652 * {@link android.animation.Animator Animator}-based animations, described more in the 653 * <a href="#Animation">Animation</a> section. 654 * </p> 655 * 656 * <a name="Animation"></a> 657 * <h3>Animation</h3> 658 * <p> 659 * Starting with Android 3.0, the preferred way of animating views is to use the 660 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 661 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 662 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 663 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 664 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 665 * makes animating these View properties particularly easy and efficient. 666 * </p> 667 * <p> 668 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 669 * You can attach an {@link Animation} object to a view using 670 * {@link #setAnimation(Animation)} or 671 * {@link #startAnimation(Animation)}. The animation can alter the scale, 672 * rotation, translation and alpha of a view over time. If the animation is 673 * attached to a view that has children, the animation will affect the entire 674 * subtree rooted by that node. When an animation is started, the framework will 675 * take care of redrawing the appropriate views until the animation completes. 676 * </p> 677 * 678 * <a name="Security"></a> 679 * <h3>Security</h3> 680 * <p> 681 * Sometimes it is essential that an application be able to verify that an action 682 * is being performed with the full knowledge and consent of the user, such as 683 * granting a permission request, making a purchase or clicking on an advertisement. 684 * Unfortunately, a malicious application could try to spoof the user into 685 * performing these actions, unaware, by concealing the intended purpose of the view. 686 * As a remedy, the framework offers a touch filtering mechanism that can be used to 687 * improve the security of views that provide access to sensitive functionality. 688 * </p><p> 689 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 690 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 691 * will discard touches that are received whenever the view's window is obscured by 692 * another visible window. As a result, the view will not receive touches whenever a 693 * toast, dialog or other window appears above the view's window. 694 * </p><p> 695 * For more fine-grained control over security, consider overriding the 696 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 697 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 698 * </p> 699 * 700 * @attr ref android.R.styleable#View_accessibilityHeading 701 * @attr ref android.R.styleable#View_alpha 702 * @attr ref android.R.styleable#View_background 703 * @attr ref android.R.styleable#View_clickable 704 * @attr ref android.R.styleable#View_contentDescription 705 * @attr ref android.R.styleable#View_drawingCacheQuality 706 * @attr ref android.R.styleable#View_duplicateParentState 707 * @attr ref android.R.styleable#View_id 708 * @attr ref android.R.styleable#View_requiresFadingEdge 709 * @attr ref android.R.styleable#View_fadeScrollbars 710 * @attr ref android.R.styleable#View_fadingEdgeLength 711 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 712 * @attr ref android.R.styleable#View_fitsSystemWindows 713 * @attr ref android.R.styleable#View_isScrollContainer 714 * @attr ref android.R.styleable#View_focusable 715 * @attr ref android.R.styleable#View_focusableInTouchMode 716 * @attr ref android.R.styleable#View_focusedByDefault 717 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 718 * @attr ref android.R.styleable#View_keepScreenOn 719 * @attr ref android.R.styleable#View_keyboardNavigationCluster 720 * @attr ref android.R.styleable#View_layerType 721 * @attr ref android.R.styleable#View_layoutDirection 722 * @attr ref android.R.styleable#View_longClickable 723 * @attr ref android.R.styleable#View_minHeight 724 * @attr ref android.R.styleable#View_minWidth 725 * @attr ref android.R.styleable#View_nextClusterForward 726 * @attr ref android.R.styleable#View_nextFocusDown 727 * @attr ref android.R.styleable#View_nextFocusLeft 728 * @attr ref android.R.styleable#View_nextFocusRight 729 * @attr ref android.R.styleable#View_nextFocusUp 730 * @attr ref android.R.styleable#View_onClick 731 * @attr ref android.R.styleable#View_outlineSpotShadowColor 732 * @attr ref android.R.styleable#View_outlineAmbientShadowColor 733 * @attr ref android.R.styleable#View_padding 734 * @attr ref android.R.styleable#View_paddingHorizontal 735 * @attr ref android.R.styleable#View_paddingVertical 736 * @attr ref android.R.styleable#View_paddingBottom 737 * @attr ref android.R.styleable#View_paddingLeft 738 * @attr ref android.R.styleable#View_paddingRight 739 * @attr ref android.R.styleable#View_paddingTop 740 * @attr ref android.R.styleable#View_paddingStart 741 * @attr ref android.R.styleable#View_paddingEnd 742 * @attr ref android.R.styleable#View_saveEnabled 743 * @attr ref android.R.styleable#View_rotation 744 * @attr ref android.R.styleable#View_rotationX 745 * @attr ref android.R.styleable#View_rotationY 746 * @attr ref android.R.styleable#View_scaleX 747 * @attr ref android.R.styleable#View_scaleY 748 * @attr ref android.R.styleable#View_scrollX 749 * @attr ref android.R.styleable#View_scrollY 750 * @attr ref android.R.styleable#View_scrollbarSize 751 * @attr ref android.R.styleable#View_scrollbarStyle 752 * @attr ref android.R.styleable#View_scrollbars 753 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 754 * @attr ref android.R.styleable#View_scrollbarFadeDuration 755 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 756 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 757 * @attr ref android.R.styleable#View_scrollbarThumbVertical 758 * @attr ref android.R.styleable#View_scrollbarTrackVertical 759 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 760 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 761 * @attr ref android.R.styleable#View_stateListAnimator 762 * @attr ref android.R.styleable#View_transitionName 763 * @attr ref android.R.styleable#View_soundEffectsEnabled 764 * @attr ref android.R.styleable#View_tag 765 * @attr ref android.R.styleable#View_textAlignment 766 * @attr ref android.R.styleable#View_textDirection 767 * @attr ref android.R.styleable#View_transformPivotX 768 * @attr ref android.R.styleable#View_transformPivotY 769 * @attr ref android.R.styleable#View_translationX 770 * @attr ref android.R.styleable#View_translationY 771 * @attr ref android.R.styleable#View_translationZ 772 * @attr ref android.R.styleable#View_visibility 773 * @attr ref android.R.styleable#View_theme 774 * 775 * @see android.view.ViewGroup 776 */ 777@UiThread 778public class View implements Drawable.Callback, KeyEvent.Callback, 779 AccessibilityEventSource { 780 private static final boolean DBG = false; 781 782 /** @hide */ 783 public static boolean DEBUG_DRAW = false; 784 785 /** 786 * The logging tag used by this class with android.util.Log. 787 */ 788 protected static final String VIEW_LOG_TAG = "View"; 789 790 /** 791 * When set to true, apps will draw debugging information about their layouts. 792 * 793 * @hide 794 */ 795 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 796 797 /** 798 * When set to true, this view will save its attribute data. 799 * 800 * @hide 801 */ 802 public static boolean mDebugViewAttributes = false; 803 804 /** 805 * Used to mark a View that has no ID. 806 */ 807 public static final int NO_ID = -1; 808 809 /** 810 * Last ID that is given to Views that are no part of activities. 811 * 812 * {@hide} 813 */ 814 public static final int LAST_APP_AUTOFILL_ID = Integer.MAX_VALUE / 2; 815 816 /** 817 * Attribute to find the autofilled highlight 818 * 819 * @see #getAutofilledDrawable() 820 */ 821 private static final int[] AUTOFILL_HIGHLIGHT_ATTR = 822 new int[]{android.R.attr.autofilledHighlight}; 823 824 /** 825 * Signals that compatibility booleans have been initialized according to 826 * target SDK versions. 827 */ 828 private static boolean sCompatibilityDone = false; 829 830 /** 831 * Use the old (broken) way of building MeasureSpecs. 832 */ 833 private static boolean sUseBrokenMakeMeasureSpec = false; 834 835 /** 836 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 837 */ 838 static boolean sUseZeroUnspecifiedMeasureSpec = false; 839 840 /** 841 * Ignore any optimizations using the measure cache. 842 */ 843 private static boolean sIgnoreMeasureCache = false; 844 845 /** 846 * Ignore an optimization that skips unnecessary EXACTLY layout passes. 847 */ 848 private static boolean sAlwaysRemeasureExactly = false; 849 850 /** 851 * Relax constraints around whether setLayoutParams() must be called after 852 * modifying the layout params. 853 */ 854 private static boolean sLayoutParamsAlwaysChanged = false; 855 856 /** 857 * Allow setForeground/setBackground to be called (and ignored) on a textureview, 858 * without throwing 859 */ 860 static boolean sTextureViewIgnoresDrawableSetters = false; 861 862 /** 863 * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend 864 * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to 865 * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API 866 * check is implemented for backwards compatibility. 867 * 868 * {@hide} 869 */ 870 protected static boolean sPreserveMarginParamsInLayoutParamConversion; 871 872 /** 873 * Prior to N, when drag enters into child of a view that has already received an 874 * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event. 875 * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned 876 * false from its event handler for these events. 877 * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its 878 * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent. 879 * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation. 880 */ 881 static boolean sCascadedDragDrop; 882 883 /** 884 * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable 885 * to determine things like whether or not to permit item click events. We can't break 886 * apps that do this just because more things (clickable things) are now auto-focusable 887 * and they would get different results, so give old behavior to old apps. 888 */ 889 static boolean sHasFocusableExcludeAutoFocusable; 890 891 /** 892 * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly 893 * made focusable by default. As a result, apps could (incorrectly) change the clickable 894 * setting of views off the UI thread. Now that clickable can effect the focusable state, 895 * changing the clickable attribute off the UI thread will cause an exception (since changing 896 * the focusable state checks). In order to prevent apps from crashing, we will handle this 897 * specific case and just not notify parents on new focusables resulting from marking views 898 * clickable from outside the UI thread. 899 */ 900 private static boolean sAutoFocusableOffUIThreadWontNotifyParents; 901 902 /** 903 * Prior to P things like setScaleX() allowed passing float values that were bogus such as 904 * Float.NaN. If the app is targetting P or later then passing these values will result in an 905 * exception being thrown. If the app is targetting an earlier SDK version, then we will 906 * silently clamp these values to avoid crashes elsewhere when the rendering code hits 907 * these bogus values. 908 */ 909 private static boolean sThrowOnInvalidFloatProperties; 910 911 /** 912 * Prior to P, {@code #startDragAndDrop} accepts a builder which produces an empty drag shadow. 913 * Currently zero size SurfaceControl cannot be created thus we create a dummy 1x1 surface 914 * instead. 915 */ 916 private static boolean sAcceptZeroSizeDragShadow; 917 918 /** @hide */ 919 @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO}) 920 @Retention(RetentionPolicy.SOURCE) 921 public @interface Focusable {} 922 923 /** 924 * This view does not want keystrokes. 925 * <p> 926 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code 927 * android:focusable}. 928 */ 929 public static final int NOT_FOCUSABLE = 0x00000000; 930 931 /** 932 * This view wants keystrokes. 933 * <p> 934 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code 935 * android:focusable}. 936 */ 937 public static final int FOCUSABLE = 0x00000001; 938 939 /** 940 * This view determines focusability automatically. This is the default. 941 * <p> 942 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code 943 * android:focusable}. 944 */ 945 public static final int FOCUSABLE_AUTO = 0x00000010; 946 947 /** 948 * Mask for use with setFlags indicating bits used for focus. 949 */ 950 private static final int FOCUSABLE_MASK = 0x00000011; 951 952 /** 953 * This view will adjust its padding to fit sytem windows (e.g. status bar) 954 */ 955 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 956 957 /** @hide */ 958 @IntDef({VISIBLE, INVISIBLE, GONE}) 959 @Retention(RetentionPolicy.SOURCE) 960 public @interface Visibility {} 961 962 /** 963 * This view is visible. 964 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 965 * android:visibility}. 966 */ 967 public static final int VISIBLE = 0x00000000; 968 969 /** 970 * This view is invisible, but it still takes up space for layout purposes. 971 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 972 * android:visibility}. 973 */ 974 public static final int INVISIBLE = 0x00000004; 975 976 /** 977 * This view is invisible, and it doesn't take any space for layout 978 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 979 * android:visibility}. 980 */ 981 public static final int GONE = 0x00000008; 982 983 /** 984 * Mask for use with setFlags indicating bits used for visibility. 985 * {@hide} 986 */ 987 static final int VISIBILITY_MASK = 0x0000000C; 988 989 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 990 991 /** 992 * Hint indicating that this view can be autofilled with an email address. 993 * 994 * <p>Can be used with either {@link #setAutofillHints(String[])} or 995 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 996 * value should be <code>{@value #AUTOFILL_HINT_EMAIL_ADDRESS}</code>). 997 * 998 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 999 */ 1000 public static final String AUTOFILL_HINT_EMAIL_ADDRESS = "emailAddress"; 1001 1002 /** 1003 * Hint indicating that this view can be autofilled with a user's real name. 1004 * 1005 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1006 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1007 * value should be <code>{@value #AUTOFILL_HINT_NAME}</code>). 1008 * 1009 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1010 */ 1011 public static final String AUTOFILL_HINT_NAME = "name"; 1012 1013 /** 1014 * Hint indicating that this view can be autofilled with a username. 1015 * 1016 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1017 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1018 * value should be <code>{@value #AUTOFILL_HINT_USERNAME}</code>). 1019 * 1020 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1021 */ 1022 public static final String AUTOFILL_HINT_USERNAME = "username"; 1023 1024 /** 1025 * Hint indicating that this view can be autofilled with a password. 1026 * 1027 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1028 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1029 * value should be <code>{@value #AUTOFILL_HINT_PASSWORD}</code>). 1030 * 1031 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1032 */ 1033 public static final String AUTOFILL_HINT_PASSWORD = "password"; 1034 1035 /** 1036 * Hint indicating that this view can be autofilled with a phone number. 1037 * 1038 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1039 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1040 * value should be <code>{@value #AUTOFILL_HINT_PHONE}</code>). 1041 * 1042 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1043 */ 1044 public static final String AUTOFILL_HINT_PHONE = "phone"; 1045 1046 /** 1047 * Hint indicating that this view can be autofilled with a postal address. 1048 * 1049 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1050 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1051 * value should be <code>{@value #AUTOFILL_HINT_POSTAL_ADDRESS}</code>). 1052 * 1053 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1054 */ 1055 public static final String AUTOFILL_HINT_POSTAL_ADDRESS = "postalAddress"; 1056 1057 /** 1058 * Hint indicating that this view can be autofilled with a postal code. 1059 * 1060 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1061 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1062 * value should be <code>{@value #AUTOFILL_HINT_POSTAL_CODE}</code>). 1063 * 1064 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1065 */ 1066 public static final String AUTOFILL_HINT_POSTAL_CODE = "postalCode"; 1067 1068 /** 1069 * Hint indicating that this view can be autofilled with a credit card number. 1070 * 1071 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1072 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1073 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_NUMBER}</code>). 1074 * 1075 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1076 */ 1077 public static final String AUTOFILL_HINT_CREDIT_CARD_NUMBER = "creditCardNumber"; 1078 1079 /** 1080 * Hint indicating that this view can be autofilled with a credit card security code. 1081 * 1082 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1083 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1084 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}</code>). 1085 * 1086 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1087 */ 1088 public static final String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode"; 1089 1090 /** 1091 * Hint indicating that this view can be autofilled with a credit card expiration date. 1092 * 1093 * <p>It should be used when the credit card expiration date is represented by just one view; 1094 * if it is represented by more than one (for example, one view for the month and another view 1095 * for the year), then each of these views should use the hint specific for the unit 1096 * ({@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}, 1097 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}, 1098 * or {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}). 1099 * 1100 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1101 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1102 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}</code>). 1103 * 1104 * <p>When annotating a view with this hint, it's recommended to use a date autofill value to 1105 * avoid ambiguity when the autofill service provides a value for it. To understand why a 1106 * value can be ambiguous, consider "April of 2020", which could be represented as either of 1107 * the following options: 1108 * 1109 * <ul> 1110 * <li>{@code "04/2020"} 1111 * <li>{@code "4/2020"} 1112 * <li>{@code "2020/04"} 1113 * <li>{@code "2020/4"} 1114 * <li>{@code "April/2020"} 1115 * <li>{@code "Apr/2020"} 1116 * </ul> 1117 * 1118 * <p>You define a date autofill value for the view by overriding the following methods: 1119 * 1120 * <ol> 1121 * <li>{@link #getAutofillType()} to return {@link #AUTOFILL_TYPE_DATE}. 1122 * <li>{@link #getAutofillValue()} to return a 1123 * {@link AutofillValue#forDate(long) date autofillvalue}. 1124 * <li>{@link #autofill(AutofillValue)} to expect a data autofillvalue. 1125 * </ol> 1126 * 1127 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1128 */ 1129 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE = 1130 "creditCardExpirationDate"; 1131 1132 /** 1133 * Hint indicating that this view can be autofilled with a credit card expiration month. 1134 * 1135 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1136 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1137 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}</code>). 1138 * 1139 * <p>When annotating a view with this hint, it's recommended to use a text autofill value 1140 * whose value is the numerical representation of the month, starting on {@code 1} to avoid 1141 * ambiguity when the autofill service provides a value for it. To understand why a 1142 * value can be ambiguous, consider "January", which could be represented as either of 1143 * 1144 * <ul> 1145 * <li>{@code "1"}: recommended way. 1146 * <li>{@code "0"}: if following the {@link Calendar#MONTH} convention. 1147 * <li>{@code "January"}: full name, in English. 1148 * <li>{@code "jan"}: abbreviated name, in English. 1149 * <li>{@code "Janeiro"}: full name, in another language. 1150 * </ul> 1151 * 1152 * <p>Another recommended approach is to use a date autofill value - see 1153 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE} for more details. 1154 * 1155 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1156 */ 1157 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH = 1158 "creditCardExpirationMonth"; 1159 1160 /** 1161 * Hint indicating that this view can be autofilled with a credit card expiration year. 1162 * 1163 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1164 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1165 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}</code>). 1166 * 1167 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1168 */ 1169 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR = 1170 "creditCardExpirationYear"; 1171 1172 /** 1173 * Hint indicating that this view can be autofilled with a credit card expiration day. 1174 * 1175 * <p>Can be used with either {@link #setAutofillHints(String[])} or 1176 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the 1177 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}</code>). 1178 * 1179 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints. 1180 */ 1181 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay"; 1182 1183 /** 1184 * Hints for the autofill services that describes the content of the view. 1185 */ 1186 private @Nullable String[] mAutofillHints; 1187 1188 /** 1189 * Autofill id, lazily created on calls to {@link #getAutofillId()}. 1190 */ 1191 private AutofillId mAutofillId; 1192 1193 /** @hide */ 1194 @IntDef(prefix = { "AUTOFILL_TYPE_" }, value = { 1195 AUTOFILL_TYPE_NONE, 1196 AUTOFILL_TYPE_TEXT, 1197 AUTOFILL_TYPE_TOGGLE, 1198 AUTOFILL_TYPE_LIST, 1199 AUTOFILL_TYPE_DATE 1200 }) 1201 @Retention(RetentionPolicy.SOURCE) 1202 public @interface AutofillType {} 1203 1204 /** 1205 * Autofill type for views that cannot be autofilled. 1206 * 1207 * <p>Typically used when the view is read-only; for example, a text label. 1208 * 1209 * @see #getAutofillType() 1210 */ 1211 public static final int AUTOFILL_TYPE_NONE = 0; 1212 1213 /** 1214 * Autofill type for a text field, which is filled by a {@link CharSequence}. 1215 * 1216 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1217 * {@link AutofillValue#forText(CharSequence)}, and the value passed to autofill a 1218 * {@link View} can be fetched through {@link AutofillValue#getTextValue()}. 1219 * 1220 * @see #getAutofillType() 1221 */ 1222 public static final int AUTOFILL_TYPE_TEXT = 1; 1223 1224 /** 1225 * Autofill type for a togglable field, which is filled by a {@code boolean}. 1226 * 1227 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1228 * {@link AutofillValue#forToggle(boolean)}, and the value passed to autofill a 1229 * {@link View} can be fetched through {@link AutofillValue#getToggleValue()}. 1230 * 1231 * @see #getAutofillType() 1232 */ 1233 public static final int AUTOFILL_TYPE_TOGGLE = 2; 1234 1235 /** 1236 * Autofill type for a selection list field, which is filled by an {@code int} 1237 * representing the element index inside the list (starting at {@code 0}). 1238 * 1239 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1240 * {@link AutofillValue#forList(int)}, and the value passed to autofill a 1241 * {@link View} can be fetched through {@link AutofillValue#getListValue()}. 1242 * 1243 * <p>The available options in the selection list are typically provided by 1244 * {@link android.app.assist.AssistStructure.ViewNode#getAutofillOptions()}. 1245 * 1246 * @see #getAutofillType() 1247 */ 1248 public static final int AUTOFILL_TYPE_LIST = 3; 1249 1250 1251 /** 1252 * Autofill type for a field that contains a date, which is represented by a long representing 1253 * the number of milliseconds since the standard base time known as "the epoch", namely 1254 * January 1, 1970, 00:00:00 GMT (see {@link java.util.Date#getTime()}. 1255 * 1256 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1257 * {@link AutofillValue#forDate(long)}, and the values passed to 1258 * autofill a {@link View} can be fetched through {@link AutofillValue#getDateValue()}. 1259 * 1260 * @see #getAutofillType() 1261 */ 1262 public static final int AUTOFILL_TYPE_DATE = 4; 1263 1264 /** @hide */ 1265 @IntDef(prefix = { "IMPORTANT_FOR_AUTOFILL_" }, value = { 1266 IMPORTANT_FOR_AUTOFILL_AUTO, 1267 IMPORTANT_FOR_AUTOFILL_YES, 1268 IMPORTANT_FOR_AUTOFILL_NO, 1269 IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS, 1270 IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS 1271 }) 1272 @Retention(RetentionPolicy.SOURCE) 1273 public @interface AutofillImportance {} 1274 1275 /** 1276 * Automatically determine whether a view is important for autofill. 1277 * 1278 * @see #isImportantForAutofill() 1279 * @see #setImportantForAutofill(int) 1280 */ 1281 public static final int IMPORTANT_FOR_AUTOFILL_AUTO = 0x0; 1282 1283 /** 1284 * The view is important for autofill, and its children (if any) will be traversed. 1285 * 1286 * @see #isImportantForAutofill() 1287 * @see #setImportantForAutofill(int) 1288 */ 1289 public static final int IMPORTANT_FOR_AUTOFILL_YES = 0x1; 1290 1291 /** 1292 * The view is not important for autofill, but its children (if any) will be traversed. 1293 * 1294 * @see #isImportantForAutofill() 1295 * @see #setImportantForAutofill(int) 1296 */ 1297 public static final int IMPORTANT_FOR_AUTOFILL_NO = 0x2; 1298 1299 /** 1300 * The view is important for autofill, but its children (if any) will not be traversed. 1301 * 1302 * @see #isImportantForAutofill() 1303 * @see #setImportantForAutofill(int) 1304 */ 1305 public static final int IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS = 0x4; 1306 1307 /** 1308 * The view is not important for autofill, and its children (if any) will not be traversed. 1309 * 1310 * @see #isImportantForAutofill() 1311 * @see #setImportantForAutofill(int) 1312 */ 1313 public static final int IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS = 0x8; 1314 1315 /** @hide */ 1316 @IntDef(flag = true, prefix = { "AUTOFILL_FLAG_" }, value = { 1317 AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 1318 }) 1319 @Retention(RetentionPolicy.SOURCE) 1320 public @interface AutofillFlags {} 1321 1322 /** 1323 * Flag requesting you to add views that are marked as not important for autofill 1324 * (see {@link #setImportantForAutofill(int)}) to a {@link ViewStructure}. 1325 */ 1326 public static final int AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS = 0x1; 1327 1328 /** 1329 * This view is enabled. Interpretation varies by subclass. 1330 * Use with ENABLED_MASK when calling setFlags. 1331 * {@hide} 1332 */ 1333 static final int ENABLED = 0x00000000; 1334 1335 /** 1336 * This view is disabled. Interpretation varies by subclass. 1337 * Use with ENABLED_MASK when calling setFlags. 1338 * {@hide} 1339 */ 1340 static final int DISABLED = 0x00000020; 1341 1342 /** 1343 * Mask for use with setFlags indicating bits used for indicating whether 1344 * this view is enabled 1345 * {@hide} 1346 */ 1347 static final int ENABLED_MASK = 0x00000020; 1348 1349 /** 1350 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 1351 * called and further optimizations will be performed. It is okay to have 1352 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 1353 * {@hide} 1354 */ 1355 static final int WILL_NOT_DRAW = 0x00000080; 1356 1357 /** 1358 * Mask for use with setFlags indicating bits used for indicating whether 1359 * this view is will draw 1360 * {@hide} 1361 */ 1362 static final int DRAW_MASK = 0x00000080; 1363 1364 /** 1365 * <p>This view doesn't show scrollbars.</p> 1366 * {@hide} 1367 */ 1368 static final int SCROLLBARS_NONE = 0x00000000; 1369 1370 /** 1371 * <p>This view shows horizontal scrollbars.</p> 1372 * {@hide} 1373 */ 1374 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 1375 1376 /** 1377 * <p>This view shows vertical scrollbars.</p> 1378 * {@hide} 1379 */ 1380 static final int SCROLLBARS_VERTICAL = 0x00000200; 1381 1382 /** 1383 * <p>Mask for use with setFlags indicating bits used for indicating which 1384 * scrollbars are enabled.</p> 1385 * {@hide} 1386 */ 1387 static final int SCROLLBARS_MASK = 0x00000300; 1388 1389 /** 1390 * Indicates that the view should filter touches when its window is obscured. 1391 * Refer to the class comments for more information about this security feature. 1392 * {@hide} 1393 */ 1394 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 1395 1396 /** 1397 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 1398 * that they are optional and should be skipped if the window has 1399 * requested system UI flags that ignore those insets for layout. 1400 */ 1401 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 1402 1403 /** 1404 * <p>This view doesn't show fading edges.</p> 1405 * {@hide} 1406 */ 1407 static final int FADING_EDGE_NONE = 0x00000000; 1408 1409 /** 1410 * <p>This view shows horizontal fading edges.</p> 1411 * {@hide} 1412 */ 1413 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 1414 1415 /** 1416 * <p>This view shows vertical fading edges.</p> 1417 * {@hide} 1418 */ 1419 static final int FADING_EDGE_VERTICAL = 0x00002000; 1420 1421 /** 1422 * <p>Mask for use with setFlags indicating bits used for indicating which 1423 * fading edges are enabled.</p> 1424 * {@hide} 1425 */ 1426 static final int FADING_EDGE_MASK = 0x00003000; 1427 1428 /** 1429 * <p>Indicates this view can be clicked. When clickable, a View reacts 1430 * to clicks by notifying the OnClickListener.<p> 1431 * {@hide} 1432 */ 1433 static final int CLICKABLE = 0x00004000; 1434 1435 /** 1436 * <p>Indicates this view is caching its drawing into a bitmap.</p> 1437 * {@hide} 1438 */ 1439 static final int DRAWING_CACHE_ENABLED = 0x00008000; 1440 1441 /** 1442 * <p>Indicates that no icicle should be saved for this view.<p> 1443 * {@hide} 1444 */ 1445 static final int SAVE_DISABLED = 0x000010000; 1446 1447 /** 1448 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 1449 * property.</p> 1450 * {@hide} 1451 */ 1452 static final int SAVE_DISABLED_MASK = 0x000010000; 1453 1454 /** 1455 * <p>Indicates that no drawing cache should ever be created for this view.<p> 1456 * {@hide} 1457 */ 1458 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 1459 1460 /** 1461 * <p>Indicates this view can take / keep focus when int touch mode.</p> 1462 * {@hide} 1463 */ 1464 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 1465 1466 /** @hide */ 1467 @Retention(RetentionPolicy.SOURCE) 1468 @IntDef(prefix = { "DRAWING_CACHE_QUALITY_" }, value = { 1469 DRAWING_CACHE_QUALITY_LOW, 1470 DRAWING_CACHE_QUALITY_HIGH, 1471 DRAWING_CACHE_QUALITY_AUTO 1472 }) 1473 public @interface DrawingCacheQuality {} 1474 1475 /** 1476 * <p>Enables low quality mode for the drawing cache.</p> 1477 * 1478 * @deprecated The view drawing cache was largely made obsolete with the introduction of 1479 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 1480 * layers are largely unnecessary and can easily result in a net loss in performance due to the 1481 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 1482 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 1483 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 1484 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 1485 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 1486 * software-rendered usages are discouraged and have compatibility issues with hardware-only 1487 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 1488 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 1489 * reports or unit testing the {@link PixelCopy} API is recommended. 1490 */ 1491 @Deprecated 1492 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 1493 1494 /** 1495 * <p>Enables high quality mode for the drawing cache.</p> 1496 * 1497 * @deprecated The view drawing cache was largely made obsolete with the introduction of 1498 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 1499 * layers are largely unnecessary and can easily result in a net loss in performance due to the 1500 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 1501 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 1502 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 1503 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 1504 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 1505 * software-rendered usages are discouraged and have compatibility issues with hardware-only 1506 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 1507 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 1508 * reports or unit testing the {@link PixelCopy} API is recommended. 1509 */ 1510 @Deprecated 1511 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 1512 1513 /** 1514 * <p>Enables automatic quality mode for the drawing cache.</p> 1515 * 1516 * @deprecated The view drawing cache was largely made obsolete with the introduction of 1517 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 1518 * layers are largely unnecessary and can easily result in a net loss in performance due to the 1519 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 1520 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 1521 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 1522 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 1523 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 1524 * software-rendered usages are discouraged and have compatibility issues with hardware-only 1525 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 1526 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 1527 * reports or unit testing the {@link PixelCopy} API is recommended. 1528 */ 1529 @Deprecated 1530 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 1531 1532 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 1533 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 1534 }; 1535 1536 /** 1537 * <p>Mask for use with setFlags indicating bits used for the cache 1538 * quality property.</p> 1539 * {@hide} 1540 */ 1541 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 1542 1543 /** 1544 * <p> 1545 * Indicates this view can be long clicked. When long clickable, a View 1546 * reacts to long clicks by notifying the OnLongClickListener or showing a 1547 * context menu. 1548 * </p> 1549 * {@hide} 1550 */ 1551 static final int LONG_CLICKABLE = 0x00200000; 1552 1553 /** 1554 * <p>Indicates that this view gets its drawable states from its direct parent 1555 * and ignores its original internal states.</p> 1556 * 1557 * @hide 1558 */ 1559 static final int DUPLICATE_PARENT_STATE = 0x00400000; 1560 1561 /** 1562 * <p> 1563 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1564 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1565 * OnContextClickListener. 1566 * </p> 1567 * {@hide} 1568 */ 1569 static final int CONTEXT_CLICKABLE = 0x00800000; 1570 1571 /** @hide */ 1572 @IntDef(prefix = { "SCROLLBARS_" }, value = { 1573 SCROLLBARS_INSIDE_OVERLAY, 1574 SCROLLBARS_INSIDE_INSET, 1575 SCROLLBARS_OUTSIDE_OVERLAY, 1576 SCROLLBARS_OUTSIDE_INSET 1577 }) 1578 @Retention(RetentionPolicy.SOURCE) 1579 public @interface ScrollBarStyle {} 1580 1581 /** 1582 * The scrollbar style to display the scrollbars inside the content area, 1583 * without increasing the padding. The scrollbars will be overlaid with 1584 * translucency on the view's content. 1585 */ 1586 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1587 1588 /** 1589 * The scrollbar style to display the scrollbars inside the padded area, 1590 * increasing the padding of the view. The scrollbars will not overlap the 1591 * content area of the view. 1592 */ 1593 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1594 1595 /** 1596 * The scrollbar style to display the scrollbars at the edge of the view, 1597 * without increasing the padding. The scrollbars will be overlaid with 1598 * translucency. 1599 */ 1600 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1601 1602 /** 1603 * The scrollbar style to display the scrollbars at the edge of the view, 1604 * increasing the padding of the view. The scrollbars will only overlap the 1605 * background, if any. 1606 */ 1607 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1608 1609 /** 1610 * Mask to check if the scrollbar style is overlay or inset. 1611 * {@hide} 1612 */ 1613 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1614 1615 /** 1616 * Mask to check if the scrollbar style is inside or outside. 1617 * {@hide} 1618 */ 1619 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1620 1621 /** 1622 * Mask for scrollbar style. 1623 * {@hide} 1624 */ 1625 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1626 1627 /** 1628 * View flag indicating that the screen should remain on while the 1629 * window containing this view is visible to the user. This effectively 1630 * takes care of automatically setting the WindowManager's 1631 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1632 */ 1633 public static final int KEEP_SCREEN_ON = 0x04000000; 1634 1635 /** 1636 * View flag indicating whether this view should have sound effects enabled 1637 * for events such as clicking and touching. 1638 */ 1639 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1640 1641 /** 1642 * View flag indicating whether this view should have haptic feedback 1643 * enabled for events such as long presses. 1644 */ 1645 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1646 1647 /** 1648 * <p>Indicates that the view hierarchy should stop saving state when 1649 * it reaches this view. If state saving is initiated immediately at 1650 * the view, it will be allowed. 1651 * {@hide} 1652 */ 1653 static final int PARENT_SAVE_DISABLED = 0x20000000; 1654 1655 /** 1656 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1657 * {@hide} 1658 */ 1659 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1660 1661 private static Paint sDebugPaint; 1662 1663 /** 1664 * <p>Indicates this view can display a tooltip on hover or long press.</p> 1665 * {@hide} 1666 */ 1667 static final int TOOLTIP = 0x40000000; 1668 1669 /** @hide */ 1670 @IntDef(flag = true, prefix = { "FOCUSABLES_" }, value = { 1671 FOCUSABLES_ALL, 1672 FOCUSABLES_TOUCH_MODE 1673 }) 1674 @Retention(RetentionPolicy.SOURCE) 1675 public @interface FocusableMode {} 1676 1677 /** 1678 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1679 * should add all focusable Views regardless if they are focusable in touch mode. 1680 */ 1681 public static final int FOCUSABLES_ALL = 0x00000000; 1682 1683 /** 1684 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1685 * should add only Views focusable in touch mode. 1686 */ 1687 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1688 1689 /** @hide */ 1690 @IntDef(prefix = { "FOCUS_" }, value = { 1691 FOCUS_BACKWARD, 1692 FOCUS_FORWARD, 1693 FOCUS_LEFT, 1694 FOCUS_UP, 1695 FOCUS_RIGHT, 1696 FOCUS_DOWN 1697 }) 1698 @Retention(RetentionPolicy.SOURCE) 1699 public @interface FocusDirection {} 1700 1701 /** @hide */ 1702 @IntDef(prefix = { "FOCUS_" }, value = { 1703 FOCUS_LEFT, 1704 FOCUS_UP, 1705 FOCUS_RIGHT, 1706 FOCUS_DOWN 1707 }) 1708 @Retention(RetentionPolicy.SOURCE) 1709 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1710 1711 /** 1712 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1713 * item. 1714 */ 1715 public static final int FOCUS_BACKWARD = 0x00000001; 1716 1717 /** 1718 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1719 * item. 1720 */ 1721 public static final int FOCUS_FORWARD = 0x00000002; 1722 1723 /** 1724 * Use with {@link #focusSearch(int)}. Move focus to the left. 1725 */ 1726 public static final int FOCUS_LEFT = 0x00000011; 1727 1728 /** 1729 * Use with {@link #focusSearch(int)}. Move focus up. 1730 */ 1731 public static final int FOCUS_UP = 0x00000021; 1732 1733 /** 1734 * Use with {@link #focusSearch(int)}. Move focus to the right. 1735 */ 1736 public static final int FOCUS_RIGHT = 0x00000042; 1737 1738 /** 1739 * Use with {@link #focusSearch(int)}. Move focus down. 1740 */ 1741 public static final int FOCUS_DOWN = 0x00000082; 1742 1743 /** 1744 * Bits of {@link #getMeasuredWidthAndState()} and 1745 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1746 */ 1747 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1748 1749 /** 1750 * Bits of {@link #getMeasuredWidthAndState()} and 1751 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1752 */ 1753 public static final int MEASURED_STATE_MASK = 0xff000000; 1754 1755 /** 1756 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1757 * for functions that combine both width and height into a single int, 1758 * such as {@link #getMeasuredState()} and the childState argument of 1759 * {@link #resolveSizeAndState(int, int, int)}. 1760 */ 1761 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1762 1763 /** 1764 * Bit of {@link #getMeasuredWidthAndState()} and 1765 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1766 * is smaller that the space the view would like to have. 1767 */ 1768 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1769 1770 /** 1771 * Base View state sets 1772 */ 1773 // Singles 1774 /** 1775 * Indicates the view has no states set. States are used with 1776 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1777 * view depending on its state. 1778 * 1779 * @see android.graphics.drawable.Drawable 1780 * @see #getDrawableState() 1781 */ 1782 protected static final int[] EMPTY_STATE_SET; 1783 /** 1784 * Indicates the view is enabled. States are used with 1785 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1786 * view depending on its state. 1787 * 1788 * @see android.graphics.drawable.Drawable 1789 * @see #getDrawableState() 1790 */ 1791 protected static final int[] ENABLED_STATE_SET; 1792 /** 1793 * Indicates the view is focused. States are used with 1794 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1795 * view depending on its state. 1796 * 1797 * @see android.graphics.drawable.Drawable 1798 * @see #getDrawableState() 1799 */ 1800 protected static final int[] FOCUSED_STATE_SET; 1801 /** 1802 * Indicates the view is selected. States are used with 1803 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1804 * view depending on its state. 1805 * 1806 * @see android.graphics.drawable.Drawable 1807 * @see #getDrawableState() 1808 */ 1809 protected static final int[] SELECTED_STATE_SET; 1810 /** 1811 * Indicates the view is pressed. States are used with 1812 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1813 * view depending on its state. 1814 * 1815 * @see android.graphics.drawable.Drawable 1816 * @see #getDrawableState() 1817 */ 1818 protected static final int[] PRESSED_STATE_SET; 1819 /** 1820 * Indicates the view's window has focus. States are used with 1821 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1822 * view depending on its state. 1823 * 1824 * @see android.graphics.drawable.Drawable 1825 * @see #getDrawableState() 1826 */ 1827 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1828 // Doubles 1829 /** 1830 * Indicates the view is enabled and has the focus. 1831 * 1832 * @see #ENABLED_STATE_SET 1833 * @see #FOCUSED_STATE_SET 1834 */ 1835 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1836 /** 1837 * Indicates the view is enabled and selected. 1838 * 1839 * @see #ENABLED_STATE_SET 1840 * @see #SELECTED_STATE_SET 1841 */ 1842 protected static final int[] ENABLED_SELECTED_STATE_SET; 1843 /** 1844 * Indicates the view is enabled and that its window has focus. 1845 * 1846 * @see #ENABLED_STATE_SET 1847 * @see #WINDOW_FOCUSED_STATE_SET 1848 */ 1849 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1850 /** 1851 * Indicates the view is focused and selected. 1852 * 1853 * @see #FOCUSED_STATE_SET 1854 * @see #SELECTED_STATE_SET 1855 */ 1856 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1857 /** 1858 * Indicates the view has the focus and that its window has the focus. 1859 * 1860 * @see #FOCUSED_STATE_SET 1861 * @see #WINDOW_FOCUSED_STATE_SET 1862 */ 1863 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1864 /** 1865 * Indicates the view is selected and that its window has the focus. 1866 * 1867 * @see #SELECTED_STATE_SET 1868 * @see #WINDOW_FOCUSED_STATE_SET 1869 */ 1870 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1871 // Triples 1872 /** 1873 * Indicates the view is enabled, focused and selected. 1874 * 1875 * @see #ENABLED_STATE_SET 1876 * @see #FOCUSED_STATE_SET 1877 * @see #SELECTED_STATE_SET 1878 */ 1879 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1880 /** 1881 * Indicates the view is enabled, focused and its window has the focus. 1882 * 1883 * @see #ENABLED_STATE_SET 1884 * @see #FOCUSED_STATE_SET 1885 * @see #WINDOW_FOCUSED_STATE_SET 1886 */ 1887 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1888 /** 1889 * Indicates the view is enabled, selected and its window has the focus. 1890 * 1891 * @see #ENABLED_STATE_SET 1892 * @see #SELECTED_STATE_SET 1893 * @see #WINDOW_FOCUSED_STATE_SET 1894 */ 1895 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1896 /** 1897 * Indicates the view is focused, selected and its window has the focus. 1898 * 1899 * @see #FOCUSED_STATE_SET 1900 * @see #SELECTED_STATE_SET 1901 * @see #WINDOW_FOCUSED_STATE_SET 1902 */ 1903 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1904 /** 1905 * Indicates the view is enabled, focused, selected and its window 1906 * has the focus. 1907 * 1908 * @see #ENABLED_STATE_SET 1909 * @see #FOCUSED_STATE_SET 1910 * @see #SELECTED_STATE_SET 1911 * @see #WINDOW_FOCUSED_STATE_SET 1912 */ 1913 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1914 /** 1915 * Indicates the view is pressed and its window has the focus. 1916 * 1917 * @see #PRESSED_STATE_SET 1918 * @see #WINDOW_FOCUSED_STATE_SET 1919 */ 1920 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1921 /** 1922 * Indicates the view is pressed and selected. 1923 * 1924 * @see #PRESSED_STATE_SET 1925 * @see #SELECTED_STATE_SET 1926 */ 1927 protected static final int[] PRESSED_SELECTED_STATE_SET; 1928 /** 1929 * Indicates the view is pressed, selected and its window has the focus. 1930 * 1931 * @see #PRESSED_STATE_SET 1932 * @see #SELECTED_STATE_SET 1933 * @see #WINDOW_FOCUSED_STATE_SET 1934 */ 1935 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1936 /** 1937 * Indicates the view is pressed and focused. 1938 * 1939 * @see #PRESSED_STATE_SET 1940 * @see #FOCUSED_STATE_SET 1941 */ 1942 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1943 /** 1944 * Indicates the view is pressed, focused and its window has the focus. 1945 * 1946 * @see #PRESSED_STATE_SET 1947 * @see #FOCUSED_STATE_SET 1948 * @see #WINDOW_FOCUSED_STATE_SET 1949 */ 1950 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1951 /** 1952 * Indicates the view is pressed, focused and selected. 1953 * 1954 * @see #PRESSED_STATE_SET 1955 * @see #SELECTED_STATE_SET 1956 * @see #FOCUSED_STATE_SET 1957 */ 1958 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1959 /** 1960 * Indicates the view is pressed, focused, selected and its window has the focus. 1961 * 1962 * @see #PRESSED_STATE_SET 1963 * @see #FOCUSED_STATE_SET 1964 * @see #SELECTED_STATE_SET 1965 * @see #WINDOW_FOCUSED_STATE_SET 1966 */ 1967 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1968 /** 1969 * Indicates the view is pressed and enabled. 1970 * 1971 * @see #PRESSED_STATE_SET 1972 * @see #ENABLED_STATE_SET 1973 */ 1974 protected static final int[] PRESSED_ENABLED_STATE_SET; 1975 /** 1976 * Indicates the view is pressed, enabled and its window has the focus. 1977 * 1978 * @see #PRESSED_STATE_SET 1979 * @see #ENABLED_STATE_SET 1980 * @see #WINDOW_FOCUSED_STATE_SET 1981 */ 1982 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1983 /** 1984 * Indicates the view is pressed, enabled and selected. 1985 * 1986 * @see #PRESSED_STATE_SET 1987 * @see #ENABLED_STATE_SET 1988 * @see #SELECTED_STATE_SET 1989 */ 1990 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1991 /** 1992 * Indicates the view is pressed, enabled, selected and its window has the 1993 * focus. 1994 * 1995 * @see #PRESSED_STATE_SET 1996 * @see #ENABLED_STATE_SET 1997 * @see #SELECTED_STATE_SET 1998 * @see #WINDOW_FOCUSED_STATE_SET 1999 */ 2000 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 2001 /** 2002 * Indicates the view is pressed, enabled and focused. 2003 * 2004 * @see #PRESSED_STATE_SET 2005 * @see #ENABLED_STATE_SET 2006 * @see #FOCUSED_STATE_SET 2007 */ 2008 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 2009 /** 2010 * Indicates the view is pressed, enabled, focused and its window has the 2011 * focus. 2012 * 2013 * @see #PRESSED_STATE_SET 2014 * @see #ENABLED_STATE_SET 2015 * @see #FOCUSED_STATE_SET 2016 * @see #WINDOW_FOCUSED_STATE_SET 2017 */ 2018 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 2019 /** 2020 * Indicates the view is pressed, enabled, focused and selected. 2021 * 2022 * @see #PRESSED_STATE_SET 2023 * @see #ENABLED_STATE_SET 2024 * @see #SELECTED_STATE_SET 2025 * @see #FOCUSED_STATE_SET 2026 */ 2027 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 2028 /** 2029 * Indicates the view is pressed, enabled, focused, selected and its window 2030 * has the focus. 2031 * 2032 * @see #PRESSED_STATE_SET 2033 * @see #ENABLED_STATE_SET 2034 * @see #SELECTED_STATE_SET 2035 * @see #FOCUSED_STATE_SET 2036 * @see #WINDOW_FOCUSED_STATE_SET 2037 */ 2038 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 2039 2040 static { 2041 EMPTY_STATE_SET = StateSet.get(0); 2042 2043 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 2044 2045 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 2046 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2047 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 2048 2049 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 2050 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2051 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 2052 FOCUSED_SELECTED_STATE_SET = StateSet.get( 2053 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 2054 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2055 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 2056 | StateSet.VIEW_STATE_FOCUSED); 2057 2058 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 2059 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2060 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 2061 ENABLED_SELECTED_STATE_SET = StateSet.get( 2062 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 2063 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2064 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 2065 | StateSet.VIEW_STATE_ENABLED); 2066 ENABLED_FOCUSED_STATE_SET = StateSet.get( 2067 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 2068 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2069 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 2070 | StateSet.VIEW_STATE_ENABLED); 2071 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 2072 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 2073 | StateSet.VIEW_STATE_ENABLED); 2074 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2075 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 2076 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 2077 2078 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 2079 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2080 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 2081 PRESSED_SELECTED_STATE_SET = StateSet.get( 2082 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 2083 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2084 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 2085 | StateSet.VIEW_STATE_PRESSED); 2086 PRESSED_FOCUSED_STATE_SET = StateSet.get( 2087 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 2088 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2089 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 2090 | StateSet.VIEW_STATE_PRESSED); 2091 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 2092 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 2093 | StateSet.VIEW_STATE_PRESSED); 2094 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2095 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 2096 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 2097 PRESSED_ENABLED_STATE_SET = StateSet.get( 2098 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 2099 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2100 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 2101 | StateSet.VIEW_STATE_PRESSED); 2102 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 2103 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 2104 | StateSet.VIEW_STATE_PRESSED); 2105 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2106 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 2107 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 2108 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 2109 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 2110 | StateSet.VIEW_STATE_PRESSED); 2111 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2112 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 2113 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 2114 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 2115 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 2116 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 2117 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 2118 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 2119 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 2120 | StateSet.VIEW_STATE_PRESSED); 2121 } 2122 2123 /** 2124 * Accessibility event types that are dispatched for text population. 2125 */ 2126 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 2127 AccessibilityEvent.TYPE_VIEW_CLICKED 2128 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 2129 | AccessibilityEvent.TYPE_VIEW_SELECTED 2130 | AccessibilityEvent.TYPE_VIEW_FOCUSED 2131 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 2132 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 2133 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 2134 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 2135 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 2136 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 2137 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 2138 2139 static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255); 2140 2141 static final int DEBUG_CORNERS_SIZE_DIP = 8; 2142 2143 /** 2144 * Temporary Rect currently for use in setBackground(). This will probably 2145 * be extended in the future to hold our own class with more than just 2146 * a Rect. :) 2147 */ 2148 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 2149 2150 /** 2151 * Map used to store views' tags. 2152 */ 2153 private SparseArray<Object> mKeyedTags; 2154 2155 /** 2156 * The next available accessibility id. 2157 */ 2158 private static int sNextAccessibilityViewId; 2159 2160 /** 2161 * The animation currently associated with this view. 2162 * @hide 2163 */ 2164 protected Animation mCurrentAnimation = null; 2165 2166 /** 2167 * Width as measured during measure pass. 2168 * {@hide} 2169 */ 2170 @ViewDebug.ExportedProperty(category = "measurement") 2171 int mMeasuredWidth; 2172 2173 /** 2174 * Height as measured during measure pass. 2175 * {@hide} 2176 */ 2177 @ViewDebug.ExportedProperty(category = "measurement") 2178 int mMeasuredHeight; 2179 2180 /** 2181 * Flag to indicate that this view was marked INVALIDATED, or had its display list 2182 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 2183 * its display list. This flag, used only when hw accelerated, allows us to clear the 2184 * flag while retaining this information until it's needed (at getDisplayList() time and 2185 * in drawChild(), when we decide to draw a view's children's display lists into our own). 2186 * 2187 * {@hide} 2188 */ 2189 boolean mRecreateDisplayList = false; 2190 2191 /** 2192 * The view's identifier. 2193 * {@hide} 2194 * 2195 * @see #setId(int) 2196 * @see #getId() 2197 */ 2198 @IdRes 2199 @ViewDebug.ExportedProperty(resolveId = true) 2200 int mID = NO_ID; 2201 2202 /** The ID of this view for autofill purposes. 2203 * <ul> 2204 * <li>== {@link #NO_ID}: ID has not been assigned yet 2205 * <li>≤ {@link #LAST_APP_AUTOFILL_ID}: View is not part of a activity. The ID is 2206 * unique in the process. This might change 2207 * over activity lifecycle events. 2208 * <li>> {@link #LAST_APP_AUTOFILL_ID}: View is part of a activity. The ID is 2209 * unique in the activity. This stays the same 2210 * over activity lifecycle events. 2211 */ 2212 private int mAutofillViewId = NO_ID; 2213 2214 // ID for accessibility purposes. This ID must be unique for every window 2215 private int mAccessibilityViewId = NO_ID; 2216 2217 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 2218 2219 /** 2220 * The view's tag. 2221 * {@hide} 2222 * 2223 * @see #setTag(Object) 2224 * @see #getTag() 2225 */ 2226 protected Object mTag = null; 2227 2228 // for mPrivateFlags: 2229 /** {@hide} */ 2230 static final int PFLAG_WANTS_FOCUS = 0x00000001; 2231 /** {@hide} */ 2232 static final int PFLAG_FOCUSED = 0x00000002; 2233 /** {@hide} */ 2234 static final int PFLAG_SELECTED = 0x00000004; 2235 /** {@hide} */ 2236 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 2237 /** {@hide} */ 2238 static final int PFLAG_HAS_BOUNDS = 0x00000010; 2239 /** {@hide} */ 2240 static final int PFLAG_DRAWN = 0x00000020; 2241 /** 2242 * When this flag is set, this view is running an animation on behalf of its 2243 * children and should therefore not cancel invalidate requests, even if they 2244 * lie outside of this view's bounds. 2245 * 2246 * {@hide} 2247 */ 2248 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 2249 /** {@hide} */ 2250 static final int PFLAG_SKIP_DRAW = 0x00000080; 2251 /** {@hide} */ 2252 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 2253 /** {@hide} */ 2254 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 2255 /** {@hide} */ 2256 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 2257 /** {@hide} */ 2258 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 2259 /** {@hide} */ 2260 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 2261 2262 private static final int PFLAG_PRESSED = 0x00004000; 2263 2264 /** {@hide} */ 2265 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 2266 /** 2267 * Flag used to indicate that this view should be drawn once more (and only once 2268 * more) after its animation has completed. 2269 * {@hide} 2270 */ 2271 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 2272 2273 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 2274 2275 /** 2276 * Indicates that the View returned true when onSetAlpha() was called and that 2277 * the alpha must be restored. 2278 * {@hide} 2279 */ 2280 static final int PFLAG_ALPHA_SET = 0x00040000; 2281 2282 /** 2283 * Set by {@link #setScrollContainer(boolean)}. 2284 */ 2285 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 2286 2287 /** 2288 * Set by {@link #setScrollContainer(boolean)}. 2289 */ 2290 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 2291 2292 /** 2293 * View flag indicating whether this view was invalidated (fully or partially.) 2294 * 2295 * @hide 2296 */ 2297 static final int PFLAG_DIRTY = 0x00200000; 2298 2299 /** 2300 * View flag indicating whether this view was invalidated by an opaque 2301 * invalidate request. 2302 * 2303 * @hide 2304 */ 2305 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 2306 2307 /** 2308 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 2309 * 2310 * @hide 2311 */ 2312 static final int PFLAG_DIRTY_MASK = 0x00600000; 2313 2314 /** 2315 * Indicates whether the background is opaque. 2316 * 2317 * @hide 2318 */ 2319 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 2320 2321 /** 2322 * Indicates whether the scrollbars are opaque. 2323 * 2324 * @hide 2325 */ 2326 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 2327 2328 /** 2329 * Indicates whether the view is opaque. 2330 * 2331 * @hide 2332 */ 2333 static final int PFLAG_OPAQUE_MASK = 0x01800000; 2334 2335 /** 2336 * Indicates a prepressed state; 2337 * the short time between ACTION_DOWN and recognizing 2338 * a 'real' press. Prepressed is used to recognize quick taps 2339 * even when they are shorter than ViewConfiguration.getTapTimeout(). 2340 * 2341 * @hide 2342 */ 2343 private static final int PFLAG_PREPRESSED = 0x02000000; 2344 2345 /** 2346 * Indicates whether the view is temporarily detached. 2347 * 2348 * @hide 2349 */ 2350 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 2351 2352 /** 2353 * Indicates that we should awaken scroll bars once attached 2354 * 2355 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 2356 * during window attachment and it is no longer needed. Feel free to repurpose it. 2357 * 2358 * @hide 2359 */ 2360 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 2361 2362 /** 2363 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 2364 * @hide 2365 */ 2366 private static final int PFLAG_HOVERED = 0x10000000; 2367 2368 /** 2369 * Flag set by {@link AutofillManager} if it needs to be notified when this view is clicked. 2370 */ 2371 private static final int PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK = 0x20000000; 2372 2373 /** {@hide} */ 2374 static final int PFLAG_ACTIVATED = 0x40000000; 2375 2376 /** 2377 * Indicates that this view was specifically invalidated, not just dirtied because some 2378 * child view was invalidated. The flag is used to determine when we need to recreate 2379 * a view's display list (as opposed to just returning a reference to its existing 2380 * display list). 2381 * 2382 * @hide 2383 */ 2384 static final int PFLAG_INVALIDATED = 0x80000000; 2385 2386 /** 2387 * Masks for mPrivateFlags2, as generated by dumpFlags(): 2388 * 2389 * |-------|-------|-------|-------| 2390 * 1 PFLAG2_DRAG_CAN_ACCEPT 2391 * 1 PFLAG2_DRAG_HOVERED 2392 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 2393 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 2394 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 2395 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 2396 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 2397 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 2398 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 2399 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 2400 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 2401 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 2402 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 2403 * 111 PFLAG2_TEXT_DIRECTION_MASK 2404 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 2405 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 2406 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 2407 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 2408 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 2409 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 2410 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 2411 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 2412 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 2413 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 2414 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 2415 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 2416 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 2417 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 2418 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 2419 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 2420 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 2421 * 1 PFLAG2_VIEW_QUICK_REJECTED 2422 * 1 PFLAG2_PADDING_RESOLVED 2423 * 1 PFLAG2_DRAWABLE_RESOLVED 2424 * 1 PFLAG2_HAS_TRANSIENT_STATE 2425 * |-------|-------|-------|-------| 2426 */ 2427 2428 /** 2429 * Indicates that this view has reported that it can accept the current drag's content. 2430 * Cleared when the drag operation concludes. 2431 * @hide 2432 */ 2433 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 2434 2435 /** 2436 * Indicates that this view is currently directly under the drag location in a 2437 * drag-and-drop operation involving content that it can accept. Cleared when 2438 * the drag exits the view, or when the drag operation concludes. 2439 * @hide 2440 */ 2441 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 2442 2443 /** @hide */ 2444 @IntDef(prefix = { "LAYOUT_DIRECTION_" }, value = { 2445 LAYOUT_DIRECTION_LTR, 2446 LAYOUT_DIRECTION_RTL, 2447 LAYOUT_DIRECTION_INHERIT, 2448 LAYOUT_DIRECTION_LOCALE 2449 }) 2450 @Retention(RetentionPolicy.SOURCE) 2451 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 2452 public @interface LayoutDir {} 2453 2454 /** @hide */ 2455 @IntDef(prefix = { "LAYOUT_DIRECTION_" }, value = { 2456 LAYOUT_DIRECTION_LTR, 2457 LAYOUT_DIRECTION_RTL 2458 }) 2459 @Retention(RetentionPolicy.SOURCE) 2460 public @interface ResolvedLayoutDir {} 2461 2462 /** 2463 * A flag to indicate that the layout direction of this view has not been defined yet. 2464 * @hide 2465 */ 2466 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 2467 2468 /** 2469 * Horizontal layout direction of this view is from Left to Right. 2470 * Use with {@link #setLayoutDirection}. 2471 */ 2472 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 2473 2474 /** 2475 * Horizontal layout direction of this view is from Right to Left. 2476 * Use with {@link #setLayoutDirection}. 2477 */ 2478 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 2479 2480 /** 2481 * Horizontal layout direction of this view is inherited from its parent. 2482 * Use with {@link #setLayoutDirection}. 2483 */ 2484 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 2485 2486 /** 2487 * Horizontal layout direction of this view is from deduced from the default language 2488 * script for the locale. Use with {@link #setLayoutDirection}. 2489 */ 2490 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 2491 2492 /** 2493 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2494 * @hide 2495 */ 2496 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 2497 2498 /** 2499 * Mask for use with private flags indicating bits used for horizontal layout direction. 2500 * @hide 2501 */ 2502 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2503 2504 /** 2505 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 2506 * right-to-left direction. 2507 * @hide 2508 */ 2509 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2510 2511 /** 2512 * Indicates whether the view horizontal layout direction has been resolved. 2513 * @hide 2514 */ 2515 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2516 2517 /** 2518 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 2519 * @hide 2520 */ 2521 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 2522 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2523 2524 /* 2525 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 2526 * flag value. 2527 * @hide 2528 */ 2529 private static final int[] LAYOUT_DIRECTION_FLAGS = { 2530 LAYOUT_DIRECTION_LTR, 2531 LAYOUT_DIRECTION_RTL, 2532 LAYOUT_DIRECTION_INHERIT, 2533 LAYOUT_DIRECTION_LOCALE 2534 }; 2535 2536 /** 2537 * Default horizontal layout direction. 2538 */ 2539 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 2540 2541 /** 2542 * Default horizontal layout direction. 2543 * @hide 2544 */ 2545 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 2546 2547 /** 2548 * Text direction is inherited through {@link ViewGroup} 2549 */ 2550 public static final int TEXT_DIRECTION_INHERIT = 0; 2551 2552 /** 2553 * Text direction is using "first strong algorithm". The first strong directional character 2554 * determines the paragraph direction. If there is no strong directional character, the 2555 * paragraph direction is the view's resolved layout direction. 2556 */ 2557 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2558 2559 /** 2560 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2561 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2562 * If there are neither, the paragraph direction is the view's resolved layout direction. 2563 */ 2564 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2565 2566 /** 2567 * Text direction is forced to LTR. 2568 */ 2569 public static final int TEXT_DIRECTION_LTR = 3; 2570 2571 /** 2572 * Text direction is forced to RTL. 2573 */ 2574 public static final int TEXT_DIRECTION_RTL = 4; 2575 2576 /** 2577 * Text direction is coming from the system Locale. 2578 */ 2579 public static final int TEXT_DIRECTION_LOCALE = 5; 2580 2581 /** 2582 * Text direction is using "first strong algorithm". The first strong directional character 2583 * determines the paragraph direction. If there is no strong directional character, the 2584 * paragraph direction is LTR. 2585 */ 2586 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2587 2588 /** 2589 * Text direction is using "first strong algorithm". The first strong directional character 2590 * determines the paragraph direction. If there is no strong directional character, the 2591 * paragraph direction is RTL. 2592 */ 2593 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2594 2595 /** 2596 * Default text direction is inherited 2597 */ 2598 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2599 2600 /** 2601 * Default resolved text direction 2602 * @hide 2603 */ 2604 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2605 2606 /** 2607 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2608 * @hide 2609 */ 2610 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2611 2612 /** 2613 * Mask for use with private flags indicating bits used for text direction. 2614 * @hide 2615 */ 2616 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2617 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2618 2619 /** 2620 * Array of text direction flags for mapping attribute "textDirection" to correct 2621 * flag value. 2622 * @hide 2623 */ 2624 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2625 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2626 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2627 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2628 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2629 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2630 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2631 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2632 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2633 }; 2634 2635 /** 2636 * Indicates whether the view text direction has been resolved. 2637 * @hide 2638 */ 2639 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2640 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2641 2642 /** 2643 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2644 * @hide 2645 */ 2646 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2647 2648 /** 2649 * Mask for use with private flags indicating bits used for resolved text direction. 2650 * @hide 2651 */ 2652 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2653 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2654 2655 /** 2656 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2657 * @hide 2658 */ 2659 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2660 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2661 2662 /** @hide */ 2663 @IntDef(prefix = { "TEXT_ALIGNMENT_" }, value = { 2664 TEXT_ALIGNMENT_INHERIT, 2665 TEXT_ALIGNMENT_GRAVITY, 2666 TEXT_ALIGNMENT_CENTER, 2667 TEXT_ALIGNMENT_TEXT_START, 2668 TEXT_ALIGNMENT_TEXT_END, 2669 TEXT_ALIGNMENT_VIEW_START, 2670 TEXT_ALIGNMENT_VIEW_END 2671 }) 2672 @Retention(RetentionPolicy.SOURCE) 2673 public @interface TextAlignment {} 2674 2675 /** 2676 * Default text alignment. The text alignment of this View is inherited from its parent. 2677 * Use with {@link #setTextAlignment(int)} 2678 */ 2679 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2680 2681 /** 2682 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2683 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2684 * 2685 * Use with {@link #setTextAlignment(int)} 2686 */ 2687 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2688 2689 /** 2690 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2691 * 2692 * Use with {@link #setTextAlignment(int)} 2693 */ 2694 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2695 2696 /** 2697 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2698 * 2699 * Use with {@link #setTextAlignment(int)} 2700 */ 2701 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2702 2703 /** 2704 * Center the paragraph, e.g. ALIGN_CENTER. 2705 * 2706 * Use with {@link #setTextAlignment(int)} 2707 */ 2708 public static final int TEXT_ALIGNMENT_CENTER = 4; 2709 2710 /** 2711 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2712 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2713 * 2714 * Use with {@link #setTextAlignment(int)} 2715 */ 2716 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2717 2718 /** 2719 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2720 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2721 * 2722 * Use with {@link #setTextAlignment(int)} 2723 */ 2724 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2725 2726 /** 2727 * Default text alignment is inherited 2728 */ 2729 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2730 2731 /** 2732 * Default resolved text alignment 2733 * @hide 2734 */ 2735 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2736 2737 /** 2738 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2739 * @hide 2740 */ 2741 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2742 2743 /** 2744 * Mask for use with private flags indicating bits used for text alignment. 2745 * @hide 2746 */ 2747 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2748 2749 /** 2750 * Array of text direction flags for mapping attribute "textAlignment" to correct 2751 * flag value. 2752 * @hide 2753 */ 2754 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2755 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2756 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2757 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2758 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2759 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2760 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2761 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2762 }; 2763 2764 /** 2765 * Indicates whether the view text alignment has been resolved. 2766 * @hide 2767 */ 2768 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2769 2770 /** 2771 * Bit shift to get the resolved text alignment. 2772 * @hide 2773 */ 2774 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2775 2776 /** 2777 * Mask for use with private flags indicating bits used for text alignment. 2778 * @hide 2779 */ 2780 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2781 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2782 2783 /** 2784 * Indicates whether if the view text alignment has been resolved to gravity 2785 */ 2786 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2787 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2788 2789 // Accessiblity constants for mPrivateFlags2 2790 2791 /** 2792 * Shift for the bits in {@link #mPrivateFlags2} related to the 2793 * "importantForAccessibility" attribute. 2794 */ 2795 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2796 2797 /** 2798 * Automatically determine whether a view is important for accessibility. 2799 */ 2800 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2801 2802 /** 2803 * The view is important for accessibility. 2804 */ 2805 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2806 2807 /** 2808 * The view is not important for accessibility. 2809 */ 2810 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2811 2812 /** 2813 * The view is not important for accessibility, nor are any of its 2814 * descendant views. 2815 */ 2816 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2817 2818 /** 2819 * The default whether the view is important for accessibility. 2820 */ 2821 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2822 2823 /** 2824 * Mask for obtaining the bits which specify how to determine 2825 * whether a view is important for accessibility. 2826 */ 2827 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2828 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2829 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2830 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2831 2832 /** 2833 * Shift for the bits in {@link #mPrivateFlags2} related to the 2834 * "accessibilityLiveRegion" attribute. 2835 */ 2836 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2837 2838 /** 2839 * Live region mode specifying that accessibility services should not 2840 * automatically announce changes to this view. This is the default live 2841 * region mode for most views. 2842 * <p> 2843 * Use with {@link #setAccessibilityLiveRegion(int)}. 2844 */ 2845 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2846 2847 /** 2848 * Live region mode specifying that accessibility services should announce 2849 * changes to this view. 2850 * <p> 2851 * Use with {@link #setAccessibilityLiveRegion(int)}. 2852 */ 2853 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2854 2855 /** 2856 * Live region mode specifying that accessibility services should interrupt 2857 * ongoing speech to immediately announce changes to this view. 2858 * <p> 2859 * Use with {@link #setAccessibilityLiveRegion(int)}. 2860 */ 2861 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2862 2863 /** 2864 * The default whether the view is important for accessibility. 2865 */ 2866 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2867 2868 /** 2869 * Mask for obtaining the bits which specify a view's accessibility live 2870 * region mode. 2871 */ 2872 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2873 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2874 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2875 2876 /** 2877 * Flag indicating whether a view has accessibility focus. 2878 */ 2879 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2880 2881 /** 2882 * Flag whether the accessibility state of the subtree rooted at this view changed. 2883 */ 2884 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2885 2886 /** 2887 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2888 * is used to check whether later changes to the view's transform should invalidate the 2889 * view to force the quickReject test to run again. 2890 */ 2891 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2892 2893 /** 2894 * Flag indicating that start/end padding has been resolved into left/right padding 2895 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2896 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2897 * during measurement. In some special cases this is required such as when an adapter-based 2898 * view measures prospective children without attaching them to a window. 2899 */ 2900 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2901 2902 /** 2903 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2904 */ 2905 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2906 2907 /** 2908 * Indicates that the view is tracking some sort of transient state 2909 * that the app should not need to be aware of, but that the framework 2910 * should take special care to preserve. 2911 */ 2912 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2913 2914 /** 2915 * Group of bits indicating that RTL properties resolution is done. 2916 */ 2917 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2918 PFLAG2_TEXT_DIRECTION_RESOLVED | 2919 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2920 PFLAG2_PADDING_RESOLVED | 2921 PFLAG2_DRAWABLE_RESOLVED; 2922 2923 // There are a couple of flags left in mPrivateFlags2 2924 2925 /* End of masks for mPrivateFlags2 */ 2926 2927 /** 2928 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2929 * 2930 * |-------|-------|-------|-------| 2931 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2932 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2933 * 1 PFLAG3_IS_LAID_OUT 2934 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2935 * 1 PFLAG3_CALLED_SUPER 2936 * 1 PFLAG3_APPLYING_INSETS 2937 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2938 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2939 * 1 PFLAG3_SCROLL_INDICATOR_TOP 2940 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM 2941 * 1 PFLAG3_SCROLL_INDICATOR_LEFT 2942 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT 2943 * 1 PFLAG3_SCROLL_INDICATOR_START 2944 * 1 PFLAG3_SCROLL_INDICATOR_END 2945 * 1 PFLAG3_ASSIST_BLOCKED 2946 * 1 PFLAG3_CLUSTER 2947 * 1 PFLAG3_IS_AUTOFILLED 2948 * 1 PFLAG3_FINGER_DOWN 2949 * 1 PFLAG3_FOCUSED_BY_DEFAULT 2950 * 1111 PFLAG3_IMPORTANT_FOR_AUTOFILL 2951 * 1 PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE 2952 * 1 PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED 2953 * 1 PFLAG3_TEMPORARY_DETACH 2954 * 1 PFLAG3_NO_REVEAL_ON_FOCUS 2955 * 1 PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT 2956 * 1 PFLAG3_SCREEN_READER_FOCUSABLE 2957 * 1 PFLAG3_AGGREGATED_VISIBLE 2958 * 1 PFLAG3_AUTOFILLID_EXPLICITLY_SET 2959 * 1 PFLAG3_ACCESSIBILITY_HEADING 2960 * |-------|-------|-------|-------| 2961 */ 2962 2963 /** 2964 * Flag indicating that view has a transform animation set on it. This is used to track whether 2965 * an animation is cleared between successive frames, in order to tell the associated 2966 * DisplayList to clear its animation matrix. 2967 */ 2968 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2969 2970 /** 2971 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2972 * animation is cleared between successive frames, in order to tell the associated 2973 * DisplayList to restore its alpha value. 2974 */ 2975 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2976 2977 /** 2978 * Flag indicating that the view has been through at least one layout since it 2979 * was last attached to a window. 2980 */ 2981 static final int PFLAG3_IS_LAID_OUT = 0x4; 2982 2983 /** 2984 * Flag indicating that a call to measure() was skipped and should be done 2985 * instead when layout() is invoked. 2986 */ 2987 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2988 2989 /** 2990 * Flag indicating that an overridden method correctly called down to 2991 * the superclass implementation as required by the API spec. 2992 */ 2993 static final int PFLAG3_CALLED_SUPER = 0x10; 2994 2995 /** 2996 * Flag indicating that we're in the process of applying window insets. 2997 */ 2998 static final int PFLAG3_APPLYING_INSETS = 0x20; 2999 3000 /** 3001 * Flag indicating that we're in the process of fitting system windows using the old method. 3002 */ 3003 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 3004 3005 /** 3006 * Flag indicating that nested scrolling is enabled for this view. 3007 * The view will optionally cooperate with views up its parent chain to allow for 3008 * integrated nested scrolling along the same axis. 3009 */ 3010 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 3011 3012 /** 3013 * Flag indicating that the bottom scroll indicator should be displayed 3014 * when this view can scroll up. 3015 */ 3016 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 3017 3018 /** 3019 * Flag indicating that the bottom scroll indicator should be displayed 3020 * when this view can scroll down. 3021 */ 3022 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 3023 3024 /** 3025 * Flag indicating that the left scroll indicator should be displayed 3026 * when this view can scroll left. 3027 */ 3028 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 3029 3030 /** 3031 * Flag indicating that the right scroll indicator should be displayed 3032 * when this view can scroll right. 3033 */ 3034 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 3035 3036 /** 3037 * Flag indicating that the start scroll indicator should be displayed 3038 * when this view can scroll in the start direction. 3039 */ 3040 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 3041 3042 /** 3043 * Flag indicating that the end scroll indicator should be displayed 3044 * when this view can scroll in the end direction. 3045 */ 3046 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 3047 3048 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 3049 3050 static final int SCROLL_INDICATORS_NONE = 0x0000; 3051 3052 /** 3053 * Mask for use with setFlags indicating bits used for indicating which 3054 * scroll indicators are enabled. 3055 */ 3056 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 3057 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 3058 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 3059 | PFLAG3_SCROLL_INDICATOR_END; 3060 3061 /** 3062 * Left-shift required to translate between public scroll indicator flags 3063 * and internal PFLAGS3 flags. When used as a right-shift, translates 3064 * PFLAGS3 flags to public flags. 3065 */ 3066 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 3067 3068 /** @hide */ 3069 @Retention(RetentionPolicy.SOURCE) 3070 @IntDef(flag = true, prefix = { "SCROLL_INDICATOR_" }, value = { 3071 SCROLL_INDICATOR_TOP, 3072 SCROLL_INDICATOR_BOTTOM, 3073 SCROLL_INDICATOR_LEFT, 3074 SCROLL_INDICATOR_RIGHT, 3075 SCROLL_INDICATOR_START, 3076 SCROLL_INDICATOR_END, 3077 }) 3078 public @interface ScrollIndicators {} 3079 3080 /** 3081 * Scroll indicator direction for the top edge of the view. 3082 * 3083 * @see #setScrollIndicators(int) 3084 * @see #setScrollIndicators(int, int) 3085 * @see #getScrollIndicators() 3086 */ 3087 public static final int SCROLL_INDICATOR_TOP = 3088 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 3089 3090 /** 3091 * Scroll indicator direction for the bottom edge of the view. 3092 * 3093 * @see #setScrollIndicators(int) 3094 * @see #setScrollIndicators(int, int) 3095 * @see #getScrollIndicators() 3096 */ 3097 public static final int SCROLL_INDICATOR_BOTTOM = 3098 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 3099 3100 /** 3101 * Scroll indicator direction for the left edge of the view. 3102 * 3103 * @see #setScrollIndicators(int) 3104 * @see #setScrollIndicators(int, int) 3105 * @see #getScrollIndicators() 3106 */ 3107 public static final int SCROLL_INDICATOR_LEFT = 3108 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 3109 3110 /** 3111 * Scroll indicator direction for the right edge of the view. 3112 * 3113 * @see #setScrollIndicators(int) 3114 * @see #setScrollIndicators(int, int) 3115 * @see #getScrollIndicators() 3116 */ 3117 public static final int SCROLL_INDICATOR_RIGHT = 3118 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 3119 3120 /** 3121 * Scroll indicator direction for the starting edge of the view. 3122 * <p> 3123 * Resolved according to the view's layout direction, see 3124 * {@link #getLayoutDirection()} for more information. 3125 * 3126 * @see #setScrollIndicators(int) 3127 * @see #setScrollIndicators(int, int) 3128 * @see #getScrollIndicators() 3129 */ 3130 public static final int SCROLL_INDICATOR_START = 3131 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 3132 3133 /** 3134 * Scroll indicator direction for the ending edge of the view. 3135 * <p> 3136 * Resolved according to the view's layout direction, see 3137 * {@link #getLayoutDirection()} for more information. 3138 * 3139 * @see #setScrollIndicators(int) 3140 * @see #setScrollIndicators(int, int) 3141 * @see #getScrollIndicators() 3142 */ 3143 public static final int SCROLL_INDICATOR_END = 3144 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 3145 3146 /** 3147 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 3148 * into this view.<p> 3149 */ 3150 static final int PFLAG3_ASSIST_BLOCKED = 0x4000; 3151 3152 /** 3153 * Flag indicating that the view is a root of a keyboard navigation cluster. 3154 * 3155 * @see #isKeyboardNavigationCluster() 3156 * @see #setKeyboardNavigationCluster(boolean) 3157 */ 3158 private static final int PFLAG3_CLUSTER = 0x8000; 3159 3160 /** 3161 * Flag indicating that the view is autofilled 3162 * 3163 * @see #isAutofilled() 3164 * @see #setAutofilled(boolean) 3165 */ 3166 private static final int PFLAG3_IS_AUTOFILLED = 0x10000; 3167 3168 /** 3169 * Indicates that the user is currently touching the screen. 3170 * Currently used for the tooltip positioning only. 3171 */ 3172 private static final int PFLAG3_FINGER_DOWN = 0x20000; 3173 3174 /** 3175 * Flag indicating that this view is the default-focus view. 3176 * 3177 * @see #isFocusedByDefault() 3178 * @see #setFocusedByDefault(boolean) 3179 */ 3180 private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000; 3181 3182 /** 3183 * Shift for the bits in {@link #mPrivateFlags3} related to the 3184 * "importantForAutofill" attribute. 3185 */ 3186 static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT = 19; 3187 3188 /** 3189 * Mask for obtaining the bits which specify how to determine 3190 * whether a view is important for autofill. 3191 */ 3192 static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK = (IMPORTANT_FOR_AUTOFILL_AUTO 3193 | IMPORTANT_FOR_AUTOFILL_YES | IMPORTANT_FOR_AUTOFILL_NO 3194 | IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS 3195 | IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS) 3196 << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT; 3197 3198 /** 3199 * Whether this view has rendered elements that overlap (see {@link 3200 * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and 3201 * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when 3202 * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is 3203 * determined by whatever {@link #hasOverlappingRendering()} returns. 3204 */ 3205 private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000; 3206 3207 /** 3208 * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value 3209 * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid. 3210 */ 3211 private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000; 3212 3213 /** 3214 * Flag indicating that the view is temporarily detached from the parent view. 3215 * 3216 * @see #onStartTemporaryDetach() 3217 * @see #onFinishTemporaryDetach() 3218 */ 3219 static final int PFLAG3_TEMPORARY_DETACH = 0x2000000; 3220 3221 /** 3222 * Flag indicating that the view does not wish to be revealed within its parent 3223 * hierarchy when it gains focus. Expressed in the negative since the historical 3224 * default behavior is to reveal on focus; this flag suppresses that behavior. 3225 * 3226 * @see #setRevealOnFocusHint(boolean) 3227 * @see #getRevealOnFocusHint() 3228 */ 3229 private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000; 3230 3231 /** 3232 * Flag indicating that when layout is completed we should notify 3233 * that the view was entered for autofill purposes. To minimize 3234 * showing autofill for views not visible to the user we evaluate 3235 * user visibility which cannot be done until the view is laid out. 3236 */ 3237 static final int PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT = 0x8000000; 3238 3239 /** 3240 * Works like focusable for screen readers, but without the side effects on input focus. 3241 * @see #setScreenReaderFocusable(boolean) 3242 */ 3243 private static final int PFLAG3_SCREEN_READER_FOCUSABLE = 0x10000000; 3244 3245 /** 3246 * The last aggregated visibility. Used to detect when it truly changes. 3247 */ 3248 private static final int PFLAG3_AGGREGATED_VISIBLE = 0x20000000; 3249 3250 /** 3251 * Used to indicate that {@link #mAutofillId} was explicitly set through 3252 * {@link #setAutofillId(AutofillId)}. 3253 */ 3254 private static final int PFLAG3_AUTOFILLID_EXPLICITLY_SET = 0x40000000; 3255 3256 /** 3257 * Indicates if the View is a heading for accessibility purposes 3258 */ 3259 private static final int PFLAG3_ACCESSIBILITY_HEADING = 0x80000000; 3260 3261 /* End of masks for mPrivateFlags3 */ 3262 3263 /** 3264 * Always allow a user to over-scroll this view, provided it is a 3265 * view that can scroll. 3266 * 3267 * @see #getOverScrollMode() 3268 * @see #setOverScrollMode(int) 3269 */ 3270 public static final int OVER_SCROLL_ALWAYS = 0; 3271 3272 /** 3273 * Allow a user to over-scroll this view only if the content is large 3274 * enough to meaningfully scroll, provided it is a view that can scroll. 3275 * 3276 * @see #getOverScrollMode() 3277 * @see #setOverScrollMode(int) 3278 */ 3279 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 3280 3281 /** 3282 * Never allow a user to over-scroll this view. 3283 * 3284 * @see #getOverScrollMode() 3285 * @see #setOverScrollMode(int) 3286 */ 3287 public static final int OVER_SCROLL_NEVER = 2; 3288 3289 /** 3290 * Special constant for {@link #setSystemUiVisibility(int)}: View has 3291 * requested the system UI (status bar) to be visible (the default). 3292 * 3293 * @see #setSystemUiVisibility(int) 3294 */ 3295 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 3296 3297 /** 3298 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 3299 * system UI to enter an unobtrusive "low profile" mode. 3300 * 3301 * <p>This is for use in games, book readers, video players, or any other 3302 * "immersive" application where the usual system chrome is deemed too distracting. 3303 * 3304 * <p>In low profile mode, the status bar and/or navigation icons may dim. 3305 * 3306 * @see #setSystemUiVisibility(int) 3307 */ 3308 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 3309 3310 /** 3311 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 3312 * system navigation be temporarily hidden. 3313 * 3314 * <p>This is an even less obtrusive state than that called for by 3315 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 3316 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 3317 * those to disappear. This is useful (in conjunction with the 3318 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 3319 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 3320 * window flags) for displaying content using every last pixel on the display. 3321 * 3322 * <p>There is a limitation: because navigation controls are so important, the least user 3323 * interaction will cause them to reappear immediately. When this happens, both 3324 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 3325 * so that both elements reappear at the same time. 3326 * 3327 * @see #setSystemUiVisibility(int) 3328 */ 3329 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 3330 3331 /** 3332 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 3333 * into the normal fullscreen mode so that its content can take over the screen 3334 * while still allowing the user to interact with the application. 3335 * 3336 * <p>This has the same visual effect as 3337 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 3338 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 3339 * meaning that non-critical screen decorations (such as the status bar) will be 3340 * hidden while the user is in the View's window, focusing the experience on 3341 * that content. Unlike the window flag, if you are using ActionBar in 3342 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 3343 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 3344 * hide the action bar. 3345 * 3346 * <p>This approach to going fullscreen is best used over the window flag when 3347 * it is a transient state -- that is, the application does this at certain 3348 * points in its user interaction where it wants to allow the user to focus 3349 * on content, but not as a continuous state. For situations where the application 3350 * would like to simply stay full screen the entire time (such as a game that 3351 * wants to take over the screen), the 3352 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 3353 * is usually a better approach. The state set here will be removed by the system 3354 * in various situations (such as the user moving to another application) like 3355 * the other system UI states. 3356 * 3357 * <p>When using this flag, the application should provide some easy facility 3358 * for the user to go out of it. A common example would be in an e-book 3359 * reader, where tapping on the screen brings back whatever screen and UI 3360 * decorations that had been hidden while the user was immersed in reading 3361 * the book. 3362 * 3363 * @see #setSystemUiVisibility(int) 3364 */ 3365 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 3366 3367 /** 3368 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 3369 * flags, we would like a stable view of the content insets given to 3370 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 3371 * will always represent the worst case that the application can expect 3372 * as a continuous state. In the stock Android UI this is the space for 3373 * the system bar, nav bar, and status bar, but not more transient elements 3374 * such as an input method. 3375 * 3376 * The stable layout your UI sees is based on the system UI modes you can 3377 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 3378 * then you will get a stable layout for changes of the 3379 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 3380 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 3381 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 3382 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 3383 * with a stable layout. (Note that you should avoid using 3384 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 3385 * 3386 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 3387 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 3388 * then a hidden status bar will be considered a "stable" state for purposes 3389 * here. This allows your UI to continually hide the status bar, while still 3390 * using the system UI flags to hide the action bar while still retaining 3391 * a stable layout. Note that changing the window fullscreen flag will never 3392 * provide a stable layout for a clean transition. 3393 * 3394 * <p>If you are using ActionBar in 3395 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 3396 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 3397 * insets it adds to those given to the application. 3398 */ 3399 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 3400 3401 /** 3402 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 3403 * to be laid out as if it has requested 3404 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 3405 * allows it to avoid artifacts when switching in and out of that mode, at 3406 * the expense that some of its user interface may be covered by screen 3407 * decorations when they are shown. You can perform layout of your inner 3408 * UI elements to account for the navigation system UI through the 3409 * {@link #fitSystemWindows(Rect)} method. 3410 */ 3411 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 3412 3413 /** 3414 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 3415 * to be laid out as if it has requested 3416 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 3417 * allows it to avoid artifacts when switching in and out of that mode, at 3418 * the expense that some of its user interface may be covered by screen 3419 * decorations when they are shown. You can perform layout of your inner 3420 * UI elements to account for non-fullscreen system UI through the 3421 * {@link #fitSystemWindows(Rect)} method. 3422 * 3423 * <p>Note: on displays that have a {@link DisplayCutout}, the window may still be placed 3424 * differently than if {@link #SYSTEM_UI_FLAG_FULLSCREEN} was set, if the 3425 * window's {@link WindowManager.LayoutParams#layoutInDisplayCutoutMode 3426 * layoutInDisplayCutoutMode} is 3427 * {@link WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT 3428 * LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT}. To avoid this, use either of the other modes. 3429 * 3430 * @see WindowManager.LayoutParams#layoutInDisplayCutoutMode 3431 * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT 3432 * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS 3433 * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER 3434 */ 3435 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 3436 3437 /** 3438 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 3439 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 3440 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 3441 * user interaction. 3442 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 3443 * has an effect when used in combination with that flag.</p> 3444 */ 3445 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 3446 3447 /** 3448 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 3449 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 3450 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 3451 * experience while also hiding the system bars. If this flag is not set, 3452 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 3453 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 3454 * if the user swipes from the top of the screen. 3455 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 3456 * system gestures, such as swiping from the top of the screen. These transient system bars 3457 * will overlay app’s content, may have some degree of transparency, and will automatically 3458 * hide after a short timeout. 3459 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 3460 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 3461 * with one or both of those flags.</p> 3462 */ 3463 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 3464 3465 /** 3466 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 3467 * is compatible with light status bar backgrounds. 3468 * 3469 * <p>For this to take effect, the window must request 3470 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 3471 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 3472 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 3473 * FLAG_TRANSLUCENT_STATUS}. 3474 * 3475 * @see android.R.attr#windowLightStatusBar 3476 */ 3477 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 3478 3479 /** 3480 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might 3481 * trigger undefined behavior on older platforms with apps compiled against a new SDK. 3482 */ 3483 private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000; 3484 3485 /** 3486 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might 3487 * trigger undefined behavior on older platforms with apps compiled against a new SDK. 3488 */ 3489 private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000; 3490 3491 /** 3492 * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode 3493 * that is compatible with light navigation bar backgrounds. 3494 * 3495 * <p>For this to take effect, the window must request 3496 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 3497 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 3498 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION 3499 * FLAG_TRANSLUCENT_NAVIGATION}. 3500 * 3501 * @see android.R.attr#windowLightNavigationBar 3502 */ 3503 public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010; 3504 3505 /** 3506 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 3507 */ 3508 @Deprecated 3509 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 3510 3511 /** 3512 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 3513 */ 3514 @Deprecated 3515 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 3516 3517 /** 3518 * @hide 3519 * 3520 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3521 * out of the public fields to keep the undefined bits out of the developer's way. 3522 * 3523 * Flag to make the status bar not expandable. Unless you also 3524 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 3525 */ 3526 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 3527 3528 /** 3529 * @hide 3530 * 3531 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3532 * out of the public fields to keep the undefined bits out of the developer's way. 3533 * 3534 * Flag to hide notification icons and scrolling ticker text. 3535 */ 3536 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 3537 3538 /** 3539 * @hide 3540 * 3541 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3542 * out of the public fields to keep the undefined bits out of the developer's way. 3543 * 3544 * Flag to disable incoming notification alerts. This will not block 3545 * icons, but it will block sound, vibrating and other visual or aural notifications. 3546 */ 3547 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 3548 3549 /** 3550 * @hide 3551 * 3552 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3553 * out of the public fields to keep the undefined bits out of the developer's way. 3554 * 3555 * Flag to hide only the scrolling ticker. Note that 3556 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 3557 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 3558 */ 3559 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 3560 3561 /** 3562 * @hide 3563 * 3564 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3565 * out of the public fields to keep the undefined bits out of the developer's way. 3566 * 3567 * Flag to hide the center system info area. 3568 */ 3569 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 3570 3571 /** 3572 * @hide 3573 * 3574 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3575 * out of the public fields to keep the undefined bits out of the developer's way. 3576 * 3577 * Flag to hide only the home button. Don't use this 3578 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3579 */ 3580 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 3581 3582 /** 3583 * @hide 3584 * 3585 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3586 * out of the public fields to keep the undefined bits out of the developer's way. 3587 * 3588 * Flag to hide only the back button. Don't use this 3589 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3590 */ 3591 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 3592 3593 /** 3594 * @hide 3595 * 3596 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3597 * out of the public fields to keep the undefined bits out of the developer's way. 3598 * 3599 * Flag to hide only the clock. You might use this if your activity has 3600 * its own clock making the status bar's clock redundant. 3601 */ 3602 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 3603 3604 /** 3605 * @hide 3606 * 3607 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3608 * out of the public fields to keep the undefined bits out of the developer's way. 3609 * 3610 * Flag to hide only the recent apps button. Don't use this 3611 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3612 */ 3613 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 3614 3615 /** 3616 * @hide 3617 * 3618 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3619 * out of the public fields to keep the undefined bits out of the developer's way. 3620 * 3621 * Flag to disable the global search gesture. Don't use this 3622 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3623 */ 3624 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 3625 3626 /** 3627 * @hide 3628 * 3629 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3630 * out of the public fields to keep the undefined bits out of the developer's way. 3631 * 3632 * Flag to specify that the status bar is displayed in transient mode. 3633 */ 3634 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 3635 3636 /** 3637 * @hide 3638 * 3639 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3640 * out of the public fields to keep the undefined bits out of the developer's way. 3641 * 3642 * Flag to specify that the navigation bar is displayed in transient mode. 3643 */ 3644 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 3645 3646 /** 3647 * @hide 3648 * 3649 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3650 * out of the public fields to keep the undefined bits out of the developer's way. 3651 * 3652 * Flag to specify that the hidden status bar would like to be shown. 3653 */ 3654 public static final int STATUS_BAR_UNHIDE = 0x10000000; 3655 3656 /** 3657 * @hide 3658 * 3659 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3660 * out of the public fields to keep the undefined bits out of the developer's way. 3661 * 3662 * Flag to specify that the hidden navigation bar would like to be shown. 3663 */ 3664 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 3665 3666 /** 3667 * @hide 3668 * 3669 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3670 * out of the public fields to keep the undefined bits out of the developer's way. 3671 * 3672 * Flag to specify that the status bar is displayed in translucent mode. 3673 */ 3674 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 3675 3676 /** 3677 * @hide 3678 * 3679 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3680 * out of the public fields to keep the undefined bits out of the developer's way. 3681 * 3682 * Flag to specify that the navigation bar is displayed in translucent mode. 3683 */ 3684 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 3685 3686 /** 3687 * @hide 3688 * 3689 * Makes navigation bar transparent (but not the status bar). 3690 */ 3691 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3692 3693 /** 3694 * @hide 3695 * 3696 * Makes status bar transparent (but not the navigation bar). 3697 */ 3698 public static final int STATUS_BAR_TRANSPARENT = 0x00000008; 3699 3700 /** 3701 * @hide 3702 * 3703 * Makes both status bar and navigation bar transparent. 3704 */ 3705 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3706 | STATUS_BAR_TRANSPARENT; 3707 3708 /** 3709 * @hide 3710 */ 3711 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3712 3713 /** 3714 * These are the system UI flags that can be cleared by events outside 3715 * of an application. Currently this is just the ability to tap on the 3716 * screen while hiding the navigation bar to have it return. 3717 * @hide 3718 */ 3719 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3720 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3721 | SYSTEM_UI_FLAG_FULLSCREEN; 3722 3723 /** 3724 * Flags that can impact the layout in relation to system UI. 3725 */ 3726 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3727 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3728 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3729 3730 /** @hide */ 3731 @IntDef(flag = true, prefix = { "FIND_VIEWS_" }, value = { 3732 FIND_VIEWS_WITH_TEXT, 3733 FIND_VIEWS_WITH_CONTENT_DESCRIPTION 3734 }) 3735 @Retention(RetentionPolicy.SOURCE) 3736 public @interface FindViewFlags {} 3737 3738 /** 3739 * Find views that render the specified text. 3740 * 3741 * @see #findViewsWithText(ArrayList, CharSequence, int) 3742 */ 3743 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3744 3745 /** 3746 * Find find views that contain the specified content description. 3747 * 3748 * @see #findViewsWithText(ArrayList, CharSequence, int) 3749 */ 3750 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3751 3752 /** 3753 * Find views that contain {@link AccessibilityNodeProvider}. Such 3754 * a View is a root of virtual view hierarchy and may contain the searched 3755 * text. If this flag is set Views with providers are automatically 3756 * added and it is a responsibility of the client to call the APIs of 3757 * the provider to determine whether the virtual tree rooted at this View 3758 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3759 * representing the virtual views with this text. 3760 * 3761 * @see #findViewsWithText(ArrayList, CharSequence, int) 3762 * 3763 * @hide 3764 */ 3765 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3766 3767 /** 3768 * The undefined cursor position. 3769 * 3770 * @hide 3771 */ 3772 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3773 3774 /** 3775 * Indicates that the screen has changed state and is now off. 3776 * 3777 * @see #onScreenStateChanged(int) 3778 */ 3779 public static final int SCREEN_STATE_OFF = 0x0; 3780 3781 /** 3782 * Indicates that the screen has changed state and is now on. 3783 * 3784 * @see #onScreenStateChanged(int) 3785 */ 3786 public static final int SCREEN_STATE_ON = 0x1; 3787 3788 /** 3789 * Indicates no axis of view scrolling. 3790 */ 3791 public static final int SCROLL_AXIS_NONE = 0; 3792 3793 /** 3794 * Indicates scrolling along the horizontal axis. 3795 */ 3796 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3797 3798 /** 3799 * Indicates scrolling along the vertical axis. 3800 */ 3801 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3802 3803 /** 3804 * Controls the over-scroll mode for this view. 3805 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3806 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3807 * and {@link #OVER_SCROLL_NEVER}. 3808 */ 3809 private int mOverScrollMode; 3810 3811 /** 3812 * The parent this view is attached to. 3813 * {@hide} 3814 * 3815 * @see #getParent() 3816 */ 3817 protected ViewParent mParent; 3818 3819 /** 3820 * {@hide} 3821 */ 3822 AttachInfo mAttachInfo; 3823 3824 /** 3825 * {@hide} 3826 */ 3827 @ViewDebug.ExportedProperty(flagMapping = { 3828 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3829 name = "FORCE_LAYOUT"), 3830 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3831 name = "LAYOUT_REQUIRED"), 3832 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3833 name = "DRAWING_CACHE_INVALID", outputIf = false), 3834 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3835 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3836 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3837 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3838 }, formatToHexString = true) 3839 3840 /* @hide */ 3841 public int mPrivateFlags; 3842 int mPrivateFlags2; 3843 int mPrivateFlags3; 3844 3845 /** 3846 * This view's request for the visibility of the status bar. 3847 * @hide 3848 */ 3849 @ViewDebug.ExportedProperty(flagMapping = { 3850 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3851 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3852 name = "LOW_PROFILE"), 3853 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3854 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3855 name = "HIDE_NAVIGATION"), 3856 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_FULLSCREEN, 3857 equals = SYSTEM_UI_FLAG_FULLSCREEN, 3858 name = "FULLSCREEN"), 3859 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_STABLE, 3860 equals = SYSTEM_UI_FLAG_LAYOUT_STABLE, 3861 name = "LAYOUT_STABLE"), 3862 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION, 3863 equals = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION, 3864 name = "LAYOUT_HIDE_NAVIGATION"), 3865 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, 3866 equals = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, 3867 name = "LAYOUT_FULLSCREEN"), 3868 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_IMMERSIVE, 3869 equals = SYSTEM_UI_FLAG_IMMERSIVE, 3870 name = "IMMERSIVE"), 3871 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_IMMERSIVE_STICKY, 3872 equals = SYSTEM_UI_FLAG_IMMERSIVE_STICKY, 3873 name = "IMMERSIVE_STICKY"), 3874 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LIGHT_STATUS_BAR, 3875 equals = SYSTEM_UI_FLAG_LIGHT_STATUS_BAR, 3876 name = "LIGHT_STATUS_BAR"), 3877 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR, 3878 equals = SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR, 3879 name = "LIGHT_NAVIGATION_BAR"), 3880 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_EXPAND, 3881 equals = STATUS_BAR_DISABLE_EXPAND, 3882 name = "STATUS_BAR_DISABLE_EXPAND"), 3883 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_ICONS, 3884 equals = STATUS_BAR_DISABLE_NOTIFICATION_ICONS, 3885 name = "STATUS_BAR_DISABLE_NOTIFICATION_ICONS"), 3886 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_ALERTS, 3887 equals = STATUS_BAR_DISABLE_NOTIFICATION_ALERTS, 3888 name = "STATUS_BAR_DISABLE_NOTIFICATION_ALERTS"), 3889 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_TICKER, 3890 equals = STATUS_BAR_DISABLE_NOTIFICATION_TICKER, 3891 name = "STATUS_BAR_DISABLE_NOTIFICATION_TICKER"), 3892 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_SYSTEM_INFO, 3893 equals = STATUS_BAR_DISABLE_SYSTEM_INFO, 3894 name = "STATUS_BAR_DISABLE_SYSTEM_INFO"), 3895 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_HOME, 3896 equals = STATUS_BAR_DISABLE_HOME, 3897 name = "STATUS_BAR_DISABLE_HOME"), 3898 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_BACK, 3899 equals = STATUS_BAR_DISABLE_BACK, 3900 name = "STATUS_BAR_DISABLE_BACK"), 3901 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_CLOCK, 3902 equals = STATUS_BAR_DISABLE_CLOCK, 3903 name = "STATUS_BAR_DISABLE_CLOCK"), 3904 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_RECENT, 3905 equals = STATUS_BAR_DISABLE_RECENT, 3906 name = "STATUS_BAR_DISABLE_RECENT"), 3907 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_SEARCH, 3908 equals = STATUS_BAR_DISABLE_SEARCH, 3909 name = "STATUS_BAR_DISABLE_SEARCH"), 3910 @ViewDebug.FlagToString(mask = STATUS_BAR_TRANSIENT, 3911 equals = STATUS_BAR_TRANSIENT, 3912 name = "STATUS_BAR_TRANSIENT"), 3913 @ViewDebug.FlagToString(mask = NAVIGATION_BAR_TRANSIENT, 3914 equals = NAVIGATION_BAR_TRANSIENT, 3915 name = "NAVIGATION_BAR_TRANSIENT"), 3916 @ViewDebug.FlagToString(mask = STATUS_BAR_UNHIDE, 3917 equals = STATUS_BAR_UNHIDE, 3918 name = "STATUS_BAR_UNHIDE"), 3919 @ViewDebug.FlagToString(mask = NAVIGATION_BAR_UNHIDE, 3920 equals = NAVIGATION_BAR_UNHIDE, 3921 name = "NAVIGATION_BAR_UNHIDE"), 3922 @ViewDebug.FlagToString(mask = STATUS_BAR_TRANSLUCENT, 3923 equals = STATUS_BAR_TRANSLUCENT, 3924 name = "STATUS_BAR_TRANSLUCENT"), 3925 @ViewDebug.FlagToString(mask = NAVIGATION_BAR_TRANSLUCENT, 3926 equals = NAVIGATION_BAR_TRANSLUCENT, 3927 name = "NAVIGATION_BAR_TRANSLUCENT"), 3928 @ViewDebug.FlagToString(mask = NAVIGATION_BAR_TRANSPARENT, 3929 equals = NAVIGATION_BAR_TRANSPARENT, 3930 name = "NAVIGATION_BAR_TRANSPARENT"), 3931 @ViewDebug.FlagToString(mask = STATUS_BAR_TRANSPARENT, 3932 equals = STATUS_BAR_TRANSPARENT, 3933 name = "STATUS_BAR_TRANSPARENT") 3934 }, formatToHexString = true) 3935 int mSystemUiVisibility; 3936 3937 /** 3938 * Reference count for transient state. 3939 * @see #setHasTransientState(boolean) 3940 */ 3941 int mTransientStateCount = 0; 3942 3943 /** 3944 * Count of how many windows this view has been attached to. 3945 */ 3946 int mWindowAttachCount; 3947 3948 /** 3949 * The layout parameters associated with this view and used by the parent 3950 * {@link android.view.ViewGroup} to determine how this view should be 3951 * laid out. 3952 * {@hide} 3953 */ 3954 protected ViewGroup.LayoutParams mLayoutParams; 3955 3956 /** 3957 * The view flags hold various views states. 3958 * {@hide} 3959 */ 3960 @ViewDebug.ExportedProperty(formatToHexString = true) 3961 int mViewFlags; 3962 3963 static class TransformationInfo { 3964 /** 3965 * The transform matrix for the View. This transform is calculated internally 3966 * based on the translation, rotation, and scale properties. 3967 * 3968 * Do *not* use this variable directly; instead call getMatrix(), which will 3969 * load the value from the View's RenderNode. 3970 */ 3971 private final Matrix mMatrix = new Matrix(); 3972 3973 /** 3974 * The inverse transform matrix for the View. This transform is calculated 3975 * internally based on the translation, rotation, and scale properties. 3976 * 3977 * Do *not* use this variable directly; instead call getInverseMatrix(), 3978 * which will load the value from the View's RenderNode. 3979 */ 3980 private Matrix mInverseMatrix; 3981 3982 /** 3983 * The opacity of the View. This is a value from 0 to 1, where 0 means 3984 * completely transparent and 1 means completely opaque. 3985 */ 3986 @ViewDebug.ExportedProperty 3987 float mAlpha = 1f; 3988 3989 /** 3990 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3991 * property only used by transitions, which is composited with the other alpha 3992 * values to calculate the final visual alpha value. 3993 */ 3994 float mTransitionAlpha = 1f; 3995 } 3996 3997 /** @hide */ 3998 public TransformationInfo mTransformationInfo; 3999 4000 /** 4001 * Current clip bounds. to which all drawing of this view are constrained. 4002 */ 4003 @ViewDebug.ExportedProperty(category = "drawing") 4004 Rect mClipBounds = null; 4005 4006 private boolean mLastIsOpaque; 4007 4008 /** 4009 * The distance in pixels from the left edge of this view's parent 4010 * to the left edge of this view. 4011 * {@hide} 4012 */ 4013 @ViewDebug.ExportedProperty(category = "layout") 4014 protected int mLeft; 4015 /** 4016 * The distance in pixels from the left edge of this view's parent 4017 * to the right edge of this view. 4018 * {@hide} 4019 */ 4020 @ViewDebug.ExportedProperty(category = "layout") 4021 protected int mRight; 4022 /** 4023 * The distance in pixels from the top edge of this view's parent 4024 * to the top edge of this view. 4025 * {@hide} 4026 */ 4027 @ViewDebug.ExportedProperty(category = "layout") 4028 protected int mTop; 4029 /** 4030 * The distance in pixels from the top edge of this view's parent 4031 * to the bottom edge of this view. 4032 * {@hide} 4033 */ 4034 @ViewDebug.ExportedProperty(category = "layout") 4035 protected int mBottom; 4036 4037 /** 4038 * The offset, in pixels, by which the content of this view is scrolled 4039 * horizontally. 4040 * {@hide} 4041 */ 4042 @ViewDebug.ExportedProperty(category = "scrolling") 4043 protected int mScrollX; 4044 /** 4045 * The offset, in pixels, by which the content of this view is scrolled 4046 * vertically. 4047 * {@hide} 4048 */ 4049 @ViewDebug.ExportedProperty(category = "scrolling") 4050 protected int mScrollY; 4051 4052 /** 4053 * The left padding in pixels, that is the distance in pixels between the 4054 * left edge of this view and the left edge of its content. 4055 * {@hide} 4056 */ 4057 @ViewDebug.ExportedProperty(category = "padding") 4058 protected int mPaddingLeft = 0; 4059 /** 4060 * The right padding in pixels, that is the distance in pixels between the 4061 * right edge of this view and the right edge of its content. 4062 * {@hide} 4063 */ 4064 @ViewDebug.ExportedProperty(category = "padding") 4065 protected int mPaddingRight = 0; 4066 /** 4067 * The top padding in pixels, that is the distance in pixels between the 4068 * top edge of this view and the top edge of its content. 4069 * {@hide} 4070 */ 4071 @ViewDebug.ExportedProperty(category = "padding") 4072 protected int mPaddingTop; 4073 /** 4074 * The bottom padding in pixels, that is the distance in pixels between the 4075 * bottom edge of this view and the bottom edge of its content. 4076 * {@hide} 4077 */ 4078 @ViewDebug.ExportedProperty(category = "padding") 4079 protected int mPaddingBottom; 4080 4081 /** 4082 * The layout insets in pixels, that is the distance in pixels between the 4083 * visible edges of this view its bounds. 4084 */ 4085 private Insets mLayoutInsets; 4086 4087 /** 4088 * Briefly describes the view and is primarily used for accessibility support. 4089 */ 4090 private CharSequence mContentDescription; 4091 4092 /** 4093 * If this view represents a distinct part of the window, it can have a title that labels the 4094 * area. 4095 */ 4096 private CharSequence mAccessibilityPaneTitle; 4097 4098 /** 4099 * Specifies the id of a view for which this view serves as a label for 4100 * accessibility purposes. 4101 */ 4102 private int mLabelForId = View.NO_ID; 4103 4104 /** 4105 * Predicate for matching labeled view id with its label for 4106 * accessibility purposes. 4107 */ 4108 private MatchLabelForPredicate mMatchLabelForPredicate; 4109 4110 /** 4111 * Specifies a view before which this one is visited in accessibility traversal. 4112 */ 4113 private int mAccessibilityTraversalBeforeId = NO_ID; 4114 4115 /** 4116 * Specifies a view after which this one is visited in accessibility traversal. 4117 */ 4118 private int mAccessibilityTraversalAfterId = NO_ID; 4119 4120 /** 4121 * Predicate for matching a view by its id. 4122 */ 4123 private MatchIdPredicate mMatchIdPredicate; 4124 4125 /** 4126 * Cache the paddingRight set by the user to append to the scrollbar's size. 4127 * 4128 * @hide 4129 */ 4130 @ViewDebug.ExportedProperty(category = "padding") 4131 protected int mUserPaddingRight; 4132 4133 /** 4134 * Cache the paddingBottom set by the user to append to the scrollbar's size. 4135 * 4136 * @hide 4137 */ 4138 @ViewDebug.ExportedProperty(category = "padding") 4139 protected int mUserPaddingBottom; 4140 4141 /** 4142 * Cache the paddingLeft set by the user to append to the scrollbar's size. 4143 * 4144 * @hide 4145 */ 4146 @ViewDebug.ExportedProperty(category = "padding") 4147 protected int mUserPaddingLeft; 4148 4149 /** 4150 * Cache the paddingStart set by the user to append to the scrollbar's size. 4151 * 4152 */ 4153 @ViewDebug.ExportedProperty(category = "padding") 4154 int mUserPaddingStart; 4155 4156 /** 4157 * Cache the paddingEnd set by the user to append to the scrollbar's size. 4158 * 4159 */ 4160 @ViewDebug.ExportedProperty(category = "padding") 4161 int mUserPaddingEnd; 4162 4163 /** 4164 * Cache initial left padding. 4165 * 4166 * @hide 4167 */ 4168 int mUserPaddingLeftInitial; 4169 4170 /** 4171 * Cache initial right padding. 4172 * 4173 * @hide 4174 */ 4175 int mUserPaddingRightInitial; 4176 4177 /** 4178 * Default undefined padding 4179 */ 4180 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 4181 4182 /** 4183 * Cache if a left padding has been defined 4184 */ 4185 private boolean mLeftPaddingDefined = false; 4186 4187 /** 4188 * Cache if a right padding has been defined 4189 */ 4190 private boolean mRightPaddingDefined = false; 4191 4192 /** 4193 * @hide 4194 */ 4195 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 4196 /** 4197 * @hide 4198 */ 4199 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 4200 4201 private LongSparseLongArray mMeasureCache; 4202 4203 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 4204 private Drawable mBackground; 4205 private TintInfo mBackgroundTint; 4206 4207 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 4208 private ForegroundInfo mForegroundInfo; 4209 4210 private Drawable mScrollIndicatorDrawable; 4211 4212 /** 4213 * RenderNode used for backgrounds. 4214 * <p> 4215 * When non-null and valid, this is expected to contain an up-to-date copy 4216 * of the background drawable. It is cleared on temporary detach, and reset 4217 * on cleanup. 4218 */ 4219 private RenderNode mBackgroundRenderNode; 4220 4221 private int mBackgroundResource; 4222 private boolean mBackgroundSizeChanged; 4223 4224 /** The default focus highlight. 4225 * @see #mDefaultFocusHighlightEnabled 4226 * @see Drawable#hasFocusStateSpecified() 4227 */ 4228 private Drawable mDefaultFocusHighlight; 4229 private Drawable mDefaultFocusHighlightCache; 4230 private boolean mDefaultFocusHighlightSizeChanged; 4231 /** 4232 * True if the default focus highlight is needed on the target device. 4233 */ 4234 private static boolean sUseDefaultFocusHighlight; 4235 4236 /** 4237 * True if zero-sized views can be focused. 4238 */ 4239 private static boolean sCanFocusZeroSized; 4240 4241 /** 4242 * Always assign focus if a focusable View is available. 4243 */ 4244 private static boolean sAlwaysAssignFocus; 4245 4246 private String mTransitionName; 4247 4248 static class TintInfo { 4249 ColorStateList mTintList; 4250 PorterDuff.Mode mTintMode; 4251 boolean mHasTintMode; 4252 boolean mHasTintList; 4253 } 4254 4255 private static class ForegroundInfo { 4256 private Drawable mDrawable; 4257 private TintInfo mTintInfo; 4258 private int mGravity = Gravity.FILL; 4259 private boolean mInsidePadding = true; 4260 private boolean mBoundsChanged = true; 4261 private final Rect mSelfBounds = new Rect(); 4262 private final Rect mOverlayBounds = new Rect(); 4263 } 4264 4265 static class ListenerInfo { 4266 /** 4267 * Listener used to dispatch focus change events. 4268 * This field should be made private, so it is hidden from the SDK. 4269 * {@hide} 4270 */ 4271 protected OnFocusChangeListener mOnFocusChangeListener; 4272 4273 /** 4274 * Listeners for layout change events. 4275 */ 4276 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 4277 4278 protected OnScrollChangeListener mOnScrollChangeListener; 4279 4280 /** 4281 * Listeners for attach events. 4282 */ 4283 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 4284 4285 /** 4286 * Listener used to dispatch click events. 4287 * This field should be made private, so it is hidden from the SDK. 4288 * {@hide} 4289 */ 4290 public OnClickListener mOnClickListener; 4291 4292 /** 4293 * Listener used to dispatch long click events. 4294 * This field should be made private, so it is hidden from the SDK. 4295 * {@hide} 4296 */ 4297 protected OnLongClickListener mOnLongClickListener; 4298 4299 /** 4300 * Listener used to dispatch context click events. This field should be made private, so it 4301 * is hidden from the SDK. 4302 * {@hide} 4303 */ 4304 protected OnContextClickListener mOnContextClickListener; 4305 4306 /** 4307 * Listener used to build the context menu. 4308 * This field should be made private, so it is hidden from the SDK. 4309 * {@hide} 4310 */ 4311 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 4312 4313 private OnKeyListener mOnKeyListener; 4314 4315 private OnTouchListener mOnTouchListener; 4316 4317 private OnHoverListener mOnHoverListener; 4318 4319 private OnGenericMotionListener mOnGenericMotionListener; 4320 4321 private OnDragListener mOnDragListener; 4322 4323 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 4324 4325 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 4326 4327 OnCapturedPointerListener mOnCapturedPointerListener; 4328 4329 private ArrayList<OnUnhandledKeyEventListener> mUnhandledKeyListeners; 4330 } 4331 4332 ListenerInfo mListenerInfo; 4333 4334 private static class TooltipInfo { 4335 /** 4336 * Text to be displayed in a tooltip popup. 4337 */ 4338 @Nullable 4339 CharSequence mTooltipText; 4340 4341 /** 4342 * View-relative position of the tooltip anchor point. 4343 */ 4344 int mAnchorX; 4345 int mAnchorY; 4346 4347 /** 4348 * The tooltip popup. 4349 */ 4350 @Nullable 4351 TooltipPopup mTooltipPopup; 4352 4353 /** 4354 * Set to true if the tooltip was shown as a result of a long click. 4355 */ 4356 boolean mTooltipFromLongClick; 4357 4358 /** 4359 * Keep these Runnables so that they can be used to reschedule. 4360 */ 4361 Runnable mShowTooltipRunnable; 4362 Runnable mHideTooltipRunnable; 4363 4364 /** 4365 * Hover move is ignored if it is within this distance in pixels from the previous one. 4366 */ 4367 int mHoverSlop; 4368 4369 /** 4370 * Update the anchor position if it significantly (that is by at least mHoverSlop) 4371 * different from the previously stored position. Ignoring insignificant changes 4372 * filters out the jitter which is typical for such input sources as stylus. 4373 * 4374 * @return True if the position has been updated. 4375 */ 4376 private boolean updateAnchorPos(MotionEvent event) { 4377 final int newAnchorX = (int) event.getX(); 4378 final int newAnchorY = (int) event.getY(); 4379 if (Math.abs(newAnchorX - mAnchorX) <= mHoverSlop 4380 && Math.abs(newAnchorY - mAnchorY) <= mHoverSlop) { 4381 return false; 4382 } 4383 mAnchorX = newAnchorX; 4384 mAnchorY = newAnchorY; 4385 return true; 4386 } 4387 4388 /** 4389 * Clear the anchor position to ensure that the next change is considered significant. 4390 */ 4391 private void clearAnchorPos() { 4392 mAnchorX = Integer.MAX_VALUE; 4393 mAnchorY = Integer.MAX_VALUE; 4394 } 4395 } 4396 4397 TooltipInfo mTooltipInfo; 4398 4399 // Temporary values used to hold (x,y) coordinates when delegating from the 4400 // two-arg performLongClick() method to the legacy no-arg version. 4401 private float mLongClickX = Float.NaN; 4402 private float mLongClickY = Float.NaN; 4403 4404 /** 4405 * The application environment this view lives in. 4406 * This field should be made private, so it is hidden from the SDK. 4407 * {@hide} 4408 */ 4409 @ViewDebug.ExportedProperty(deepExport = true) 4410 protected Context mContext; 4411 4412 private final Resources mResources; 4413 4414 private ScrollabilityCache mScrollCache; 4415 4416 private int[] mDrawableState = null; 4417 4418 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 4419 4420 /** 4421 * Animator that automatically runs based on state changes. 4422 */ 4423 private StateListAnimator mStateListAnimator; 4424 4425 /** 4426 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 4427 * the user may specify which view to go to next. 4428 */ 4429 private int mNextFocusLeftId = View.NO_ID; 4430 4431 /** 4432 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 4433 * the user may specify which view to go to next. 4434 */ 4435 private int mNextFocusRightId = View.NO_ID; 4436 4437 /** 4438 * When this view has focus and the next focus is {@link #FOCUS_UP}, 4439 * the user may specify which view to go to next. 4440 */ 4441 private int mNextFocusUpId = View.NO_ID; 4442 4443 /** 4444 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 4445 * the user may specify which view to go to next. 4446 */ 4447 private int mNextFocusDownId = View.NO_ID; 4448 4449 /** 4450 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 4451 * the user may specify which view to go to next. 4452 */ 4453 int mNextFocusForwardId = View.NO_ID; 4454 4455 /** 4456 * User-specified next keyboard navigation cluster in the {@link #FOCUS_FORWARD} direction. 4457 * 4458 * @see #findUserSetNextKeyboardNavigationCluster(View, int) 4459 */ 4460 int mNextClusterForwardId = View.NO_ID; 4461 4462 /** 4463 * Whether this View should use a default focus highlight when it gets focused but doesn't 4464 * have {@link android.R.attr#state_focused} defined in its background. 4465 */ 4466 boolean mDefaultFocusHighlightEnabled = true; 4467 4468 private CheckForLongPress mPendingCheckForLongPress; 4469 private CheckForTap mPendingCheckForTap = null; 4470 private PerformClick mPerformClick; 4471 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 4472 4473 private UnsetPressedState mUnsetPressedState; 4474 4475 /** 4476 * Whether the long press's action has been invoked. The tap's action is invoked on the 4477 * up event while a long press is invoked as soon as the long press duration is reached, so 4478 * a long press could be performed before the tap is checked, in which case the tap's action 4479 * should not be invoked. 4480 */ 4481 private boolean mHasPerformedLongPress; 4482 4483 /** 4484 * Whether a context click button is currently pressed down. This is true when the stylus is 4485 * touching the screen and the primary button has been pressed, or if a mouse's right button is 4486 * pressed. This is false once the button is released or if the stylus has been lifted. 4487 */ 4488 private boolean mInContextButtonPress; 4489 4490 /** 4491 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 4492 * true after a stylus button press has occured, when the next up event should not be recognized 4493 * as a tap. 4494 */ 4495 private boolean mIgnoreNextUpEvent; 4496 4497 /** 4498 * The minimum height of the view. We'll try our best to have the height 4499 * of this view to at least this amount. 4500 */ 4501 @ViewDebug.ExportedProperty(category = "measurement") 4502 private int mMinHeight; 4503 4504 /** 4505 * The minimum width of the view. We'll try our best to have the width 4506 * of this view to at least this amount. 4507 */ 4508 @ViewDebug.ExportedProperty(category = "measurement") 4509 private int mMinWidth; 4510 4511 /** 4512 * The delegate to handle touch events that are physically in this view 4513 * but should be handled by another view. 4514 */ 4515 private TouchDelegate mTouchDelegate = null; 4516 4517 /** 4518 * Solid color to use as a background when creating the drawing cache. Enables 4519 * the cache to use 16 bit bitmaps instead of 32 bit. 4520 */ 4521 private int mDrawingCacheBackgroundColor = 0; 4522 4523 /** 4524 * Special tree observer used when mAttachInfo is null. 4525 */ 4526 private ViewTreeObserver mFloatingTreeObserver; 4527 4528 /** 4529 * Cache the touch slop from the context that created the view. 4530 */ 4531 private int mTouchSlop; 4532 4533 /** 4534 * Object that handles automatic animation of view properties. 4535 */ 4536 private ViewPropertyAnimator mAnimator = null; 4537 4538 /** 4539 * List of registered FrameMetricsObservers. 4540 */ 4541 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 4542 4543 /** 4544 * Flag indicating that a drag can cross window boundaries. When 4545 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 4546 * with this flag set, all visible applications with targetSdkVersion >= 4547 * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate 4548 * in the drag operation and receive the dragged content. 4549 * 4550 * <p>If this is the only flag set, then the drag recipient will only have access to text data 4551 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 4552 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p> 4553 */ 4554 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 4555 4556 /** 4557 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 4558 * request read access to the content URI(s) contained in the {@link ClipData} object. 4559 * @see android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION 4560 */ 4561 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 4562 4563 /** 4564 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 4565 * request write access to the content URI(s) contained in the {@link ClipData} object. 4566 * @see android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION 4567 */ 4568 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 4569 4570 /** 4571 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 4572 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 4573 * reboots until explicitly revoked with 4574 * {@link android.content.Context#revokeUriPermission(Uri, int)} Context.revokeUriPermission}. 4575 * @see android.content.Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION 4576 */ 4577 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 4578 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 4579 4580 /** 4581 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 4582 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix 4583 * match against the original granted URI. 4584 * @see android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION 4585 */ 4586 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 4587 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 4588 4589 /** 4590 * Flag indicating that the drag shadow will be opaque. When 4591 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 4592 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 4593 */ 4594 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 4595 4596 /** 4597 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 4598 */ 4599 private float mVerticalScrollFactor; 4600 4601 /** 4602 * Position of the vertical scroll bar. 4603 */ 4604 private int mVerticalScrollbarPosition; 4605 4606 /** 4607 * Position the scroll bar at the default position as determined by the system. 4608 */ 4609 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 4610 4611 /** 4612 * Position the scroll bar along the left edge. 4613 */ 4614 public static final int SCROLLBAR_POSITION_LEFT = 1; 4615 4616 /** 4617 * Position the scroll bar along the right edge. 4618 */ 4619 public static final int SCROLLBAR_POSITION_RIGHT = 2; 4620 4621 /** 4622 * Indicates that the view does not have a layer. 4623 * 4624 * @see #getLayerType() 4625 * @see #setLayerType(int, android.graphics.Paint) 4626 * @see #LAYER_TYPE_SOFTWARE 4627 * @see #LAYER_TYPE_HARDWARE 4628 */ 4629 public static final int LAYER_TYPE_NONE = 0; 4630 4631 /** 4632 * <p>Indicates that the view has a software layer. A software layer is backed 4633 * by a bitmap and causes the view to be rendered using Android's software 4634 * rendering pipeline, even if hardware acceleration is enabled.</p> 4635 * 4636 * <p>Software layers have various usages:</p> 4637 * <p>When the application is not using hardware acceleration, a software layer 4638 * is useful to apply a specific color filter and/or blending mode and/or 4639 * translucency to a view and all its children.</p> 4640 * <p>When the application is using hardware acceleration, a software layer 4641 * is useful to render drawing primitives not supported by the hardware 4642 * accelerated pipeline. It can also be used to cache a complex view tree 4643 * into a texture and reduce the complexity of drawing operations. For instance, 4644 * when animating a complex view tree with a translation, a software layer can 4645 * be used to render the view tree only once.</p> 4646 * <p>Software layers should be avoided when the affected view tree updates 4647 * often. Every update will require to re-render the software layer, which can 4648 * potentially be slow (particularly when hardware acceleration is turned on 4649 * since the layer will have to be uploaded into a hardware texture after every 4650 * update.)</p> 4651 * 4652 * @see #getLayerType() 4653 * @see #setLayerType(int, android.graphics.Paint) 4654 * @see #LAYER_TYPE_NONE 4655 * @see #LAYER_TYPE_HARDWARE 4656 */ 4657 public static final int LAYER_TYPE_SOFTWARE = 1; 4658 4659 /** 4660 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 4661 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 4662 * OpenGL hardware) and causes the view to be rendered using Android's hardware 4663 * rendering pipeline, but only if hardware acceleration is turned on for the 4664 * view hierarchy. When hardware acceleration is turned off, hardware layers 4665 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 4666 * 4667 * <p>A hardware layer is useful to apply a specific color filter and/or 4668 * blending mode and/or translucency to a view and all its children.</p> 4669 * <p>A hardware layer can be used to cache a complex view tree into a 4670 * texture and reduce the complexity of drawing operations. For instance, 4671 * when animating a complex view tree with a translation, a hardware layer can 4672 * be used to render the view tree only once.</p> 4673 * <p>A hardware layer can also be used to increase the rendering quality when 4674 * rotation transformations are applied on a view. It can also be used to 4675 * prevent potential clipping issues when applying 3D transforms on a view.</p> 4676 * 4677 * @see #getLayerType() 4678 * @see #setLayerType(int, android.graphics.Paint) 4679 * @see #LAYER_TYPE_NONE 4680 * @see #LAYER_TYPE_SOFTWARE 4681 */ 4682 public static final int LAYER_TYPE_HARDWARE = 2; 4683 4684 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 4685 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 4686 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 4687 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 4688 }) 4689 int mLayerType = LAYER_TYPE_NONE; 4690 Paint mLayerPaint; 4691 4692 /** 4693 * Set to true when drawing cache is enabled and cannot be created. 4694 * 4695 * @hide 4696 */ 4697 public boolean mCachingFailed; 4698 private Bitmap mDrawingCache; 4699 private Bitmap mUnscaledDrawingCache; 4700 4701 /** 4702 * RenderNode holding View properties, potentially holding a DisplayList of View content. 4703 * <p> 4704 * When non-null and valid, this is expected to contain an up-to-date copy 4705 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 4706 * cleanup. 4707 */ 4708 final RenderNode mRenderNode; 4709 4710 /** 4711 * Set to true when the view is sending hover accessibility events because it 4712 * is the innermost hovered view. 4713 */ 4714 private boolean mSendingHoverAccessibilityEvents; 4715 4716 /** 4717 * Delegate for injecting accessibility functionality. 4718 */ 4719 AccessibilityDelegate mAccessibilityDelegate; 4720 4721 /** 4722 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 4723 * and add/remove objects to/from the overlay directly through the Overlay methods. 4724 */ 4725 ViewOverlay mOverlay; 4726 4727 /** 4728 * The currently active parent view for receiving delegated nested scrolling events. 4729 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 4730 * by {@link #stopNestedScroll()} at the same point where we clear 4731 * requestDisallowInterceptTouchEvent. 4732 */ 4733 private ViewParent mNestedScrollingParent; 4734 4735 /** 4736 * Consistency verifier for debugging purposes. 4737 * @hide 4738 */ 4739 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 4740 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 4741 new InputEventConsistencyVerifier(this, 0) : null; 4742 4743 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 4744 4745 private int[] mTempNestedScrollConsumed; 4746 4747 /** 4748 * An overlay is going to draw this View instead of being drawn as part of this 4749 * View's parent. mGhostView is the View in the Overlay that must be invalidated 4750 * when this view is invalidated. 4751 */ 4752 GhostView mGhostView; 4753 4754 /** 4755 * Holds pairs of adjacent attribute data: attribute name followed by its value. 4756 * @hide 4757 */ 4758 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 4759 public String[] mAttributes; 4760 4761 /** 4762 * Maps a Resource id to its name. 4763 */ 4764 private static SparseArray<String> mAttributeMap; 4765 4766 /** 4767 * Queue of pending runnables. Used to postpone calls to post() until this 4768 * view is attached and has a handler. 4769 */ 4770 private HandlerActionQueue mRunQueue; 4771 4772 /** 4773 * The pointer icon when the mouse hovers on this view. The default is null. 4774 */ 4775 private PointerIcon mPointerIcon; 4776 4777 /** 4778 * @hide 4779 */ 4780 String mStartActivityRequestWho; 4781 4782 @Nullable 4783 private RoundScrollbarRenderer mRoundScrollbarRenderer; 4784 4785 /** Used to delay visibility updates sent to the autofill manager */ 4786 private Handler mVisibilityChangeForAutofillHandler; 4787 4788 /** 4789 * Simple constructor to use when creating a view from code. 4790 * 4791 * @param context The Context the view is running in, through which it can 4792 * access the current theme, resources, etc. 4793 */ 4794 public View(Context context) { 4795 mContext = context; 4796 mResources = context != null ? context.getResources() : null; 4797 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO; 4798 // Set some flags defaults 4799 mPrivateFlags2 = 4800 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 4801 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 4802 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 4803 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 4804 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 4805 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 4806 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 4807 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 4808 mUserPaddingStart = UNDEFINED_PADDING; 4809 mUserPaddingEnd = UNDEFINED_PADDING; 4810 mRenderNode = RenderNode.create(getClass().getName(), this); 4811 4812 if (!sCompatibilityDone && context != null) { 4813 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4814 4815 // Older apps may need this compatibility hack for measurement. 4816 sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1; 4817 4818 // Older apps expect onMeasure() to always be called on a layout pass, regardless 4819 // of whether a layout was requested on that View. 4820 sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT; 4821 4822 Canvas.sCompatibilityRestore = targetSdkVersion < Build.VERSION_CODES.M; 4823 Canvas.sCompatibilitySetBitmap = targetSdkVersion < Build.VERSION_CODES.O; 4824 Canvas.setCompatibilityVersion(targetSdkVersion); 4825 4826 // In M and newer, our widgets can pass a "hint" value in the size 4827 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 4828 // know what the expected parent size is going to be, so e.g. list items can size 4829 // themselves at 1/3 the size of their container. It breaks older apps though, 4830 // specifically apps that use some popular open source libraries. 4831 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M; 4832 4833 // Old versions of the platform would give different results from 4834 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 4835 // modes, so we always need to run an additional EXACTLY pass. 4836 sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M; 4837 4838 // Prior to N, layout params could change without requiring a 4839 // subsequent call to setLayoutParams() and they would usually 4840 // work. Partial layout breaks this assumption. 4841 sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M; 4842 4843 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4844 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4845 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M; 4846 4847 // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs 4848 // in apps so we target check it to avoid breaking existing apps. 4849 sPreserveMarginParamsInLayoutParamConversion = 4850 targetSdkVersion >= Build.VERSION_CODES.N; 4851 4852 sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N; 4853 4854 sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O; 4855 4856 sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O; 4857 4858 sUseDefaultFocusHighlight = context.getResources().getBoolean( 4859 com.android.internal.R.bool.config_useDefaultFocusHighlight); 4860 4861 sThrowOnInvalidFloatProperties = targetSdkVersion >= Build.VERSION_CODES.P; 4862 4863 sCanFocusZeroSized = targetSdkVersion < Build.VERSION_CODES.P; 4864 4865 sAlwaysAssignFocus = targetSdkVersion < Build.VERSION_CODES.P; 4866 4867 sAcceptZeroSizeDragShadow = targetSdkVersion < Build.VERSION_CODES.P; 4868 4869 sCompatibilityDone = true; 4870 } 4871 } 4872 4873 /** 4874 * Constructor that is called when inflating a view from XML. This is called 4875 * when a view is being constructed from an XML file, supplying attributes 4876 * that were specified in the XML file. This version uses a default style of 4877 * 0, so the only attribute values applied are those in the Context's Theme 4878 * and the given AttributeSet. 4879 * 4880 * <p> 4881 * The method onFinishInflate() will be called after all children have been 4882 * added. 4883 * 4884 * @param context The Context the view is running in, through which it can 4885 * access the current theme, resources, etc. 4886 * @param attrs The attributes of the XML tag that is inflating the view. 4887 * @see #View(Context, AttributeSet, int) 4888 */ 4889 public View(Context context, @Nullable AttributeSet attrs) { 4890 this(context, attrs, 0); 4891 } 4892 4893 /** 4894 * Perform inflation from XML and apply a class-specific base style from a 4895 * theme attribute. This constructor of View allows subclasses to use their 4896 * own base style when they are inflating. For example, a Button class's 4897 * constructor would call this version of the super class constructor and 4898 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4899 * allows the theme's button style to modify all of the base view attributes 4900 * (in particular its background) as well as the Button class's attributes. 4901 * 4902 * @param context The Context the view is running in, through which it can 4903 * access the current theme, resources, etc. 4904 * @param attrs The attributes of the XML tag that is inflating the view. 4905 * @param defStyleAttr An attribute in the current theme that contains a 4906 * reference to a style resource that supplies default values for 4907 * the view. Can be 0 to not look for defaults. 4908 * @see #View(Context, AttributeSet) 4909 */ 4910 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4911 this(context, attrs, defStyleAttr, 0); 4912 } 4913 4914 /** 4915 * Perform inflation from XML and apply a class-specific base style from a 4916 * theme attribute or style resource. This constructor of View allows 4917 * subclasses to use their own base style when they are inflating. 4918 * <p> 4919 * When determining the final value of a particular attribute, there are 4920 * four inputs that come into play: 4921 * <ol> 4922 * <li>Any attribute values in the given AttributeSet. 4923 * <li>The style resource specified in the AttributeSet (named "style"). 4924 * <li>The default style specified by <var>defStyleAttr</var>. 4925 * <li>The default style specified by <var>defStyleRes</var>. 4926 * <li>The base values in this theme. 4927 * </ol> 4928 * <p> 4929 * Each of these inputs is considered in-order, with the first listed taking 4930 * precedence over the following ones. In other words, if in the 4931 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4932 * , then the button's text will <em>always</em> be black, regardless of 4933 * what is specified in any of the styles. 4934 * 4935 * @param context The Context the view is running in, through which it can 4936 * access the current theme, resources, etc. 4937 * @param attrs The attributes of the XML tag that is inflating the view. 4938 * @param defStyleAttr An attribute in the current theme that contains a 4939 * reference to a style resource that supplies default values for 4940 * the view. Can be 0 to not look for defaults. 4941 * @param defStyleRes A resource identifier of a style resource that 4942 * supplies default values for the view, used only if 4943 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4944 * to not look for defaults. 4945 * @see #View(Context, AttributeSet, int) 4946 */ 4947 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4948 this(context); 4949 4950 final TypedArray a = context.obtainStyledAttributes( 4951 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4952 4953 if (mDebugViewAttributes) { 4954 saveAttributeData(attrs, a); 4955 } 4956 4957 Drawable background = null; 4958 4959 int leftPadding = -1; 4960 int topPadding = -1; 4961 int rightPadding = -1; 4962 int bottomPadding = -1; 4963 int startPadding = UNDEFINED_PADDING; 4964 int endPadding = UNDEFINED_PADDING; 4965 4966 int padding = -1; 4967 int paddingHorizontal = -1; 4968 int paddingVertical = -1; 4969 4970 int viewFlagValues = 0; 4971 int viewFlagMasks = 0; 4972 4973 boolean setScrollContainer = false; 4974 4975 int x = 0; 4976 int y = 0; 4977 4978 float tx = 0; 4979 float ty = 0; 4980 float tz = 0; 4981 float elevation = 0; 4982 float rotation = 0; 4983 float rotationX = 0; 4984 float rotationY = 0; 4985 float sx = 1f; 4986 float sy = 1f; 4987 boolean transformSet = false; 4988 4989 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4990 int overScrollMode = mOverScrollMode; 4991 boolean initializeScrollbars = false; 4992 boolean initializeScrollIndicators = false; 4993 4994 boolean startPaddingDefined = false; 4995 boolean endPaddingDefined = false; 4996 boolean leftPaddingDefined = false; 4997 boolean rightPaddingDefined = false; 4998 4999 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 5000 5001 // Set default values. 5002 viewFlagValues |= FOCUSABLE_AUTO; 5003 viewFlagMasks |= FOCUSABLE_AUTO; 5004 5005 final int N = a.getIndexCount(); 5006 for (int i = 0; i < N; i++) { 5007 int attr = a.getIndex(i); 5008 switch (attr) { 5009 case com.android.internal.R.styleable.View_background: 5010 background = a.getDrawable(attr); 5011 break; 5012 case com.android.internal.R.styleable.View_padding: 5013 padding = a.getDimensionPixelSize(attr, -1); 5014 mUserPaddingLeftInitial = padding; 5015 mUserPaddingRightInitial = padding; 5016 leftPaddingDefined = true; 5017 rightPaddingDefined = true; 5018 break; 5019 case com.android.internal.R.styleable.View_paddingHorizontal: 5020 paddingHorizontal = a.getDimensionPixelSize(attr, -1); 5021 mUserPaddingLeftInitial = paddingHorizontal; 5022 mUserPaddingRightInitial = paddingHorizontal; 5023 leftPaddingDefined = true; 5024 rightPaddingDefined = true; 5025 break; 5026 case com.android.internal.R.styleable.View_paddingVertical: 5027 paddingVertical = a.getDimensionPixelSize(attr, -1); 5028 break; 5029 case com.android.internal.R.styleable.View_paddingLeft: 5030 leftPadding = a.getDimensionPixelSize(attr, -1); 5031 mUserPaddingLeftInitial = leftPadding; 5032 leftPaddingDefined = true; 5033 break; 5034 case com.android.internal.R.styleable.View_paddingTop: 5035 topPadding = a.getDimensionPixelSize(attr, -1); 5036 break; 5037 case com.android.internal.R.styleable.View_paddingRight: 5038 rightPadding = a.getDimensionPixelSize(attr, -1); 5039 mUserPaddingRightInitial = rightPadding; 5040 rightPaddingDefined = true; 5041 break; 5042 case com.android.internal.R.styleable.View_paddingBottom: 5043 bottomPadding = a.getDimensionPixelSize(attr, -1); 5044 break; 5045 case com.android.internal.R.styleable.View_paddingStart: 5046 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 5047 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 5048 break; 5049 case com.android.internal.R.styleable.View_paddingEnd: 5050 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 5051 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 5052 break; 5053 case com.android.internal.R.styleable.View_scrollX: 5054 x = a.getDimensionPixelOffset(attr, 0); 5055 break; 5056 case com.android.internal.R.styleable.View_scrollY: 5057 y = a.getDimensionPixelOffset(attr, 0); 5058 break; 5059 case com.android.internal.R.styleable.View_alpha: 5060 setAlpha(a.getFloat(attr, 1f)); 5061 break; 5062 case com.android.internal.R.styleable.View_transformPivotX: 5063 setPivotX(a.getDimension(attr, 0)); 5064 break; 5065 case com.android.internal.R.styleable.View_transformPivotY: 5066 setPivotY(a.getDimension(attr, 0)); 5067 break; 5068 case com.android.internal.R.styleable.View_translationX: 5069 tx = a.getDimension(attr, 0); 5070 transformSet = true; 5071 break; 5072 case com.android.internal.R.styleable.View_translationY: 5073 ty = a.getDimension(attr, 0); 5074 transformSet = true; 5075 break; 5076 case com.android.internal.R.styleable.View_translationZ: 5077 tz = a.getDimension(attr, 0); 5078 transformSet = true; 5079 break; 5080 case com.android.internal.R.styleable.View_elevation: 5081 elevation = a.getDimension(attr, 0); 5082 transformSet = true; 5083 break; 5084 case com.android.internal.R.styleable.View_rotation: 5085 rotation = a.getFloat(attr, 0); 5086 transformSet = true; 5087 break; 5088 case com.android.internal.R.styleable.View_rotationX: 5089 rotationX = a.getFloat(attr, 0); 5090 transformSet = true; 5091 break; 5092 case com.android.internal.R.styleable.View_rotationY: 5093 rotationY = a.getFloat(attr, 0); 5094 transformSet = true; 5095 break; 5096 case com.android.internal.R.styleable.View_scaleX: 5097 sx = a.getFloat(attr, 1f); 5098 transformSet = true; 5099 break; 5100 case com.android.internal.R.styleable.View_scaleY: 5101 sy = a.getFloat(attr, 1f); 5102 transformSet = true; 5103 break; 5104 case com.android.internal.R.styleable.View_id: 5105 mID = a.getResourceId(attr, NO_ID); 5106 break; 5107 case com.android.internal.R.styleable.View_tag: 5108 mTag = a.getText(attr); 5109 break; 5110 case com.android.internal.R.styleable.View_fitsSystemWindows: 5111 if (a.getBoolean(attr, false)) { 5112 viewFlagValues |= FITS_SYSTEM_WINDOWS; 5113 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 5114 } 5115 break; 5116 case com.android.internal.R.styleable.View_focusable: 5117 viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a); 5118 if ((viewFlagValues & FOCUSABLE_AUTO) == 0) { 5119 viewFlagMasks |= FOCUSABLE_MASK; 5120 } 5121 break; 5122 case com.android.internal.R.styleable.View_focusableInTouchMode: 5123 if (a.getBoolean(attr, false)) { 5124 // unset auto focus since focusableInTouchMode implies explicit focusable 5125 viewFlagValues &= ~FOCUSABLE_AUTO; 5126 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 5127 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 5128 } 5129 break; 5130 case com.android.internal.R.styleable.View_clickable: 5131 if (a.getBoolean(attr, false)) { 5132 viewFlagValues |= CLICKABLE; 5133 viewFlagMasks |= CLICKABLE; 5134 } 5135 break; 5136 case com.android.internal.R.styleable.View_longClickable: 5137 if (a.getBoolean(attr, false)) { 5138 viewFlagValues |= LONG_CLICKABLE; 5139 viewFlagMasks |= LONG_CLICKABLE; 5140 } 5141 break; 5142 case com.android.internal.R.styleable.View_contextClickable: 5143 if (a.getBoolean(attr, false)) { 5144 viewFlagValues |= CONTEXT_CLICKABLE; 5145 viewFlagMasks |= CONTEXT_CLICKABLE; 5146 } 5147 break; 5148 case com.android.internal.R.styleable.View_saveEnabled: 5149 if (!a.getBoolean(attr, true)) { 5150 viewFlagValues |= SAVE_DISABLED; 5151 viewFlagMasks |= SAVE_DISABLED_MASK; 5152 } 5153 break; 5154 case com.android.internal.R.styleable.View_duplicateParentState: 5155 if (a.getBoolean(attr, false)) { 5156 viewFlagValues |= DUPLICATE_PARENT_STATE; 5157 viewFlagMasks |= DUPLICATE_PARENT_STATE; 5158 } 5159 break; 5160 case com.android.internal.R.styleable.View_visibility: 5161 final int visibility = a.getInt(attr, 0); 5162 if (visibility != 0) { 5163 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 5164 viewFlagMasks |= VISIBILITY_MASK; 5165 } 5166 break; 5167 case com.android.internal.R.styleable.View_layoutDirection: 5168 // Clear any layout direction flags (included resolved bits) already set 5169 mPrivateFlags2 &= 5170 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 5171 // Set the layout direction flags depending on the value of the attribute 5172 final int layoutDirection = a.getInt(attr, -1); 5173 final int value = (layoutDirection != -1) ? 5174 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 5175 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 5176 break; 5177 case com.android.internal.R.styleable.View_drawingCacheQuality: 5178 final int cacheQuality = a.getInt(attr, 0); 5179 if (cacheQuality != 0) { 5180 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 5181 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 5182 } 5183 break; 5184 case com.android.internal.R.styleable.View_contentDescription: 5185 setContentDescription(a.getString(attr)); 5186 break; 5187 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 5188 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 5189 break; 5190 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 5191 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 5192 break; 5193 case com.android.internal.R.styleable.View_labelFor: 5194 setLabelFor(a.getResourceId(attr, NO_ID)); 5195 break; 5196 case com.android.internal.R.styleable.View_soundEffectsEnabled: 5197 if (!a.getBoolean(attr, true)) { 5198 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 5199 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 5200 } 5201 break; 5202 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 5203 if (!a.getBoolean(attr, true)) { 5204 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 5205 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 5206 } 5207 break; 5208 case R.styleable.View_scrollbars: 5209 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 5210 if (scrollbars != SCROLLBARS_NONE) { 5211 viewFlagValues |= scrollbars; 5212 viewFlagMasks |= SCROLLBARS_MASK; 5213 initializeScrollbars = true; 5214 } 5215 break; 5216 //noinspection deprecation 5217 case R.styleable.View_fadingEdge: 5218 if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 5219 // Ignore the attribute starting with ICS 5220 break; 5221 } 5222 // With builds < ICS, fall through and apply fading edges 5223 case R.styleable.View_requiresFadingEdge: 5224 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 5225 if (fadingEdge != FADING_EDGE_NONE) { 5226 viewFlagValues |= fadingEdge; 5227 viewFlagMasks |= FADING_EDGE_MASK; 5228 initializeFadingEdgeInternal(a); 5229 } 5230 break; 5231 case R.styleable.View_scrollbarStyle: 5232 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 5233 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 5234 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 5235 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 5236 } 5237 break; 5238 case R.styleable.View_isScrollContainer: 5239 setScrollContainer = true; 5240 if (a.getBoolean(attr, false)) { 5241 setScrollContainer(true); 5242 } 5243 break; 5244 case com.android.internal.R.styleable.View_keepScreenOn: 5245 if (a.getBoolean(attr, false)) { 5246 viewFlagValues |= KEEP_SCREEN_ON; 5247 viewFlagMasks |= KEEP_SCREEN_ON; 5248 } 5249 break; 5250 case R.styleable.View_filterTouchesWhenObscured: 5251 if (a.getBoolean(attr, false)) { 5252 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 5253 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 5254 } 5255 break; 5256 case R.styleable.View_nextFocusLeft: 5257 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 5258 break; 5259 case R.styleable.View_nextFocusRight: 5260 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 5261 break; 5262 case R.styleable.View_nextFocusUp: 5263 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 5264 break; 5265 case R.styleable.View_nextFocusDown: 5266 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 5267 break; 5268 case R.styleable.View_nextFocusForward: 5269 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 5270 break; 5271 case R.styleable.View_nextClusterForward: 5272 mNextClusterForwardId = a.getResourceId(attr, View.NO_ID); 5273 break; 5274 case R.styleable.View_minWidth: 5275 mMinWidth = a.getDimensionPixelSize(attr, 0); 5276 break; 5277 case R.styleable.View_minHeight: 5278 mMinHeight = a.getDimensionPixelSize(attr, 0); 5279 break; 5280 case R.styleable.View_onClick: 5281 if (context.isRestricted()) { 5282 throw new IllegalStateException("The android:onClick attribute cannot " 5283 + "be used within a restricted context"); 5284 } 5285 5286 final String handlerName = a.getString(attr); 5287 if (handlerName != null) { 5288 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 5289 } 5290 break; 5291 case R.styleable.View_overScrollMode: 5292 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 5293 break; 5294 case R.styleable.View_verticalScrollbarPosition: 5295 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 5296 break; 5297 case R.styleable.View_layerType: 5298 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 5299 break; 5300 case R.styleable.View_textDirection: 5301 // Clear any text direction flag already set 5302 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 5303 // Set the text direction flags depending on the value of the attribute 5304 final int textDirection = a.getInt(attr, -1); 5305 if (textDirection != -1) { 5306 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 5307 } 5308 break; 5309 case R.styleable.View_textAlignment: 5310 // Clear any text alignment flag already set 5311 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 5312 // Set the text alignment flag depending on the value of the attribute 5313 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 5314 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 5315 break; 5316 case R.styleable.View_importantForAccessibility: 5317 setImportantForAccessibility(a.getInt(attr, 5318 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 5319 break; 5320 case R.styleable.View_accessibilityLiveRegion: 5321 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 5322 break; 5323 case R.styleable.View_transitionName: 5324 setTransitionName(a.getString(attr)); 5325 break; 5326 case R.styleable.View_nestedScrollingEnabled: 5327 setNestedScrollingEnabled(a.getBoolean(attr, false)); 5328 break; 5329 case R.styleable.View_stateListAnimator: 5330 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 5331 a.getResourceId(attr, 0))); 5332 break; 5333 case R.styleable.View_backgroundTint: 5334 // This will get applied later during setBackground(). 5335 if (mBackgroundTint == null) { 5336 mBackgroundTint = new TintInfo(); 5337 } 5338 mBackgroundTint.mTintList = a.getColorStateList( 5339 R.styleable.View_backgroundTint); 5340 mBackgroundTint.mHasTintList = true; 5341 break; 5342 case R.styleable.View_backgroundTintMode: 5343 // This will get applied later during setBackground(). 5344 if (mBackgroundTint == null) { 5345 mBackgroundTint = new TintInfo(); 5346 } 5347 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 5348 R.styleable.View_backgroundTintMode, -1), null); 5349 mBackgroundTint.mHasTintMode = true; 5350 break; 5351 case R.styleable.View_outlineProvider: 5352 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 5353 PROVIDER_BACKGROUND)); 5354 break; 5355 case R.styleable.View_foreground: 5356 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 5357 setForeground(a.getDrawable(attr)); 5358 } 5359 break; 5360 case R.styleable.View_foregroundGravity: 5361 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 5362 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 5363 } 5364 break; 5365 case R.styleable.View_foregroundTintMode: 5366 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 5367 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 5368 } 5369 break; 5370 case R.styleable.View_foregroundTint: 5371 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 5372 setForegroundTintList(a.getColorStateList(attr)); 5373 } 5374 break; 5375 case R.styleable.View_foregroundInsidePadding: 5376 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 5377 if (mForegroundInfo == null) { 5378 mForegroundInfo = new ForegroundInfo(); 5379 } 5380 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 5381 mForegroundInfo.mInsidePadding); 5382 } 5383 break; 5384 case R.styleable.View_scrollIndicators: 5385 final int scrollIndicators = 5386 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 5387 & SCROLL_INDICATORS_PFLAG3_MASK; 5388 if (scrollIndicators != 0) { 5389 mPrivateFlags3 |= scrollIndicators; 5390 initializeScrollIndicators = true; 5391 } 5392 break; 5393 case R.styleable.View_pointerIcon: 5394 final int resourceId = a.getResourceId(attr, 0); 5395 if (resourceId != 0) { 5396 setPointerIcon(PointerIcon.load( 5397 context.getResources(), resourceId)); 5398 } else { 5399 final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED); 5400 if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) { 5401 setPointerIcon(PointerIcon.getSystemIcon(context, pointerType)); 5402 } 5403 } 5404 break; 5405 case R.styleable.View_forceHasOverlappingRendering: 5406 if (a.peekValue(attr) != null) { 5407 forceHasOverlappingRendering(a.getBoolean(attr, true)); 5408 } 5409 break; 5410 case R.styleable.View_tooltipText: 5411 setTooltipText(a.getText(attr)); 5412 break; 5413 case R.styleable.View_keyboardNavigationCluster: 5414 if (a.peekValue(attr) != null) { 5415 setKeyboardNavigationCluster(a.getBoolean(attr, true)); 5416 } 5417 break; 5418 case R.styleable.View_focusedByDefault: 5419 if (a.peekValue(attr) != null) { 5420 setFocusedByDefault(a.getBoolean(attr, true)); 5421 } 5422 break; 5423 case R.styleable.View_autofillHints: 5424 if (a.peekValue(attr) != null) { 5425 CharSequence[] rawHints = null; 5426 String rawString = null; 5427 5428 if (a.getType(attr) == TypedValue.TYPE_REFERENCE) { 5429 int resId = a.getResourceId(attr, 0); 5430 5431 try { 5432 rawHints = a.getTextArray(attr); 5433 } catch (Resources.NotFoundException e) { 5434 rawString = getResources().getString(resId); 5435 } 5436 } else { 5437 rawString = a.getString(attr); 5438 } 5439 5440 if (rawHints == null) { 5441 if (rawString == null) { 5442 throw new IllegalArgumentException( 5443 "Could not resolve autofillHints"); 5444 } else { 5445 rawHints = rawString.split(","); 5446 } 5447 } 5448 5449 String[] hints = new String[rawHints.length]; 5450 5451 int numHints = rawHints.length; 5452 for (int rawHintNum = 0; rawHintNum < numHints; rawHintNum++) { 5453 hints[rawHintNum] = rawHints[rawHintNum].toString().trim(); 5454 } 5455 setAutofillHints(hints); 5456 } 5457 break; 5458 case R.styleable.View_importantForAutofill: 5459 if (a.peekValue(attr) != null) { 5460 setImportantForAutofill(a.getInt(attr, IMPORTANT_FOR_AUTOFILL_AUTO)); 5461 } 5462 break; 5463 case R.styleable.View_defaultFocusHighlightEnabled: 5464 if (a.peekValue(attr) != null) { 5465 setDefaultFocusHighlightEnabled(a.getBoolean(attr, true)); 5466 } 5467 break; 5468 case R.styleable.View_screenReaderFocusable: 5469 if (a.peekValue(attr) != null) { 5470 setScreenReaderFocusable(a.getBoolean(attr, false)); 5471 } 5472 break; 5473 case R.styleable.View_accessibilityPaneTitle: 5474 if (a.peekValue(attr) != null) { 5475 setAccessibilityPaneTitle(a.getString(attr)); 5476 } 5477 break; 5478 case R.styleable.View_outlineSpotShadowColor: 5479 setOutlineSpotShadowColor(a.getColor(attr, Color.BLACK)); 5480 break; 5481 case R.styleable.View_outlineAmbientShadowColor: 5482 setOutlineAmbientShadowColor(a.getColor(attr, Color.BLACK)); 5483 break; 5484 case com.android.internal.R.styleable.View_accessibilityHeading: 5485 setAccessibilityHeading(a.getBoolean(attr, false)); 5486 } 5487 } 5488 5489 setOverScrollMode(overScrollMode); 5490 5491 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 5492 // the resolved layout direction). Those cached values will be used later during padding 5493 // resolution. 5494 mUserPaddingStart = startPadding; 5495 mUserPaddingEnd = endPadding; 5496 5497 if (background != null) { 5498 setBackground(background); 5499 } 5500 5501 // setBackground above will record that padding is currently provided by the background. 5502 // If we have padding specified via xml, record that here instead and use it. 5503 mLeftPaddingDefined = leftPaddingDefined; 5504 mRightPaddingDefined = rightPaddingDefined; 5505 5506 if (padding >= 0) { 5507 leftPadding = padding; 5508 topPadding = padding; 5509 rightPadding = padding; 5510 bottomPadding = padding; 5511 mUserPaddingLeftInitial = padding; 5512 mUserPaddingRightInitial = padding; 5513 } else { 5514 if (paddingHorizontal >= 0) { 5515 leftPadding = paddingHorizontal; 5516 rightPadding = paddingHorizontal; 5517 mUserPaddingLeftInitial = paddingHorizontal; 5518 mUserPaddingRightInitial = paddingHorizontal; 5519 } 5520 if (paddingVertical >= 0) { 5521 topPadding = paddingVertical; 5522 bottomPadding = paddingVertical; 5523 } 5524 } 5525 5526 if (isRtlCompatibilityMode()) { 5527 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 5528 // left / right padding are used if defined (meaning here nothing to do). If they are not 5529 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 5530 // start / end and resolve them as left / right (layout direction is not taken into account). 5531 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 5532 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 5533 // defined. 5534 if (!mLeftPaddingDefined && startPaddingDefined) { 5535 leftPadding = startPadding; 5536 } 5537 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 5538 if (!mRightPaddingDefined && endPaddingDefined) { 5539 rightPadding = endPadding; 5540 } 5541 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 5542 } else { 5543 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 5544 // values defined. Otherwise, left /right values are used. 5545 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 5546 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 5547 // defined. 5548 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 5549 5550 if (mLeftPaddingDefined && !hasRelativePadding) { 5551 mUserPaddingLeftInitial = leftPadding; 5552 } 5553 if (mRightPaddingDefined && !hasRelativePadding) { 5554 mUserPaddingRightInitial = rightPadding; 5555 } 5556 } 5557 5558 internalSetPadding( 5559 mUserPaddingLeftInitial, 5560 topPadding >= 0 ? topPadding : mPaddingTop, 5561 mUserPaddingRightInitial, 5562 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 5563 5564 if (viewFlagMasks != 0) { 5565 setFlags(viewFlagValues, viewFlagMasks); 5566 } 5567 5568 if (initializeScrollbars) { 5569 initializeScrollbarsInternal(a); 5570 } 5571 5572 if (initializeScrollIndicators) { 5573 initializeScrollIndicatorsInternal(); 5574 } 5575 5576 a.recycle(); 5577 5578 // Needs to be called after mViewFlags is set 5579 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 5580 recomputePadding(); 5581 } 5582 5583 if (x != 0 || y != 0) { 5584 scrollTo(x, y); 5585 } 5586 5587 if (transformSet) { 5588 setTranslationX(tx); 5589 setTranslationY(ty); 5590 setTranslationZ(tz); 5591 setElevation(elevation); 5592 setRotation(rotation); 5593 setRotationX(rotationX); 5594 setRotationY(rotationY); 5595 setScaleX(sx); 5596 setScaleY(sy); 5597 } 5598 5599 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 5600 setScrollContainer(true); 5601 } 5602 5603 computeOpaqueFlags(); 5604 } 5605 5606 /** 5607 * An implementation of OnClickListener that attempts to lazily load a 5608 * named click handling method from a parent or ancestor context. 5609 */ 5610 private static class DeclaredOnClickListener implements OnClickListener { 5611 private final View mHostView; 5612 private final String mMethodName; 5613 5614 private Method mResolvedMethod; 5615 private Context mResolvedContext; 5616 5617 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 5618 mHostView = hostView; 5619 mMethodName = methodName; 5620 } 5621 5622 @Override 5623 public void onClick(@NonNull View v) { 5624 if (mResolvedMethod == null) { 5625 resolveMethod(mHostView.getContext(), mMethodName); 5626 } 5627 5628 try { 5629 mResolvedMethod.invoke(mResolvedContext, v); 5630 } catch (IllegalAccessException e) { 5631 throw new IllegalStateException( 5632 "Could not execute non-public method for android:onClick", e); 5633 } catch (InvocationTargetException e) { 5634 throw new IllegalStateException( 5635 "Could not execute method for android:onClick", e); 5636 } 5637 } 5638 5639 @NonNull 5640 private void resolveMethod(@Nullable Context context, @NonNull String name) { 5641 while (context != null) { 5642 try { 5643 if (!context.isRestricted()) { 5644 final Method method = context.getClass().getMethod(mMethodName, View.class); 5645 if (method != null) { 5646 mResolvedMethod = method; 5647 mResolvedContext = context; 5648 return; 5649 } 5650 } 5651 } catch (NoSuchMethodException e) { 5652 // Failed to find method, keep searching up the hierarchy. 5653 } 5654 5655 if (context instanceof ContextWrapper) { 5656 context = ((ContextWrapper) context).getBaseContext(); 5657 } else { 5658 // Can't search up the hierarchy, null out and fail. 5659 context = null; 5660 } 5661 } 5662 5663 final int id = mHostView.getId(); 5664 final String idText = id == NO_ID ? "" : " with id '" 5665 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 5666 throw new IllegalStateException("Could not find method " + mMethodName 5667 + "(View) in a parent or ancestor Context for android:onClick " 5668 + "attribute defined on view " + mHostView.getClass() + idText); 5669 } 5670 } 5671 5672 /** 5673 * Non-public constructor for use in testing 5674 */ 5675 View() { 5676 mResources = null; 5677 mRenderNode = RenderNode.create(getClass().getName(), this); 5678 } 5679 5680 final boolean debugDraw() { 5681 return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout; 5682 } 5683 5684 private static SparseArray<String> getAttributeMap() { 5685 if (mAttributeMap == null) { 5686 mAttributeMap = new SparseArray<>(); 5687 } 5688 return mAttributeMap; 5689 } 5690 5691 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 5692 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 5693 final int indexCount = t.getIndexCount(); 5694 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 5695 5696 int i = 0; 5697 5698 // Store raw XML attributes. 5699 for (int j = 0; j < attrsCount; ++j) { 5700 attributes[i] = attrs.getAttributeName(j); 5701 attributes[i + 1] = attrs.getAttributeValue(j); 5702 i += 2; 5703 } 5704 5705 // Store resolved styleable attributes. 5706 final Resources res = t.getResources(); 5707 final SparseArray<String> attributeMap = getAttributeMap(); 5708 for (int j = 0; j < indexCount; ++j) { 5709 final int index = t.getIndex(j); 5710 if (!t.hasValueOrEmpty(index)) { 5711 // Value is undefined. Skip it. 5712 continue; 5713 } 5714 5715 final int resourceId = t.getResourceId(index, 0); 5716 if (resourceId == 0) { 5717 // Value is not a reference. Skip it. 5718 continue; 5719 } 5720 5721 String resourceName = attributeMap.get(resourceId); 5722 if (resourceName == null) { 5723 try { 5724 resourceName = res.getResourceName(resourceId); 5725 } catch (Resources.NotFoundException e) { 5726 resourceName = "0x" + Integer.toHexString(resourceId); 5727 } 5728 attributeMap.put(resourceId, resourceName); 5729 } 5730 5731 attributes[i] = resourceName; 5732 attributes[i + 1] = t.getString(index); 5733 i += 2; 5734 } 5735 5736 // Trim to fit contents. 5737 final String[] trimmed = new String[i]; 5738 System.arraycopy(attributes, 0, trimmed, 0, i); 5739 mAttributes = trimmed; 5740 } 5741 5742 public String toString() { 5743 StringBuilder out = new StringBuilder(128); 5744 out.append(getClass().getName()); 5745 out.append('{'); 5746 out.append(Integer.toHexString(System.identityHashCode(this))); 5747 out.append(' '); 5748 switch (mViewFlags&VISIBILITY_MASK) { 5749 case VISIBLE: out.append('V'); break; 5750 case INVISIBLE: out.append('I'); break; 5751 case GONE: out.append('G'); break; 5752 default: out.append('.'); break; 5753 } 5754 out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.'); 5755 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 5756 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 5757 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 5758 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 5759 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 5760 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 5761 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 5762 out.append(' '); 5763 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 5764 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 5765 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 5766 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 5767 out.append('p'); 5768 } else { 5769 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 5770 } 5771 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 5772 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 5773 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 5774 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 5775 out.append(' '); 5776 out.append(mLeft); 5777 out.append(','); 5778 out.append(mTop); 5779 out.append('-'); 5780 out.append(mRight); 5781 out.append(','); 5782 out.append(mBottom); 5783 final int id = getId(); 5784 if (id != NO_ID) { 5785 out.append(" #"); 5786 out.append(Integer.toHexString(id)); 5787 final Resources r = mResources; 5788 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 5789 try { 5790 String pkgname; 5791 switch (id&0xff000000) { 5792 case 0x7f000000: 5793 pkgname="app"; 5794 break; 5795 case 0x01000000: 5796 pkgname="android"; 5797 break; 5798 default: 5799 pkgname = r.getResourcePackageName(id); 5800 break; 5801 } 5802 String typename = r.getResourceTypeName(id); 5803 String entryname = r.getResourceEntryName(id); 5804 out.append(" "); 5805 out.append(pkgname); 5806 out.append(":"); 5807 out.append(typename); 5808 out.append("/"); 5809 out.append(entryname); 5810 } catch (Resources.NotFoundException e) { 5811 } 5812 } 5813 } 5814 out.append("}"); 5815 return out.toString(); 5816 } 5817 5818 /** 5819 * <p> 5820 * Initializes the fading edges from a given set of styled attributes. This 5821 * method should be called by subclasses that need fading edges and when an 5822 * instance of these subclasses is created programmatically rather than 5823 * being inflated from XML. This method is automatically called when the XML 5824 * is inflated. 5825 * </p> 5826 * 5827 * @param a the styled attributes set to initialize the fading edges from 5828 * 5829 * @removed 5830 */ 5831 protected void initializeFadingEdge(TypedArray a) { 5832 // This method probably shouldn't have been included in the SDK to begin with. 5833 // It relies on 'a' having been initialized using an attribute filter array that is 5834 // not publicly available to the SDK. The old method has been renamed 5835 // to initializeFadingEdgeInternal and hidden for framework use only; 5836 // this one initializes using defaults to make it safe to call for apps. 5837 5838 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5839 5840 initializeFadingEdgeInternal(arr); 5841 5842 arr.recycle(); 5843 } 5844 5845 /** 5846 * <p> 5847 * Initializes the fading edges from a given set of styled attributes. This 5848 * method should be called by subclasses that need fading edges and when an 5849 * instance of these subclasses is created programmatically rather than 5850 * being inflated from XML. This method is automatically called when the XML 5851 * is inflated. 5852 * </p> 5853 * 5854 * @param a the styled attributes set to initialize the fading edges from 5855 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 5856 */ 5857 protected void initializeFadingEdgeInternal(TypedArray a) { 5858 initScrollCache(); 5859 5860 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 5861 R.styleable.View_fadingEdgeLength, 5862 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 5863 } 5864 5865 /** 5866 * Returns the size of the vertical faded edges used to indicate that more 5867 * content in this view is visible. 5868 * 5869 * @return The size in pixels of the vertical faded edge or 0 if vertical 5870 * faded edges are not enabled for this view. 5871 * @attr ref android.R.styleable#View_fadingEdgeLength 5872 */ 5873 public int getVerticalFadingEdgeLength() { 5874 if (isVerticalFadingEdgeEnabled()) { 5875 ScrollabilityCache cache = mScrollCache; 5876 if (cache != null) { 5877 return cache.fadingEdgeLength; 5878 } 5879 } 5880 return 0; 5881 } 5882 5883 /** 5884 * Set the size of the faded edge used to indicate that more content in this 5885 * view is available. Will not change whether the fading edge is enabled; use 5886 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 5887 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 5888 * for the vertical or horizontal fading edges. 5889 * 5890 * @param length The size in pixels of the faded edge used to indicate that more 5891 * content in this view is visible. 5892 */ 5893 public void setFadingEdgeLength(int length) { 5894 initScrollCache(); 5895 mScrollCache.fadingEdgeLength = length; 5896 } 5897 5898 /** 5899 * Returns the size of the horizontal faded edges used to indicate that more 5900 * content in this view is visible. 5901 * 5902 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 5903 * faded edges are not enabled for this view. 5904 * @attr ref android.R.styleable#View_fadingEdgeLength 5905 */ 5906 public int getHorizontalFadingEdgeLength() { 5907 if (isHorizontalFadingEdgeEnabled()) { 5908 ScrollabilityCache cache = mScrollCache; 5909 if (cache != null) { 5910 return cache.fadingEdgeLength; 5911 } 5912 } 5913 return 0; 5914 } 5915 5916 /** 5917 * Returns the width of the vertical scrollbar. 5918 * 5919 * @return The width in pixels of the vertical scrollbar or 0 if there 5920 * is no vertical scrollbar. 5921 */ 5922 public int getVerticalScrollbarWidth() { 5923 ScrollabilityCache cache = mScrollCache; 5924 if (cache != null) { 5925 ScrollBarDrawable scrollBar = cache.scrollBar; 5926 if (scrollBar != null) { 5927 int size = scrollBar.getSize(true); 5928 if (size <= 0) { 5929 size = cache.scrollBarSize; 5930 } 5931 return size; 5932 } 5933 return 0; 5934 } 5935 return 0; 5936 } 5937 5938 /** 5939 * Returns the height of the horizontal scrollbar. 5940 * 5941 * @return The height in pixels of the horizontal scrollbar or 0 if 5942 * there is no horizontal scrollbar. 5943 */ 5944 protected int getHorizontalScrollbarHeight() { 5945 ScrollabilityCache cache = mScrollCache; 5946 if (cache != null) { 5947 ScrollBarDrawable scrollBar = cache.scrollBar; 5948 if (scrollBar != null) { 5949 int size = scrollBar.getSize(false); 5950 if (size <= 0) { 5951 size = cache.scrollBarSize; 5952 } 5953 return size; 5954 } 5955 return 0; 5956 } 5957 return 0; 5958 } 5959 5960 /** 5961 * <p> 5962 * Initializes the scrollbars from a given set of styled attributes. This 5963 * method should be called by subclasses that need scrollbars and when an 5964 * instance of these subclasses is created programmatically rather than 5965 * being inflated from XML. This method is automatically called when the XML 5966 * is inflated. 5967 * </p> 5968 * 5969 * @param a the styled attributes set to initialize the scrollbars from 5970 * 5971 * @removed 5972 */ 5973 protected void initializeScrollbars(TypedArray a) { 5974 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 5975 // using the View filter array which is not available to the SDK. As such, internal 5976 // framework usage now uses initializeScrollbarsInternal and we grab a default 5977 // TypedArray with the right filter instead here. 5978 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5979 5980 initializeScrollbarsInternal(arr); 5981 5982 // We ignored the method parameter. Recycle the one we actually did use. 5983 arr.recycle(); 5984 } 5985 5986 /** 5987 * <p> 5988 * Initializes the scrollbars from a given set of styled attributes. This 5989 * method should be called by subclasses that need scrollbars and when an 5990 * instance of these subclasses is created programmatically rather than 5991 * being inflated from XML. This method is automatically called when the XML 5992 * is inflated. 5993 * </p> 5994 * 5995 * @param a the styled attributes set to initialize the scrollbars from 5996 * @hide 5997 */ 5998 protected void initializeScrollbarsInternal(TypedArray a) { 5999 initScrollCache(); 6000 6001 final ScrollabilityCache scrollabilityCache = mScrollCache; 6002 6003 if (scrollabilityCache.scrollBar == null) { 6004 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 6005 scrollabilityCache.scrollBar.setState(getDrawableState()); 6006 scrollabilityCache.scrollBar.setCallback(this); 6007 } 6008 6009 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 6010 6011 if (!fadeScrollbars) { 6012 scrollabilityCache.state = ScrollabilityCache.ON; 6013 } 6014 scrollabilityCache.fadeScrollBars = fadeScrollbars; 6015 6016 6017 scrollabilityCache.scrollBarFadeDuration = a.getInt( 6018 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 6019 .getScrollBarFadeDuration()); 6020 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 6021 R.styleable.View_scrollbarDefaultDelayBeforeFade, 6022 ViewConfiguration.getScrollDefaultDelay()); 6023 6024 6025 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 6026 com.android.internal.R.styleable.View_scrollbarSize, 6027 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 6028 6029 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 6030 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 6031 6032 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 6033 if (thumb != null) { 6034 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 6035 } 6036 6037 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 6038 false); 6039 if (alwaysDraw) { 6040 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 6041 } 6042 6043 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 6044 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 6045 6046 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 6047 if (thumb != null) { 6048 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 6049 } 6050 6051 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 6052 false); 6053 if (alwaysDraw) { 6054 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 6055 } 6056 6057 // Apply layout direction to the new Drawables if needed 6058 final int layoutDirection = getLayoutDirection(); 6059 if (track != null) { 6060 track.setLayoutDirection(layoutDirection); 6061 } 6062 if (thumb != null) { 6063 thumb.setLayoutDirection(layoutDirection); 6064 } 6065 6066 // Re-apply user/background padding so that scrollbar(s) get added 6067 resolvePadding(); 6068 } 6069 6070 private void initializeScrollIndicatorsInternal() { 6071 // Some day maybe we'll break this into top/left/start/etc. and let the 6072 // client control it. Until then, you can have any scroll indicator you 6073 // want as long as it's a 1dp foreground-colored rectangle. 6074 if (mScrollIndicatorDrawable == null) { 6075 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 6076 } 6077 } 6078 6079 /** 6080 * <p> 6081 * Initalizes the scrollability cache if necessary. 6082 * </p> 6083 */ 6084 private void initScrollCache() { 6085 if (mScrollCache == null) { 6086 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 6087 } 6088 } 6089 6090 private ScrollabilityCache getScrollCache() { 6091 initScrollCache(); 6092 return mScrollCache; 6093 } 6094 6095 /** 6096 * Set the position of the vertical scroll bar. Should be one of 6097 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 6098 * {@link #SCROLLBAR_POSITION_RIGHT}. 6099 * 6100 * @param position Where the vertical scroll bar should be positioned. 6101 */ 6102 public void setVerticalScrollbarPosition(int position) { 6103 if (mVerticalScrollbarPosition != position) { 6104 mVerticalScrollbarPosition = position; 6105 computeOpaqueFlags(); 6106 resolvePadding(); 6107 } 6108 } 6109 6110 /** 6111 * @return The position where the vertical scroll bar will show, if applicable. 6112 * @see #setVerticalScrollbarPosition(int) 6113 */ 6114 public int getVerticalScrollbarPosition() { 6115 return mVerticalScrollbarPosition; 6116 } 6117 6118 boolean isOnScrollbar(float x, float y) { 6119 if (mScrollCache == null) { 6120 return false; 6121 } 6122 x += getScrollX(); 6123 y += getScrollY(); 6124 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 6125 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 6126 getVerticalScrollBarBounds(null, touchBounds); 6127 if (touchBounds.contains((int) x, (int) y)) { 6128 return true; 6129 } 6130 } 6131 if (isHorizontalScrollBarEnabled()) { 6132 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 6133 getHorizontalScrollBarBounds(null, touchBounds); 6134 if (touchBounds.contains((int) x, (int) y)) { 6135 return true; 6136 } 6137 } 6138 return false; 6139 } 6140 6141 boolean isOnScrollbarThumb(float x, float y) { 6142 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 6143 } 6144 6145 private boolean isOnVerticalScrollbarThumb(float x, float y) { 6146 if (mScrollCache == null) { 6147 return false; 6148 } 6149 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 6150 x += getScrollX(); 6151 y += getScrollY(); 6152 final Rect bounds = mScrollCache.mScrollBarBounds; 6153 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 6154 getVerticalScrollBarBounds(bounds, touchBounds); 6155 final int range = computeVerticalScrollRange(); 6156 final int offset = computeVerticalScrollOffset(); 6157 final int extent = computeVerticalScrollExtent(); 6158 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 6159 extent, range); 6160 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 6161 extent, range, offset); 6162 final int thumbTop = bounds.top + thumbOffset; 6163 final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2; 6164 if (x >= touchBounds.left && x <= touchBounds.right 6165 && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) { 6166 return true; 6167 } 6168 } 6169 return false; 6170 } 6171 6172 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 6173 if (mScrollCache == null) { 6174 return false; 6175 } 6176 if (isHorizontalScrollBarEnabled()) { 6177 x += getScrollX(); 6178 y += getScrollY(); 6179 final Rect bounds = mScrollCache.mScrollBarBounds; 6180 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 6181 getHorizontalScrollBarBounds(bounds, touchBounds); 6182 final int range = computeHorizontalScrollRange(); 6183 final int offset = computeHorizontalScrollOffset(); 6184 final int extent = computeHorizontalScrollExtent(); 6185 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 6186 extent, range); 6187 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 6188 extent, range, offset); 6189 final int thumbLeft = bounds.left + thumbOffset; 6190 final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2; 6191 if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust 6192 && y >= touchBounds.top && y <= touchBounds.bottom) { 6193 return true; 6194 } 6195 } 6196 return false; 6197 } 6198 6199 boolean isDraggingScrollBar() { 6200 return mScrollCache != null 6201 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 6202 } 6203 6204 /** 6205 * Sets the state of all scroll indicators. 6206 * <p> 6207 * See {@link #setScrollIndicators(int, int)} for usage information. 6208 * 6209 * @param indicators a bitmask of indicators that should be enabled, or 6210 * {@code 0} to disable all indicators 6211 * @see #setScrollIndicators(int, int) 6212 * @see #getScrollIndicators() 6213 * @attr ref android.R.styleable#View_scrollIndicators 6214 */ 6215 public void setScrollIndicators(@ScrollIndicators int indicators) { 6216 setScrollIndicators(indicators, 6217 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 6218 } 6219 6220 /** 6221 * Sets the state of the scroll indicators specified by the mask. To change 6222 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 6223 * <p> 6224 * When a scroll indicator is enabled, it will be displayed if the view 6225 * can scroll in the direction of the indicator. 6226 * <p> 6227 * Multiple indicator types may be enabled or disabled by passing the 6228 * logical OR of the desired types. If multiple types are specified, they 6229 * will all be set to the same enabled state. 6230 * <p> 6231 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 6232 * 6233 * @param indicators the indicator direction, or the logical OR of multiple 6234 * indicator directions. One or more of: 6235 * <ul> 6236 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 6237 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 6238 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 6239 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 6240 * <li>{@link #SCROLL_INDICATOR_START}</li> 6241 * <li>{@link #SCROLL_INDICATOR_END}</li> 6242 * </ul> 6243 * @see #setScrollIndicators(int) 6244 * @see #getScrollIndicators() 6245 * @attr ref android.R.styleable#View_scrollIndicators 6246 */ 6247 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 6248 // Shift and sanitize mask. 6249 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 6250 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 6251 6252 // Shift and mask indicators. 6253 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 6254 indicators &= mask; 6255 6256 // Merge with non-masked flags. 6257 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 6258 6259 if (mPrivateFlags3 != updatedFlags) { 6260 mPrivateFlags3 = updatedFlags; 6261 6262 if (indicators != 0) { 6263 initializeScrollIndicatorsInternal(); 6264 } 6265 invalidate(); 6266 } 6267 } 6268 6269 /** 6270 * Returns a bitmask representing the enabled scroll indicators. 6271 * <p> 6272 * For example, if the top and left scroll indicators are enabled and all 6273 * other indicators are disabled, the return value will be 6274 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 6275 * <p> 6276 * To check whether the bottom scroll indicator is enabled, use the value 6277 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 6278 * 6279 * @return a bitmask representing the enabled scroll indicators 6280 */ 6281 @ScrollIndicators 6282 public int getScrollIndicators() { 6283 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 6284 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 6285 } 6286 6287 ListenerInfo getListenerInfo() { 6288 if (mListenerInfo != null) { 6289 return mListenerInfo; 6290 } 6291 mListenerInfo = new ListenerInfo(); 6292 return mListenerInfo; 6293 } 6294 6295 /** 6296 * Register a callback to be invoked when the scroll X or Y positions of 6297 * this view change. 6298 * <p> 6299 * <b>Note:</b> Some views handle scrolling independently from View and may 6300 * have their own separate listeners for scroll-type events. For example, 6301 * {@link android.widget.ListView ListView} allows clients to register an 6302 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 6303 * to listen for changes in list scroll position. 6304 * 6305 * @param l The listener to notify when the scroll X or Y position changes. 6306 * @see android.view.View#getScrollX() 6307 * @see android.view.View#getScrollY() 6308 */ 6309 public void setOnScrollChangeListener(OnScrollChangeListener l) { 6310 getListenerInfo().mOnScrollChangeListener = l; 6311 } 6312 6313 /** 6314 * Register a callback to be invoked when focus of this view changed. 6315 * 6316 * @param l The callback that will run. 6317 */ 6318 public void setOnFocusChangeListener(OnFocusChangeListener l) { 6319 getListenerInfo().mOnFocusChangeListener = l; 6320 } 6321 6322 /** 6323 * Add a listener that will be called when the bounds of the view change due to 6324 * layout processing. 6325 * 6326 * @param listener The listener that will be called when layout bounds change. 6327 */ 6328 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 6329 ListenerInfo li = getListenerInfo(); 6330 if (li.mOnLayoutChangeListeners == null) { 6331 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 6332 } 6333 if (!li.mOnLayoutChangeListeners.contains(listener)) { 6334 li.mOnLayoutChangeListeners.add(listener); 6335 } 6336 } 6337 6338 /** 6339 * Remove a listener for layout changes. 6340 * 6341 * @param listener The listener for layout bounds change. 6342 */ 6343 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 6344 ListenerInfo li = mListenerInfo; 6345 if (li == null || li.mOnLayoutChangeListeners == null) { 6346 return; 6347 } 6348 li.mOnLayoutChangeListeners.remove(listener); 6349 } 6350 6351 /** 6352 * Add a listener for attach state changes. 6353 * 6354 * This listener will be called whenever this view is attached or detached 6355 * from a window. Remove the listener using 6356 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 6357 * 6358 * @param listener Listener to attach 6359 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 6360 */ 6361 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 6362 ListenerInfo li = getListenerInfo(); 6363 if (li.mOnAttachStateChangeListeners == null) { 6364 li.mOnAttachStateChangeListeners 6365 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 6366 } 6367 li.mOnAttachStateChangeListeners.add(listener); 6368 } 6369 6370 /** 6371 * Remove a listener for attach state changes. The listener will receive no further 6372 * notification of window attach/detach events. 6373 * 6374 * @param listener Listener to remove 6375 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 6376 */ 6377 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 6378 ListenerInfo li = mListenerInfo; 6379 if (li == null || li.mOnAttachStateChangeListeners == null) { 6380 return; 6381 } 6382 li.mOnAttachStateChangeListeners.remove(listener); 6383 } 6384 6385 /** 6386 * Returns the focus-change callback registered for this view. 6387 * 6388 * @return The callback, or null if one is not registered. 6389 */ 6390 public OnFocusChangeListener getOnFocusChangeListener() { 6391 ListenerInfo li = mListenerInfo; 6392 return li != null ? li.mOnFocusChangeListener : null; 6393 } 6394 6395 /** 6396 * Register a callback to be invoked when this view is clicked. If this view is not 6397 * clickable, it becomes clickable. 6398 * 6399 * @param l The callback that will run 6400 * 6401 * @see #setClickable(boolean) 6402 */ 6403 public void setOnClickListener(@Nullable OnClickListener l) { 6404 if (!isClickable()) { 6405 setClickable(true); 6406 } 6407 getListenerInfo().mOnClickListener = l; 6408 } 6409 6410 /** 6411 * Return whether this view has an attached OnClickListener. Returns 6412 * true if there is a listener, false if there is none. 6413 */ 6414 public boolean hasOnClickListeners() { 6415 ListenerInfo li = mListenerInfo; 6416 return (li != null && li.mOnClickListener != null); 6417 } 6418 6419 /** 6420 * Register a callback to be invoked when this view is clicked and held. If this view is not 6421 * long clickable, it becomes long clickable. 6422 * 6423 * @param l The callback that will run 6424 * 6425 * @see #setLongClickable(boolean) 6426 */ 6427 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 6428 if (!isLongClickable()) { 6429 setLongClickable(true); 6430 } 6431 getListenerInfo().mOnLongClickListener = l; 6432 } 6433 6434 /** 6435 * Register a callback to be invoked when this view is context clicked. If the view is not 6436 * context clickable, it becomes context clickable. 6437 * 6438 * @param l The callback that will run 6439 * @see #setContextClickable(boolean) 6440 */ 6441 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 6442 if (!isContextClickable()) { 6443 setContextClickable(true); 6444 } 6445 getListenerInfo().mOnContextClickListener = l; 6446 } 6447 6448 /** 6449 * Register a callback to be invoked when the context menu for this view is 6450 * being built. If this view is not long clickable, it becomes long clickable. 6451 * 6452 * @param l The callback that will run 6453 * 6454 */ 6455 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 6456 if (!isLongClickable()) { 6457 setLongClickable(true); 6458 } 6459 getListenerInfo().mOnCreateContextMenuListener = l; 6460 } 6461 6462 /** 6463 * Set an observer to collect stats for each frame rendered for this view. 6464 * 6465 * @hide 6466 */ 6467 public void addFrameMetricsListener(Window window, 6468 Window.OnFrameMetricsAvailableListener listener, 6469 Handler handler) { 6470 if (mAttachInfo != null) { 6471 if (mAttachInfo.mThreadedRenderer != null) { 6472 if (mFrameMetricsObservers == null) { 6473 mFrameMetricsObservers = new ArrayList<>(); 6474 } 6475 6476 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 6477 handler.getLooper(), listener); 6478 mFrameMetricsObservers.add(fmo); 6479 mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo); 6480 } else { 6481 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 6482 } 6483 } else { 6484 if (mFrameMetricsObservers == null) { 6485 mFrameMetricsObservers = new ArrayList<>(); 6486 } 6487 6488 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 6489 handler.getLooper(), listener); 6490 mFrameMetricsObservers.add(fmo); 6491 } 6492 } 6493 6494 /** 6495 * Remove observer configured to collect frame stats for this view. 6496 * 6497 * @hide 6498 */ 6499 public void removeFrameMetricsListener( 6500 Window.OnFrameMetricsAvailableListener listener) { 6501 ThreadedRenderer renderer = getThreadedRenderer(); 6502 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 6503 if (fmo == null) { 6504 throw new IllegalArgumentException( 6505 "attempt to remove OnFrameMetricsAvailableListener that was never added"); 6506 } 6507 6508 if (mFrameMetricsObservers != null) { 6509 mFrameMetricsObservers.remove(fmo); 6510 if (renderer != null) { 6511 renderer.removeFrameMetricsObserver(fmo); 6512 } 6513 } 6514 } 6515 6516 private void registerPendingFrameMetricsObservers() { 6517 if (mFrameMetricsObservers != null) { 6518 ThreadedRenderer renderer = getThreadedRenderer(); 6519 if (renderer != null) { 6520 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 6521 renderer.addFrameMetricsObserver(fmo); 6522 } 6523 } else { 6524 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 6525 } 6526 } 6527 } 6528 6529 private FrameMetricsObserver findFrameMetricsObserver( 6530 Window.OnFrameMetricsAvailableListener listener) { 6531 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 6532 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 6533 if (observer.mListener == listener) { 6534 return observer; 6535 } 6536 } 6537 6538 return null; 6539 } 6540 6541 /** @hide */ 6542 public void setNotifyAutofillManagerOnClick(boolean notify) { 6543 if (notify) { 6544 mPrivateFlags |= PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK; 6545 } else { 6546 mPrivateFlags &= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK; 6547 } 6548 } 6549 6550 private void notifyAutofillManagerOnClick() { 6551 if ((mPrivateFlags & PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK) != 0) { 6552 try { 6553 getAutofillManager().notifyViewClicked(this); 6554 } finally { 6555 // Set it to already called so it's not called twice when called by 6556 // performClickInternal() 6557 mPrivateFlags &= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK; 6558 } 6559 } 6560 } 6561 6562 /** 6563 * Entry point for {@link #performClick()} - other methods on View should call it instead of 6564 * {@code performClick()} directly to make sure the autofill manager is notified when 6565 * necessary (as subclasses could extend {@code performClick()} without calling the parent's 6566 * method). 6567 */ 6568 private boolean performClickInternal() { 6569 // Must notify autofill manager before performing the click actions to avoid scenarios where 6570 // the app has a click listener that changes the state of views the autofill service might 6571 // be interested on. 6572 notifyAutofillManagerOnClick(); 6573 6574 return performClick(); 6575 } 6576 6577 /** 6578 * Call this view's OnClickListener, if it is defined. Performs all normal 6579 * actions associated with clicking: reporting accessibility event, playing 6580 * a sound, etc. 6581 * 6582 * @return True there was an assigned OnClickListener that was called, false 6583 * otherwise is returned. 6584 */ 6585 // NOTE: other methods on View should not call this method directly, but performClickInternal() 6586 // instead, to guarantee that the autofill manager is notified when necessary (as subclasses 6587 // could extend this method without calling super.performClick()). 6588 public boolean performClick() { 6589 // We still need to call this method to handle the cases where performClick() was called 6590 // externally, instead of through performClickInternal() 6591 notifyAutofillManagerOnClick(); 6592 6593 final boolean result; 6594 final ListenerInfo li = mListenerInfo; 6595 if (li != null && li.mOnClickListener != null) { 6596 playSoundEffect(SoundEffectConstants.CLICK); 6597 li.mOnClickListener.onClick(this); 6598 result = true; 6599 } else { 6600 result = false; 6601 } 6602 6603 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 6604 6605 notifyEnterOrExitForAutoFillIfNeeded(true); 6606 6607 return result; 6608 } 6609 6610 /** 6611 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 6612 * this only calls the listener, and does not do any associated clicking 6613 * actions like reporting an accessibility event. 6614 * 6615 * @return True there was an assigned OnClickListener that was called, false 6616 * otherwise is returned. 6617 */ 6618 public boolean callOnClick() { 6619 ListenerInfo li = mListenerInfo; 6620 if (li != null && li.mOnClickListener != null) { 6621 li.mOnClickListener.onClick(this); 6622 return true; 6623 } 6624 return false; 6625 } 6626 6627 /** 6628 * Calls this view's OnLongClickListener, if it is defined. Invokes the 6629 * context menu if the OnLongClickListener did not consume the event. 6630 * 6631 * @return {@code true} if one of the above receivers consumed the event, 6632 * {@code false} otherwise 6633 */ 6634 public boolean performLongClick() { 6635 return performLongClickInternal(mLongClickX, mLongClickY); 6636 } 6637 6638 /** 6639 * Calls this view's OnLongClickListener, if it is defined. Invokes the 6640 * context menu if the OnLongClickListener did not consume the event, 6641 * anchoring it to an (x,y) coordinate. 6642 * 6643 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 6644 * to disable anchoring 6645 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 6646 * to disable anchoring 6647 * @return {@code true} if one of the above receivers consumed the event, 6648 * {@code false} otherwise 6649 */ 6650 public boolean performLongClick(float x, float y) { 6651 mLongClickX = x; 6652 mLongClickY = y; 6653 final boolean handled = performLongClick(); 6654 mLongClickX = Float.NaN; 6655 mLongClickY = Float.NaN; 6656 return handled; 6657 } 6658 6659 /** 6660 * Calls this view's OnLongClickListener, if it is defined. Invokes the 6661 * context menu if the OnLongClickListener did not consume the event, 6662 * optionally anchoring it to an (x,y) coordinate. 6663 * 6664 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 6665 * to disable anchoring 6666 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 6667 * to disable anchoring 6668 * @return {@code true} if one of the above receivers consumed the event, 6669 * {@code false} otherwise 6670 */ 6671 private boolean performLongClickInternal(float x, float y) { 6672 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 6673 6674 boolean handled = false; 6675 final ListenerInfo li = mListenerInfo; 6676 if (li != null && li.mOnLongClickListener != null) { 6677 handled = li.mOnLongClickListener.onLongClick(View.this); 6678 } 6679 if (!handled) { 6680 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 6681 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 6682 } 6683 if ((mViewFlags & TOOLTIP) == TOOLTIP) { 6684 if (!handled) { 6685 handled = showLongClickTooltip((int) x, (int) y); 6686 } 6687 } 6688 if (handled) { 6689 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 6690 } 6691 return handled; 6692 } 6693 6694 /** 6695 * Call this view's OnContextClickListener, if it is defined. 6696 * 6697 * @param x the x coordinate of the context click 6698 * @param y the y coordinate of the context click 6699 * @return True if there was an assigned OnContextClickListener that consumed the event, false 6700 * otherwise. 6701 */ 6702 public boolean performContextClick(float x, float y) { 6703 return performContextClick(); 6704 } 6705 6706 /** 6707 * Call this view's OnContextClickListener, if it is defined. 6708 * 6709 * @return True if there was an assigned OnContextClickListener that consumed the event, false 6710 * otherwise. 6711 */ 6712 public boolean performContextClick() { 6713 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 6714 6715 boolean handled = false; 6716 ListenerInfo li = mListenerInfo; 6717 if (li != null && li.mOnContextClickListener != null) { 6718 handled = li.mOnContextClickListener.onContextClick(View.this); 6719 } 6720 if (handled) { 6721 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 6722 } 6723 return handled; 6724 } 6725 6726 /** 6727 * Performs button-related actions during a touch down event. 6728 * 6729 * @param event The event. 6730 * @return True if the down was consumed. 6731 * 6732 * @hide 6733 */ 6734 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 6735 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 6736 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 6737 showContextMenu(event.getX(), event.getY()); 6738 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 6739 return true; 6740 } 6741 return false; 6742 } 6743 6744 /** 6745 * Shows the context menu for this view. 6746 * 6747 * @return {@code true} if the context menu was shown, {@code false} 6748 * otherwise 6749 * @see #showContextMenu(float, float) 6750 */ 6751 public boolean showContextMenu() { 6752 return getParent().showContextMenuForChild(this); 6753 } 6754 6755 /** 6756 * Shows the context menu for this view anchored to the specified 6757 * view-relative coordinate. 6758 * 6759 * @param x the X coordinate in pixels relative to the view to which the 6760 * menu should be anchored, or {@link Float#NaN} to disable anchoring 6761 * @param y the Y coordinate in pixels relative to the view to which the 6762 * menu should be anchored, or {@link Float#NaN} to disable anchoring 6763 * @return {@code true} if the context menu was shown, {@code false} 6764 * otherwise 6765 */ 6766 public boolean showContextMenu(float x, float y) { 6767 return getParent().showContextMenuForChild(this, x, y); 6768 } 6769 6770 /** 6771 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 6772 * 6773 * @param callback Callback that will control the lifecycle of the action mode 6774 * @return The new action mode if it is started, null otherwise 6775 * 6776 * @see ActionMode 6777 * @see #startActionMode(android.view.ActionMode.Callback, int) 6778 */ 6779 public ActionMode startActionMode(ActionMode.Callback callback) { 6780 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 6781 } 6782 6783 /** 6784 * Start an action mode with the given type. 6785 * 6786 * @param callback Callback that will control the lifecycle of the action mode 6787 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 6788 * @return The new action mode if it is started, null otherwise 6789 * 6790 * @see ActionMode 6791 */ 6792 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 6793 ViewParent parent = getParent(); 6794 if (parent == null) return null; 6795 try { 6796 return parent.startActionModeForChild(this, callback, type); 6797 } catch (AbstractMethodError ame) { 6798 // Older implementations of custom views might not implement this. 6799 return parent.startActionModeForChild(this, callback); 6800 } 6801 } 6802 6803 /** 6804 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 6805 * Context, creating a unique View identifier to retrieve the result. 6806 * 6807 * @param intent The Intent to be started. 6808 * @param requestCode The request code to use. 6809 * @hide 6810 */ 6811 public void startActivityForResult(Intent intent, int requestCode) { 6812 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 6813 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 6814 } 6815 6816 /** 6817 * If this View corresponds to the calling who, dispatches the activity result. 6818 * @param who The identifier for the targeted View to receive the result. 6819 * @param requestCode The integer request code originally supplied to 6820 * startActivityForResult(), allowing you to identify who this 6821 * result came from. 6822 * @param resultCode The integer result code returned by the child activity 6823 * through its setResult(). 6824 * @param data An Intent, which can return result data to the caller 6825 * (various data can be attached to Intent "extras"). 6826 * @return {@code true} if the activity result was dispatched. 6827 * @hide 6828 */ 6829 public boolean dispatchActivityResult( 6830 String who, int requestCode, int resultCode, Intent data) { 6831 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 6832 onActivityResult(requestCode, resultCode, data); 6833 mStartActivityRequestWho = null; 6834 return true; 6835 } 6836 return false; 6837 } 6838 6839 /** 6840 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 6841 * 6842 * @param requestCode The integer request code originally supplied to 6843 * startActivityForResult(), allowing you to identify who this 6844 * result came from. 6845 * @param resultCode The integer result code returned by the child activity 6846 * through its setResult(). 6847 * @param data An Intent, which can return result data to the caller 6848 * (various data can be attached to Intent "extras"). 6849 * @hide 6850 */ 6851 public void onActivityResult(int requestCode, int resultCode, Intent data) { 6852 // Do nothing. 6853 } 6854 6855 /** 6856 * Register a callback to be invoked when a hardware key is pressed in this view. 6857 * Key presses in software input methods will generally not trigger the methods of 6858 * this listener. 6859 * @param l the key listener to attach to this view 6860 */ 6861 public void setOnKeyListener(OnKeyListener l) { 6862 getListenerInfo().mOnKeyListener = l; 6863 } 6864 6865 /** 6866 * Register a callback to be invoked when a touch event is sent to this view. 6867 * @param l the touch listener to attach to this view 6868 */ 6869 public void setOnTouchListener(OnTouchListener l) { 6870 getListenerInfo().mOnTouchListener = l; 6871 } 6872 6873 /** 6874 * Register a callback to be invoked when a generic motion event is sent to this view. 6875 * @param l the generic motion listener to attach to this view 6876 */ 6877 public void setOnGenericMotionListener(OnGenericMotionListener l) { 6878 getListenerInfo().mOnGenericMotionListener = l; 6879 } 6880 6881 /** 6882 * Register a callback to be invoked when a hover event is sent to this view. 6883 * @param l the hover listener to attach to this view 6884 */ 6885 public void setOnHoverListener(OnHoverListener l) { 6886 getListenerInfo().mOnHoverListener = l; 6887 } 6888 6889 /** 6890 * Register a drag event listener callback object for this View. The parameter is 6891 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 6892 * View, the system calls the 6893 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 6894 * @param l An implementation of {@link android.view.View.OnDragListener}. 6895 */ 6896 public void setOnDragListener(OnDragListener l) { 6897 getListenerInfo().mOnDragListener = l; 6898 } 6899 6900 /** 6901 * Give this view focus. This will cause 6902 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 6903 * 6904 * Note: this does not check whether this {@link View} should get focus, it just 6905 * gives it focus no matter what. It should only be called internally by framework 6906 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 6907 * 6908 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 6909 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 6910 * focus moved when requestFocus() is called. It may not always 6911 * apply, in which case use the default View.FOCUS_DOWN. 6912 * @param previouslyFocusedRect The rectangle of the view that had focus 6913 * prior in this View's coordinate system. 6914 */ 6915 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 6916 if (DBG) { 6917 System.out.println(this + " requestFocus()"); 6918 } 6919 6920 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 6921 mPrivateFlags |= PFLAG_FOCUSED; 6922 6923 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 6924 6925 if (mParent != null) { 6926 mParent.requestChildFocus(this, this); 6927 updateFocusedInCluster(oldFocus, direction); 6928 } 6929 6930 if (mAttachInfo != null) { 6931 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 6932 } 6933 6934 onFocusChanged(true, direction, previouslyFocusedRect); 6935 refreshDrawableState(); 6936 } 6937 } 6938 6939 /** 6940 * Sets this view's preference for reveal behavior when it gains focus. 6941 * 6942 * <p>When set to true, this is a signal to ancestor views in the hierarchy that 6943 * this view would prefer to be brought fully into view when it gains focus. 6944 * For example, a text field that a user is meant to type into. Other views such 6945 * as scrolling containers may prefer to opt-out of this behavior.</p> 6946 * 6947 * <p>The default value for views is true, though subclasses may change this 6948 * based on their preferred behavior.</p> 6949 * 6950 * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise 6951 * 6952 * @see #getRevealOnFocusHint() 6953 */ 6954 public final void setRevealOnFocusHint(boolean revealOnFocus) { 6955 if (revealOnFocus) { 6956 mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS; 6957 } else { 6958 mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS; 6959 } 6960 } 6961 6962 /** 6963 * Returns this view's preference for reveal behavior when it gains focus. 6964 * 6965 * <p>When this method returns true for a child view requesting focus, ancestor 6966 * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)} 6967 * should make a best effort to make the newly focused child fully visible to the user. 6968 * When it returns false, ancestor views should preferably not disrupt scroll positioning or 6969 * other properties affecting visibility to the user as part of the focus change.</p> 6970 * 6971 * @return true if this view would prefer to become fully visible when it gains focus, 6972 * false if it would prefer not to disrupt scroll positioning 6973 * 6974 * @see #setRevealOnFocusHint(boolean) 6975 */ 6976 public final boolean getRevealOnFocusHint() { 6977 return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0; 6978 } 6979 6980 /** 6981 * Populates <code>outRect</code> with the hotspot bounds. By default, 6982 * the hotspot bounds are identical to the screen bounds. 6983 * 6984 * @param outRect rect to populate with hotspot bounds 6985 * @hide Only for internal use by views and widgets. 6986 */ 6987 public void getHotspotBounds(Rect outRect) { 6988 final Drawable background = getBackground(); 6989 if (background != null) { 6990 background.getHotspotBounds(outRect); 6991 } else { 6992 getBoundsOnScreen(outRect); 6993 } 6994 } 6995 6996 /** 6997 * Request that a rectangle of this view be visible on the screen, 6998 * scrolling if necessary just enough. 6999 * 7000 * <p>A View should call this if it maintains some notion of which part 7001 * of its content is interesting. For example, a text editing view 7002 * should call this when its cursor moves. 7003 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 7004 * It should not be affected by which part of the View is currently visible or its scroll 7005 * position. 7006 * 7007 * @param rectangle The rectangle in the View's content coordinate space 7008 * @return Whether any parent scrolled. 7009 */ 7010 public boolean requestRectangleOnScreen(Rect rectangle) { 7011 return requestRectangleOnScreen(rectangle, false); 7012 } 7013 7014 /** 7015 * Request that a rectangle of this view be visible on the screen, 7016 * scrolling if necessary just enough. 7017 * 7018 * <p>A View should call this if it maintains some notion of which part 7019 * of its content is interesting. For example, a text editing view 7020 * should call this when its cursor moves. 7021 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 7022 * It should not be affected by which part of the View is currently visible or its scroll 7023 * position. 7024 * <p>When <code>immediate</code> is set to true, scrolling will not be 7025 * animated. 7026 * 7027 * @param rectangle The rectangle in the View's content coordinate space 7028 * @param immediate True to forbid animated scrolling, false otherwise 7029 * @return Whether any parent scrolled. 7030 */ 7031 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 7032 if (mParent == null) { 7033 return false; 7034 } 7035 7036 View child = this; 7037 7038 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 7039 position.set(rectangle); 7040 7041 ViewParent parent = mParent; 7042 boolean scrolled = false; 7043 while (parent != null) { 7044 rectangle.set((int) position.left, (int) position.top, 7045 (int) position.right, (int) position.bottom); 7046 7047 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 7048 7049 if (!(parent instanceof View)) { 7050 break; 7051 } 7052 7053 // move it from child's content coordinate space to parent's content coordinate space 7054 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 7055 7056 child = (View) parent; 7057 parent = child.getParent(); 7058 } 7059 7060 return scrolled; 7061 } 7062 7063 /** 7064 * Called when this view wants to give up focus. If focus is cleared 7065 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 7066 * <p> 7067 * <strong>Note:</strong> When not in touch-mode, the framework will try to give focus 7068 * to the first focusable View from the top after focus is cleared. Hence, if this 7069 * View is the first from the top that can take focus, then all callbacks 7070 * related to clearing focus will be invoked after which the framework will 7071 * give focus to this view. 7072 * </p> 7073 */ 7074 public void clearFocus() { 7075 if (DBG) { 7076 System.out.println(this + " clearFocus()"); 7077 } 7078 7079 final boolean refocus = sAlwaysAssignFocus || !isInTouchMode(); 7080 clearFocusInternal(null, true, refocus); 7081 } 7082 7083 /** 7084 * Clears focus from the view, optionally propagating the change up through 7085 * the parent hierarchy and requesting that the root view place new focus. 7086 * 7087 * @param propagate whether to propagate the change up through the parent 7088 * hierarchy 7089 * @param refocus when propagate is true, specifies whether to request the 7090 * root view place new focus 7091 */ 7092 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 7093 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 7094 mPrivateFlags &= ~PFLAG_FOCUSED; 7095 clearParentsWantFocus(); 7096 7097 if (propagate && mParent != null) { 7098 mParent.clearChildFocus(this); 7099 } 7100 7101 onFocusChanged(false, 0, null); 7102 refreshDrawableState(); 7103 7104 if (propagate && (!refocus || !rootViewRequestFocus())) { 7105 notifyGlobalFocusCleared(this); 7106 } 7107 } 7108 } 7109 7110 void notifyGlobalFocusCleared(View oldFocus) { 7111 if (oldFocus != null && mAttachInfo != null) { 7112 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 7113 } 7114 } 7115 7116 boolean rootViewRequestFocus() { 7117 final View root = getRootView(); 7118 return root != null && root.requestFocus(); 7119 } 7120 7121 /** 7122 * Called internally by the view system when a new view is getting focus. 7123 * This is what clears the old focus. 7124 * <p> 7125 * <b>NOTE:</b> The parent view's focused child must be updated manually 7126 * after calling this method. Otherwise, the view hierarchy may be left in 7127 * an inconstent state. 7128 */ 7129 void unFocus(View focused) { 7130 if (DBG) { 7131 System.out.println(this + " unFocus()"); 7132 } 7133 7134 clearFocusInternal(focused, false, false); 7135 } 7136 7137 /** 7138 * Returns true if this view has focus itself, or is the ancestor of the 7139 * view that has focus. 7140 * 7141 * @return True if this view has or contains focus, false otherwise. 7142 */ 7143 @ViewDebug.ExportedProperty(category = "focus") 7144 public boolean hasFocus() { 7145 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7146 } 7147 7148 /** 7149 * Returns true if this view is focusable or if it contains a reachable View 7150 * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()" 7151 * is a view whose parents do not block descendants focus. 7152 * Only {@link #VISIBLE} views are considered focusable. 7153 * 7154 * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable 7155 * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}. 7156 * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of 7157 * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return 7158 * {@code false} for views not explicitly marked as focusable. 7159 * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O} 7160 * behavior.</p> 7161 * 7162 * @return {@code true} if the view is focusable or if the view contains a focusable 7163 * view, {@code false} otherwise 7164 * 7165 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 7166 * @see ViewGroup#getTouchscreenBlocksFocus() 7167 * @see #hasExplicitFocusable() 7168 */ 7169 public boolean hasFocusable() { 7170 return hasFocusable(!sHasFocusableExcludeAutoFocusable, false); 7171 } 7172 7173 /** 7174 * Returns true if this view is focusable or if it contains a reachable View 7175 * for which {@link #hasExplicitFocusable()} returns {@code true}. 7176 * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus. 7177 * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return 7178 * {@link #FOCUSABLE} are considered focusable. 7179 * 7180 * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of 7181 * {@link #hasFocusable()} in that only views explicitly set focusable will cause 7182 * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves 7183 * to focusable will not.</p> 7184 * 7185 * @return {@code true} if the view is focusable or if the view contains a focusable 7186 * view, {@code false} otherwise 7187 * 7188 * @see #hasFocusable() 7189 */ 7190 public boolean hasExplicitFocusable() { 7191 return hasFocusable(false, true); 7192 } 7193 7194 boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) { 7195 if (!isFocusableInTouchMode()) { 7196 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 7197 final ViewGroup g = (ViewGroup) p; 7198 if (g.shouldBlockFocusForTouchscreen()) { 7199 return false; 7200 } 7201 } 7202 } 7203 7204 // Invisible, gone, or disabled views are never focusable. 7205 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE 7206 || (mViewFlags & ENABLED_MASK) != ENABLED) { 7207 return false; 7208 } 7209 7210 // Only use effective focusable value when allowed. 7211 if ((allowAutoFocus || getFocusable() != FOCUSABLE_AUTO) && isFocusable()) { 7212 return true; 7213 } 7214 7215 return false; 7216 } 7217 7218 /** 7219 * Called by the view system when the focus state of this view changes. 7220 * When the focus change event is caused by directional navigation, direction 7221 * and previouslyFocusedRect provide insight into where the focus is coming from. 7222 * When overriding, be sure to call up through to the super class so that 7223 * the standard focus handling will occur. 7224 * 7225 * @param gainFocus True if the View has focus; false otherwise. 7226 * @param direction The direction focus has moved when requestFocus() 7227 * is called to give this view focus. Values are 7228 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 7229 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 7230 * It may not always apply, in which case use the default. 7231 * @param previouslyFocusedRect The rectangle, in this view's coordinate 7232 * system, of the previously focused view. If applicable, this will be 7233 * passed in as finer grained information about where the focus is coming 7234 * from (in addition to direction). Will be <code>null</code> otherwise. 7235 */ 7236 @CallSuper 7237 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 7238 @Nullable Rect previouslyFocusedRect) { 7239 if (gainFocus) { 7240 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 7241 } else { 7242 notifyViewAccessibilityStateChangedIfNeeded( 7243 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7244 } 7245 7246 // Here we check whether we still need the default focus highlight, and switch it on/off. 7247 switchDefaultFocusHighlight(); 7248 7249 InputMethodManager imm = InputMethodManager.peekInstance(); 7250 if (!gainFocus) { 7251 if (isPressed()) { 7252 setPressed(false); 7253 } 7254 if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 7255 imm.focusOut(this); 7256 } 7257 onFocusLost(); 7258 } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 7259 imm.focusIn(this); 7260 } 7261 7262 invalidate(true); 7263 ListenerInfo li = mListenerInfo; 7264 if (li != null && li.mOnFocusChangeListener != null) { 7265 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 7266 } 7267 7268 if (mAttachInfo != null) { 7269 mAttachInfo.mKeyDispatchState.reset(this); 7270 } 7271 7272 notifyEnterOrExitForAutoFillIfNeeded(gainFocus); 7273 } 7274 7275 /** @hide */ 7276 public void notifyEnterOrExitForAutoFillIfNeeded(boolean enter) { 7277 if (canNotifyAutofillEnterExitEvent()) { 7278 AutofillManager afm = getAutofillManager(); 7279 if (afm != null) { 7280 if (enter && isFocused()) { 7281 // We have not been laid out yet, hence cannot evaluate 7282 // whether this view is visible to the user, we will do 7283 // the evaluation once layout is complete. 7284 if (!isLaidOut()) { 7285 mPrivateFlags3 |= PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT; 7286 } else if (isVisibleToUser()) { 7287 // TODO This is a potential problem that View gets focus before it's visible 7288 // to User. Ideally View should handle the event when isVisibleToUser() 7289 // becomes true where it should issue notifyViewEntered(). 7290 afm.notifyViewEntered(this); 7291 } 7292 } else if (!enter && !isFocused()) { 7293 afm.notifyViewExited(this); 7294 } 7295 } 7296 } 7297 } 7298 7299 /** 7300 * Visually distinct portion of a window with window-like semantics are considered panes for 7301 * accessibility purposes. One example is the content view of a fragment that is replaced. 7302 * In order for accessibility services to understand a pane's window-like behavior, panes 7303 * should have descriptive titles. Views with pane titles produce {@link AccessibilityEvent}s 7304 * when they appear, disappear, or change title. 7305 * 7306 * @param accessibilityPaneTitle The pane's title. Setting to {@code null} indicates that this 7307 * View is not a pane. 7308 * 7309 * {@see AccessibilityNodeInfo#setPaneTitle(CharSequence)} 7310 */ 7311 public void setAccessibilityPaneTitle(@Nullable CharSequence accessibilityPaneTitle) { 7312 if (!TextUtils.equals(accessibilityPaneTitle, mAccessibilityPaneTitle)) { 7313 mAccessibilityPaneTitle = accessibilityPaneTitle; 7314 notifyViewAccessibilityStateChangedIfNeeded( 7315 AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_TITLE); 7316 } 7317 } 7318 7319 /** 7320 * Get the title of the pane for purposes of accessibility. 7321 * 7322 * @return The current pane title. 7323 * 7324 * {@see #setAccessibilityPaneTitle}. 7325 */ 7326 @Nullable public CharSequence getAccessibilityPaneTitle() { 7327 return mAccessibilityPaneTitle; 7328 } 7329 7330 private boolean isAccessibilityPane() { 7331 return mAccessibilityPaneTitle != null; 7332 } 7333 7334 /** 7335 * Sends an accessibility event of the given type. If accessibility is 7336 * not enabled this method has no effect. The default implementation calls 7337 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 7338 * to populate information about the event source (this View), then calls 7339 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 7340 * populate the text content of the event source including its descendants, 7341 * and last calls 7342 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 7343 * on its parent to request sending of the event to interested parties. 7344 * <p> 7345 * If an {@link AccessibilityDelegate} has been specified via calling 7346 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7347 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 7348 * responsible for handling this call. 7349 * </p> 7350 * 7351 * @param eventType The type of the event to send, as defined by several types from 7352 * {@link android.view.accessibility.AccessibilityEvent}, such as 7353 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 7354 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 7355 * 7356 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 7357 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 7358 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 7359 * @see AccessibilityDelegate 7360 */ 7361 public void sendAccessibilityEvent(int eventType) { 7362 if (mAccessibilityDelegate != null) { 7363 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 7364 } else { 7365 sendAccessibilityEventInternal(eventType); 7366 } 7367 } 7368 7369 /** 7370 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 7371 * {@link AccessibilityEvent} to make an announcement which is related to some 7372 * sort of a context change for which none of the events representing UI transitions 7373 * is a good fit. For example, announcing a new page in a book. If accessibility 7374 * is not enabled this method does nothing. 7375 * 7376 * @param text The announcement text. 7377 */ 7378 public void announceForAccessibility(CharSequence text) { 7379 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 7380 AccessibilityEvent event = AccessibilityEvent.obtain( 7381 AccessibilityEvent.TYPE_ANNOUNCEMENT); 7382 onInitializeAccessibilityEvent(event); 7383 event.getText().add(text); 7384 event.setContentDescription(null); 7385 mParent.requestSendAccessibilityEvent(this, event); 7386 } 7387 } 7388 7389 /** 7390 * @see #sendAccessibilityEvent(int) 7391 * 7392 * Note: Called from the default {@link AccessibilityDelegate}. 7393 * 7394 * @hide 7395 */ 7396 public void sendAccessibilityEventInternal(int eventType) { 7397 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 7398 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 7399 } 7400 } 7401 7402 /** 7403 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 7404 * takes as an argument an empty {@link AccessibilityEvent} and does not 7405 * perform a check whether accessibility is enabled. 7406 * <p> 7407 * If an {@link AccessibilityDelegate} has been specified via calling 7408 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7409 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 7410 * is responsible for handling this call. 7411 * </p> 7412 * 7413 * @param event The event to send. 7414 * 7415 * @see #sendAccessibilityEvent(int) 7416 */ 7417 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 7418 if (mAccessibilityDelegate != null) { 7419 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 7420 } else { 7421 sendAccessibilityEventUncheckedInternal(event); 7422 } 7423 } 7424 7425 /** 7426 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 7427 * 7428 * Note: Called from the default {@link AccessibilityDelegate}. 7429 * 7430 * @hide 7431 */ 7432 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 7433 // Panes disappearing are relevant even if though the view is no longer visible. 7434 boolean isWindowStateChanged = 7435 (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 7436 boolean isWindowDisappearedEvent = isWindowStateChanged && ((event.getContentChangeTypes() 7437 & AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED) != 0); 7438 if (!isShown() && !isWindowDisappearedEvent) { 7439 return; 7440 } 7441 onInitializeAccessibilityEvent(event); 7442 // Only a subset of accessibility events populates text content. 7443 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 7444 dispatchPopulateAccessibilityEvent(event); 7445 } 7446 // In the beginning we called #isShown(), so we know that getParent() is not null. 7447 ViewParent parent = getParent(); 7448 if (parent != null) { 7449 getParent().requestSendAccessibilityEvent(this, event); 7450 } 7451 } 7452 7453 /** 7454 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 7455 * to its children for adding their text content to the event. Note that the 7456 * event text is populated in a separate dispatch path since we add to the 7457 * event not only the text of the source but also the text of all its descendants. 7458 * A typical implementation will call 7459 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 7460 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 7461 * on each child. Override this method if custom population of the event text 7462 * content is required. 7463 * <p> 7464 * If an {@link AccessibilityDelegate} has been specified via calling 7465 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7466 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 7467 * is responsible for handling this call. 7468 * </p> 7469 * <p> 7470 * <em>Note:</em> Accessibility events of certain types are not dispatched for 7471 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 7472 * </p> 7473 * 7474 * @param event The event. 7475 * 7476 * @return True if the event population was completed. 7477 */ 7478 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 7479 if (mAccessibilityDelegate != null) { 7480 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 7481 } else { 7482 return dispatchPopulateAccessibilityEventInternal(event); 7483 } 7484 } 7485 7486 /** 7487 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 7488 * 7489 * Note: Called from the default {@link AccessibilityDelegate}. 7490 * 7491 * @hide 7492 */ 7493 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 7494 onPopulateAccessibilityEvent(event); 7495 return false; 7496 } 7497 7498 /** 7499 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 7500 * giving a chance to this View to populate the accessibility event with its 7501 * text content. While this method is free to modify event 7502 * attributes other than text content, doing so should normally be performed in 7503 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 7504 * <p> 7505 * Example: Adding formatted date string to an accessibility event in addition 7506 * to the text added by the super implementation: 7507 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 7508 * super.onPopulateAccessibilityEvent(event); 7509 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 7510 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 7511 * mCurrentDate.getTimeInMillis(), flags); 7512 * event.getText().add(selectedDateUtterance); 7513 * }</pre> 7514 * <p> 7515 * If an {@link AccessibilityDelegate} has been specified via calling 7516 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7517 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 7518 * is responsible for handling this call. 7519 * </p> 7520 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 7521 * information to the event, in case the default implementation has basic information to add. 7522 * </p> 7523 * 7524 * @param event The accessibility event which to populate. 7525 * 7526 * @see #sendAccessibilityEvent(int) 7527 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 7528 */ 7529 @CallSuper 7530 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 7531 if (mAccessibilityDelegate != null) { 7532 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 7533 } else { 7534 onPopulateAccessibilityEventInternal(event); 7535 } 7536 } 7537 7538 /** 7539 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 7540 * 7541 * Note: Called from the default {@link AccessibilityDelegate}. 7542 * 7543 * @hide 7544 */ 7545 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 7546 if ((event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) 7547 && !TextUtils.isEmpty(getAccessibilityPaneTitle())) { 7548 event.getText().add(getAccessibilityPaneTitle()); 7549 } 7550 } 7551 7552 /** 7553 * Initializes an {@link AccessibilityEvent} with information about 7554 * this View which is the event source. In other words, the source of 7555 * an accessibility event is the view whose state change triggered firing 7556 * the event. 7557 * <p> 7558 * Example: Setting the password property of an event in addition 7559 * to properties set by the super implementation: 7560 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 7561 * super.onInitializeAccessibilityEvent(event); 7562 * event.setPassword(true); 7563 * }</pre> 7564 * <p> 7565 * If an {@link AccessibilityDelegate} has been specified via calling 7566 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7567 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 7568 * is responsible for handling this call. 7569 * </p> 7570 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 7571 * information to the event, in case the default implementation has basic information to add. 7572 * </p> 7573 * @param event The event to initialize. 7574 * 7575 * @see #sendAccessibilityEvent(int) 7576 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 7577 */ 7578 @CallSuper 7579 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 7580 if (mAccessibilityDelegate != null) { 7581 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 7582 } else { 7583 onInitializeAccessibilityEventInternal(event); 7584 } 7585 } 7586 7587 /** 7588 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 7589 * 7590 * Note: Called from the default {@link AccessibilityDelegate}. 7591 * 7592 * @hide 7593 */ 7594 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 7595 event.setSource(this); 7596 event.setClassName(getAccessibilityClassName()); 7597 event.setPackageName(getContext().getPackageName()); 7598 event.setEnabled(isEnabled()); 7599 event.setContentDescription(mContentDescription); 7600 7601 switch (event.getEventType()) { 7602 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 7603 ArrayList<View> focusablesTempList = (mAttachInfo != null) 7604 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 7605 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 7606 event.setItemCount(focusablesTempList.size()); 7607 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 7608 if (mAttachInfo != null) { 7609 focusablesTempList.clear(); 7610 } 7611 } break; 7612 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 7613 CharSequence text = getIterableTextForAccessibility(); 7614 if (text != null && text.length() > 0) { 7615 event.setFromIndex(getAccessibilitySelectionStart()); 7616 event.setToIndex(getAccessibilitySelectionEnd()); 7617 event.setItemCount(text.length()); 7618 } 7619 } break; 7620 } 7621 } 7622 7623 /** 7624 * Returns an {@link AccessibilityNodeInfo} representing this view from the 7625 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 7626 * This method is responsible for obtaining an accessibility node info from a 7627 * pool of reusable instances and calling 7628 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 7629 * initialize the former. 7630 * <p> 7631 * Note: The client is responsible for recycling the obtained instance by calling 7632 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 7633 * </p> 7634 * 7635 * @return A populated {@link AccessibilityNodeInfo}. 7636 * 7637 * @see AccessibilityNodeInfo 7638 */ 7639 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 7640 if (mAccessibilityDelegate != null) { 7641 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 7642 } else { 7643 return createAccessibilityNodeInfoInternal(); 7644 } 7645 } 7646 7647 /** 7648 * @see #createAccessibilityNodeInfo() 7649 * 7650 * @hide 7651 */ 7652 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 7653 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 7654 if (provider != null) { 7655 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 7656 } else { 7657 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 7658 onInitializeAccessibilityNodeInfo(info); 7659 return info; 7660 } 7661 } 7662 7663 /** 7664 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 7665 * The base implementation sets: 7666 * <ul> 7667 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 7668 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 7669 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 7670 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 7671 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 7672 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 7673 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 7674 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 7675 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 7676 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 7677 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 7678 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 7679 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 7680 * </ul> 7681 * <p> 7682 * Subclasses should override this method, call the super implementation, 7683 * and set additional attributes. 7684 * </p> 7685 * <p> 7686 * If an {@link AccessibilityDelegate} has been specified via calling 7687 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7688 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 7689 * is responsible for handling this call. 7690 * </p> 7691 * 7692 * @param info The instance to initialize. 7693 */ 7694 @CallSuper 7695 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 7696 if (mAccessibilityDelegate != null) { 7697 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 7698 } else { 7699 onInitializeAccessibilityNodeInfoInternal(info); 7700 } 7701 } 7702 7703 /** 7704 * Gets the location of this view in screen coordinates. 7705 * 7706 * @param outRect The output location 7707 * @hide 7708 */ 7709 public void getBoundsOnScreen(Rect outRect) { 7710 getBoundsOnScreen(outRect, false); 7711 } 7712 7713 /** 7714 * Gets the location of this view in screen coordinates. 7715 * 7716 * @param outRect The output location 7717 * @param clipToParent Whether to clip child bounds to the parent ones. 7718 * @hide 7719 */ 7720 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 7721 if (mAttachInfo == null) { 7722 return; 7723 } 7724 7725 RectF position = mAttachInfo.mTmpTransformRect; 7726 position.set(0, 0, mRight - mLeft, mBottom - mTop); 7727 mapRectFromViewToScreenCoords(position, clipToParent); 7728 outRect.set(Math.round(position.left), Math.round(position.top), 7729 Math.round(position.right), Math.round(position.bottom)); 7730 } 7731 7732 /** 7733 * Map a rectangle from view-relative coordinates to screen-relative coordinates 7734 * 7735 * @param rect The rectangle to be mapped 7736 * @param clipToParent Whether to clip child bounds to the parent ones. 7737 * @hide 7738 */ 7739 public void mapRectFromViewToScreenCoords(RectF rect, boolean clipToParent) { 7740 if (!hasIdentityMatrix()) { 7741 getMatrix().mapRect(rect); 7742 } 7743 7744 rect.offset(mLeft, mTop); 7745 7746 ViewParent parent = mParent; 7747 while (parent instanceof View) { 7748 View parentView = (View) parent; 7749 7750 rect.offset(-parentView.mScrollX, -parentView.mScrollY); 7751 7752 if (clipToParent) { 7753 rect.left = Math.max(rect.left, 0); 7754 rect.top = Math.max(rect.top, 0); 7755 rect.right = Math.min(rect.right, parentView.getWidth()); 7756 rect.bottom = Math.min(rect.bottom, parentView.getHeight()); 7757 } 7758 7759 if (!parentView.hasIdentityMatrix()) { 7760 parentView.getMatrix().mapRect(rect); 7761 } 7762 7763 rect.offset(parentView.mLeft, parentView.mTop); 7764 7765 parent = parentView.mParent; 7766 } 7767 7768 if (parent instanceof ViewRootImpl) { 7769 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 7770 rect.offset(0, -viewRootImpl.mCurScrollY); 7771 } 7772 7773 rect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 7774 } 7775 7776 /** 7777 * Return the class name of this object to be used for accessibility purposes. 7778 * Subclasses should only override this if they are implementing something that 7779 * should be seen as a completely new class of view when used by accessibility, 7780 * unrelated to the class it is deriving from. This is used to fill in 7781 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 7782 */ 7783 public CharSequence getAccessibilityClassName() { 7784 return View.class.getName(); 7785 } 7786 7787 /** 7788 * Called when assist structure is being retrieved from a view as part of 7789 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 7790 * @param structure Fill in with structured view data. The default implementation 7791 * fills in all data that can be inferred from the view itself. 7792 */ 7793 public void onProvideStructure(ViewStructure structure) { 7794 onProvideStructureForAssistOrAutofill(structure, false, 0); 7795 } 7796 7797 /** 7798 * Populates a {@link ViewStructure} to fullfil an autofill request. 7799 * 7800 * <p>The structure should contain at least the following properties: 7801 * <ul> 7802 * <li>Autofill id ({@link ViewStructure#setAutofillId(AutofillId, int)}). 7803 * <li>Autofill type ({@link ViewStructure#setAutofillType(int)}). 7804 * <li>Autofill value ({@link ViewStructure#setAutofillValue(AutofillValue)}). 7805 * <li>Whether the data is sensitive ({@link ViewStructure#setDataIsSensitive(boolean)}). 7806 * </ul> 7807 * 7808 * <p>It's also recommended to set the following properties - the more properties the structure 7809 * has, the higher the changes of an {@link android.service.autofill.AutofillService} properly 7810 * using the structure: 7811 * 7812 * <ul> 7813 * <li>Autofill hints ({@link ViewStructure#setAutofillHints(String[])}). 7814 * <li>Autofill options ({@link ViewStructure#setAutofillOptions(CharSequence[])}) when the 7815 * view can only be filled with predefined values (typically used when the autofill type 7816 * is {@link #AUTOFILL_TYPE_LIST}). 7817 * <li>Resource id ({@link ViewStructure#setId(int, String, String, String)}). 7818 * <li>Class name ({@link ViewStructure#setClassName(String)}). 7819 * <li>Content description ({@link ViewStructure#setContentDescription(CharSequence)}). 7820 * <li>Visual properties such as visibility ({@link ViewStructure#setVisibility(int)}), 7821 * dimensions ({@link ViewStructure#setDimens(int, int, int, int, int, int)}), and 7822 * opacity ({@link ViewStructure#setOpaque(boolean)}). 7823 * <li>For views representing text fields, text properties such as the text itself 7824 * ({@link ViewStructure#setText(CharSequence)}), text hints 7825 * ({@link ViewStructure#setHint(CharSequence)}, input type 7826 * ({@link ViewStructure#setInputType(int)}), 7827 * <li>For views representing HTML nodes, its web domain 7828 * ({@link ViewStructure#setWebDomain(String)}) and HTML properties 7829 * (({@link ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)}). 7830 * </ul> 7831 * 7832 * <p>The default implementation of this method already sets most of these properties based on 7833 * related {@link View} methods (for example, the autofill id is set using 7834 * {@link #getAutofillId()}, the autofill type set using {@link #getAutofillType()}, etc.), 7835 * and views in the standard Android widgets library also override it to set their 7836 * relevant properties (for example, {@link android.widget.TextView} already sets the text 7837 * properties), so it's recommended to only override this method 7838 * (and call {@code super.onProvideAutofillStructure()}) when: 7839 * 7840 * <ul> 7841 * <li>The view contents does not include PII (Personally Identifiable Information), so it 7842 * can call {@link ViewStructure#setDataIsSensitive(boolean)} passing {@code false}. 7843 * <li>The view can only be autofilled with predefined options, so it can call 7844 * {@link ViewStructure#setAutofillOptions(CharSequence[])}. 7845 * </ul> 7846 * 7847 * <p><b>Note:</b> The {@code left} and {@code top} values set in 7848 * {@link ViewStructure#setDimens(int, int, int, int, int, int)} must be relative to the next 7849 * {@link ViewGroup#isImportantForAutofill()} predecessor view included in the structure. 7850 * 7851 * <p>Views support the Autofill Framework mainly by: 7852 * <ul> 7853 * <li>Providing the metadata defining what the view means and how it can be autofilled. 7854 * <li>Notifying the Android System when the view value changed by calling 7855 * {@link AutofillManager#notifyValueChanged(View)}. 7856 * <li>Implementing the methods that autofill the view. 7857 * </ul> 7858 * <p>This method is responsible for the former; {@link #autofill(AutofillValue)} is responsible 7859 * for the latter. 7860 * 7861 * @param structure fill in with structured view data for autofill purposes. 7862 * @param flags optional flags. 7863 * 7864 * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 7865 */ 7866 public void onProvideAutofillStructure(ViewStructure structure, @AutofillFlags int flags) { 7867 onProvideStructureForAssistOrAutofill(structure, true, flags); 7868 } 7869 7870 private void onProvideStructureForAssistOrAutofill(ViewStructure structure, 7871 boolean forAutofill, @AutofillFlags int flags) { 7872 final int id = mID; 7873 if (id != NO_ID && !isViewIdGenerated(id)) { 7874 String pkg, type, entry; 7875 try { 7876 final Resources res = getResources(); 7877 entry = res.getResourceEntryName(id); 7878 type = res.getResourceTypeName(id); 7879 pkg = res.getResourcePackageName(id); 7880 } catch (Resources.NotFoundException e) { 7881 entry = type = pkg = null; 7882 } 7883 structure.setId(id, pkg, type, entry); 7884 } else { 7885 structure.setId(id, null, null, null); 7886 } 7887 7888 if (forAutofill) { 7889 final @AutofillType int autofillType = getAutofillType(); 7890 // Don't need to fill autofill info if view does not support it. 7891 // For example, only TextViews that are editable support autofill 7892 if (autofillType != AUTOFILL_TYPE_NONE) { 7893 structure.setAutofillType(autofillType); 7894 structure.setAutofillHints(getAutofillHints()); 7895 structure.setAutofillValue(getAutofillValue()); 7896 } 7897 structure.setImportantForAutofill(getImportantForAutofill()); 7898 } 7899 7900 int ignoredParentLeft = 0; 7901 int ignoredParentTop = 0; 7902 if (forAutofill && (flags & AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) == 0) { 7903 View parentGroup = null; 7904 7905 ViewParent viewParent = getParent(); 7906 if (viewParent instanceof View) { 7907 parentGroup = (View) viewParent; 7908 } 7909 7910 while (parentGroup != null && !parentGroup.isImportantForAutofill()) { 7911 ignoredParentLeft += parentGroup.mLeft; 7912 ignoredParentTop += parentGroup.mTop; 7913 7914 viewParent = parentGroup.getParent(); 7915 if (viewParent instanceof View) { 7916 parentGroup = (View) viewParent; 7917 } else { 7918 break; 7919 } 7920 } 7921 } 7922 7923 structure.setDimens(ignoredParentLeft + mLeft, ignoredParentTop + mTop, mScrollX, mScrollY, 7924 mRight - mLeft, mBottom - mTop); 7925 if (!forAutofill) { 7926 if (!hasIdentityMatrix()) { 7927 structure.setTransformation(getMatrix()); 7928 } 7929 structure.setElevation(getZ()); 7930 } 7931 structure.setVisibility(getVisibility()); 7932 structure.setEnabled(isEnabled()); 7933 if (isClickable()) { 7934 structure.setClickable(true); 7935 } 7936 if (isFocusable()) { 7937 structure.setFocusable(true); 7938 } 7939 if (isFocused()) { 7940 structure.setFocused(true); 7941 } 7942 if (isAccessibilityFocused()) { 7943 structure.setAccessibilityFocused(true); 7944 } 7945 if (isSelected()) { 7946 structure.setSelected(true); 7947 } 7948 if (isActivated()) { 7949 structure.setActivated(true); 7950 } 7951 if (isLongClickable()) { 7952 structure.setLongClickable(true); 7953 } 7954 if (this instanceof Checkable) { 7955 structure.setCheckable(true); 7956 if (((Checkable)this).isChecked()) { 7957 structure.setChecked(true); 7958 } 7959 } 7960 if (isOpaque()) { 7961 structure.setOpaque(true); 7962 } 7963 if (isContextClickable()) { 7964 structure.setContextClickable(true); 7965 } 7966 structure.setClassName(getAccessibilityClassName().toString()); 7967 structure.setContentDescription(getContentDescription()); 7968 } 7969 7970 /** 7971 * Called when assist structure is being retrieved from a view as part of 7972 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 7973 * generate additional virtual structure under this view. The defaullt implementation 7974 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 7975 * view's virtual accessibility nodes, if any. You can override this for a more 7976 * optimal implementation providing this data. 7977 */ 7978 public void onProvideVirtualStructure(ViewStructure structure) { 7979 onProvideVirtualStructureCompat(structure, false); 7980 } 7981 7982 /** 7983 * Fallback implementation to populate a ViewStructure from accessibility state. 7984 * 7985 * @param structure The structure to populate. 7986 * @param forAutofill Whether the structure is needed for autofill. 7987 */ 7988 private void onProvideVirtualStructureCompat(ViewStructure structure, boolean forAutofill) { 7989 final AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 7990 if (provider != null) { 7991 if (android.view.autofill.Helper.sVerbose && forAutofill) { 7992 Log.v(VIEW_LOG_TAG, "onProvideVirtualStructureCompat() for " + this); 7993 } 7994 7995 final AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 7996 structure.setChildCount(1); 7997 final ViewStructure root = structure.newChild(0); 7998 populateVirtualStructure(root, provider, info, forAutofill); 7999 info.recycle(); 8000 } 8001 } 8002 8003 /** 8004 * Populates a {@link ViewStructure} containing virtual children to fullfil an autofill 8005 * request. 8006 * 8007 * <p>This method should be used when the view manages a virtual structure under this view. For 8008 * example, a view that draws input fields using {@link #draw(Canvas)}. 8009 * 8010 * <p>When implementing this method, subclasses must follow the rules below: 8011 * 8012 * <ul> 8013 * <li>Add virtual children by calling the {@link ViewStructure#newChild(int)} or 8014 * {@link ViewStructure#asyncNewChild(int)} methods, where the {@code id} is an unique id 8015 * identifying the children in the virtual structure. 8016 * <li>The children hierarchy can have multiple levels if necessary, but ideally it should 8017 * exclude intermediate levels that are irrelevant for autofill; that would improve the 8018 * autofill performance. 8019 * <li>Also implement {@link #autofill(SparseArray)} to autofill the virtual 8020 * children. 8021 * <li>Set the autofill properties of the child structure as defined by 8022 * {@link #onProvideAutofillStructure(ViewStructure, int)}, using 8023 * {@link ViewStructure#setAutofillId(AutofillId, int)} to set its autofill id. 8024 * <li>Call {@link android.view.autofill.AutofillManager#notifyViewEntered(View, int, Rect)} 8025 * and/or {@link android.view.autofill.AutofillManager#notifyViewExited(View, int)} 8026 * when the focused virtual child changed. 8027 * <li>Override {@link #isVisibleToUserForAutofill(int)} to allow the platform to query 8028 * whether a given virtual view is visible to the user in order to support triggering 8029 * save when all views of interest go away. 8030 * <li>Call 8031 * {@link android.view.autofill.AutofillManager#notifyValueChanged(View, int, AutofillValue)} 8032 * when the value of a virtual child changed. 8033 * <li>Call {@link 8034 * android.view.autofill.AutofillManager#notifyViewVisibilityChanged(View, int, boolean)} 8035 * when the visibility of a virtual child changed. 8036 * <li>Call 8037 * {@link android.view.autofill.AutofillManager#notifyViewClicked(View, int)} when a virtual 8038 * child is clicked. 8039 * <li>Call {@link AutofillManager#commit()} when the autofill context of the view structure 8040 * changed and the current context should be committed (for example, when the user tapped 8041 * a {@code SUBMIT} button in an HTML page). 8042 * <li>Call {@link AutofillManager#cancel()} when the autofill context of the view structure 8043 * changed and the current context should be canceled (for example, when the user tapped 8044 * a {@code CANCEL} button in an HTML page). 8045 * <li>Provide ways for users to manually request autofill by calling 8046 * {@link AutofillManager#requestAutofill(View, int, Rect)}. 8047 * <li>The {@code left} and {@code top} values set in 8048 * {@link ViewStructure#setDimens(int, int, int, int, int, int)} must be relative to the 8049 * next {@link ViewGroup#isImportantForAutofill()} predecessor view included in the 8050 * structure. 8051 * </ul> 8052 * 8053 * <p>Views with virtual children support the Autofill Framework mainly by: 8054 * <ul> 8055 * <li>Providing the metadata defining what the virtual children mean and how they can be 8056 * autofilled. 8057 * <li>Implementing the methods that autofill the virtual children. 8058 * </ul> 8059 * <p>This method is responsible for the former; {@link #autofill(SparseArray)} is responsible 8060 * for the latter. 8061 * 8062 * @param structure fill in with virtual children data for autofill purposes. 8063 * @param flags optional flags. 8064 * 8065 * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 8066 */ 8067 public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) { 8068 if (mContext.isAutofillCompatibilityEnabled()) { 8069 onProvideVirtualStructureCompat(structure, true); 8070 } 8071 } 8072 8073 /** 8074 * Automatically fills the content of this view with the {@code value}. 8075 * 8076 * <p>Views support the Autofill Framework mainly by: 8077 * <ul> 8078 * <li>Providing the metadata defining what the view means and how it can be autofilled. 8079 * <li>Implementing the methods that autofill the view. 8080 * </ul> 8081 * <p>{@link #onProvideAutofillStructure(ViewStructure, int)} is responsible for the former, 8082 * this method is responsible for latter. 8083 * 8084 * <p>This method does nothing by default, but when overridden it typically: 8085 * <ol> 8086 * <li>Checks if the provided value matches the expected type (which is defined by 8087 * {@link #getAutofillType()}). 8088 * <li>Checks if the view is editable - if it isn't, it should return right away. 8089 * <li>Call the proper getter method on {@link AutofillValue} to fetch the actual value. 8090 * <li>Pass the actual value to the equivalent setter in the view. 8091 * </ol> 8092 * 8093 * <p>For example, a text-field view could implement the method this way: 8094 * 8095 * <pre class="prettyprint"> 8096 * @Override 8097 * public void autofill(AutofillValue value) { 8098 * if (!value.isText() || !this.isEditable()) { 8099 * return; 8100 * } 8101 * CharSequence text = value.getTextValue(); 8102 * if (text != null) { 8103 * this.setText(text); 8104 * } 8105 * } 8106 * </pre> 8107 * 8108 * <p>If the value is updated asynchronously, the next call to 8109 * {@link AutofillManager#notifyValueChanged(View)} must happen <b>after</b> the value was 8110 * changed to the autofilled value. If not, the view will not be considered autofilled. 8111 * 8112 * <p><b>Note:</b> After this method is called, the value returned by 8113 * {@link #getAutofillValue()} must be equal to the {@code value} passed to it, otherwise the 8114 * view will not be highlighted as autofilled. 8115 * 8116 * @param value value to be autofilled. 8117 */ 8118 public void autofill(@SuppressWarnings("unused") AutofillValue value) { 8119 } 8120 8121 /** 8122 * Automatically fills the content of the virtual children within this view. 8123 * 8124 * <p>Views with virtual children support the Autofill Framework mainly by: 8125 * <ul> 8126 * <li>Providing the metadata defining what the virtual children mean and how they can be 8127 * autofilled. 8128 * <li>Implementing the methods that autofill the virtual children. 8129 * </ul> 8130 * <p>{@link #onProvideAutofillVirtualStructure(ViewStructure, int)} is responsible for the 8131 * former, this method is responsible for the latter - see {@link #autofill(AutofillValue)} and 8132 * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} for more info about autofill. 8133 * 8134 * <p>If a child value is updated asynchronously, the next call to 8135 * {@link AutofillManager#notifyValueChanged(View, int, AutofillValue)} must happen 8136 * <b>after</b> the value was changed to the autofilled value. If not, the child will not be 8137 * considered autofilled. 8138 * 8139 * <p><b>Note:</b> To indicate that a virtual view was autofilled, 8140 * <code>?android:attr/autofilledHighlight</code> should be drawn over it until the data 8141 * changes. 8142 * 8143 * @param values map of values to be autofilled, keyed by virtual child id. 8144 * 8145 * @attr ref android.R.styleable#Theme_autofilledHighlight 8146 */ 8147 public void autofill(@NonNull @SuppressWarnings("unused") SparseArray<AutofillValue> values) { 8148 if (!mContext.isAutofillCompatibilityEnabled()) { 8149 return; 8150 } 8151 final AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 8152 if (provider == null) { 8153 return; 8154 } 8155 final int valueCount = values.size(); 8156 for (int i = 0; i < valueCount; i++) { 8157 final AutofillValue value = values.valueAt(i); 8158 if (value.isText()) { 8159 final int virtualId = values.keyAt(i); 8160 final CharSequence text = value.getTextValue(); 8161 final Bundle arguments = new Bundle(); 8162 arguments.putCharSequence( 8163 AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text); 8164 provider.performAction(virtualId, AccessibilityNodeInfo.ACTION_SET_TEXT, arguments); 8165 } 8166 } 8167 } 8168 8169 /** 8170 * Gets the unique, logical identifier of this view in the activity, for autofill purposes. 8171 * 8172 * <p>The autofill id is created on demand, unless it is explicitly set by 8173 * {@link #setAutofillId(AutofillId)}. 8174 * 8175 * <p>See {@link #setAutofillId(AutofillId)} for more info. 8176 * 8177 * @return The View's autofill id. 8178 */ 8179 public final AutofillId getAutofillId() { 8180 if (mAutofillId == null) { 8181 // The autofill id needs to be unique, but its value doesn't matter, 8182 // so it's better to reuse the accessibility id to save space. 8183 mAutofillId = new AutofillId(getAutofillViewId()); 8184 } 8185 return mAutofillId; 8186 } 8187 8188 /** 8189 * Sets the unique, logical identifier of this view in the activity, for autofill purposes. 8190 * 8191 * <p>The autofill id is created on demand, and this method should only be called when a view is 8192 * reused after {@link #dispatchProvideAutofillStructure(ViewStructure, int)} is called, as 8193 * that method creates a snapshot of the view that is passed along to the autofill service. 8194 * 8195 * <p>This method is typically used when view subtrees are recycled to represent different 8196 * content* —in this case, the autofill id can be saved before the view content is swapped 8197 * out, and restored later when it's swapped back in. For example: 8198 * 8199 * <pre> 8200 * EditText reusableView = ...; 8201 * ViewGroup parentView = ...; 8202 * AutofillManager afm = ...; 8203 * 8204 * // Swap out the view and change its contents 8205 * AutofillId oldId = reusableView.getAutofillId(); 8206 * CharSequence oldText = reusableView.getText(); 8207 * parentView.removeView(reusableView); 8208 * AutofillId newId = afm.getNextAutofillId(); 8209 * reusableView.setText("New I am"); 8210 * reusableView.setAutofillId(newId); 8211 * parentView.addView(reusableView); 8212 * 8213 * // Later, swap the old content back in 8214 * parentView.removeView(reusableView); 8215 * reusableView.setAutofillId(oldId); 8216 * reusableView.setText(oldText); 8217 * parentView.addView(reusableView); 8218 * </pre> 8219 * 8220 * @param id an autofill ID that is unique in the {@link android.app.Activity} hosting the view, 8221 * or {@code null} to reset it. Usually it's an id previously allocated to another view (and 8222 * obtained through {@link #getAutofillId()}), or a new value obtained through 8223 * {@link AutofillManager#getNextAutofillId()}. 8224 * 8225 * @throws IllegalStateException if the view is already {@link #isAttachedToWindow() attached to 8226 * a window}. 8227 * 8228 * @throws IllegalArgumentException if the id is an autofill id associated with a virtual view. 8229 */ 8230 public void setAutofillId(@Nullable AutofillId id) { 8231 // TODO(b/37566627): add unit / CTS test for all possible combinations below 8232 if (android.view.autofill.Helper.sVerbose) { 8233 Log.v(VIEW_LOG_TAG, "setAutofill(): from " + mAutofillId + " to " + id); 8234 } 8235 if (isAttachedToWindow()) { 8236 throw new IllegalStateException("Cannot set autofill id when view is attached"); 8237 } 8238 if (id != null && id.isVirtual()) { 8239 throw new IllegalStateException("Cannot set autofill id assigned to virtual views"); 8240 } 8241 if (id == null && (mPrivateFlags3 & PFLAG3_AUTOFILLID_EXPLICITLY_SET) == 0) { 8242 // Ignore reset because it was never explicitly set before. 8243 return; 8244 } 8245 mAutofillId = id; 8246 if (id != null) { 8247 mAutofillViewId = id.getViewId(); 8248 mPrivateFlags3 |= PFLAG3_AUTOFILLID_EXPLICITLY_SET; 8249 } else { 8250 mAutofillViewId = NO_ID; 8251 mPrivateFlags3 &= ~PFLAG3_AUTOFILLID_EXPLICITLY_SET; 8252 } 8253 } 8254 8255 /** 8256 * Describes the autofill type of this view, so an 8257 * {@link android.service.autofill.AutofillService} can create the proper {@link AutofillValue} 8258 * when autofilling the view. 8259 * 8260 * <p>By default returns {@link #AUTOFILL_TYPE_NONE}, but views should override it to properly 8261 * support the Autofill Framework. 8262 * 8263 * @return either {@link #AUTOFILL_TYPE_NONE}, {@link #AUTOFILL_TYPE_TEXT}, 8264 * {@link #AUTOFILL_TYPE_LIST}, {@link #AUTOFILL_TYPE_DATE}, or {@link #AUTOFILL_TYPE_TOGGLE}. 8265 * 8266 * @see #onProvideAutofillStructure(ViewStructure, int) 8267 * @see #autofill(AutofillValue) 8268 */ 8269 public @AutofillType int getAutofillType() { 8270 return AUTOFILL_TYPE_NONE; 8271 } 8272 8273 /** 8274 * Gets the hints that help an {@link android.service.autofill.AutofillService} determine how 8275 * to autofill the view with the user's data. 8276 * 8277 * <p>See {@link #setAutofillHints(String...)} for more info about these hints. 8278 * 8279 * @return The hints set via the attribute or {@link #setAutofillHints(String...)}, or 8280 * {@code null} if no hints were set. 8281 * 8282 * @attr ref android.R.styleable#View_autofillHints 8283 */ 8284 @ViewDebug.ExportedProperty() 8285 @Nullable public String[] getAutofillHints() { 8286 return mAutofillHints; 8287 } 8288 8289 /** 8290 * @hide 8291 */ 8292 public boolean isAutofilled() { 8293 return (mPrivateFlags3 & PFLAG3_IS_AUTOFILLED) != 0; 8294 } 8295 8296 /** 8297 * Gets the {@link View}'s current autofill value. 8298 * 8299 * <p>By default returns {@code null}, but subclasses should override it and return an 8300 * appropriate value to properly support the Autofill Framework. 8301 * 8302 * @see #onProvideAutofillStructure(ViewStructure, int) 8303 * @see #autofill(AutofillValue) 8304 */ 8305 @Nullable 8306 public AutofillValue getAutofillValue() { 8307 return null; 8308 } 8309 8310 /** 8311 * Gets the mode for determining whether this view is important for autofill. 8312 * 8313 * <p>See {@link #setImportantForAutofill(int)} and {@link #isImportantForAutofill()} for more 8314 * info about this mode. 8315 * 8316 * @return {@link #IMPORTANT_FOR_AUTOFILL_AUTO} by default, or value passed to 8317 * {@link #setImportantForAutofill(int)}. 8318 * 8319 * @attr ref android.R.styleable#View_importantForAutofill 8320 */ 8321 @ViewDebug.ExportedProperty(mapping = { 8322 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_AUTO, to = "auto"), 8323 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES, to = "yes"), 8324 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO, to = "no"), 8325 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS, 8326 to = "yesExcludeDescendants"), 8327 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS, 8328 to = "noExcludeDescendants")}) 8329 public @AutofillImportance int getImportantForAutofill() { 8330 return (mPrivateFlags3 8331 & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK) >> PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT; 8332 } 8333 8334 /** 8335 * Sets the mode for determining whether this view is considered important for autofill. 8336 * 8337 * <p>The platform determines the importance for autofill automatically but you 8338 * can use this method to customize the behavior. For example: 8339 * 8340 * <ol> 8341 * <li>When the view contents is irrelevant for autofill (for example, a text field used in a 8342 * "Captcha" challenge), it should be {@link #IMPORTANT_FOR_AUTOFILL_NO}. 8343 * <li>When both the view and its children are irrelevant for autofill (for example, the root 8344 * view of an activity containing a spreadhseet editor), it should be 8345 * {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}. 8346 * <li>When the view content is relevant for autofill but its children aren't (for example, 8347 * a credit card expiration date represented by a custom view that overrides the proper 8348 * autofill methods and has 2 children representing the month and year), it should 8349 * be {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}. 8350 * </ol> 8351 * 8352 * <p><b>Note:</b> Setting the mode as {@link #IMPORTANT_FOR_AUTOFILL_NO} or 8353 * {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS} does not guarantee the view (and its 8354 * children) will be always be considered not important; for example, when the user explicitly 8355 * makes an autofill request, all views are considered important. See 8356 * {@link #isImportantForAutofill()} for more details about how the View's importance for 8357 * autofill is used. 8358 * 8359 * @param mode {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, {@link #IMPORTANT_FOR_AUTOFILL_YES}, 8360 * {@link #IMPORTANT_FOR_AUTOFILL_NO}, {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}, 8361 * or {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}. 8362 * 8363 * @attr ref android.R.styleable#View_importantForAutofill 8364 */ 8365 public void setImportantForAutofill(@AutofillImportance int mode) { 8366 mPrivateFlags3 &= ~PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK; 8367 mPrivateFlags3 |= (mode << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT) 8368 & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK; 8369 } 8370 8371 /** 8372 * Hints the Android System whether the {@link android.app.assist.AssistStructure.ViewNode} 8373 * associated with this view is considered important for autofill purposes. 8374 * 8375 * <p>Generally speaking, a view is important for autofill if: 8376 * <ol> 8377 * <li>The view can be autofilled by an {@link android.service.autofill.AutofillService}. 8378 * <li>The view contents can help an {@link android.service.autofill.AutofillService} 8379 * determine how other views can be autofilled. 8380 * <ol> 8381 * 8382 * <p>For example, view containers should typically return {@code false} for performance reasons 8383 * (since the important info is provided by their children), but if its properties have relevant 8384 * information (for example, a resource id called {@code credentials}, it should return 8385 * {@code true}. On the other hand, views representing labels or editable fields should 8386 * typically return {@code true}, but in some cases they could return {@code false} 8387 * (for example, if they're part of a "Captcha" mechanism). 8388 * 8389 * <p>The value returned by this method depends on the value returned by 8390 * {@link #getImportantForAutofill()}: 8391 * 8392 * <ol> 8393 * <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_YES} or 8394 * {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}, then it returns {@code true} 8395 * <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_NO} or 8396 * {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}, then it returns {@code false} 8397 * <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, then it uses some simple heuristics 8398 * that can return {@code true} in some cases (like a container with a resource id), 8399 * but {@code false} in most. 8400 * <li>otherwise, it returns {@code false}. 8401 * </ol> 8402 * 8403 * <p>When a view is considered important for autofill: 8404 * <ul> 8405 * <li>The view might automatically trigger an autofill request when focused on. 8406 * <li>The contents of the view are included in the {@link ViewStructure} used in an autofill 8407 * request. 8408 * </ul> 8409 * 8410 * <p>On the other hand, when a view is considered not important for autofill: 8411 * <ul> 8412 * <li>The view never automatically triggers autofill requests, but it can trigger a manual 8413 * request through {@link AutofillManager#requestAutofill(View)}. 8414 * <li>The contents of the view are not included in the {@link ViewStructure} used in an 8415 * autofill request, unless the request has the 8416 * {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag. 8417 * </ul> 8418 * 8419 * @return whether the view is considered important for autofill. 8420 * 8421 * @see #setImportantForAutofill(int) 8422 * @see #IMPORTANT_FOR_AUTOFILL_AUTO 8423 * @see #IMPORTANT_FOR_AUTOFILL_YES 8424 * @see #IMPORTANT_FOR_AUTOFILL_NO 8425 * @see #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS 8426 * @see #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS 8427 * @see AutofillManager#requestAutofill(View) 8428 */ 8429 public final boolean isImportantForAutofill() { 8430 // Check parent mode to ensure we're not hidden. 8431 ViewParent parent = mParent; 8432 while (parent instanceof View) { 8433 final int parentImportance = ((View) parent).getImportantForAutofill(); 8434 if (parentImportance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS 8435 || parentImportance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS) { 8436 return false; 8437 } 8438 parent = parent.getParent(); 8439 } 8440 8441 final int importance = getImportantForAutofill(); 8442 8443 // First, check the explicit states. 8444 if (importance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS 8445 || importance == IMPORTANT_FOR_AUTOFILL_YES) { 8446 return true; 8447 } 8448 if (importance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS 8449 || importance == IMPORTANT_FOR_AUTOFILL_NO) { 8450 return false; 8451 } 8452 8453 // Then use some heuristics to handle AUTO. 8454 8455 // Always include views that have an explicit resource id. 8456 final int id = mID; 8457 if (id != NO_ID && !isViewIdGenerated(id)) { 8458 final Resources res = getResources(); 8459 String entry = null; 8460 String pkg = null; 8461 try { 8462 entry = res.getResourceEntryName(id); 8463 pkg = res.getResourcePackageName(id); 8464 } catch (Resources.NotFoundException e) { 8465 // ignore 8466 } 8467 if (entry != null && pkg != null && pkg.equals(mContext.getPackageName())) { 8468 return true; 8469 } 8470 } 8471 8472 // If the app developer explicitly set hints for it, it's important. 8473 if (getAutofillHints() != null) { 8474 return true; 8475 } 8476 8477 // Otherwise, assume it's not important... 8478 return false; 8479 } 8480 8481 @Nullable 8482 private AutofillManager getAutofillManager() { 8483 return mContext.getSystemService(AutofillManager.class); 8484 } 8485 8486 private boolean isAutofillable() { 8487 return getAutofillType() != AUTOFILL_TYPE_NONE && isImportantForAutofill() 8488 && getAutofillViewId() > LAST_APP_AUTOFILL_ID; 8489 } 8490 8491 /** @hide */ 8492 public boolean canNotifyAutofillEnterExitEvent() { 8493 return isAutofillable() && isAttachedToWindow(); 8494 } 8495 8496 private void populateVirtualStructure(ViewStructure structure, 8497 AccessibilityNodeProvider provider, AccessibilityNodeInfo info, 8498 boolean forAutofill) { 8499 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 8500 null, null, info.getViewIdResourceName()); 8501 Rect rect = structure.getTempRect(); 8502 info.getBoundsInParent(rect); 8503 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 8504 structure.setVisibility(VISIBLE); 8505 structure.setEnabled(info.isEnabled()); 8506 if (info.isClickable()) { 8507 structure.setClickable(true); 8508 } 8509 if (info.isFocusable()) { 8510 structure.setFocusable(true); 8511 } 8512 if (info.isFocused()) { 8513 structure.setFocused(true); 8514 } 8515 if (info.isAccessibilityFocused()) { 8516 structure.setAccessibilityFocused(true); 8517 } 8518 if (info.isSelected()) { 8519 structure.setSelected(true); 8520 } 8521 if (info.isLongClickable()) { 8522 structure.setLongClickable(true); 8523 } 8524 if (info.isCheckable()) { 8525 structure.setCheckable(true); 8526 if (info.isChecked()) { 8527 structure.setChecked(true); 8528 } 8529 } 8530 if (info.isContextClickable()) { 8531 structure.setContextClickable(true); 8532 } 8533 if (forAutofill) { 8534 structure.setAutofillId(new AutofillId(getAutofillId(), 8535 AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()))); 8536 } 8537 CharSequence cname = info.getClassName(); 8538 structure.setClassName(cname != null ? cname.toString() : null); 8539 structure.setContentDescription(info.getContentDescription()); 8540 if (forAutofill) { 8541 final int maxTextLength = info.getMaxTextLength(); 8542 if (maxTextLength != -1) { 8543 structure.setMaxTextLength(maxTextLength); 8544 } 8545 structure.setHint(info.getHintText()); 8546 } 8547 CharSequence text = info.getText(); 8548 boolean hasText = text != null || info.getError() != null; 8549 if (hasText) { 8550 structure.setText(text, info.getTextSelectionStart(), info.getTextSelectionEnd()); 8551 } 8552 if (forAutofill) { 8553 if (info.isEditable()) { 8554 structure.setDataIsSensitive(true); 8555 if (hasText) { 8556 structure.setAutofillType(AUTOFILL_TYPE_TEXT); 8557 structure.setAutofillValue(AutofillValue.forText(text)); 8558 } 8559 int inputType = info.getInputType(); 8560 if (inputType == 0 && info.isPassword()) { 8561 inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD; 8562 } 8563 structure.setInputType(inputType); 8564 } else { 8565 structure.setDataIsSensitive(false); 8566 } 8567 } 8568 final int NCHILDREN = info.getChildCount(); 8569 if (NCHILDREN > 0) { 8570 structure.setChildCount(NCHILDREN); 8571 for (int i=0; i<NCHILDREN; i++) { 8572 if (AccessibilityNodeInfo.getVirtualDescendantId(info.getChildNodeIds().get(i)) 8573 == AccessibilityNodeProvider.HOST_VIEW_ID) { 8574 Log.e(VIEW_LOG_TAG, "Virtual view pointing to its host. Ignoring"); 8575 continue; 8576 } 8577 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 8578 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 8579 ViewStructure child = structure.newChild(i); 8580 populateVirtualStructure(child, provider, cinfo, forAutofill); 8581 cinfo.recycle(); 8582 } 8583 } 8584 } 8585 8586 /** 8587 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 8588 * implementation calls {@link #onProvideStructure} and 8589 * {@link #onProvideVirtualStructure}. 8590 */ 8591 public void dispatchProvideStructure(ViewStructure structure) { 8592 dispatchProvideStructureForAssistOrAutofill(structure, false, 0); 8593 } 8594 8595 /** 8596 * Dispatches creation of a {@link ViewStructure}s for autofill purposes down the hierarchy, 8597 * when an Assist structure is being created as part of an autofill request. 8598 * 8599 * <p>The default implementation does the following: 8600 * <ul> 8601 * <li>Sets the {@link AutofillId} in the structure. 8602 * <li>Calls {@link #onProvideAutofillStructure(ViewStructure, int)}. 8603 * <li>Calls {@link #onProvideAutofillVirtualStructure(ViewStructure, int)}. 8604 * </ul> 8605 * 8606 * <p>Typically, this method should only be overridden by subclasses that provide a view 8607 * hierarchy (such as {@link ViewGroup}) - other classes should override 8608 * {@link #onProvideAutofillStructure(ViewStructure, int)} or 8609 * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} instead. 8610 * 8611 * <p>When overridden, it must: 8612 * 8613 * <ul> 8614 * <li>Either call 8615 * {@code super.dispatchProvideAutofillStructure(structure, flags)} or explicitly 8616 * set the {@link AutofillId} in the structure (for example, by calling 8617 * {@code structure.setAutofillId(getAutofillId())}). 8618 * <li>Decide how to handle the {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag - when 8619 * set, all views in the structure should be considered important for autofill, 8620 * regardless of what {@link #isImportantForAutofill()} returns. We encourage you to 8621 * respect this flag to provide a better user experience - this flag is typically used 8622 * when an user explicitly requested autofill. If the flag is not set, 8623 * then only views marked as important for autofill should be included in the 8624 * structure - skipping non-important views optimizes the overall autofill performance. 8625 * </ul> 8626 * 8627 * @param structure fill in with structured view data for autofill purposes. 8628 * @param flags optional flags. 8629 * 8630 * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 8631 */ 8632 public void dispatchProvideAutofillStructure(@NonNull ViewStructure structure, 8633 @AutofillFlags int flags) { 8634 dispatchProvideStructureForAssistOrAutofill(structure, true, flags); 8635 } 8636 8637 private void dispatchProvideStructureForAssistOrAutofill(ViewStructure structure, 8638 boolean forAutofill, @AutofillFlags int flags) { 8639 if (forAutofill) { 8640 structure.setAutofillId(getAutofillId()); 8641 onProvideAutofillStructure(structure, flags); 8642 onProvideAutofillVirtualStructure(structure, flags); 8643 } else if (!isAssistBlocked()) { 8644 onProvideStructure(structure); 8645 onProvideVirtualStructure(structure); 8646 } else { 8647 structure.setClassName(getAccessibilityClassName().toString()); 8648 structure.setAssistBlocked(true); 8649 } 8650 } 8651 8652 /** 8653 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 8654 * 8655 * Note: Called from the default {@link AccessibilityDelegate}. 8656 * 8657 * @hide 8658 */ 8659 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 8660 if (mAttachInfo == null) { 8661 return; 8662 } 8663 8664 Rect bounds = mAttachInfo.mTmpInvalRect; 8665 8666 getDrawingRect(bounds); 8667 info.setBoundsInParent(bounds); 8668 8669 getBoundsOnScreen(bounds, true); 8670 info.setBoundsInScreen(bounds); 8671 8672 ViewParent parent = getParentForAccessibility(); 8673 if (parent instanceof View) { 8674 info.setParent((View) parent); 8675 } 8676 8677 if (mID != View.NO_ID) { 8678 View rootView = getRootView(); 8679 if (rootView == null) { 8680 rootView = this; 8681 } 8682 8683 View label = rootView.findLabelForView(this, mID); 8684 if (label != null) { 8685 info.setLabeledBy(label); 8686 } 8687 8688 if ((mAttachInfo.mAccessibilityFetchFlags 8689 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 8690 && Resources.resourceHasPackage(mID)) { 8691 try { 8692 String viewId = getResources().getResourceName(mID); 8693 info.setViewIdResourceName(viewId); 8694 } catch (Resources.NotFoundException nfe) { 8695 /* ignore */ 8696 } 8697 } 8698 } 8699 8700 if (mLabelForId != View.NO_ID) { 8701 View rootView = getRootView(); 8702 if (rootView == null) { 8703 rootView = this; 8704 } 8705 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 8706 if (labeled != null) { 8707 info.setLabelFor(labeled); 8708 } 8709 } 8710 8711 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 8712 View rootView = getRootView(); 8713 if (rootView == null) { 8714 rootView = this; 8715 } 8716 View next = rootView.findViewInsideOutShouldExist(this, 8717 mAccessibilityTraversalBeforeId); 8718 if (next != null && next.includeForAccessibility()) { 8719 info.setTraversalBefore(next); 8720 } 8721 } 8722 8723 if (mAccessibilityTraversalAfterId != View.NO_ID) { 8724 View rootView = getRootView(); 8725 if (rootView == null) { 8726 rootView = this; 8727 } 8728 View next = rootView.findViewInsideOutShouldExist(this, 8729 mAccessibilityTraversalAfterId); 8730 if (next != null && next.includeForAccessibility()) { 8731 info.setTraversalAfter(next); 8732 } 8733 } 8734 8735 info.setVisibleToUser(isVisibleToUser()); 8736 8737 info.setImportantForAccessibility(isImportantForAccessibility()); 8738 info.setPackageName(mContext.getPackageName()); 8739 info.setClassName(getAccessibilityClassName()); 8740 info.setContentDescription(getContentDescription()); 8741 8742 info.setEnabled(isEnabled()); 8743 info.setClickable(isClickable()); 8744 info.setFocusable(isFocusable()); 8745 info.setScreenReaderFocusable(isScreenReaderFocusable()); 8746 info.setFocused(isFocused()); 8747 info.setAccessibilityFocused(isAccessibilityFocused()); 8748 info.setSelected(isSelected()); 8749 info.setLongClickable(isLongClickable()); 8750 info.setContextClickable(isContextClickable()); 8751 info.setLiveRegion(getAccessibilityLiveRegion()); 8752 if ((mTooltipInfo != null) && (mTooltipInfo.mTooltipText != null)) { 8753 info.setTooltipText(mTooltipInfo.mTooltipText); 8754 info.addAction((mTooltipInfo.mTooltipPopup == null) 8755 ? AccessibilityNodeInfo.AccessibilityAction.ACTION_SHOW_TOOLTIP 8756 : AccessibilityNodeInfo.AccessibilityAction.ACTION_HIDE_TOOLTIP); 8757 } 8758 8759 // TODO: These make sense only if we are in an AdapterView but all 8760 // views can be selected. Maybe from accessibility perspective 8761 // we should report as selectable view in an AdapterView. 8762 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 8763 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 8764 8765 if (isFocusable()) { 8766 if (isFocused()) { 8767 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 8768 } else { 8769 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 8770 } 8771 } 8772 8773 if (!isAccessibilityFocused()) { 8774 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 8775 } else { 8776 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 8777 } 8778 8779 if (isClickable() && isEnabled()) { 8780 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 8781 } 8782 8783 if (isLongClickable() && isEnabled()) { 8784 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 8785 } 8786 8787 if (isContextClickable() && isEnabled()) { 8788 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 8789 } 8790 8791 CharSequence text = getIterableTextForAccessibility(); 8792 if (text != null && text.length() > 0) { 8793 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 8794 8795 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 8796 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 8797 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 8798 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 8799 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 8800 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 8801 } 8802 8803 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 8804 populateAccessibilityNodeInfoDrawingOrderInParent(info); 8805 info.setPaneTitle(mAccessibilityPaneTitle); 8806 info.setHeading(isAccessibilityHeading()); 8807 } 8808 8809 /** 8810 * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the 8811 * additional data. 8812 * <p> 8813 * This method only needs overloading if the node is marked as having extra data available. 8814 * </p> 8815 * 8816 * @param info The info to which to add the extra data. Never {@code null}. 8817 * @param extraDataKey A key specifying the type of extra data to add to the info. The 8818 * extra data should be added to the {@link Bundle} returned by 8819 * the info's {@link AccessibilityNodeInfo#getExtras} method. Never 8820 * {@code null}. 8821 * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be 8822 * {@code null} if the service provided no arguments. 8823 * 8824 * @see AccessibilityNodeInfo#setAvailableExtraData(List) 8825 */ 8826 public void addExtraDataToAccessibilityNodeInfo( 8827 @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey, 8828 @Nullable Bundle arguments) { 8829 } 8830 8831 /** 8832 * Determine the order in which this view will be drawn relative to its siblings for a11y 8833 * 8834 * @param info The info whose drawing order should be populated 8835 */ 8836 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 8837 /* 8838 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 8839 * drawing order may not be well-defined, and some Views with custom drawing order may 8840 * not be initialized sufficiently to respond properly getChildDrawingOrder. 8841 */ 8842 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 8843 info.setDrawingOrder(0); 8844 return; 8845 } 8846 int drawingOrderInParent = 1; 8847 // Iterate up the hierarchy if parents are not important for a11y 8848 View viewAtDrawingLevel = this; 8849 final ViewParent parent = getParentForAccessibility(); 8850 while (viewAtDrawingLevel != parent) { 8851 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 8852 if (!(currentParent instanceof ViewGroup)) { 8853 // Should only happen for the Decor 8854 drawingOrderInParent = 0; 8855 break; 8856 } else { 8857 final ViewGroup parentGroup = (ViewGroup) currentParent; 8858 final int childCount = parentGroup.getChildCount(); 8859 if (childCount > 1) { 8860 List<View> preorderedList = parentGroup.buildOrderedChildList(); 8861 if (preorderedList != null) { 8862 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 8863 for (int i = 0; i < childDrawIndex; i++) { 8864 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 8865 } 8866 } else { 8867 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 8868 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 8869 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 8870 .getChildDrawingOrder(childCount, childIndex) : childIndex; 8871 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 8872 if (childDrawIndex != 0) { 8873 for (int i = 0; i < numChildrenToIterate; i++) { 8874 final int otherDrawIndex = (customOrder ? 8875 parentGroup.getChildDrawingOrder(childCount, i) : i); 8876 if (otherDrawIndex < childDrawIndex) { 8877 drawingOrderInParent += 8878 numViewsForAccessibility(parentGroup.getChildAt(i)); 8879 } 8880 } 8881 } 8882 } 8883 } 8884 } 8885 viewAtDrawingLevel = (View) currentParent; 8886 } 8887 info.setDrawingOrder(drawingOrderInParent); 8888 } 8889 8890 private static int numViewsForAccessibility(View view) { 8891 if (view != null) { 8892 if (view.includeForAccessibility()) { 8893 return 1; 8894 } else if (view instanceof ViewGroup) { 8895 return ((ViewGroup) view).getNumChildrenForAccessibility(); 8896 } 8897 } 8898 return 0; 8899 } 8900 8901 private View findLabelForView(View view, int labeledId) { 8902 if (mMatchLabelForPredicate == null) { 8903 mMatchLabelForPredicate = new MatchLabelForPredicate(); 8904 } 8905 mMatchLabelForPredicate.mLabeledId = labeledId; 8906 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 8907 } 8908 8909 /** 8910 * Computes whether this virtual autofill view is visible to the user. 8911 * 8912 * <p><b>Note: </b>By default it returns {@code true}, but views providing a virtual hierarchy 8913 * view must override it. 8914 * 8915 * @return Whether the view is visible on the screen. 8916 */ 8917 public boolean isVisibleToUserForAutofill(int virtualId) { 8918 if (mContext.isAutofillCompatibilityEnabled()) { 8919 final AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 8920 if (provider != null) { 8921 final AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo(virtualId); 8922 if (node != null) { 8923 return node.isVisibleToUser(); 8924 } 8925 // if node is null, assume it's not visible anymore 8926 } else { 8927 Log.w(VIEW_LOG_TAG, "isVisibleToUserForAutofill(" + virtualId + "): no provider"); 8928 } 8929 return false; 8930 } 8931 return true; 8932 } 8933 8934 /** 8935 * Computes whether this view is visible to the user. Such a view is 8936 * attached, visible, all its predecessors are visible, it is not clipped 8937 * entirely by its predecessors, and has an alpha greater than zero. 8938 * 8939 * @return Whether the view is visible on the screen. 8940 * 8941 * @hide 8942 */ 8943 public boolean isVisibleToUser() { 8944 return isVisibleToUser(null); 8945 } 8946 8947 /** 8948 * Computes whether the given portion of this view is visible to the user. 8949 * Such a view is attached, visible, all its predecessors are visible, 8950 * has an alpha greater than zero, and the specified portion is not 8951 * clipped entirely by its predecessors. 8952 * 8953 * @param boundInView the portion of the view to test; coordinates should be relative; may be 8954 * <code>null</code>, and the entire view will be tested in this case. 8955 * When <code>true</code> is returned by the function, the actual visible 8956 * region will be stored in this parameter; that is, if boundInView is fully 8957 * contained within the view, no modification will be made, otherwise regions 8958 * outside of the visible area of the view will be clipped. 8959 * 8960 * @return Whether the specified portion of the view is visible on the screen. 8961 * 8962 * @hide 8963 */ 8964 protected boolean isVisibleToUser(Rect boundInView) { 8965 if (mAttachInfo != null) { 8966 // Attached to invisible window means this view is not visible. 8967 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 8968 return false; 8969 } 8970 // An invisible predecessor or one with alpha zero means 8971 // that this view is not visible to the user. 8972 Object current = this; 8973 while (current instanceof View) { 8974 View view = (View) current; 8975 // We have attach info so this view is attached and there is no 8976 // need to check whether we reach to ViewRootImpl on the way up. 8977 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 8978 view.getVisibility() != VISIBLE) { 8979 return false; 8980 } 8981 current = view.mParent; 8982 } 8983 // Check if the view is entirely covered by its predecessors. 8984 Rect visibleRect = mAttachInfo.mTmpInvalRect; 8985 Point offset = mAttachInfo.mPoint; 8986 if (!getGlobalVisibleRect(visibleRect, offset)) { 8987 return false; 8988 } 8989 // Check if the visible portion intersects the rectangle of interest. 8990 if (boundInView != null) { 8991 visibleRect.offset(-offset.x, -offset.y); 8992 return boundInView.intersect(visibleRect); 8993 } 8994 return true; 8995 } 8996 return false; 8997 } 8998 8999 /** 9000 * Returns the delegate for implementing accessibility support via 9001 * composition. For more details see {@link AccessibilityDelegate}. 9002 * 9003 * @return The delegate, or null if none set. 9004 * 9005 * @hide 9006 */ 9007 public AccessibilityDelegate getAccessibilityDelegate() { 9008 return mAccessibilityDelegate; 9009 } 9010 9011 /** 9012 * Sets a delegate for implementing accessibility support via composition 9013 * (as opposed to inheritance). For more details, see 9014 * {@link AccessibilityDelegate}. 9015 * <p> 9016 * <strong>Note:</strong> On platform versions prior to 9017 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 9018 * views in the {@code android.widget.*} package are called <i>before</i> 9019 * host methods. This prevents certain properties such as class name from 9020 * being modified by overriding 9021 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 9022 * as any changes will be overwritten by the host class. 9023 * <p> 9024 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 9025 * methods are called <i>after</i> host methods, which all properties to be 9026 * modified without being overwritten by the host class. 9027 * 9028 * @param delegate the object to which accessibility method calls should be 9029 * delegated 9030 * @see AccessibilityDelegate 9031 */ 9032 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 9033 mAccessibilityDelegate = delegate; 9034 } 9035 9036 /** 9037 * Gets the provider for managing a virtual view hierarchy rooted at this View 9038 * and reported to {@link android.accessibilityservice.AccessibilityService}s 9039 * that explore the window content. 9040 * <p> 9041 * If this method returns an instance, this instance is responsible for managing 9042 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 9043 * View including the one representing the View itself. Similarly the returned 9044 * instance is responsible for performing accessibility actions on any virtual 9045 * view or the root view itself. 9046 * </p> 9047 * <p> 9048 * If an {@link AccessibilityDelegate} has been specified via calling 9049 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 9050 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 9051 * is responsible for handling this call. 9052 * </p> 9053 * 9054 * @return The provider. 9055 * 9056 * @see AccessibilityNodeProvider 9057 */ 9058 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 9059 if (mAccessibilityDelegate != null) { 9060 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 9061 } else { 9062 return null; 9063 } 9064 } 9065 9066 /** 9067 * Gets the unique identifier of this view on the screen for accessibility purposes. 9068 * 9069 * @return The view accessibility id. 9070 * 9071 * @hide 9072 */ 9073 public int getAccessibilityViewId() { 9074 if (mAccessibilityViewId == NO_ID) { 9075 mAccessibilityViewId = sNextAccessibilityViewId++; 9076 } 9077 return mAccessibilityViewId; 9078 } 9079 9080 /** 9081 * Gets the unique identifier of this view on the screen for autofill purposes. 9082 * 9083 * @return The view autofill id. 9084 * 9085 * @hide 9086 */ 9087 public int getAutofillViewId() { 9088 if (mAutofillViewId == NO_ID) { 9089 mAutofillViewId = mContext.getNextAutofillId(); 9090 } 9091 return mAutofillViewId; 9092 } 9093 9094 /** 9095 * Gets the unique identifier of the window in which this View reseides. 9096 * 9097 * @return The window accessibility id. 9098 * 9099 * @hide 9100 */ 9101 public int getAccessibilityWindowId() { 9102 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 9103 : AccessibilityWindowInfo.UNDEFINED_WINDOW_ID; 9104 } 9105 9106 /** 9107 * Returns the {@link View}'s content description. 9108 * <p> 9109 * <strong>Note:</strong> Do not override this method, as it will have no 9110 * effect on the content description presented to accessibility services. 9111 * You must call {@link #setContentDescription(CharSequence)} to modify the 9112 * content description. 9113 * 9114 * @return the content description 9115 * @see #setContentDescription(CharSequence) 9116 * @attr ref android.R.styleable#View_contentDescription 9117 */ 9118 @ViewDebug.ExportedProperty(category = "accessibility") 9119 public CharSequence getContentDescription() { 9120 return mContentDescription; 9121 } 9122 9123 /** 9124 * Sets the {@link View}'s content description. 9125 * <p> 9126 * A content description briefly describes the view and is primarily used 9127 * for accessibility support to determine how a view should be presented to 9128 * the user. In the case of a view with no textual representation, such as 9129 * {@link android.widget.ImageButton}, a useful content description 9130 * explains what the view does. For example, an image button with a phone 9131 * icon that is used to place a call may use "Call" as its content 9132 * description. An image of a floppy disk that is used to save a file may 9133 * use "Save". 9134 * 9135 * @param contentDescription The content description. 9136 * @see #getContentDescription() 9137 * @attr ref android.R.styleable#View_contentDescription 9138 */ 9139 @RemotableViewMethod 9140 public void setContentDescription(CharSequence contentDescription) { 9141 if (mContentDescription == null) { 9142 if (contentDescription == null) { 9143 return; 9144 } 9145 } else if (mContentDescription.equals(contentDescription)) { 9146 return; 9147 } 9148 mContentDescription = contentDescription; 9149 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 9150 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 9151 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 9152 notifySubtreeAccessibilityStateChangedIfNeeded(); 9153 } else { 9154 notifyViewAccessibilityStateChangedIfNeeded( 9155 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 9156 } 9157 } 9158 9159 /** 9160 * Sets the id of a view before which this one is visited in accessibility traversal. 9161 * A screen-reader must visit the content of this view before the content of the one 9162 * it precedes. For example, if view B is set to be before view A, then a screen-reader 9163 * will traverse the entire content of B before traversing the entire content of A, 9164 * regardles of what traversal strategy it is using. 9165 * <p> 9166 * Views that do not have specified before/after relationships are traversed in order 9167 * determined by the screen-reader. 9168 * </p> 9169 * <p> 9170 * Setting that this view is before a view that is not important for accessibility 9171 * or if this view is not important for accessibility will have no effect as the 9172 * screen-reader is not aware of unimportant views. 9173 * </p> 9174 * 9175 * @param beforeId The id of a view this one precedes in accessibility traversal. 9176 * 9177 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 9178 * 9179 * @see #setImportantForAccessibility(int) 9180 */ 9181 @RemotableViewMethod 9182 public void setAccessibilityTraversalBefore(int beforeId) { 9183 if (mAccessibilityTraversalBeforeId == beforeId) { 9184 return; 9185 } 9186 mAccessibilityTraversalBeforeId = beforeId; 9187 notifyViewAccessibilityStateChangedIfNeeded( 9188 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9189 } 9190 9191 /** 9192 * Gets the id of a view before which this one is visited in accessibility traversal. 9193 * 9194 * @return The id of a view this one precedes in accessibility traversal if 9195 * specified, otherwise {@link #NO_ID}. 9196 * 9197 * @see #setAccessibilityTraversalBefore(int) 9198 */ 9199 public int getAccessibilityTraversalBefore() { 9200 return mAccessibilityTraversalBeforeId; 9201 } 9202 9203 /** 9204 * Sets the id of a view after which this one is visited in accessibility traversal. 9205 * A screen-reader must visit the content of the other view before the content of this 9206 * one. For example, if view B is set to be after view A, then a screen-reader 9207 * will traverse the entire content of A before traversing the entire content of B, 9208 * regardles of what traversal strategy it is using. 9209 * <p> 9210 * Views that do not have specified before/after relationships are traversed in order 9211 * determined by the screen-reader. 9212 * </p> 9213 * <p> 9214 * Setting that this view is after a view that is not important for accessibility 9215 * or if this view is not important for accessibility will have no effect as the 9216 * screen-reader is not aware of unimportant views. 9217 * </p> 9218 * 9219 * @param afterId The id of a view this one succedees in accessibility traversal. 9220 * 9221 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 9222 * 9223 * @see #setImportantForAccessibility(int) 9224 */ 9225 @RemotableViewMethod 9226 public void setAccessibilityTraversalAfter(int afterId) { 9227 if (mAccessibilityTraversalAfterId == afterId) { 9228 return; 9229 } 9230 mAccessibilityTraversalAfterId = afterId; 9231 notifyViewAccessibilityStateChangedIfNeeded( 9232 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9233 } 9234 9235 /** 9236 * Gets the id of a view after which this one is visited in accessibility traversal. 9237 * 9238 * @return The id of a view this one succeedes in accessibility traversal if 9239 * specified, otherwise {@link #NO_ID}. 9240 * 9241 * @see #setAccessibilityTraversalAfter(int) 9242 */ 9243 public int getAccessibilityTraversalAfter() { 9244 return mAccessibilityTraversalAfterId; 9245 } 9246 9247 /** 9248 * Gets the id of a view for which this view serves as a label for 9249 * accessibility purposes. 9250 * 9251 * @return The labeled view id. 9252 */ 9253 @ViewDebug.ExportedProperty(category = "accessibility") 9254 public int getLabelFor() { 9255 return mLabelForId; 9256 } 9257 9258 /** 9259 * Sets the id of a view for which this view serves as a label for 9260 * accessibility purposes. 9261 * 9262 * @param id The labeled view id. 9263 */ 9264 @RemotableViewMethod 9265 public void setLabelFor(@IdRes int id) { 9266 if (mLabelForId == id) { 9267 return; 9268 } 9269 mLabelForId = id; 9270 if (mLabelForId != View.NO_ID 9271 && mID == View.NO_ID) { 9272 mID = generateViewId(); 9273 } 9274 notifyViewAccessibilityStateChangedIfNeeded( 9275 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9276 } 9277 9278 /** 9279 * Invoked whenever this view loses focus, either by losing window focus or by losing 9280 * focus within its window. This method can be used to clear any state tied to the 9281 * focus. For instance, if a button is held pressed with the trackball and the window 9282 * loses focus, this method can be used to cancel the press. 9283 * 9284 * Subclasses of View overriding this method should always call super.onFocusLost(). 9285 * 9286 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 9287 * @see #onWindowFocusChanged(boolean) 9288 * 9289 * @hide pending API council approval 9290 */ 9291 @CallSuper 9292 protected void onFocusLost() { 9293 resetPressedState(); 9294 } 9295 9296 private void resetPressedState() { 9297 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9298 return; 9299 } 9300 9301 if (isPressed()) { 9302 setPressed(false); 9303 9304 if (!mHasPerformedLongPress) { 9305 removeLongPressCallback(); 9306 } 9307 } 9308 } 9309 9310 /** 9311 * Returns true if this view has focus 9312 * 9313 * @return True if this view has focus, false otherwise. 9314 */ 9315 @ViewDebug.ExportedProperty(category = "focus") 9316 public boolean isFocused() { 9317 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 9318 } 9319 9320 /** 9321 * Find the view in the hierarchy rooted at this view that currently has 9322 * focus. 9323 * 9324 * @return The view that currently has focus, or null if no focused view can 9325 * be found. 9326 */ 9327 public View findFocus() { 9328 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 9329 } 9330 9331 /** 9332 * Indicates whether this view is one of the set of scrollable containers in 9333 * its window. 9334 * 9335 * @return whether this view is one of the set of scrollable containers in 9336 * its window 9337 * 9338 * @attr ref android.R.styleable#View_isScrollContainer 9339 */ 9340 public boolean isScrollContainer() { 9341 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 9342 } 9343 9344 /** 9345 * Change whether this view is one of the set of scrollable containers in 9346 * its window. This will be used to determine whether the window can 9347 * resize or must pan when a soft input area is open -- scrollable 9348 * containers allow the window to use resize mode since the container 9349 * will appropriately shrink. 9350 * 9351 * @attr ref android.R.styleable#View_isScrollContainer 9352 */ 9353 public void setScrollContainer(boolean isScrollContainer) { 9354 if (isScrollContainer) { 9355 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 9356 mAttachInfo.mScrollContainers.add(this); 9357 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 9358 } 9359 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 9360 } else { 9361 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 9362 mAttachInfo.mScrollContainers.remove(this); 9363 } 9364 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 9365 } 9366 } 9367 9368 /** 9369 * Returns the quality of the drawing cache. 9370 * 9371 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 9372 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 9373 * 9374 * @see #setDrawingCacheQuality(int) 9375 * @see #setDrawingCacheEnabled(boolean) 9376 * @see #isDrawingCacheEnabled() 9377 * 9378 * @attr ref android.R.styleable#View_drawingCacheQuality 9379 * 9380 * @deprecated The view drawing cache was largely made obsolete with the introduction of 9381 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 9382 * layers are largely unnecessary and can easily result in a net loss in performance due to the 9383 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 9384 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 9385 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 9386 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 9387 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 9388 * software-rendered usages are discouraged and have compatibility issues with hardware-only 9389 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 9390 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 9391 * reports or unit testing the {@link PixelCopy} API is recommended. 9392 */ 9393 @Deprecated 9394 @DrawingCacheQuality 9395 public int getDrawingCacheQuality() { 9396 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 9397 } 9398 9399 /** 9400 * Set the drawing cache quality of this view. This value is used only when the 9401 * drawing cache is enabled 9402 * 9403 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 9404 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 9405 * 9406 * @see #getDrawingCacheQuality() 9407 * @see #setDrawingCacheEnabled(boolean) 9408 * @see #isDrawingCacheEnabled() 9409 * 9410 * @attr ref android.R.styleable#View_drawingCacheQuality 9411 * 9412 * @deprecated The view drawing cache was largely made obsolete with the introduction of 9413 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 9414 * layers are largely unnecessary and can easily result in a net loss in performance due to the 9415 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 9416 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 9417 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 9418 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 9419 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 9420 * software-rendered usages are discouraged and have compatibility issues with hardware-only 9421 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 9422 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 9423 * reports or unit testing the {@link PixelCopy} API is recommended. 9424 */ 9425 @Deprecated 9426 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 9427 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 9428 } 9429 9430 /** 9431 * Returns whether the screen should remain on, corresponding to the current 9432 * value of {@link #KEEP_SCREEN_ON}. 9433 * 9434 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 9435 * 9436 * @see #setKeepScreenOn(boolean) 9437 * 9438 * @attr ref android.R.styleable#View_keepScreenOn 9439 */ 9440 public boolean getKeepScreenOn() { 9441 return (mViewFlags & KEEP_SCREEN_ON) != 0; 9442 } 9443 9444 /** 9445 * Controls whether the screen should remain on, modifying the 9446 * value of {@link #KEEP_SCREEN_ON}. 9447 * 9448 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 9449 * 9450 * @see #getKeepScreenOn() 9451 * 9452 * @attr ref android.R.styleable#View_keepScreenOn 9453 */ 9454 public void setKeepScreenOn(boolean keepScreenOn) { 9455 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 9456 } 9457 9458 /** 9459 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 9460 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 9461 * 9462 * @attr ref android.R.styleable#View_nextFocusLeft 9463 */ 9464 public int getNextFocusLeftId() { 9465 return mNextFocusLeftId; 9466 } 9467 9468 /** 9469 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 9470 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 9471 * decide automatically. 9472 * 9473 * @attr ref android.R.styleable#View_nextFocusLeft 9474 */ 9475 public void setNextFocusLeftId(int nextFocusLeftId) { 9476 mNextFocusLeftId = nextFocusLeftId; 9477 } 9478 9479 /** 9480 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 9481 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 9482 * 9483 * @attr ref android.R.styleable#View_nextFocusRight 9484 */ 9485 public int getNextFocusRightId() { 9486 return mNextFocusRightId; 9487 } 9488 9489 /** 9490 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 9491 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 9492 * decide automatically. 9493 * 9494 * @attr ref android.R.styleable#View_nextFocusRight 9495 */ 9496 public void setNextFocusRightId(int nextFocusRightId) { 9497 mNextFocusRightId = nextFocusRightId; 9498 } 9499 9500 /** 9501 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 9502 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 9503 * 9504 * @attr ref android.R.styleable#View_nextFocusUp 9505 */ 9506 public int getNextFocusUpId() { 9507 return mNextFocusUpId; 9508 } 9509 9510 /** 9511 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 9512 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 9513 * decide automatically. 9514 * 9515 * @attr ref android.R.styleable#View_nextFocusUp 9516 */ 9517 public void setNextFocusUpId(int nextFocusUpId) { 9518 mNextFocusUpId = nextFocusUpId; 9519 } 9520 9521 /** 9522 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 9523 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 9524 * 9525 * @attr ref android.R.styleable#View_nextFocusDown 9526 */ 9527 public int getNextFocusDownId() { 9528 return mNextFocusDownId; 9529 } 9530 9531 /** 9532 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 9533 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 9534 * decide automatically. 9535 * 9536 * @attr ref android.R.styleable#View_nextFocusDown 9537 */ 9538 public void setNextFocusDownId(int nextFocusDownId) { 9539 mNextFocusDownId = nextFocusDownId; 9540 } 9541 9542 /** 9543 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 9544 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 9545 * 9546 * @attr ref android.R.styleable#View_nextFocusForward 9547 */ 9548 public int getNextFocusForwardId() { 9549 return mNextFocusForwardId; 9550 } 9551 9552 /** 9553 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 9554 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 9555 * decide automatically. 9556 * 9557 * @attr ref android.R.styleable#View_nextFocusForward 9558 */ 9559 public void setNextFocusForwardId(int nextFocusForwardId) { 9560 mNextFocusForwardId = nextFocusForwardId; 9561 } 9562 9563 /** 9564 * Gets the id of the root of the next keyboard navigation cluster. 9565 * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should 9566 * decide automatically. 9567 * 9568 * @attr ref android.R.styleable#View_nextClusterForward 9569 */ 9570 public int getNextClusterForwardId() { 9571 return mNextClusterForwardId; 9572 } 9573 9574 /** 9575 * Sets the id of the view to use as the root of the next keyboard navigation cluster. 9576 * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should 9577 * decide automatically. 9578 * 9579 * @attr ref android.R.styleable#View_nextClusterForward 9580 */ 9581 public void setNextClusterForwardId(int nextClusterForwardId) { 9582 mNextClusterForwardId = nextClusterForwardId; 9583 } 9584 9585 /** 9586 * Returns the visibility of this view and all of its ancestors 9587 * 9588 * @return True if this view and all of its ancestors are {@link #VISIBLE} 9589 */ 9590 public boolean isShown() { 9591 View current = this; 9592 //noinspection ConstantConditions 9593 do { 9594 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 9595 return false; 9596 } 9597 ViewParent parent = current.mParent; 9598 if (parent == null) { 9599 return false; // We are not attached to the view root 9600 } 9601 if (!(parent instanceof View)) { 9602 return true; 9603 } 9604 current = (View) parent; 9605 } while (current != null); 9606 9607 return false; 9608 } 9609 9610 /** 9611 * Called by the view hierarchy when the content insets for a window have 9612 * changed, to allow it to adjust its content to fit within those windows. 9613 * The content insets tell you the space that the status bar, input method, 9614 * and other system windows infringe on the application's window. 9615 * 9616 * <p>You do not normally need to deal with this function, since the default 9617 * window decoration given to applications takes care of applying it to the 9618 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 9619 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 9620 * and your content can be placed under those system elements. You can then 9621 * use this method within your view hierarchy if you have parts of your UI 9622 * which you would like to ensure are not being covered. 9623 * 9624 * <p>The default implementation of this method simply applies the content 9625 * insets to the view's padding, consuming that content (modifying the 9626 * insets to be 0), and returning true. This behavior is off by default, but can 9627 * be enabled through {@link #setFitsSystemWindows(boolean)}. 9628 * 9629 * <p>This function's traversal down the hierarchy is depth-first. The same content 9630 * insets object is propagated down the hierarchy, so any changes made to it will 9631 * be seen by all following views (including potentially ones above in 9632 * the hierarchy since this is a depth-first traversal). The first view 9633 * that returns true will abort the entire traversal. 9634 * 9635 * <p>The default implementation works well for a situation where it is 9636 * used with a container that covers the entire window, allowing it to 9637 * apply the appropriate insets to its content on all edges. If you need 9638 * a more complicated layout (such as two different views fitting system 9639 * windows, one on the top of the window, and one on the bottom), 9640 * you can override the method and handle the insets however you would like. 9641 * Note that the insets provided by the framework are always relative to the 9642 * far edges of the window, not accounting for the location of the called view 9643 * within that window. (In fact when this method is called you do not yet know 9644 * where the layout will place the view, as it is done before layout happens.) 9645 * 9646 * <p>Note: unlike many View methods, there is no dispatch phase to this 9647 * call. If you are overriding it in a ViewGroup and want to allow the 9648 * call to continue to your children, you must be sure to call the super 9649 * implementation. 9650 * 9651 * <p>Here is a sample layout that makes use of fitting system windows 9652 * to have controls for a video view placed inside of the window decorations 9653 * that it hides and shows. This can be used with code like the second 9654 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 9655 * 9656 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 9657 * 9658 * @param insets Current content insets of the window. Prior to 9659 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 9660 * the insets or else you and Android will be unhappy. 9661 * 9662 * @return {@code true} if this view applied the insets and it should not 9663 * continue propagating further down the hierarchy, {@code false} otherwise. 9664 * @see #getFitsSystemWindows() 9665 * @see #setFitsSystemWindows(boolean) 9666 * @see #setSystemUiVisibility(int) 9667 * 9668 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 9669 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 9670 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 9671 * to implement handling their own insets. 9672 */ 9673 @Deprecated 9674 protected boolean fitSystemWindows(Rect insets) { 9675 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 9676 if (insets == null) { 9677 // Null insets by definition have already been consumed. 9678 // This call cannot apply insets since there are none to apply, 9679 // so return false. 9680 return false; 9681 } 9682 // If we're not in the process of dispatching the newer apply insets call, 9683 // that means we're not in the compatibility path. Dispatch into the newer 9684 // apply insets path and take things from there. 9685 try { 9686 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 9687 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 9688 } finally { 9689 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 9690 } 9691 } else { 9692 // We're being called from the newer apply insets path. 9693 // Perform the standard fallback behavior. 9694 return fitSystemWindowsInt(insets); 9695 } 9696 } 9697 9698 private boolean fitSystemWindowsInt(Rect insets) { 9699 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 9700 mUserPaddingStart = UNDEFINED_PADDING; 9701 mUserPaddingEnd = UNDEFINED_PADDING; 9702 Rect localInsets = sThreadLocal.get(); 9703 if (localInsets == null) { 9704 localInsets = new Rect(); 9705 sThreadLocal.set(localInsets); 9706 } 9707 boolean res = computeFitSystemWindows(insets, localInsets); 9708 mUserPaddingLeftInitial = localInsets.left; 9709 mUserPaddingRightInitial = localInsets.right; 9710 internalSetPadding(localInsets.left, localInsets.top, 9711 localInsets.right, localInsets.bottom); 9712 return res; 9713 } 9714 return false; 9715 } 9716 9717 /** 9718 * Called when the view should apply {@link WindowInsets} according to its internal policy. 9719 * 9720 * <p>This method should be overridden by views that wish to apply a policy different from or 9721 * in addition to the default behavior. Clients that wish to force a view subtree 9722 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 9723 * 9724 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 9725 * it will be called during dispatch instead of this method. The listener may optionally 9726 * call this method from its own implementation if it wishes to apply the view's default 9727 * insets policy in addition to its own.</p> 9728 * 9729 * <p>Implementations of this method should either return the insets parameter unchanged 9730 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 9731 * that this view applied itself. This allows new inset types added in future platform 9732 * versions to pass through existing implementations unchanged without being erroneously 9733 * consumed.</p> 9734 * 9735 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 9736 * property is set then the view will consume the system window insets and apply them 9737 * as padding for the view.</p> 9738 * 9739 * @param insets Insets to apply 9740 * @return The supplied insets with any applied insets consumed 9741 */ 9742 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 9743 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 9744 // We weren't called from within a direct call to fitSystemWindows, 9745 // call into it as a fallback in case we're in a class that overrides it 9746 // and has logic to perform. 9747 if (fitSystemWindows(insets.getSystemWindowInsets())) { 9748 return insets.consumeSystemWindowInsets(); 9749 } 9750 } else { 9751 // We were called from within a direct call to fitSystemWindows. 9752 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 9753 return insets.consumeSystemWindowInsets(); 9754 } 9755 } 9756 return insets; 9757 } 9758 9759 /** 9760 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 9761 * window insets to this view. The listener's 9762 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 9763 * method will be called instead of the view's 9764 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 9765 * 9766 * @param listener Listener to set 9767 * 9768 * @see #onApplyWindowInsets(WindowInsets) 9769 */ 9770 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 9771 getListenerInfo().mOnApplyWindowInsetsListener = listener; 9772 } 9773 9774 /** 9775 * Request to apply the given window insets to this view or another view in its subtree. 9776 * 9777 * <p>This method should be called by clients wishing to apply insets corresponding to areas 9778 * obscured by window decorations or overlays. This can include the status and navigation bars, 9779 * action bars, input methods and more. New inset categories may be added in the future. 9780 * The method returns the insets provided minus any that were applied by this view or its 9781 * children.</p> 9782 * 9783 * <p>Clients wishing to provide custom behavior should override the 9784 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 9785 * {@link OnApplyWindowInsetsListener} via the 9786 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 9787 * method.</p> 9788 * 9789 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 9790 * </p> 9791 * 9792 * @param insets Insets to apply 9793 * @return The provided insets minus the insets that were consumed 9794 */ 9795 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 9796 try { 9797 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 9798 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 9799 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 9800 } else { 9801 return onApplyWindowInsets(insets); 9802 } 9803 } finally { 9804 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 9805 } 9806 } 9807 9808 /** 9809 * Compute the view's coordinate within the surface. 9810 * 9811 * <p>Computes the coordinates of this view in its surface. The argument 9812 * must be an array of two integers. After the method returns, the array 9813 * contains the x and y location in that order.</p> 9814 * @hide 9815 * @param location an array of two integers in which to hold the coordinates 9816 */ 9817 public void getLocationInSurface(@Size(2) int[] location) { 9818 getLocationInWindow(location); 9819 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 9820 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 9821 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 9822 } 9823 } 9824 9825 /** 9826 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 9827 * only available if the view is attached. 9828 * 9829 * @return WindowInsets from the top of the view hierarchy or null if View is detached 9830 */ 9831 public WindowInsets getRootWindowInsets() { 9832 if (mAttachInfo != null) { 9833 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 9834 } 9835 return null; 9836 } 9837 9838 /** 9839 * @hide Compute the insets that should be consumed by this view and the ones 9840 * that should propagate to those under it. 9841 */ 9842 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 9843 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 9844 || mAttachInfo == null 9845 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 9846 && !mAttachInfo.mOverscanRequested)) { 9847 outLocalInsets.set(inoutInsets); 9848 inoutInsets.set(0, 0, 0, 0); 9849 return true; 9850 } else { 9851 // The application wants to take care of fitting system window for 9852 // the content... however we still need to take care of any overscan here. 9853 final Rect overscan = mAttachInfo.mOverscanInsets; 9854 outLocalInsets.set(overscan); 9855 inoutInsets.left -= overscan.left; 9856 inoutInsets.top -= overscan.top; 9857 inoutInsets.right -= overscan.right; 9858 inoutInsets.bottom -= overscan.bottom; 9859 return false; 9860 } 9861 } 9862 9863 /** 9864 * Compute insets that should be consumed by this view and the ones that should propagate 9865 * to those under it. 9866 * 9867 * @param in Insets currently being processed by this View, likely received as a parameter 9868 * to {@link #onApplyWindowInsets(WindowInsets)}. 9869 * @param outLocalInsets A Rect that will receive the insets that should be consumed 9870 * by this view 9871 * @return Insets that should be passed along to views under this one 9872 */ 9873 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 9874 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 9875 || mAttachInfo == null 9876 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 9877 outLocalInsets.set(in.getSystemWindowInsets()); 9878 return in.consumeSystemWindowInsets(); 9879 } else { 9880 outLocalInsets.set(0, 0, 0, 0); 9881 return in; 9882 } 9883 } 9884 9885 /** 9886 * Sets whether or not this view should account for system screen decorations 9887 * such as the status bar and inset its content; that is, controlling whether 9888 * the default implementation of {@link #fitSystemWindows(Rect)} will be 9889 * executed. See that method for more details. 9890 * 9891 * <p>Note that if you are providing your own implementation of 9892 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 9893 * flag to true -- your implementation will be overriding the default 9894 * implementation that checks this flag. 9895 * 9896 * @param fitSystemWindows If true, then the default implementation of 9897 * {@link #fitSystemWindows(Rect)} will be executed. 9898 * 9899 * @attr ref android.R.styleable#View_fitsSystemWindows 9900 * @see #getFitsSystemWindows() 9901 * @see #fitSystemWindows(Rect) 9902 * @see #setSystemUiVisibility(int) 9903 */ 9904 public void setFitsSystemWindows(boolean fitSystemWindows) { 9905 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 9906 } 9907 9908 /** 9909 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 9910 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 9911 * will be executed. 9912 * 9913 * @return {@code true} if the default implementation of 9914 * {@link #fitSystemWindows(Rect)} will be executed. 9915 * 9916 * @attr ref android.R.styleable#View_fitsSystemWindows 9917 * @see #setFitsSystemWindows(boolean) 9918 * @see #fitSystemWindows(Rect) 9919 * @see #setSystemUiVisibility(int) 9920 */ 9921 @ViewDebug.ExportedProperty 9922 public boolean getFitsSystemWindows() { 9923 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 9924 } 9925 9926 /** @hide */ 9927 public boolean fitsSystemWindows() { 9928 return getFitsSystemWindows(); 9929 } 9930 9931 /** 9932 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 9933 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 9934 */ 9935 @Deprecated 9936 public void requestFitSystemWindows() { 9937 if (mParent != null) { 9938 mParent.requestFitSystemWindows(); 9939 } 9940 } 9941 9942 /** 9943 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 9944 */ 9945 public void requestApplyInsets() { 9946 requestFitSystemWindows(); 9947 } 9948 9949 /** 9950 * For use by PhoneWindow to make its own system window fitting optional. 9951 * @hide 9952 */ 9953 public void makeOptionalFitsSystemWindows() { 9954 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 9955 } 9956 9957 /** 9958 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 9959 * treat them as such. 9960 * @hide 9961 */ 9962 public void getOutsets(Rect outOutsetRect) { 9963 if (mAttachInfo != null) { 9964 outOutsetRect.set(mAttachInfo.mOutsets); 9965 } else { 9966 outOutsetRect.setEmpty(); 9967 } 9968 } 9969 9970 /** 9971 * Returns the visibility status for this view. 9972 * 9973 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9974 * @attr ref android.R.styleable#View_visibility 9975 */ 9976 @ViewDebug.ExportedProperty(mapping = { 9977 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 9978 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 9979 @ViewDebug.IntToString(from = GONE, to = "GONE") 9980 }) 9981 @Visibility 9982 public int getVisibility() { 9983 return mViewFlags & VISIBILITY_MASK; 9984 } 9985 9986 /** 9987 * Set the visibility state of this view. 9988 * 9989 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9990 * @attr ref android.R.styleable#View_visibility 9991 */ 9992 @RemotableViewMethod 9993 public void setVisibility(@Visibility int visibility) { 9994 setFlags(visibility, VISIBILITY_MASK); 9995 } 9996 9997 /** 9998 * Returns the enabled status for this view. The interpretation of the 9999 * enabled state varies by subclass. 10000 * 10001 * @return True if this view is enabled, false otherwise. 10002 */ 10003 @ViewDebug.ExportedProperty 10004 public boolean isEnabled() { 10005 return (mViewFlags & ENABLED_MASK) == ENABLED; 10006 } 10007 10008 /** 10009 * Set the enabled state of this view. The interpretation of the enabled 10010 * state varies by subclass. 10011 * 10012 * @param enabled True if this view is enabled, false otherwise. 10013 */ 10014 @RemotableViewMethod 10015 public void setEnabled(boolean enabled) { 10016 if (enabled == isEnabled()) return; 10017 10018 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 10019 10020 /* 10021 * The View most likely has to change its appearance, so refresh 10022 * the drawable state. 10023 */ 10024 refreshDrawableState(); 10025 10026 // Invalidate too, since the default behavior for views is to be 10027 // be drawn at 50% alpha rather than to change the drawable. 10028 invalidate(true); 10029 10030 if (!enabled) { 10031 cancelPendingInputEvents(); 10032 } 10033 } 10034 10035 /** 10036 * Set whether this view can receive the focus. 10037 * <p> 10038 * Setting this to false will also ensure that this view is not focusable 10039 * in touch mode. 10040 * 10041 * @param focusable If true, this view can receive the focus. 10042 * 10043 * @see #setFocusableInTouchMode(boolean) 10044 * @see #setFocusable(int) 10045 * @attr ref android.R.styleable#View_focusable 10046 */ 10047 public void setFocusable(boolean focusable) { 10048 setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE); 10049 } 10050 10051 /** 10052 * Sets whether this view can receive focus. 10053 * <p> 10054 * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability 10055 * automatically based on the view's interactivity. This is the default. 10056 * <p> 10057 * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable 10058 * in touch mode. 10059 * 10060 * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, 10061 * or {@link #FOCUSABLE_AUTO}. 10062 * @see #setFocusableInTouchMode(boolean) 10063 * @attr ref android.R.styleable#View_focusable 10064 */ 10065 public void setFocusable(@Focusable int focusable) { 10066 if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) { 10067 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 10068 } 10069 setFlags(focusable, FOCUSABLE_MASK); 10070 } 10071 10072 /** 10073 * Set whether this view can receive focus while in touch mode. 10074 * 10075 * Setting this to true will also ensure that this view is focusable. 10076 * 10077 * @param focusableInTouchMode If true, this view can receive the focus while 10078 * in touch mode. 10079 * 10080 * @see #setFocusable(boolean) 10081 * @attr ref android.R.styleable#View_focusableInTouchMode 10082 */ 10083 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 10084 // Focusable in touch mode should always be set before the focusable flag 10085 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 10086 // which, in touch mode, will not successfully request focus on this view 10087 // because the focusable in touch mode flag is not set 10088 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 10089 10090 // Clear FOCUSABLE_AUTO if set. 10091 if (focusableInTouchMode) { 10092 // Clears FOCUSABLE_AUTO if set. 10093 setFlags(FOCUSABLE, FOCUSABLE_MASK); 10094 } 10095 } 10096 10097 /** 10098 * Sets the hints that help an {@link android.service.autofill.AutofillService} determine how 10099 * to autofill the view with the user's data. 10100 * 10101 * <p>Typically, there is only one way to autofill a view, but there could be more than one. 10102 * For example, if the application accepts either an username or email address to identify 10103 * an user. 10104 * 10105 * <p>These hints are not validated by the Android System, but passed "as is" to the service. 10106 * Hence, they can have any value, but it's recommended to use the {@code AUTOFILL_HINT_} 10107 * constants such as: 10108 * {@link #AUTOFILL_HINT_USERNAME}, {@link #AUTOFILL_HINT_PASSWORD}, 10109 * {@link #AUTOFILL_HINT_EMAIL_ADDRESS}, 10110 * {@link #AUTOFILL_HINT_NAME}, 10111 * {@link #AUTOFILL_HINT_PHONE}, 10112 * {@link #AUTOFILL_HINT_POSTAL_ADDRESS}, {@link #AUTOFILL_HINT_POSTAL_CODE}, 10113 * {@link #AUTOFILL_HINT_CREDIT_CARD_NUMBER}, {@link #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}, 10114 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}, 10115 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}, 10116 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH} or 10117 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}. 10118 * 10119 * @param autofillHints The autofill hints to set. If the array is emtpy, {@code null} is set. 10120 * @attr ref android.R.styleable#View_autofillHints 10121 */ 10122 public void setAutofillHints(@Nullable String... autofillHints) { 10123 if (autofillHints == null || autofillHints.length == 0) { 10124 mAutofillHints = null; 10125 } else { 10126 mAutofillHints = autofillHints; 10127 } 10128 } 10129 10130 /** 10131 * @hide 10132 */ 10133 @TestApi 10134 public void setAutofilled(boolean isAutofilled) { 10135 boolean wasChanged = isAutofilled != isAutofilled(); 10136 10137 if (wasChanged) { 10138 if (isAutofilled) { 10139 mPrivateFlags3 |= PFLAG3_IS_AUTOFILLED; 10140 } else { 10141 mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED; 10142 } 10143 10144 invalidate(); 10145 } 10146 } 10147 10148 /** 10149 * Set whether this view should have sound effects enabled for events such as 10150 * clicking and touching. 10151 * 10152 * <p>You may wish to disable sound effects for a view if you already play sounds, 10153 * for instance, a dial key that plays dtmf tones. 10154 * 10155 * @param soundEffectsEnabled whether sound effects are enabled for this view. 10156 * @see #isSoundEffectsEnabled() 10157 * @see #playSoundEffect(int) 10158 * @attr ref android.R.styleable#View_soundEffectsEnabled 10159 */ 10160 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 10161 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 10162 } 10163 10164 /** 10165 * @return whether this view should have sound effects enabled for events such as 10166 * clicking and touching. 10167 * 10168 * @see #setSoundEffectsEnabled(boolean) 10169 * @see #playSoundEffect(int) 10170 * @attr ref android.R.styleable#View_soundEffectsEnabled 10171 */ 10172 @ViewDebug.ExportedProperty 10173 public boolean isSoundEffectsEnabled() { 10174 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 10175 } 10176 10177 /** 10178 * Set whether this view should have haptic feedback for events such as 10179 * long presses. 10180 * 10181 * <p>You may wish to disable haptic feedback if your view already controls 10182 * its own haptic feedback. 10183 * 10184 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 10185 * @see #isHapticFeedbackEnabled() 10186 * @see #performHapticFeedback(int) 10187 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 10188 */ 10189 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 10190 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 10191 } 10192 10193 /** 10194 * @return whether this view should have haptic feedback enabled for events 10195 * long presses. 10196 * 10197 * @see #setHapticFeedbackEnabled(boolean) 10198 * @see #performHapticFeedback(int) 10199 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 10200 */ 10201 @ViewDebug.ExportedProperty 10202 public boolean isHapticFeedbackEnabled() { 10203 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 10204 } 10205 10206 /** 10207 * Returns the layout direction for this view. 10208 * 10209 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 10210 * {@link #LAYOUT_DIRECTION_RTL}, 10211 * {@link #LAYOUT_DIRECTION_INHERIT} or 10212 * {@link #LAYOUT_DIRECTION_LOCALE}. 10213 * 10214 * @attr ref android.R.styleable#View_layoutDirection 10215 * 10216 * @hide 10217 */ 10218 @ViewDebug.ExportedProperty(category = "layout", mapping = { 10219 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 10220 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 10221 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 10222 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 10223 }) 10224 @LayoutDir 10225 public int getRawLayoutDirection() { 10226 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 10227 } 10228 10229 /** 10230 * Set the layout direction for this view. This will propagate a reset of layout direction 10231 * resolution to the view's children and resolve layout direction for this view. 10232 * 10233 * @param layoutDirection the layout direction to set. Should be one of: 10234 * 10235 * {@link #LAYOUT_DIRECTION_LTR}, 10236 * {@link #LAYOUT_DIRECTION_RTL}, 10237 * {@link #LAYOUT_DIRECTION_INHERIT}, 10238 * {@link #LAYOUT_DIRECTION_LOCALE}. 10239 * 10240 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 10241 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 10242 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 10243 * 10244 * @attr ref android.R.styleable#View_layoutDirection 10245 */ 10246 @RemotableViewMethod 10247 public void setLayoutDirection(@LayoutDir int layoutDirection) { 10248 if (getRawLayoutDirection() != layoutDirection) { 10249 // Reset the current layout direction and the resolved one 10250 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 10251 resetRtlProperties(); 10252 // Set the new layout direction (filtered) 10253 mPrivateFlags2 |= 10254 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 10255 // We need to resolve all RTL properties as they all depend on layout direction 10256 resolveRtlPropertiesIfNeeded(); 10257 requestLayout(); 10258 invalidate(true); 10259 } 10260 } 10261 10262 /** 10263 * Returns the resolved layout direction for this view. 10264 * 10265 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 10266 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 10267 * 10268 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 10269 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 10270 * 10271 * @attr ref android.R.styleable#View_layoutDirection 10272 */ 10273 @ViewDebug.ExportedProperty(category = "layout", mapping = { 10274 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 10275 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 10276 }) 10277 @ResolvedLayoutDir 10278 public int getLayoutDirection() { 10279 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 10280 if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) { 10281 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 10282 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 10283 } 10284 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 10285 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 10286 } 10287 10288 /** 10289 * Indicates whether or not this view's layout is right-to-left. This is resolved from 10290 * layout attribute and/or the inherited value from the parent 10291 * 10292 * @return true if the layout is right-to-left. 10293 * 10294 * @hide 10295 */ 10296 @ViewDebug.ExportedProperty(category = "layout") 10297 public boolean isLayoutRtl() { 10298 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 10299 } 10300 10301 /** 10302 * Indicates whether the view is currently tracking transient state that the 10303 * app should not need to concern itself with saving and restoring, but that 10304 * the framework should take special note to preserve when possible. 10305 * 10306 * <p>A view with transient state cannot be trivially rebound from an external 10307 * data source, such as an adapter binding item views in a list. This may be 10308 * because the view is performing an animation, tracking user selection 10309 * of content, or similar.</p> 10310 * 10311 * @return true if the view has transient state 10312 */ 10313 @ViewDebug.ExportedProperty(category = "layout") 10314 public boolean hasTransientState() { 10315 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 10316 } 10317 10318 /** 10319 * Set whether this view is currently tracking transient state that the 10320 * framework should attempt to preserve when possible. This flag is reference counted, 10321 * so every call to setHasTransientState(true) should be paired with a later call 10322 * to setHasTransientState(false). 10323 * 10324 * <p>A view with transient state cannot be trivially rebound from an external 10325 * data source, such as an adapter binding item views in a list. This may be 10326 * because the view is performing an animation, tracking user selection 10327 * of content, or similar.</p> 10328 * 10329 * @param hasTransientState true if this view has transient state 10330 */ 10331 public void setHasTransientState(boolean hasTransientState) { 10332 final boolean oldHasTransientState = hasTransientState(); 10333 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 10334 mTransientStateCount - 1; 10335 if (mTransientStateCount < 0) { 10336 mTransientStateCount = 0; 10337 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 10338 "unmatched pair of setHasTransientState calls"); 10339 } else if ((hasTransientState && mTransientStateCount == 1) || 10340 (!hasTransientState && mTransientStateCount == 0)) { 10341 // update flag if we've just incremented up from 0 or decremented down to 0 10342 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 10343 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 10344 final boolean newHasTransientState = hasTransientState(); 10345 if (mParent != null && newHasTransientState != oldHasTransientState) { 10346 try { 10347 mParent.childHasTransientStateChanged(this, newHasTransientState); 10348 } catch (AbstractMethodError e) { 10349 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 10350 " does not fully implement ViewParent", e); 10351 } 10352 } 10353 } 10354 } 10355 10356 /** 10357 * Returns true if this view is currently attached to a window. 10358 */ 10359 public boolean isAttachedToWindow() { 10360 return mAttachInfo != null; 10361 } 10362 10363 /** 10364 * Returns true if this view has been through at least one layout since it 10365 * was last attached to or detached from a window. 10366 */ 10367 public boolean isLaidOut() { 10368 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 10369 } 10370 10371 /** 10372 * @return {@code true} if laid-out and not about to do another layout. 10373 */ 10374 boolean isLayoutValid() { 10375 return isLaidOut() && ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == 0); 10376 } 10377 10378 /** 10379 * If this view doesn't do any drawing on its own, set this flag to 10380 * allow further optimizations. By default, this flag is not set on 10381 * View, but could be set on some View subclasses such as ViewGroup. 10382 * 10383 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 10384 * you should clear this flag. 10385 * 10386 * @param willNotDraw whether or not this View draw on its own 10387 */ 10388 public void setWillNotDraw(boolean willNotDraw) { 10389 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 10390 } 10391 10392 /** 10393 * Returns whether or not this View draws on its own. 10394 * 10395 * @return true if this view has nothing to draw, false otherwise 10396 */ 10397 @ViewDebug.ExportedProperty(category = "drawing") 10398 public boolean willNotDraw() { 10399 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 10400 } 10401 10402 /** 10403 * When a View's drawing cache is enabled, drawing is redirected to an 10404 * offscreen bitmap. Some views, like an ImageView, must be able to 10405 * bypass this mechanism if they already draw a single bitmap, to avoid 10406 * unnecessary usage of the memory. 10407 * 10408 * @param willNotCacheDrawing true if this view does not cache its 10409 * drawing, false otherwise 10410 * 10411 * @deprecated The view drawing cache was largely made obsolete with the introduction of 10412 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 10413 * layers are largely unnecessary and can easily result in a net loss in performance due to the 10414 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 10415 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 10416 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 10417 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 10418 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 10419 * software-rendered usages are discouraged and have compatibility issues with hardware-only 10420 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 10421 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 10422 * reports or unit testing the {@link PixelCopy} API is recommended. 10423 */ 10424 @Deprecated 10425 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 10426 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 10427 } 10428 10429 /** 10430 * Returns whether or not this View can cache its drawing or not. 10431 * 10432 * @return true if this view does not cache its drawing, false otherwise 10433 * 10434 * @deprecated The view drawing cache was largely made obsolete with the introduction of 10435 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 10436 * layers are largely unnecessary and can easily result in a net loss in performance due to the 10437 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 10438 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 10439 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 10440 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 10441 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 10442 * software-rendered usages are discouraged and have compatibility issues with hardware-only 10443 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 10444 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 10445 * reports or unit testing the {@link PixelCopy} API is recommended. 10446 */ 10447 @ViewDebug.ExportedProperty(category = "drawing") 10448 @Deprecated 10449 public boolean willNotCacheDrawing() { 10450 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 10451 } 10452 10453 /** 10454 * Indicates whether this view reacts to click events or not. 10455 * 10456 * @return true if the view is clickable, false otherwise 10457 * 10458 * @see #setClickable(boolean) 10459 * @attr ref android.R.styleable#View_clickable 10460 */ 10461 @ViewDebug.ExportedProperty 10462 public boolean isClickable() { 10463 return (mViewFlags & CLICKABLE) == CLICKABLE; 10464 } 10465 10466 /** 10467 * Enables or disables click events for this view. When a view 10468 * is clickable it will change its state to "pressed" on every click. 10469 * Subclasses should set the view clickable to visually react to 10470 * user's clicks. 10471 * 10472 * @param clickable true to make the view clickable, false otherwise 10473 * 10474 * @see #isClickable() 10475 * @attr ref android.R.styleable#View_clickable 10476 */ 10477 public void setClickable(boolean clickable) { 10478 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 10479 } 10480 10481 /** 10482 * Indicates whether this view reacts to long click events or not. 10483 * 10484 * @return true if the view is long clickable, false otherwise 10485 * 10486 * @see #setLongClickable(boolean) 10487 * @attr ref android.R.styleable#View_longClickable 10488 */ 10489 public boolean isLongClickable() { 10490 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 10491 } 10492 10493 /** 10494 * Enables or disables long click events for this view. When a view is long 10495 * clickable it reacts to the user holding down the button for a longer 10496 * duration than a tap. This event can either launch the listener or a 10497 * context menu. 10498 * 10499 * @param longClickable true to make the view long clickable, false otherwise 10500 * @see #isLongClickable() 10501 * @attr ref android.R.styleable#View_longClickable 10502 */ 10503 public void setLongClickable(boolean longClickable) { 10504 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 10505 } 10506 10507 /** 10508 * Indicates whether this view reacts to context clicks or not. 10509 * 10510 * @return true if the view is context clickable, false otherwise 10511 * @see #setContextClickable(boolean) 10512 * @attr ref android.R.styleable#View_contextClickable 10513 */ 10514 public boolean isContextClickable() { 10515 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10516 } 10517 10518 /** 10519 * Enables or disables context clicking for this view. This event can launch the listener. 10520 * 10521 * @param contextClickable true to make the view react to a context click, false otherwise 10522 * @see #isContextClickable() 10523 * @attr ref android.R.styleable#View_contextClickable 10524 */ 10525 public void setContextClickable(boolean contextClickable) { 10526 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 10527 } 10528 10529 /** 10530 * Sets the pressed state for this view and provides a touch coordinate for 10531 * animation hinting. 10532 * 10533 * @param pressed Pass true to set the View's internal state to "pressed", 10534 * or false to reverts the View's internal state from a 10535 * previously set "pressed" state. 10536 * @param x The x coordinate of the touch that caused the press 10537 * @param y The y coordinate of the touch that caused the press 10538 */ 10539 private void setPressed(boolean pressed, float x, float y) { 10540 if (pressed) { 10541 drawableHotspotChanged(x, y); 10542 } 10543 10544 setPressed(pressed); 10545 } 10546 10547 /** 10548 * Sets the pressed state for this view. 10549 * 10550 * @see #isClickable() 10551 * @see #setClickable(boolean) 10552 * 10553 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 10554 * the View's internal state from a previously set "pressed" state. 10555 */ 10556 public void setPressed(boolean pressed) { 10557 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 10558 10559 if (pressed) { 10560 mPrivateFlags |= PFLAG_PRESSED; 10561 } else { 10562 mPrivateFlags &= ~PFLAG_PRESSED; 10563 } 10564 10565 if (needsRefresh) { 10566 refreshDrawableState(); 10567 } 10568 dispatchSetPressed(pressed); 10569 } 10570 10571 /** 10572 * Dispatch setPressed to all of this View's children. 10573 * 10574 * @see #setPressed(boolean) 10575 * 10576 * @param pressed The new pressed state 10577 */ 10578 protected void dispatchSetPressed(boolean pressed) { 10579 } 10580 10581 /** 10582 * Indicates whether the view is currently in pressed state. Unless 10583 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 10584 * the pressed state. 10585 * 10586 * @see #setPressed(boolean) 10587 * @see #isClickable() 10588 * @see #setClickable(boolean) 10589 * 10590 * @return true if the view is currently pressed, false otherwise 10591 */ 10592 @ViewDebug.ExportedProperty 10593 public boolean isPressed() { 10594 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 10595 } 10596 10597 /** 10598 * @hide 10599 * Indicates whether this view will participate in data collection through 10600 * {@link ViewStructure}. If true, it will not provide any data 10601 * for itself or its children. If false, the normal data collection will be allowed. 10602 * 10603 * @return Returns false if assist data collection is not blocked, else true. 10604 * 10605 * @see #setAssistBlocked(boolean) 10606 * @attr ref android.R.styleable#View_assistBlocked 10607 */ 10608 public boolean isAssistBlocked() { 10609 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 10610 } 10611 10612 /** 10613 * @hide 10614 * Controls whether assist data collection from this view and its children is enabled 10615 * (that is, whether {@link #onProvideStructure} and 10616 * {@link #onProvideVirtualStructure} will be called). The default value is false, 10617 * allowing normal assist collection. Setting this to false will disable assist collection. 10618 * 10619 * @param enabled Set to true to <em>disable</em> assist data collection, or false 10620 * (the default) to allow it. 10621 * 10622 * @see #isAssistBlocked() 10623 * @see #onProvideStructure 10624 * @see #onProvideVirtualStructure 10625 * @attr ref android.R.styleable#View_assistBlocked 10626 */ 10627 public void setAssistBlocked(boolean enabled) { 10628 if (enabled) { 10629 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 10630 } else { 10631 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 10632 } 10633 } 10634 10635 /** 10636 * Indicates whether this view will save its state (that is, 10637 * whether its {@link #onSaveInstanceState} method will be called). 10638 * 10639 * @return Returns true if the view state saving is enabled, else false. 10640 * 10641 * @see #setSaveEnabled(boolean) 10642 * @attr ref android.R.styleable#View_saveEnabled 10643 */ 10644 public boolean isSaveEnabled() { 10645 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 10646 } 10647 10648 /** 10649 * Controls whether the saving of this view's state is 10650 * enabled (that is, whether its {@link #onSaveInstanceState} method 10651 * will be called). Note that even if freezing is enabled, the 10652 * view still must have an id assigned to it (via {@link #setId(int)}) 10653 * for its state to be saved. This flag can only disable the 10654 * saving of this view; any child views may still have their state saved. 10655 * 10656 * @param enabled Set to false to <em>disable</em> state saving, or true 10657 * (the default) to allow it. 10658 * 10659 * @see #isSaveEnabled() 10660 * @see #setId(int) 10661 * @see #onSaveInstanceState() 10662 * @attr ref android.R.styleable#View_saveEnabled 10663 */ 10664 public void setSaveEnabled(boolean enabled) { 10665 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 10666 } 10667 10668 /** 10669 * Gets whether the framework should discard touches when the view's 10670 * window is obscured by another visible window. 10671 * Refer to the {@link View} security documentation for more details. 10672 * 10673 * @return True if touch filtering is enabled. 10674 * 10675 * @see #setFilterTouchesWhenObscured(boolean) 10676 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 10677 */ 10678 @ViewDebug.ExportedProperty 10679 public boolean getFilterTouchesWhenObscured() { 10680 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 10681 } 10682 10683 /** 10684 * Sets whether the framework should discard touches when the view's 10685 * window is obscured by another visible window. 10686 * Refer to the {@link View} security documentation for more details. 10687 * 10688 * @param enabled True if touch filtering should be enabled. 10689 * 10690 * @see #getFilterTouchesWhenObscured 10691 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 10692 */ 10693 public void setFilterTouchesWhenObscured(boolean enabled) { 10694 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 10695 FILTER_TOUCHES_WHEN_OBSCURED); 10696 } 10697 10698 /** 10699 * Indicates whether the entire hierarchy under this view will save its 10700 * state when a state saving traversal occurs from its parent. The default 10701 * is true; if false, these views will not be saved unless 10702 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 10703 * 10704 * @return Returns true if the view state saving from parent is enabled, else false. 10705 * 10706 * @see #setSaveFromParentEnabled(boolean) 10707 */ 10708 public boolean isSaveFromParentEnabled() { 10709 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 10710 } 10711 10712 /** 10713 * Controls whether the entire hierarchy under this view will save its 10714 * state when a state saving traversal occurs from its parent. The default 10715 * is true; if false, these views will not be saved unless 10716 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 10717 * 10718 * @param enabled Set to false to <em>disable</em> state saving, or true 10719 * (the default) to allow it. 10720 * 10721 * @see #isSaveFromParentEnabled() 10722 * @see #setId(int) 10723 * @see #onSaveInstanceState() 10724 */ 10725 public void setSaveFromParentEnabled(boolean enabled) { 10726 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 10727 } 10728 10729 10730 /** 10731 * Returns whether this View is currently able to take focus. 10732 * 10733 * @return True if this view can take focus, or false otherwise. 10734 */ 10735 @ViewDebug.ExportedProperty(category = "focus") 10736 public final boolean isFocusable() { 10737 return FOCUSABLE == (mViewFlags & FOCUSABLE); 10738 } 10739 10740 /** 10741 * Returns the focusable setting for this view. 10742 * 10743 * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}. 10744 * @attr ref android.R.styleable#View_focusable 10745 */ 10746 @ViewDebug.ExportedProperty(mapping = { 10747 @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"), 10748 @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"), 10749 @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO") 10750 }, category = "focus") 10751 @Focusable 10752 public int getFocusable() { 10753 return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE; 10754 } 10755 10756 /** 10757 * When a view is focusable, it may not want to take focus when in touch mode. 10758 * For example, a button would like focus when the user is navigating via a D-pad 10759 * so that the user can click on it, but once the user starts touching the screen, 10760 * the button shouldn't take focus 10761 * @return Whether the view is focusable in touch mode. 10762 * @attr ref android.R.styleable#View_focusableInTouchMode 10763 */ 10764 @ViewDebug.ExportedProperty(category = "focus") 10765 public final boolean isFocusableInTouchMode() { 10766 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 10767 } 10768 10769 /** 10770 * Returns whether the view should be treated as a focusable unit by screen reader 10771 * accessibility tools. 10772 * @see #setScreenReaderFocusable(boolean) 10773 * 10774 * @return Whether the view should be treated as a focusable unit by screen reader. 10775 */ 10776 public boolean isScreenReaderFocusable() { 10777 return (mPrivateFlags3 & PFLAG3_SCREEN_READER_FOCUSABLE) != 0; 10778 } 10779 10780 /** 10781 * When screen readers (one type of accessibility tool) decide what should be read to the 10782 * user, they typically look for input focusable ({@link #isFocusable()}) parents of 10783 * non-focusable text items, and read those focusable parents and their non-focusable children 10784 * as a unit. In some situations, this behavior is desirable for views that should not take 10785 * input focus. Setting an item to be screen reader focusable requests that the view be 10786 * treated as a unit by screen readers without any effect on input focusability. The default 10787 * value of {@code false} lets screen readers use other signals, like focusable, to determine 10788 * how to group items. 10789 * 10790 * @param screenReaderFocusable Whether the view should be treated as a unit by screen reader 10791 * accessibility tools. 10792 */ 10793 public void setScreenReaderFocusable(boolean screenReaderFocusable) { 10794 updatePflags3AndNotifyA11yIfChanged(PFLAG3_SCREEN_READER_FOCUSABLE, screenReaderFocusable); 10795 } 10796 10797 /** 10798 * Gets whether this view is a heading for accessibility purposes. 10799 * 10800 * @return {@code true} if the view is a heading, {@code false} otherwise. 10801 * 10802 * @attr ref android.R.styleable#View_accessibilityHeading 10803 */ 10804 public boolean isAccessibilityHeading() { 10805 return (mPrivateFlags3 & PFLAG3_ACCESSIBILITY_HEADING) != 0; 10806 } 10807 10808 /** 10809 * Set if view is a heading for a section of content for accessibility purposes. 10810 * 10811 * @param isHeading {@code true} if the view is a heading, {@code false} otherwise. 10812 * 10813 * @attr ref android.R.styleable#View_accessibilityHeading 10814 */ 10815 public void setAccessibilityHeading(boolean isHeading) { 10816 updatePflags3AndNotifyA11yIfChanged(PFLAG3_ACCESSIBILITY_HEADING, isHeading); 10817 } 10818 10819 private void updatePflags3AndNotifyA11yIfChanged(int mask, boolean newValue) { 10820 int pflags3 = mPrivateFlags3; 10821 if (newValue) { 10822 pflags3 |= mask; 10823 } else { 10824 pflags3 &= ~mask; 10825 } 10826 10827 if (pflags3 != mPrivateFlags3) { 10828 mPrivateFlags3 = pflags3; 10829 notifyViewAccessibilityStateChangedIfNeeded( 10830 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10831 } 10832 } 10833 10834 /** 10835 * Find the nearest view in the specified direction that can take focus. 10836 * This does not actually give focus to that view. 10837 * 10838 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 10839 * 10840 * @return The nearest focusable in the specified direction, or null if none 10841 * can be found. 10842 */ 10843 public View focusSearch(@FocusRealDirection int direction) { 10844 if (mParent != null) { 10845 return mParent.focusSearch(this, direction); 10846 } else { 10847 return null; 10848 } 10849 } 10850 10851 /** 10852 * Returns whether this View is a root of a keyboard navigation cluster. 10853 * 10854 * @return True if this view is a root of a cluster, or false otherwise. 10855 * @attr ref android.R.styleable#View_keyboardNavigationCluster 10856 */ 10857 @ViewDebug.ExportedProperty(category = "focus") 10858 public final boolean isKeyboardNavigationCluster() { 10859 return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0; 10860 } 10861 10862 /** 10863 * Searches up the view hierarchy to find the top-most cluster. All deeper/nested clusters 10864 * will be ignored. 10865 * 10866 * @return the keyboard navigation cluster that this view is in (can be this view) 10867 * or {@code null} if not in one 10868 */ 10869 View findKeyboardNavigationCluster() { 10870 if (mParent instanceof View) { 10871 View cluster = ((View) mParent).findKeyboardNavigationCluster(); 10872 if (cluster != null) { 10873 return cluster; 10874 } else if (isKeyboardNavigationCluster()) { 10875 return this; 10876 } 10877 } 10878 return null; 10879 } 10880 10881 /** 10882 * Set whether this view is a root of a keyboard navigation cluster. 10883 * 10884 * @param isCluster If true, this view is a root of a cluster. 10885 * 10886 * @attr ref android.R.styleable#View_keyboardNavigationCluster 10887 */ 10888 public void setKeyboardNavigationCluster(boolean isCluster) { 10889 if (isCluster) { 10890 mPrivateFlags3 |= PFLAG3_CLUSTER; 10891 } else { 10892 mPrivateFlags3 &= ~PFLAG3_CLUSTER; 10893 } 10894 } 10895 10896 /** 10897 * Sets this View as the one which receives focus the next time cluster navigation jumps 10898 * to the cluster containing this View. This does NOT change focus even if the cluster 10899 * containing this view is current. 10900 * 10901 * @hide 10902 */ 10903 @TestApi 10904 public final void setFocusedInCluster() { 10905 setFocusedInCluster(findKeyboardNavigationCluster()); 10906 } 10907 10908 private void setFocusedInCluster(View cluster) { 10909 if (this instanceof ViewGroup) { 10910 ((ViewGroup) this).mFocusedInCluster = null; 10911 } 10912 if (cluster == this) { 10913 return; 10914 } 10915 ViewParent parent = mParent; 10916 View child = this; 10917 while (parent instanceof ViewGroup) { 10918 ((ViewGroup) parent).mFocusedInCluster = child; 10919 if (parent == cluster) { 10920 break; 10921 } 10922 child = (View) parent; 10923 parent = parent.getParent(); 10924 } 10925 } 10926 10927 private void updateFocusedInCluster(View oldFocus, @FocusDirection int direction) { 10928 if (oldFocus != null) { 10929 View oldCluster = oldFocus.findKeyboardNavigationCluster(); 10930 View cluster = findKeyboardNavigationCluster(); 10931 if (oldCluster != cluster) { 10932 // Going from one cluster to another, so save last-focused. 10933 // This covers cluster jumps because they are always FOCUS_DOWN 10934 oldFocus.setFocusedInCluster(oldCluster); 10935 if (!(oldFocus.mParent instanceof ViewGroup)) { 10936 return; 10937 } 10938 if (direction == FOCUS_FORWARD || direction == FOCUS_BACKWARD) { 10939 // This is a result of ordered navigation so consider navigation through 10940 // the previous cluster "complete" and clear its last-focused memory. 10941 ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus); 10942 } else if (oldFocus instanceof ViewGroup 10943 && ((ViewGroup) oldFocus).getDescendantFocusability() 10944 == ViewGroup.FOCUS_AFTER_DESCENDANTS 10945 && ViewRootImpl.isViewDescendantOf(this, oldFocus)) { 10946 // This means oldFocus is not focusable since it obviously has a focusable 10947 // child (this). Don't restore focus to it in the future. 10948 ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus); 10949 } 10950 } 10951 } 10952 } 10953 10954 /** 10955 * Returns whether this View should receive focus when the focus is restored for the view 10956 * hierarchy containing this view. 10957 * <p> 10958 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a 10959 * window or serves as a target of cluster navigation. 10960 * 10961 * @see #restoreDefaultFocus() 10962 * 10963 * @return {@code true} if this view is the default-focus view, {@code false} otherwise 10964 * @attr ref android.R.styleable#View_focusedByDefault 10965 */ 10966 @ViewDebug.ExportedProperty(category = "focus") 10967 public final boolean isFocusedByDefault() { 10968 return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0; 10969 } 10970 10971 /** 10972 * Sets whether this View should receive focus when the focus is restored for the view 10973 * hierarchy containing this view. 10974 * <p> 10975 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a 10976 * window or serves as a target of cluster navigation. 10977 * 10978 * @param isFocusedByDefault {@code true} to set this view as the default-focus view, 10979 * {@code false} otherwise. 10980 * 10981 * @see #restoreDefaultFocus() 10982 * 10983 * @attr ref android.R.styleable#View_focusedByDefault 10984 */ 10985 public void setFocusedByDefault(boolean isFocusedByDefault) { 10986 if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) { 10987 return; 10988 } 10989 10990 if (isFocusedByDefault) { 10991 mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT; 10992 } else { 10993 mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT; 10994 } 10995 10996 if (mParent instanceof ViewGroup) { 10997 if (isFocusedByDefault) { 10998 ((ViewGroup) mParent).setDefaultFocus(this); 10999 } else { 11000 ((ViewGroup) mParent).clearDefaultFocus(this); 11001 } 11002 } 11003 } 11004 11005 /** 11006 * Returns whether the view hierarchy with this view as a root contain a default-focus view. 11007 * 11008 * @return {@code true} if this view has default focus, {@code false} otherwise 11009 */ 11010 boolean hasDefaultFocus() { 11011 return isFocusedByDefault(); 11012 } 11013 11014 /** 11015 * Find the nearest keyboard navigation cluster in the specified direction. 11016 * This does not actually give focus to that cluster. 11017 * 11018 * @param currentCluster The starting point of the search. Null means the current cluster is not 11019 * found yet 11020 * @param direction Direction to look 11021 * 11022 * @return The nearest keyboard navigation cluster in the specified direction, or null if none 11023 * can be found 11024 */ 11025 public View keyboardNavigationClusterSearch(View currentCluster, 11026 @FocusDirection int direction) { 11027 if (isKeyboardNavigationCluster()) { 11028 currentCluster = this; 11029 } 11030 if (isRootNamespace()) { 11031 // Root namespace means we should consider ourselves the top of the 11032 // tree for group searching; otherwise we could be group searching 11033 // into other tabs. see LocalActivityManager and TabHost for more info. 11034 return FocusFinder.getInstance().findNextKeyboardNavigationCluster( 11035 this, currentCluster, direction); 11036 } else if (mParent != null) { 11037 return mParent.keyboardNavigationClusterSearch(currentCluster, direction); 11038 } 11039 return null; 11040 } 11041 11042 /** 11043 * This method is the last chance for the focused view and its ancestors to 11044 * respond to an arrow key. This is called when the focused view did not 11045 * consume the key internally, nor could the view system find a new view in 11046 * the requested direction to give focus to. 11047 * 11048 * @param focused The currently focused view. 11049 * @param direction The direction focus wants to move. One of FOCUS_UP, 11050 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 11051 * @return True if the this view consumed this unhandled move. 11052 */ 11053 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 11054 return false; 11055 } 11056 11057 /** 11058 * Sets whether this View should use a default focus highlight when it gets focused but doesn't 11059 * have {@link android.R.attr#state_focused} defined in its background. 11060 * 11061 * @param defaultFocusHighlightEnabled {@code true} to set this view to use a default focus 11062 * highlight, {@code false} otherwise. 11063 * 11064 * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled 11065 */ 11066 public void setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled) { 11067 mDefaultFocusHighlightEnabled = defaultFocusHighlightEnabled; 11068 } 11069 11070 /** 11071 11072 /** 11073 * Returns whether this View should use a default focus highlight when it gets focused but 11074 * doesn't have {@link android.R.attr#state_focused} defined in its background. 11075 * 11076 * @return True if this View should use a default focus highlight. 11077 * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled 11078 */ 11079 @ViewDebug.ExportedProperty(category = "focus") 11080 public final boolean getDefaultFocusHighlightEnabled() { 11081 return mDefaultFocusHighlightEnabled; 11082 } 11083 11084 /** 11085 * If a user manually specified the next view id for a particular direction, 11086 * use the root to look up the view. 11087 * @param root The root view of the hierarchy containing this view. 11088 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 11089 * or FOCUS_BACKWARD. 11090 * @return The user specified next view, or null if there is none. 11091 */ 11092 View findUserSetNextFocus(View root, @FocusDirection int direction) { 11093 switch (direction) { 11094 case FOCUS_LEFT: 11095 if (mNextFocusLeftId == View.NO_ID) return null; 11096 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 11097 case FOCUS_RIGHT: 11098 if (mNextFocusRightId == View.NO_ID) return null; 11099 return findViewInsideOutShouldExist(root, mNextFocusRightId); 11100 case FOCUS_UP: 11101 if (mNextFocusUpId == View.NO_ID) return null; 11102 return findViewInsideOutShouldExist(root, mNextFocusUpId); 11103 case FOCUS_DOWN: 11104 if (mNextFocusDownId == View.NO_ID) return null; 11105 return findViewInsideOutShouldExist(root, mNextFocusDownId); 11106 case FOCUS_FORWARD: 11107 if (mNextFocusForwardId == View.NO_ID) return null; 11108 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 11109 case FOCUS_BACKWARD: { 11110 if (mID == View.NO_ID) return null; 11111 final int id = mID; 11112 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 11113 @Override 11114 public boolean test(View t) { 11115 return t.mNextFocusForwardId == id; 11116 } 11117 }); 11118 } 11119 } 11120 return null; 11121 } 11122 11123 /** 11124 * If a user manually specified the next keyboard-navigation cluster for a particular direction, 11125 * use the root to look up the view. 11126 * 11127 * @param root the root view of the hierarchy containing this view 11128 * @param direction {@link #FOCUS_FORWARD} or {@link #FOCUS_BACKWARD} 11129 * @return the user-specified next cluster, or {@code null} if there is none 11130 */ 11131 View findUserSetNextKeyboardNavigationCluster(View root, @FocusDirection int direction) { 11132 switch (direction) { 11133 case FOCUS_FORWARD: 11134 if (mNextClusterForwardId == View.NO_ID) return null; 11135 return findViewInsideOutShouldExist(root, mNextClusterForwardId); 11136 case FOCUS_BACKWARD: { 11137 if (mID == View.NO_ID) return null; 11138 final int id = mID; 11139 return root.findViewByPredicateInsideOut(this, 11140 (Predicate<View>) t -> t.mNextClusterForwardId == id); 11141 } 11142 } 11143 return null; 11144 } 11145 11146 private View findViewInsideOutShouldExist(View root, int id) { 11147 if (mMatchIdPredicate == null) { 11148 mMatchIdPredicate = new MatchIdPredicate(); 11149 } 11150 mMatchIdPredicate.mId = id; 11151 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 11152 if (result == null) { 11153 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 11154 } 11155 return result; 11156 } 11157 11158 /** 11159 * Find and return all focusable views that are descendants of this view, 11160 * possibly including this view if it is focusable itself. 11161 * 11162 * @param direction The direction of the focus 11163 * @return A list of focusable views 11164 */ 11165 public ArrayList<View> getFocusables(@FocusDirection int direction) { 11166 ArrayList<View> result = new ArrayList<View>(24); 11167 addFocusables(result, direction); 11168 return result; 11169 } 11170 11171 /** 11172 * Add any focusable views that are descendants of this view (possibly 11173 * including this view if it is focusable itself) to views. If we are in touch mode, 11174 * only add views that are also focusable in touch mode. 11175 * 11176 * @param views Focusable views found so far 11177 * @param direction The direction of the focus 11178 */ 11179 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 11180 addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL); 11181 } 11182 11183 /** 11184 * Adds any focusable views that are descendants of this view (possibly 11185 * including this view if it is focusable itself) to views. This method 11186 * adds all focusable views regardless if we are in touch mode or 11187 * only views focusable in touch mode if we are in touch mode or 11188 * only views that can take accessibility focus if accessibility is enabled 11189 * depending on the focusable mode parameter. 11190 * 11191 * @param views Focusable views found so far or null if all we are interested is 11192 * the number of focusables. 11193 * @param direction The direction of the focus. 11194 * @param focusableMode The type of focusables to be added. 11195 * 11196 * @see #FOCUSABLES_ALL 11197 * @see #FOCUSABLES_TOUCH_MODE 11198 */ 11199 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 11200 @FocusableMode int focusableMode) { 11201 if (views == null) { 11202 return; 11203 } 11204 if (!canTakeFocus()) { 11205 return; 11206 } 11207 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 11208 && !isFocusableInTouchMode()) { 11209 return; 11210 } 11211 views.add(this); 11212 } 11213 11214 /** 11215 * Adds any keyboard navigation cluster roots that are descendants of this view (possibly 11216 * including this view if it is a cluster root itself) to views. 11217 * 11218 * @param views Keyboard navigation cluster roots found so far 11219 * @param direction Direction to look 11220 */ 11221 public void addKeyboardNavigationClusters( 11222 @NonNull Collection<View> views, 11223 int direction) { 11224 if (!isKeyboardNavigationCluster()) { 11225 return; 11226 } 11227 if (!hasFocusable()) { 11228 return; 11229 } 11230 views.add(this); 11231 } 11232 11233 /** 11234 * Finds the Views that contain given text. The containment is case insensitive. 11235 * The search is performed by either the text that the View renders or the content 11236 * description that describes the view for accessibility purposes and the view does 11237 * not render or both. Clients can specify how the search is to be performed via 11238 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 11239 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 11240 * 11241 * @param outViews The output list of matching Views. 11242 * @param searched The text to match against. 11243 * 11244 * @see #FIND_VIEWS_WITH_TEXT 11245 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 11246 * @see #setContentDescription(CharSequence) 11247 */ 11248 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 11249 @FindViewFlags int flags) { 11250 if (getAccessibilityNodeProvider() != null) { 11251 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 11252 outViews.add(this); 11253 } 11254 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 11255 && (searched != null && searched.length() > 0) 11256 && (mContentDescription != null && mContentDescription.length() > 0)) { 11257 String searchedLowerCase = searched.toString().toLowerCase(); 11258 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 11259 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 11260 outViews.add(this); 11261 } 11262 } 11263 } 11264 11265 /** 11266 * Find and return all touchable views that are descendants of this view, 11267 * possibly including this view if it is touchable itself. 11268 * 11269 * @return A list of touchable views 11270 */ 11271 public ArrayList<View> getTouchables() { 11272 ArrayList<View> result = new ArrayList<View>(); 11273 addTouchables(result); 11274 return result; 11275 } 11276 11277 /** 11278 * Add any touchable views that are descendants of this view (possibly 11279 * including this view if it is touchable itself) to views. 11280 * 11281 * @param views Touchable views found so far 11282 */ 11283 public void addTouchables(ArrayList<View> views) { 11284 final int viewFlags = mViewFlags; 11285 11286 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 11287 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 11288 && (viewFlags & ENABLED_MASK) == ENABLED) { 11289 views.add(this); 11290 } 11291 } 11292 11293 /** 11294 * Returns whether this View is accessibility focused. 11295 * 11296 * @return True if this View is accessibility focused. 11297 */ 11298 public boolean isAccessibilityFocused() { 11299 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 11300 } 11301 11302 /** 11303 * Call this to try to give accessibility focus to this view. 11304 * 11305 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 11306 * returns false or the view is no visible or the view already has accessibility 11307 * focus. 11308 * 11309 * See also {@link #focusSearch(int)}, which is what you call to say that you 11310 * have focus, and you want your parent to look for the next one. 11311 * 11312 * @return Whether this view actually took accessibility focus. 11313 * 11314 * @hide 11315 */ 11316 public boolean requestAccessibilityFocus() { 11317 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 11318 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 11319 return false; 11320 } 11321 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 11322 return false; 11323 } 11324 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 11325 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 11326 ViewRootImpl viewRootImpl = getViewRootImpl(); 11327 if (viewRootImpl != null) { 11328 viewRootImpl.setAccessibilityFocus(this, null); 11329 } 11330 invalidate(); 11331 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 11332 return true; 11333 } 11334 return false; 11335 } 11336 11337 /** 11338 * Call this to try to clear accessibility focus of this view. 11339 * 11340 * See also {@link #focusSearch(int)}, which is what you call to say that you 11341 * have focus, and you want your parent to look for the next one. 11342 * 11343 * @hide 11344 */ 11345 public void clearAccessibilityFocus() { 11346 clearAccessibilityFocusNoCallbacks(0); 11347 11348 // Clear the global reference of accessibility focus if this view or 11349 // any of its descendants had accessibility focus. This will NOT send 11350 // an event or update internal state if focus is cleared from a 11351 // descendant view, which may leave views in inconsistent states. 11352 final ViewRootImpl viewRootImpl = getViewRootImpl(); 11353 if (viewRootImpl != null) { 11354 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 11355 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 11356 viewRootImpl.setAccessibilityFocus(null, null); 11357 } 11358 } 11359 } 11360 11361 private void sendAccessibilityHoverEvent(int eventType) { 11362 // Since we are not delivering to a client accessibility events from not 11363 // important views (unless the clinet request that) we need to fire the 11364 // event from the deepest view exposed to the client. As a consequence if 11365 // the user crosses a not exposed view the client will see enter and exit 11366 // of the exposed predecessor followed by and enter and exit of that same 11367 // predecessor when entering and exiting the not exposed descendant. This 11368 // is fine since the client has a clear idea which view is hovered at the 11369 // price of a couple more events being sent. This is a simple and 11370 // working solution. 11371 View source = this; 11372 while (true) { 11373 if (source.includeForAccessibility()) { 11374 source.sendAccessibilityEvent(eventType); 11375 return; 11376 } 11377 ViewParent parent = source.getParent(); 11378 if (parent instanceof View) { 11379 source = (View) parent; 11380 } else { 11381 return; 11382 } 11383 } 11384 } 11385 11386 /** 11387 * Clears accessibility focus without calling any callback methods 11388 * normally invoked in {@link #clearAccessibilityFocus()}. This method 11389 * is used separately from that one for clearing accessibility focus when 11390 * giving this focus to another view. 11391 * 11392 * @param action The action, if any, that led to focus being cleared. Set to 11393 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 11394 * the window. 11395 */ 11396 void clearAccessibilityFocusNoCallbacks(int action) { 11397 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 11398 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 11399 invalidate(); 11400 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 11401 AccessibilityEvent event = AccessibilityEvent.obtain( 11402 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 11403 event.setAction(action); 11404 if (mAccessibilityDelegate != null) { 11405 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 11406 } else { 11407 sendAccessibilityEventUnchecked(event); 11408 } 11409 } 11410 } 11411 } 11412 11413 /** 11414 * Call this to try to give focus to a specific view or to one of its 11415 * descendants. 11416 * 11417 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 11418 * false), or if it can't be focused due to other conditions (not focusable in touch mode 11419 * ({@link #isFocusableInTouchMode}) while the device is in touch mode, not visible, not 11420 * enabled, or has no size). 11421 * 11422 * See also {@link #focusSearch(int)}, which is what you call to say that you 11423 * have focus, and you want your parent to look for the next one. 11424 * 11425 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 11426 * {@link #FOCUS_DOWN} and <code>null</code>. 11427 * 11428 * @return Whether this view or one of its descendants actually took focus. 11429 */ 11430 public final boolean requestFocus() { 11431 return requestFocus(View.FOCUS_DOWN); 11432 } 11433 11434 /** 11435 * This will request focus for whichever View was last focused within this 11436 * cluster before a focus-jump out of it. 11437 * 11438 * @hide 11439 */ 11440 @TestApi 11441 public boolean restoreFocusInCluster(@FocusRealDirection int direction) { 11442 // Prioritize focusableByDefault over algorithmic focus selection. 11443 if (restoreDefaultFocus()) { 11444 return true; 11445 } 11446 return requestFocus(direction); 11447 } 11448 11449 /** 11450 * This will request focus for whichever View not in a cluster was last focused before a 11451 * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus 11452 * the "first" focusable view it finds. 11453 * 11454 * @hide 11455 */ 11456 @TestApi 11457 public boolean restoreFocusNotInCluster() { 11458 return requestFocus(View.FOCUS_DOWN); 11459 } 11460 11461 /** 11462 * Gives focus to the default-focus view in the view hierarchy that has this view as a root. 11463 * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}. 11464 * 11465 * @return Whether this view or one of its descendants actually took focus 11466 */ 11467 public boolean restoreDefaultFocus() { 11468 return requestFocus(View.FOCUS_DOWN); 11469 } 11470 11471 /** 11472 * Call this to try to give focus to a specific view or to one of its 11473 * descendants and give it a hint about what direction focus is heading. 11474 * 11475 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 11476 * false), or if it is focusable and it is not focusable in touch mode 11477 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 11478 * 11479 * See also {@link #focusSearch(int)}, which is what you call to say that you 11480 * have focus, and you want your parent to look for the next one. 11481 * 11482 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 11483 * <code>null</code> set for the previously focused rectangle. 11484 * 11485 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 11486 * @return Whether this view or one of its descendants actually took focus. 11487 */ 11488 public final boolean requestFocus(int direction) { 11489 return requestFocus(direction, null); 11490 } 11491 11492 /** 11493 * Call this to try to give focus to a specific view or to one of its descendants 11494 * and give it hints about the direction and a specific rectangle that the focus 11495 * is coming from. The rectangle can help give larger views a finer grained hint 11496 * about where focus is coming from, and therefore, where to show selection, or 11497 * forward focus change internally. 11498 * 11499 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 11500 * false), or if it is focusable and it is not focusable in touch mode 11501 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 11502 * 11503 * A View will not take focus if it is not visible. 11504 * 11505 * A View will not take focus if one of its parents has 11506 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 11507 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 11508 * 11509 * See also {@link #focusSearch(int)}, which is what you call to say that you 11510 * have focus, and you want your parent to look for the next one. 11511 * 11512 * You may wish to override this method if your custom {@link View} has an internal 11513 * {@link View} that it wishes to forward the request to. 11514 * 11515 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 11516 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 11517 * to give a finer grained hint about where focus is coming from. May be null 11518 * if there is no hint. 11519 * @return Whether this view or one of its descendants actually took focus. 11520 */ 11521 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 11522 return requestFocusNoSearch(direction, previouslyFocusedRect); 11523 } 11524 11525 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 11526 // need to be focusable 11527 if (!canTakeFocus()) { 11528 return false; 11529 } 11530 11531 // need to be focusable in touch mode if in touch mode 11532 if (isInTouchMode() && 11533 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 11534 return false; 11535 } 11536 11537 // need to not have any parents blocking us 11538 if (hasAncestorThatBlocksDescendantFocus()) { 11539 return false; 11540 } 11541 11542 if (!isLayoutValid()) { 11543 mPrivateFlags |= PFLAG_WANTS_FOCUS; 11544 } else { 11545 clearParentsWantFocus(); 11546 } 11547 11548 handleFocusGainInternal(direction, previouslyFocusedRect); 11549 return true; 11550 } 11551 11552 void clearParentsWantFocus() { 11553 if (mParent instanceof View) { 11554 ((View) mParent).mPrivateFlags &= ~PFLAG_WANTS_FOCUS; 11555 ((View) mParent).clearParentsWantFocus(); 11556 } 11557 } 11558 11559 /** 11560 * Call this to try to give focus to a specific view or to one of its descendants. This is a 11561 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 11562 * touch mode to request focus when they are touched. 11563 * 11564 * @return Whether this view or one of its descendants actually took focus. 11565 * 11566 * @see #isInTouchMode() 11567 * 11568 */ 11569 public final boolean requestFocusFromTouch() { 11570 // Leave touch mode if we need to 11571 if (isInTouchMode()) { 11572 ViewRootImpl viewRoot = getViewRootImpl(); 11573 if (viewRoot != null) { 11574 viewRoot.ensureTouchMode(false); 11575 } 11576 } 11577 return requestFocus(View.FOCUS_DOWN); 11578 } 11579 11580 /** 11581 * @return Whether any ancestor of this view blocks descendant focus. 11582 */ 11583 private boolean hasAncestorThatBlocksDescendantFocus() { 11584 final boolean focusableInTouchMode = isFocusableInTouchMode(); 11585 ViewParent ancestor = mParent; 11586 while (ancestor instanceof ViewGroup) { 11587 final ViewGroup vgAncestor = (ViewGroup) ancestor; 11588 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 11589 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 11590 return true; 11591 } else { 11592 ancestor = vgAncestor.getParent(); 11593 } 11594 } 11595 return false; 11596 } 11597 11598 /** 11599 * Gets the mode for determining whether this View is important for accessibility. 11600 * A view is important for accessibility if it fires accessibility events and if it 11601 * is reported to accessibility services that query the screen. 11602 * 11603 * @return The mode for determining whether a view is important for accessibility, one 11604 * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, 11605 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or 11606 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}. 11607 * 11608 * @attr ref android.R.styleable#View_importantForAccessibility 11609 * 11610 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 11611 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 11612 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 11613 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 11614 */ 11615 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 11616 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 11617 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 11618 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 11619 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 11620 to = "noHideDescendants") 11621 }) 11622 public int getImportantForAccessibility() { 11623 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 11624 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 11625 } 11626 11627 /** 11628 * Sets the live region mode for this view. This indicates to accessibility 11629 * services whether they should automatically notify the user about changes 11630 * to the view's content description or text, or to the content descriptions 11631 * or text of the view's children (where applicable). 11632 * <p> 11633 * For example, in a login screen with a TextView that displays an "incorrect 11634 * password" notification, that view should be marked as a live region with 11635 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 11636 * <p> 11637 * To disable change notifications for this view, use 11638 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 11639 * mode for most views. 11640 * <p> 11641 * To indicate that the user should be notified of changes, use 11642 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 11643 * <p> 11644 * If the view's changes should interrupt ongoing speech and notify the user 11645 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 11646 * 11647 * @param mode The live region mode for this view, one of: 11648 * <ul> 11649 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 11650 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 11651 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 11652 * </ul> 11653 * @attr ref android.R.styleable#View_accessibilityLiveRegion 11654 */ 11655 public void setAccessibilityLiveRegion(int mode) { 11656 if (mode != getAccessibilityLiveRegion()) { 11657 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 11658 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 11659 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 11660 notifyViewAccessibilityStateChangedIfNeeded( 11661 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11662 } 11663 } 11664 11665 /** 11666 * Gets the live region mode for this View. 11667 * 11668 * @return The live region mode for the view. 11669 * 11670 * @attr ref android.R.styleable#View_accessibilityLiveRegion 11671 * 11672 * @see #setAccessibilityLiveRegion(int) 11673 */ 11674 public int getAccessibilityLiveRegion() { 11675 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 11676 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 11677 } 11678 11679 /** 11680 * Sets how to determine whether this view is important for accessibility 11681 * which is if it fires accessibility events and if it is reported to 11682 * accessibility services that query the screen. 11683 * 11684 * @param mode How to determine whether this view is important for accessibility. 11685 * 11686 * @attr ref android.R.styleable#View_importantForAccessibility 11687 * 11688 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 11689 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 11690 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 11691 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 11692 */ 11693 public void setImportantForAccessibility(int mode) { 11694 final int oldMode = getImportantForAccessibility(); 11695 if (mode != oldMode) { 11696 final boolean hideDescendants = 11697 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 11698 11699 // If this node or its descendants are no longer important, try to 11700 // clear accessibility focus. 11701 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 11702 final View focusHost = findAccessibilityFocusHost(hideDescendants); 11703 if (focusHost != null) { 11704 focusHost.clearAccessibilityFocus(); 11705 } 11706 } 11707 11708 // If we're moving between AUTO and another state, we might not need 11709 // to send a subtree changed notification. We'll store the computed 11710 // importance, since we'll need to check it later to make sure. 11711 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 11712 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 11713 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 11714 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 11715 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 11716 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 11717 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 11718 notifySubtreeAccessibilityStateChangedIfNeeded(); 11719 } else { 11720 notifyViewAccessibilityStateChangedIfNeeded( 11721 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11722 } 11723 } 11724 } 11725 11726 /** 11727 * Returns the view within this view's hierarchy that is hosting 11728 * accessibility focus. 11729 * 11730 * @param searchDescendants whether to search for focus in descendant views 11731 * @return the view hosting accessibility focus, or {@code null} 11732 */ 11733 private View findAccessibilityFocusHost(boolean searchDescendants) { 11734 if (isAccessibilityFocusedViewOrHost()) { 11735 return this; 11736 } 11737 11738 if (searchDescendants) { 11739 final ViewRootImpl viewRoot = getViewRootImpl(); 11740 if (viewRoot != null) { 11741 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 11742 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 11743 return focusHost; 11744 } 11745 } 11746 } 11747 11748 return null; 11749 } 11750 11751 /** 11752 * Computes whether this view should be exposed for accessibility. In 11753 * general, views that are interactive or provide information are exposed 11754 * while views that serve only as containers are hidden. 11755 * <p> 11756 * If an ancestor of this view has importance 11757 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 11758 * returns <code>false</code>. 11759 * <p> 11760 * Otherwise, the value is computed according to the view's 11761 * {@link #getImportantForAccessibility()} value: 11762 * <ol> 11763 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 11764 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 11765 * </code> 11766 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 11767 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 11768 * view satisfies any of the following: 11769 * <ul> 11770 * <li>Is actionable, e.g. {@link #isClickable()}, 11771 * {@link #isLongClickable()}, or {@link #isFocusable()} 11772 * <li>Has an {@link AccessibilityDelegate} 11773 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 11774 * {@link OnKeyListener}, etc. 11775 * <li>Is an accessibility live region, e.g. 11776 * {@link #getAccessibilityLiveRegion()} is not 11777 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 11778 * </ul> 11779 * <li>Has an accessibility pane title, see {@link #setAccessibilityPaneTitle}</li> 11780 * </ol> 11781 * 11782 * @return Whether the view is exposed for accessibility. 11783 * @see #setImportantForAccessibility(int) 11784 * @see #getImportantForAccessibility() 11785 */ 11786 public boolean isImportantForAccessibility() { 11787 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 11788 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 11789 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 11790 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 11791 return false; 11792 } 11793 11794 // Check parent mode to ensure we're not hidden. 11795 ViewParent parent = mParent; 11796 while (parent instanceof View) { 11797 if (((View) parent).getImportantForAccessibility() 11798 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 11799 return false; 11800 } 11801 parent = parent.getParent(); 11802 } 11803 11804 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 11805 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 11806 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE 11807 || isAccessibilityPane(); 11808 } 11809 11810 /** 11811 * Gets the parent for accessibility purposes. Note that the parent for 11812 * accessibility is not necessary the immediate parent. It is the first 11813 * predecessor that is important for accessibility. 11814 * 11815 * @return The parent for accessibility purposes. 11816 */ 11817 public ViewParent getParentForAccessibility() { 11818 if (mParent instanceof View) { 11819 View parentView = (View) mParent; 11820 if (parentView.includeForAccessibility()) { 11821 return mParent; 11822 } else { 11823 return mParent.getParentForAccessibility(); 11824 } 11825 } 11826 return null; 11827 } 11828 11829 /** @hide */ 11830 View getSelfOrParentImportantForA11y() { 11831 if (isImportantForAccessibility()) return this; 11832 ViewParent parent = getParentForAccessibility(); 11833 if (parent instanceof View) return (View) parent; 11834 return null; 11835 } 11836 11837 /** 11838 * Adds the children of this View relevant for accessibility to the given list 11839 * as output. Since some Views are not important for accessibility the added 11840 * child views are not necessarily direct children of this view, rather they are 11841 * the first level of descendants important for accessibility. 11842 * 11843 * @param outChildren The output list that will receive children for accessibility. 11844 */ 11845 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 11846 11847 } 11848 11849 /** 11850 * Whether to regard this view for accessibility. A view is regarded for 11851 * accessibility if it is important for accessibility or the querying 11852 * accessibility service has explicitly requested that view not 11853 * important for accessibility are regarded. 11854 * 11855 * @return Whether to regard the view for accessibility. 11856 * 11857 * @hide 11858 */ 11859 public boolean includeForAccessibility() { 11860 if (mAttachInfo != null) { 11861 return (mAttachInfo.mAccessibilityFetchFlags 11862 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 11863 || isImportantForAccessibility(); 11864 } 11865 return false; 11866 } 11867 11868 /** 11869 * Returns whether the View is considered actionable from 11870 * accessibility perspective. Such view are important for 11871 * accessibility. 11872 * 11873 * @return True if the view is actionable for accessibility. 11874 * 11875 * @hide 11876 */ 11877 public boolean isActionableForAccessibility() { 11878 return (isClickable() || isLongClickable() || isFocusable()); 11879 } 11880 11881 /** 11882 * Returns whether the View has registered callbacks which makes it 11883 * important for accessibility. 11884 * 11885 * @return True if the view is actionable for accessibility. 11886 */ 11887 private boolean hasListenersForAccessibility() { 11888 ListenerInfo info = getListenerInfo(); 11889 return mTouchDelegate != null || info.mOnKeyListener != null 11890 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 11891 || info.mOnHoverListener != null || info.mOnDragListener != null; 11892 } 11893 11894 /** 11895 * Notifies that the accessibility state of this view changed. The change 11896 * is local to this view and does not represent structural changes such 11897 * as children and parent. For example, the view became focusable. The 11898 * notification is at at most once every 11899 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 11900 * to avoid unnecessary load to the system. Also once a view has a pending 11901 * notification this method is a NOP until the notification has been sent. 11902 * 11903 * @hide 11904 */ 11905 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 11906 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 11907 return; 11908 } 11909 11910 // Changes to views with a pane title count as window state changes, as the pane title 11911 // marks them as significant parts of the UI. 11912 if ((changeType != AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) 11913 && isAccessibilityPane()) { 11914 // If the pane isn't visible, content changed events are sufficient unless we're 11915 // reporting that the view just disappeared 11916 if ((getVisibility() == VISIBLE) 11917 || (changeType == AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED)) { 11918 final AccessibilityEvent event = AccessibilityEvent.obtain(); 11919 event.setEventType(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 11920 event.setContentChangeTypes(changeType); 11921 event.setSource(this); 11922 onPopulateAccessibilityEvent(event); 11923 if (mParent != null) { 11924 try { 11925 mParent.requestSendAccessibilityEvent(this, event); 11926 } catch (AbstractMethodError e) { 11927 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() 11928 + " does not fully implement ViewParent", e); 11929 } 11930 } 11931 return; 11932 } 11933 } 11934 11935 // If this is a live region, we should send a subtree change event 11936 // from this view immediately. Otherwise, we can let it propagate up. 11937 if (getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE) { 11938 final AccessibilityEvent event = AccessibilityEvent.obtain(); 11939 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 11940 event.setContentChangeTypes(changeType); 11941 sendAccessibilityEventUnchecked(event); 11942 } else if (mParent != null) { 11943 try { 11944 mParent.notifySubtreeAccessibilityStateChanged(this, this, changeType); 11945 } catch (AbstractMethodError e) { 11946 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 11947 " does not fully implement ViewParent", e); 11948 } 11949 } 11950 } 11951 11952 /** 11953 * Notifies that the accessibility state of this view changed. The change 11954 * is *not* local to this view and does represent structural changes such 11955 * as children and parent. For example, the view size changed. The 11956 * notification is at at most once every 11957 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 11958 * to avoid unnecessary load to the system. Also once a view has a pending 11959 * notification this method is a NOP until the notification has been sent. 11960 * 11961 * @hide 11962 */ 11963 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 11964 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 11965 return; 11966 } 11967 11968 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 11969 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 11970 if (mParent != null) { 11971 try { 11972 mParent.notifySubtreeAccessibilityStateChanged( 11973 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 11974 } catch (AbstractMethodError e) { 11975 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 11976 " does not fully implement ViewParent", e); 11977 } 11978 } 11979 } 11980 } 11981 11982 /** 11983 * Change the visibility of the View without triggering any other changes. This is 11984 * important for transitions, where visibility changes should not adjust focus or 11985 * trigger a new layout. This is only used when the visibility has already been changed 11986 * and we need a transient value during an animation. When the animation completes, 11987 * the original visibility value is always restored. 11988 * 11989 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 11990 * @hide 11991 */ 11992 public void setTransitionVisibility(@Visibility int visibility) { 11993 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 11994 } 11995 11996 /** 11997 * Reset the flag indicating the accessibility state of the subtree rooted 11998 * at this view changed. 11999 */ 12000 void resetSubtreeAccessibilityStateChanged() { 12001 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 12002 } 12003 12004 /** 12005 * Report an accessibility action to this view's parents for delegated processing. 12006 * 12007 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 12008 * call this method to delegate an accessibility action to a supporting parent. If the parent 12009 * returns true from its 12010 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 12011 * method this method will return true to signify that the action was consumed.</p> 12012 * 12013 * <p>This method is useful for implementing nested scrolling child views. If 12014 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 12015 * a custom view implementation may invoke this method to allow a parent to consume the 12016 * scroll first. If this method returns true the custom view should skip its own scrolling 12017 * behavior.</p> 12018 * 12019 * @param action Accessibility action to delegate 12020 * @param arguments Optional action arguments 12021 * @return true if the action was consumed by a parent 12022 */ 12023 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 12024 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 12025 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 12026 return true; 12027 } 12028 } 12029 return false; 12030 } 12031 12032 /** 12033 * Performs the specified accessibility action on the view. For 12034 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 12035 * <p> 12036 * If an {@link AccessibilityDelegate} has been specified via calling 12037 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 12038 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 12039 * is responsible for handling this call. 12040 * </p> 12041 * 12042 * <p>The default implementation will delegate 12043 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 12044 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 12045 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 12046 * 12047 * @param action The action to perform. 12048 * @param arguments Optional action arguments. 12049 * @return Whether the action was performed. 12050 */ 12051 public boolean performAccessibilityAction(int action, Bundle arguments) { 12052 if (mAccessibilityDelegate != null) { 12053 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 12054 } else { 12055 return performAccessibilityActionInternal(action, arguments); 12056 } 12057 } 12058 12059 /** 12060 * @see #performAccessibilityAction(int, Bundle) 12061 * 12062 * Note: Called from the default {@link AccessibilityDelegate}. 12063 * 12064 * @hide 12065 */ 12066 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 12067 if (isNestedScrollingEnabled() 12068 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 12069 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 12070 || action == R.id.accessibilityActionScrollUp 12071 || action == R.id.accessibilityActionScrollLeft 12072 || action == R.id.accessibilityActionScrollDown 12073 || action == R.id.accessibilityActionScrollRight)) { 12074 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 12075 return true; 12076 } 12077 } 12078 12079 switch (action) { 12080 case AccessibilityNodeInfo.ACTION_CLICK: { 12081 if (isClickable()) { 12082 performClickInternal(); 12083 return true; 12084 } 12085 } break; 12086 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 12087 if (isLongClickable()) { 12088 performLongClick(); 12089 return true; 12090 } 12091 } break; 12092 case AccessibilityNodeInfo.ACTION_FOCUS: { 12093 if (!hasFocus()) { 12094 // Get out of touch mode since accessibility 12095 // wants to move focus around. 12096 getViewRootImpl().ensureTouchMode(false); 12097 return requestFocus(); 12098 } 12099 } break; 12100 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 12101 if (hasFocus()) { 12102 clearFocus(); 12103 return !isFocused(); 12104 } 12105 } break; 12106 case AccessibilityNodeInfo.ACTION_SELECT: { 12107 if (!isSelected()) { 12108 setSelected(true); 12109 return isSelected(); 12110 } 12111 } break; 12112 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 12113 if (isSelected()) { 12114 setSelected(false); 12115 return !isSelected(); 12116 } 12117 } break; 12118 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 12119 if (!isAccessibilityFocused()) { 12120 return requestAccessibilityFocus(); 12121 } 12122 } break; 12123 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 12124 if (isAccessibilityFocused()) { 12125 clearAccessibilityFocus(); 12126 return true; 12127 } 12128 } break; 12129 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 12130 if (arguments != null) { 12131 final int granularity = arguments.getInt( 12132 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 12133 final boolean extendSelection = arguments.getBoolean( 12134 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 12135 return traverseAtGranularity(granularity, true, extendSelection); 12136 } 12137 } break; 12138 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 12139 if (arguments != null) { 12140 final int granularity = arguments.getInt( 12141 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 12142 final boolean extendSelection = arguments.getBoolean( 12143 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 12144 return traverseAtGranularity(granularity, false, extendSelection); 12145 } 12146 } break; 12147 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 12148 CharSequence text = getIterableTextForAccessibility(); 12149 if (text == null) { 12150 return false; 12151 } 12152 final int start = (arguments != null) ? arguments.getInt( 12153 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 12154 final int end = (arguments != null) ? arguments.getInt( 12155 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 12156 // Only cursor position can be specified (selection length == 0) 12157 if ((getAccessibilitySelectionStart() != start 12158 || getAccessibilitySelectionEnd() != end) 12159 && (start == end)) { 12160 setAccessibilitySelection(start, end); 12161 notifyViewAccessibilityStateChangedIfNeeded( 12162 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 12163 return true; 12164 } 12165 } break; 12166 case R.id.accessibilityActionShowOnScreen: { 12167 if (mAttachInfo != null) { 12168 final Rect r = mAttachInfo.mTmpInvalRect; 12169 getDrawingRect(r); 12170 return requestRectangleOnScreen(r, true); 12171 } 12172 } break; 12173 case R.id.accessibilityActionContextClick: { 12174 if (isContextClickable()) { 12175 performContextClick(); 12176 return true; 12177 } 12178 } break; 12179 case R.id.accessibilityActionShowTooltip: { 12180 if ((mTooltipInfo != null) && (mTooltipInfo.mTooltipPopup != null)) { 12181 // Tooltip already showing 12182 return false; 12183 } 12184 return showLongClickTooltip(0, 0); 12185 } 12186 case R.id.accessibilityActionHideTooltip: { 12187 if ((mTooltipInfo == null) || (mTooltipInfo.mTooltipPopup == null)) { 12188 // No tooltip showing 12189 return false; 12190 } 12191 hideTooltip(); 12192 return true; 12193 } 12194 } 12195 return false; 12196 } 12197 12198 private boolean traverseAtGranularity(int granularity, boolean forward, 12199 boolean extendSelection) { 12200 CharSequence text = getIterableTextForAccessibility(); 12201 if (text == null || text.length() == 0) { 12202 return false; 12203 } 12204 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 12205 if (iterator == null) { 12206 return false; 12207 } 12208 int current = getAccessibilitySelectionEnd(); 12209 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 12210 current = forward ? 0 : text.length(); 12211 } 12212 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 12213 if (range == null) { 12214 return false; 12215 } 12216 final int segmentStart = range[0]; 12217 final int segmentEnd = range[1]; 12218 int selectionStart; 12219 int selectionEnd; 12220 if (extendSelection && isAccessibilitySelectionExtendable()) { 12221 selectionStart = getAccessibilitySelectionStart(); 12222 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 12223 selectionStart = forward ? segmentStart : segmentEnd; 12224 } 12225 selectionEnd = forward ? segmentEnd : segmentStart; 12226 } else { 12227 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 12228 } 12229 setAccessibilitySelection(selectionStart, selectionEnd); 12230 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 12231 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 12232 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 12233 return true; 12234 } 12235 12236 /** 12237 * Gets the text reported for accessibility purposes. 12238 * 12239 * @return The accessibility text. 12240 * 12241 * @hide 12242 */ 12243 public CharSequence getIterableTextForAccessibility() { 12244 return getContentDescription(); 12245 } 12246 12247 /** 12248 * Gets whether accessibility selection can be extended. 12249 * 12250 * @return If selection is extensible. 12251 * 12252 * @hide 12253 */ 12254 public boolean isAccessibilitySelectionExtendable() { 12255 return false; 12256 } 12257 12258 /** 12259 * @hide 12260 */ 12261 public int getAccessibilitySelectionStart() { 12262 return mAccessibilityCursorPosition; 12263 } 12264 12265 /** 12266 * @hide 12267 */ 12268 public int getAccessibilitySelectionEnd() { 12269 return getAccessibilitySelectionStart(); 12270 } 12271 12272 /** 12273 * @hide 12274 */ 12275 public void setAccessibilitySelection(int start, int end) { 12276 if (start == end && end == mAccessibilityCursorPosition) { 12277 return; 12278 } 12279 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 12280 mAccessibilityCursorPosition = start; 12281 } else { 12282 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 12283 } 12284 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 12285 } 12286 12287 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 12288 int fromIndex, int toIndex) { 12289 if (mParent == null) { 12290 return; 12291 } 12292 AccessibilityEvent event = AccessibilityEvent.obtain( 12293 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 12294 onInitializeAccessibilityEvent(event); 12295 onPopulateAccessibilityEvent(event); 12296 event.setFromIndex(fromIndex); 12297 event.setToIndex(toIndex); 12298 event.setAction(action); 12299 event.setMovementGranularity(granularity); 12300 mParent.requestSendAccessibilityEvent(this, event); 12301 } 12302 12303 /** 12304 * @hide 12305 */ 12306 public TextSegmentIterator getIteratorForGranularity(int granularity) { 12307 switch (granularity) { 12308 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 12309 CharSequence text = getIterableTextForAccessibility(); 12310 if (text != null && text.length() > 0) { 12311 CharacterTextSegmentIterator iterator = 12312 CharacterTextSegmentIterator.getInstance( 12313 mContext.getResources().getConfiguration().locale); 12314 iterator.initialize(text.toString()); 12315 return iterator; 12316 } 12317 } break; 12318 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 12319 CharSequence text = getIterableTextForAccessibility(); 12320 if (text != null && text.length() > 0) { 12321 WordTextSegmentIterator iterator = 12322 WordTextSegmentIterator.getInstance( 12323 mContext.getResources().getConfiguration().locale); 12324 iterator.initialize(text.toString()); 12325 return iterator; 12326 } 12327 } break; 12328 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 12329 CharSequence text = getIterableTextForAccessibility(); 12330 if (text != null && text.length() > 0) { 12331 ParagraphTextSegmentIterator iterator = 12332 ParagraphTextSegmentIterator.getInstance(); 12333 iterator.initialize(text.toString()); 12334 return iterator; 12335 } 12336 } break; 12337 } 12338 return null; 12339 } 12340 12341 /** 12342 * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()} 12343 * and {@link #onFinishTemporaryDetach()}. 12344 * 12345 * <p>This method always returns {@code true} when called directly or indirectly from 12346 * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from 12347 * {@link #onFinishTemporaryDetach()}, however, depends on the OS version. 12348 * <ul> 12349 * <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li> 12350 * <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li> 12351 * </ul> 12352 * </p> 12353 * 12354 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 12355 * and {@link #onFinishTemporaryDetach()}. 12356 */ 12357 public final boolean isTemporarilyDetached() { 12358 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 12359 } 12360 12361 /** 12362 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 12363 * a container View. 12364 */ 12365 @CallSuper 12366 public void dispatchStartTemporaryDetach() { 12367 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 12368 notifyEnterOrExitForAutoFillIfNeeded(false); 12369 onStartTemporaryDetach(); 12370 } 12371 12372 /** 12373 * This is called when a container is going to temporarily detach a child, with 12374 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 12375 * It will either be followed by {@link #onFinishTemporaryDetach()} or 12376 * {@link #onDetachedFromWindow()} when the container is done. 12377 */ 12378 public void onStartTemporaryDetach() { 12379 removeUnsetPressCallback(); 12380 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 12381 } 12382 12383 /** 12384 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 12385 * a container View. 12386 */ 12387 @CallSuper 12388 public void dispatchFinishTemporaryDetach() { 12389 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 12390 onFinishTemporaryDetach(); 12391 if (hasWindowFocus() && hasFocus()) { 12392 InputMethodManager.getInstance().focusIn(this); 12393 } 12394 notifyEnterOrExitForAutoFillIfNeeded(true); 12395 } 12396 12397 /** 12398 * Called after {@link #onStartTemporaryDetach} when the container is done 12399 * changing the view. 12400 */ 12401 public void onFinishTemporaryDetach() { 12402 } 12403 12404 /** 12405 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 12406 * for this view's window. Returns null if the view is not currently attached 12407 * to the window. Normally you will not need to use this directly, but 12408 * just use the standard high-level event callbacks like 12409 * {@link #onKeyDown(int, KeyEvent)}. 12410 */ 12411 public KeyEvent.DispatcherState getKeyDispatcherState() { 12412 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 12413 } 12414 12415 /** 12416 * Dispatch a key event before it is processed by any input method 12417 * associated with the view hierarchy. This can be used to intercept 12418 * key events in special situations before the IME consumes them; a 12419 * typical example would be handling the BACK key to update the application's 12420 * UI instead of allowing the IME to see it and close itself. 12421 * 12422 * @param event The key event to be dispatched. 12423 * @return True if the event was handled, false otherwise. 12424 */ 12425 public boolean dispatchKeyEventPreIme(KeyEvent event) { 12426 return onKeyPreIme(event.getKeyCode(), event); 12427 } 12428 12429 /** 12430 * Dispatch a key event to the next view on the focus path. This path runs 12431 * from the top of the view tree down to the currently focused view. If this 12432 * view has focus, it will dispatch to itself. Otherwise it will dispatch 12433 * the next node down the focus path. This method also fires any key 12434 * listeners. 12435 * 12436 * @param event The key event to be dispatched. 12437 * @return True if the event was handled, false otherwise. 12438 */ 12439 public boolean dispatchKeyEvent(KeyEvent event) { 12440 if (mInputEventConsistencyVerifier != null) { 12441 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 12442 } 12443 12444 // Give any attached key listener a first crack at the event. 12445 //noinspection SimplifiableIfStatement 12446 ListenerInfo li = mListenerInfo; 12447 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 12448 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 12449 return true; 12450 } 12451 12452 if (event.dispatch(this, mAttachInfo != null 12453 ? mAttachInfo.mKeyDispatchState : null, this)) { 12454 return true; 12455 } 12456 12457 if (mInputEventConsistencyVerifier != null) { 12458 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 12459 } 12460 return false; 12461 } 12462 12463 /** 12464 * Dispatches a key shortcut event. 12465 * 12466 * @param event The key event to be dispatched. 12467 * @return True if the event was handled by the view, false otherwise. 12468 */ 12469 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 12470 return onKeyShortcut(event.getKeyCode(), event); 12471 } 12472 12473 /** 12474 * Pass the touch screen motion event down to the target view, or this 12475 * view if it is the target. 12476 * 12477 * @param event The motion event to be dispatched. 12478 * @return True if the event was handled by the view, false otherwise. 12479 */ 12480 public boolean dispatchTouchEvent(MotionEvent event) { 12481 // If the event should be handled by accessibility focus first. 12482 if (event.isTargetAccessibilityFocus()) { 12483 // We don't have focus or no virtual descendant has it, do not handle the event. 12484 if (!isAccessibilityFocusedViewOrHost()) { 12485 return false; 12486 } 12487 // We have focus and got the event, then use normal event dispatch. 12488 event.setTargetAccessibilityFocus(false); 12489 } 12490 12491 boolean result = false; 12492 12493 if (mInputEventConsistencyVerifier != null) { 12494 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 12495 } 12496 12497 final int actionMasked = event.getActionMasked(); 12498 if (actionMasked == MotionEvent.ACTION_DOWN) { 12499 // Defensive cleanup for new gesture 12500 stopNestedScroll(); 12501 } 12502 12503 if (onFilterTouchEventForSecurity(event)) { 12504 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 12505 result = true; 12506 } 12507 //noinspection SimplifiableIfStatement 12508 ListenerInfo li = mListenerInfo; 12509 if (li != null && li.mOnTouchListener != null 12510 && (mViewFlags & ENABLED_MASK) == ENABLED 12511 && li.mOnTouchListener.onTouch(this, event)) { 12512 result = true; 12513 } 12514 12515 if (!result && onTouchEvent(event)) { 12516 result = true; 12517 } 12518 } 12519 12520 if (!result && mInputEventConsistencyVerifier != null) { 12521 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 12522 } 12523 12524 // Clean up after nested scrolls if this is the end of a gesture; 12525 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 12526 // of the gesture. 12527 if (actionMasked == MotionEvent.ACTION_UP || 12528 actionMasked == MotionEvent.ACTION_CANCEL || 12529 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 12530 stopNestedScroll(); 12531 } 12532 12533 return result; 12534 } 12535 12536 boolean isAccessibilityFocusedViewOrHost() { 12537 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 12538 .getAccessibilityFocusedHost() == this); 12539 } 12540 12541 /** 12542 * Filter the touch event to apply security policies. 12543 * 12544 * @param event The motion event to be filtered. 12545 * @return True if the event should be dispatched, false if the event should be dropped. 12546 * 12547 * @see #getFilterTouchesWhenObscured 12548 */ 12549 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 12550 //noinspection RedundantIfStatement 12551 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 12552 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 12553 // Window is obscured, drop this touch. 12554 return false; 12555 } 12556 return true; 12557 } 12558 12559 /** 12560 * Pass a trackball motion event down to the focused view. 12561 * 12562 * @param event The motion event to be dispatched. 12563 * @return True if the event was handled by the view, false otherwise. 12564 */ 12565 public boolean dispatchTrackballEvent(MotionEvent event) { 12566 if (mInputEventConsistencyVerifier != null) { 12567 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 12568 } 12569 12570 return onTrackballEvent(event); 12571 } 12572 12573 /** 12574 * Pass a captured pointer event down to the focused view. 12575 * 12576 * @param event The motion event to be dispatched. 12577 * @return True if the event was handled by the view, false otherwise. 12578 */ 12579 public boolean dispatchCapturedPointerEvent(MotionEvent event) { 12580 if (!hasPointerCapture()) { 12581 return false; 12582 } 12583 //noinspection SimplifiableIfStatement 12584 ListenerInfo li = mListenerInfo; 12585 if (li != null && li.mOnCapturedPointerListener != null 12586 && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) { 12587 return true; 12588 } 12589 return onCapturedPointerEvent(event); 12590 } 12591 12592 /** 12593 * Dispatch a generic motion event. 12594 * <p> 12595 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 12596 * are delivered to the view under the pointer. All other generic motion events are 12597 * delivered to the focused view. Hover events are handled specially and are delivered 12598 * to {@link #onHoverEvent(MotionEvent)}. 12599 * </p> 12600 * 12601 * @param event The motion event to be dispatched. 12602 * @return True if the event was handled by the view, false otherwise. 12603 */ 12604 public boolean dispatchGenericMotionEvent(MotionEvent event) { 12605 if (mInputEventConsistencyVerifier != null) { 12606 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 12607 } 12608 12609 final int source = event.getSource(); 12610 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 12611 final int action = event.getAction(); 12612 if (action == MotionEvent.ACTION_HOVER_ENTER 12613 || action == MotionEvent.ACTION_HOVER_MOVE 12614 || action == MotionEvent.ACTION_HOVER_EXIT) { 12615 if (dispatchHoverEvent(event)) { 12616 return true; 12617 } 12618 } else if (dispatchGenericPointerEvent(event)) { 12619 return true; 12620 } 12621 } else if (dispatchGenericFocusedEvent(event)) { 12622 return true; 12623 } 12624 12625 if (dispatchGenericMotionEventInternal(event)) { 12626 return true; 12627 } 12628 12629 if (mInputEventConsistencyVerifier != null) { 12630 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 12631 } 12632 return false; 12633 } 12634 12635 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 12636 //noinspection SimplifiableIfStatement 12637 ListenerInfo li = mListenerInfo; 12638 if (li != null && li.mOnGenericMotionListener != null 12639 && (mViewFlags & ENABLED_MASK) == ENABLED 12640 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 12641 return true; 12642 } 12643 12644 if (onGenericMotionEvent(event)) { 12645 return true; 12646 } 12647 12648 final int actionButton = event.getActionButton(); 12649 switch (event.getActionMasked()) { 12650 case MotionEvent.ACTION_BUTTON_PRESS: 12651 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 12652 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 12653 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 12654 if (performContextClick(event.getX(), event.getY())) { 12655 mInContextButtonPress = true; 12656 setPressed(true, event.getX(), event.getY()); 12657 removeTapCallback(); 12658 removeLongPressCallback(); 12659 return true; 12660 } 12661 } 12662 break; 12663 12664 case MotionEvent.ACTION_BUTTON_RELEASE: 12665 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 12666 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 12667 mInContextButtonPress = false; 12668 mIgnoreNextUpEvent = true; 12669 } 12670 break; 12671 } 12672 12673 if (mInputEventConsistencyVerifier != null) { 12674 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 12675 } 12676 return false; 12677 } 12678 12679 /** 12680 * Dispatch a hover event. 12681 * <p> 12682 * Do not call this method directly. 12683 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 12684 * </p> 12685 * 12686 * @param event The motion event to be dispatched. 12687 * @return True if the event was handled by the view, false otherwise. 12688 */ 12689 protected boolean dispatchHoverEvent(MotionEvent event) { 12690 ListenerInfo li = mListenerInfo; 12691 //noinspection SimplifiableIfStatement 12692 if (li != null && li.mOnHoverListener != null 12693 && (mViewFlags & ENABLED_MASK) == ENABLED 12694 && li.mOnHoverListener.onHover(this, event)) { 12695 return true; 12696 } 12697 12698 return onHoverEvent(event); 12699 } 12700 12701 /** 12702 * Returns true if the view has a child to which it has recently sent 12703 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 12704 * it does not have a hovered child, then it must be the innermost hovered view. 12705 * @hide 12706 */ 12707 protected boolean hasHoveredChild() { 12708 return false; 12709 } 12710 12711 /** 12712 * Dispatch a generic motion event to the view under the first pointer. 12713 * <p> 12714 * Do not call this method directly. 12715 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 12716 * </p> 12717 * 12718 * @param event The motion event to be dispatched. 12719 * @return True if the event was handled by the view, false otherwise. 12720 */ 12721 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 12722 return false; 12723 } 12724 12725 /** 12726 * Dispatch a generic motion event to the currently focused view. 12727 * <p> 12728 * Do not call this method directly. 12729 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 12730 * </p> 12731 * 12732 * @param event The motion event to be dispatched. 12733 * @return True if the event was handled by the view, false otherwise. 12734 */ 12735 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 12736 return false; 12737 } 12738 12739 /** 12740 * Dispatch a pointer event. 12741 * <p> 12742 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 12743 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 12744 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 12745 * and should not be expected to handle other pointing device features. 12746 * </p> 12747 * 12748 * @param event The motion event to be dispatched. 12749 * @return True if the event was handled by the view, false otherwise. 12750 * @hide 12751 */ 12752 public final boolean dispatchPointerEvent(MotionEvent event) { 12753 if (event.isTouchEvent()) { 12754 return dispatchTouchEvent(event); 12755 } else { 12756 return dispatchGenericMotionEvent(event); 12757 } 12758 } 12759 12760 /** 12761 * Called when the window containing this view gains or loses window focus. 12762 * ViewGroups should override to route to their children. 12763 * 12764 * @param hasFocus True if the window containing this view now has focus, 12765 * false otherwise. 12766 */ 12767 public void dispatchWindowFocusChanged(boolean hasFocus) { 12768 onWindowFocusChanged(hasFocus); 12769 } 12770 12771 /** 12772 * Called when the window containing this view gains or loses focus. Note 12773 * that this is separate from view focus: to receive key events, both 12774 * your view and its window must have focus. If a window is displayed 12775 * on top of yours that takes input focus, then your own window will lose 12776 * focus but the view focus will remain unchanged. 12777 * 12778 * @param hasWindowFocus True if the window containing this view now has 12779 * focus, false otherwise. 12780 */ 12781 public void onWindowFocusChanged(boolean hasWindowFocus) { 12782 InputMethodManager imm = InputMethodManager.peekInstance(); 12783 if (!hasWindowFocus) { 12784 if (isPressed()) { 12785 setPressed(false); 12786 } 12787 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 12788 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 12789 imm.focusOut(this); 12790 } 12791 removeLongPressCallback(); 12792 removeTapCallback(); 12793 onFocusLost(); 12794 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 12795 imm.focusIn(this); 12796 } 12797 12798 refreshDrawableState(); 12799 } 12800 12801 /** 12802 * Returns true if this view is in a window that currently has window focus. 12803 * Note that this is not the same as the view itself having focus. 12804 * 12805 * @return True if this view is in a window that currently has window focus. 12806 */ 12807 public boolean hasWindowFocus() { 12808 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 12809 } 12810 12811 /** 12812 * Dispatch a view visibility change down the view hierarchy. 12813 * ViewGroups should override to route to their children. 12814 * @param changedView The view whose visibility changed. Could be 'this' or 12815 * an ancestor view. 12816 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 12817 * {@link #INVISIBLE} or {@link #GONE}. 12818 */ 12819 protected void dispatchVisibilityChanged(@NonNull View changedView, 12820 @Visibility int visibility) { 12821 onVisibilityChanged(changedView, visibility); 12822 } 12823 12824 /** 12825 * Called when the visibility of the view or an ancestor of the view has 12826 * changed. 12827 * 12828 * @param changedView The view whose visibility changed. May be 12829 * {@code this} or an ancestor view. 12830 * @param visibility The new visibility, one of {@link #VISIBLE}, 12831 * {@link #INVISIBLE} or {@link #GONE}. 12832 */ 12833 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 12834 } 12835 12836 /** 12837 * Dispatch a hint about whether this view is displayed. For instance, when 12838 * a View moves out of the screen, it might receives a display hint indicating 12839 * the view is not displayed. Applications should not <em>rely</em> on this hint 12840 * as there is no guarantee that they will receive one. 12841 * 12842 * @param hint A hint about whether or not this view is displayed: 12843 * {@link #VISIBLE} or {@link #INVISIBLE}. 12844 */ 12845 public void dispatchDisplayHint(@Visibility int hint) { 12846 onDisplayHint(hint); 12847 } 12848 12849 /** 12850 * Gives this view a hint about whether is displayed or not. For instance, when 12851 * a View moves out of the screen, it might receives a display hint indicating 12852 * the view is not displayed. Applications should not <em>rely</em> on this hint 12853 * as there is no guarantee that they will receive one. 12854 * 12855 * @param hint A hint about whether or not this view is displayed: 12856 * {@link #VISIBLE} or {@link #INVISIBLE}. 12857 */ 12858 protected void onDisplayHint(@Visibility int hint) { 12859 } 12860 12861 /** 12862 * Dispatch a window visibility change down the view hierarchy. 12863 * ViewGroups should override to route to their children. 12864 * 12865 * @param visibility The new visibility of the window. 12866 * 12867 * @see #onWindowVisibilityChanged(int) 12868 */ 12869 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 12870 onWindowVisibilityChanged(visibility); 12871 } 12872 12873 /** 12874 * Called when the window containing has change its visibility 12875 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 12876 * that this tells you whether or not your window is being made visible 12877 * to the window manager; this does <em>not</em> tell you whether or not 12878 * your window is obscured by other windows on the screen, even if it 12879 * is itself visible. 12880 * 12881 * @param visibility The new visibility of the window. 12882 */ 12883 protected void onWindowVisibilityChanged(@Visibility int visibility) { 12884 if (visibility == VISIBLE) { 12885 initialAwakenScrollBars(); 12886 } 12887 } 12888 12889 /** 12890 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 12891 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 12892 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 12893 * 12894 * @param isVisible true if this view's visibility to the user is uninterrupted by its 12895 * ancestors or by window visibility 12896 * @return true if this view is visible to the user, not counting clipping or overlapping 12897 */ 12898 boolean dispatchVisibilityAggregated(boolean isVisible) { 12899 final boolean thisVisible = getVisibility() == VISIBLE; 12900 // If we're not visible but something is telling us we are, ignore it. 12901 if (thisVisible || !isVisible) { 12902 onVisibilityAggregated(isVisible); 12903 } 12904 return thisVisible && isVisible; 12905 } 12906 12907 /** 12908 * Called when the user-visibility of this View is potentially affected by a change 12909 * to this view itself, an ancestor view or the window this view is attached to. 12910 * 12911 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 12912 * and this view's window is also visible 12913 */ 12914 @CallSuper 12915 public void onVisibilityAggregated(boolean isVisible) { 12916 // Update our internal visibility tracking so we can detect changes 12917 boolean oldVisible = (mPrivateFlags3 & PFLAG3_AGGREGATED_VISIBLE) != 0; 12918 mPrivateFlags3 = isVisible ? (mPrivateFlags3 | PFLAG3_AGGREGATED_VISIBLE) 12919 : (mPrivateFlags3 & ~PFLAG3_AGGREGATED_VISIBLE); 12920 if (isVisible && mAttachInfo != null) { 12921 initialAwakenScrollBars(); 12922 } 12923 12924 final Drawable dr = mBackground; 12925 if (dr != null && isVisible != dr.isVisible()) { 12926 dr.setVisible(isVisible, false); 12927 } 12928 final Drawable hl = mDefaultFocusHighlight; 12929 if (hl != null && isVisible != hl.isVisible()) { 12930 hl.setVisible(isVisible, false); 12931 } 12932 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 12933 if (fg != null && isVisible != fg.isVisible()) { 12934 fg.setVisible(isVisible, false); 12935 } 12936 12937 if (isAutofillable()) { 12938 AutofillManager afm = getAutofillManager(); 12939 12940 if (afm != null && getAutofillViewId() > LAST_APP_AUTOFILL_ID) { 12941 if (mVisibilityChangeForAutofillHandler != null) { 12942 mVisibilityChangeForAutofillHandler.removeMessages(0); 12943 } 12944 12945 // If the view is in the background but still part of the hierarchy this is called 12946 // with isVisible=false. Hence visibility==false requires further checks 12947 if (isVisible) { 12948 afm.notifyViewVisibilityChanged(this, true); 12949 } else { 12950 if (mVisibilityChangeForAutofillHandler == null) { 12951 mVisibilityChangeForAutofillHandler = 12952 new VisibilityChangeForAutofillHandler(afm, this); 12953 } 12954 // Let current operation (e.g. removal of the view from the hierarchy) 12955 // finish before checking state 12956 mVisibilityChangeForAutofillHandler.obtainMessage(0, this).sendToTarget(); 12957 } 12958 } 12959 } 12960 if (!TextUtils.isEmpty(getAccessibilityPaneTitle())) { 12961 if (isVisible != oldVisible) { 12962 notifyViewAccessibilityStateChangedIfNeeded(isVisible 12963 ? AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_APPEARED 12964 : AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED); 12965 } 12966 } 12967 } 12968 12969 /** 12970 * Returns the current visibility of the window this view is attached to 12971 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 12972 * 12973 * @return Returns the current visibility of the view's window. 12974 */ 12975 @Visibility 12976 public int getWindowVisibility() { 12977 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 12978 } 12979 12980 /** 12981 * Retrieve the overall visible display size in which the window this view is 12982 * attached to has been positioned in. This takes into account screen 12983 * decorations above the window, for both cases where the window itself 12984 * is being position inside of them or the window is being placed under 12985 * then and covered insets are used for the window to position its content 12986 * inside. In effect, this tells you the available area where content can 12987 * be placed and remain visible to users. 12988 * 12989 * <p>This function requires an IPC back to the window manager to retrieve 12990 * the requested information, so should not be used in performance critical 12991 * code like drawing. 12992 * 12993 * @param outRect Filled in with the visible display frame. If the view 12994 * is not attached to a window, this is simply the raw display size. 12995 */ 12996 public void getWindowVisibleDisplayFrame(Rect outRect) { 12997 if (mAttachInfo != null) { 12998 try { 12999 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 13000 } catch (RemoteException e) { 13001 return; 13002 } 13003 // XXX This is really broken, and probably all needs to be done 13004 // in the window manager, and we need to know more about whether 13005 // we want the area behind or in front of the IME. 13006 final Rect insets = mAttachInfo.mVisibleInsets; 13007 outRect.left += insets.left; 13008 outRect.top += insets.top; 13009 outRect.right -= insets.right; 13010 outRect.bottom -= insets.bottom; 13011 return; 13012 } 13013 // The view is not attached to a display so we don't have a context. 13014 // Make a best guess about the display size. 13015 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 13016 d.getRectSize(outRect); 13017 } 13018 13019 /** 13020 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 13021 * is currently in without any insets. 13022 * 13023 * @hide 13024 */ 13025 public void getWindowDisplayFrame(Rect outRect) { 13026 if (mAttachInfo != null) { 13027 try { 13028 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 13029 } catch (RemoteException e) { 13030 return; 13031 } 13032 return; 13033 } 13034 // The view is not attached to a display so we don't have a context. 13035 // Make a best guess about the display size. 13036 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 13037 d.getRectSize(outRect); 13038 } 13039 13040 /** 13041 * Dispatch a notification about a resource configuration change down 13042 * the view hierarchy. 13043 * ViewGroups should override to route to their children. 13044 * 13045 * @param newConfig The new resource configuration. 13046 * 13047 * @see #onConfigurationChanged(android.content.res.Configuration) 13048 */ 13049 public void dispatchConfigurationChanged(Configuration newConfig) { 13050 onConfigurationChanged(newConfig); 13051 } 13052 13053 /** 13054 * Called when the current configuration of the resources being used 13055 * by the application have changed. You can use this to decide when 13056 * to reload resources that can changed based on orientation and other 13057 * configuration characteristics. You only need to use this if you are 13058 * not relying on the normal {@link android.app.Activity} mechanism of 13059 * recreating the activity instance upon a configuration change. 13060 * 13061 * @param newConfig The new resource configuration. 13062 */ 13063 protected void onConfigurationChanged(Configuration newConfig) { 13064 } 13065 13066 /** 13067 * Private function to aggregate all per-view attributes in to the view 13068 * root. 13069 */ 13070 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 13071 performCollectViewAttributes(attachInfo, visibility); 13072 } 13073 13074 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 13075 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 13076 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 13077 attachInfo.mKeepScreenOn = true; 13078 } 13079 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 13080 ListenerInfo li = mListenerInfo; 13081 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 13082 attachInfo.mHasSystemUiListeners = true; 13083 } 13084 } 13085 } 13086 13087 void needGlobalAttributesUpdate(boolean force) { 13088 final AttachInfo ai = mAttachInfo; 13089 if (ai != null && !ai.mRecomputeGlobalAttributes) { 13090 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 13091 || ai.mHasSystemUiListeners) { 13092 ai.mRecomputeGlobalAttributes = true; 13093 } 13094 } 13095 } 13096 13097 /** 13098 * Returns whether the device is currently in touch mode. Touch mode is entered 13099 * once the user begins interacting with the device by touch, and affects various 13100 * things like whether focus is always visible to the user. 13101 * 13102 * @return Whether the device is in touch mode. 13103 */ 13104 @ViewDebug.ExportedProperty 13105 public boolean isInTouchMode() { 13106 if (mAttachInfo != null) { 13107 return mAttachInfo.mInTouchMode; 13108 } else { 13109 return ViewRootImpl.isInTouchMode(); 13110 } 13111 } 13112 13113 /** 13114 * Returns the context the view is running in, through which it can 13115 * access the current theme, resources, etc. 13116 * 13117 * @return The view's Context. 13118 */ 13119 @ViewDebug.CapturedViewProperty 13120 public final Context getContext() { 13121 return mContext; 13122 } 13123 13124 /** 13125 * Handle a key event before it is processed by any input method 13126 * associated with the view hierarchy. This can be used to intercept 13127 * key events in special situations before the IME consumes them; a 13128 * typical example would be handling the BACK key to update the application's 13129 * UI instead of allowing the IME to see it and close itself. 13130 * 13131 * @param keyCode The value in event.getKeyCode(). 13132 * @param event Description of the key event. 13133 * @return If you handled the event, return true. If you want to allow the 13134 * event to be handled by the next receiver, return false. 13135 */ 13136 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 13137 return false; 13138 } 13139 13140 /** 13141 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 13142 * KeyEvent.Callback.onKeyDown()}: perform press of the view 13143 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 13144 * is released, if the view is enabled and clickable. 13145 * <p> 13146 * Key presses in software keyboards will generally NOT trigger this 13147 * listener, although some may elect to do so in some situations. Do not 13148 * rely on this to catch software key presses. 13149 * 13150 * @param keyCode a key code that represents the button pressed, from 13151 * {@link android.view.KeyEvent} 13152 * @param event the KeyEvent object that defines the button action 13153 */ 13154 public boolean onKeyDown(int keyCode, KeyEvent event) { 13155 if (KeyEvent.isConfirmKey(keyCode)) { 13156 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 13157 return true; 13158 } 13159 13160 if (event.getRepeatCount() == 0) { 13161 // Long clickable items don't necessarily have to be clickable. 13162 final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE 13163 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 13164 if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) { 13165 // For the purposes of menu anchoring and drawable hotspots, 13166 // key events are considered to be at the center of the view. 13167 final float x = getWidth() / 2f; 13168 final float y = getHeight() / 2f; 13169 if (clickable) { 13170 setPressed(true, x, y); 13171 } 13172 checkForLongClick(0, x, y); 13173 return true; 13174 } 13175 } 13176 } 13177 13178 return false; 13179 } 13180 13181 /** 13182 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 13183 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 13184 * the event). 13185 * <p>Key presses in software keyboards will generally NOT trigger this listener, 13186 * although some may elect to do so in some situations. Do not rely on this to 13187 * catch software key presses. 13188 */ 13189 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 13190 return false; 13191 } 13192 13193 /** 13194 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 13195 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 13196 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 13197 * or {@link KeyEvent#KEYCODE_SPACE} is released. 13198 * <p>Key presses in software keyboards will generally NOT trigger this listener, 13199 * although some may elect to do so in some situations. Do not rely on this to 13200 * catch software key presses. 13201 * 13202 * @param keyCode A key code that represents the button pressed, from 13203 * {@link android.view.KeyEvent}. 13204 * @param event The KeyEvent object that defines the button action. 13205 */ 13206 public boolean onKeyUp(int keyCode, KeyEvent event) { 13207 if (KeyEvent.isConfirmKey(keyCode)) { 13208 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 13209 return true; 13210 } 13211 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 13212 setPressed(false); 13213 13214 if (!mHasPerformedLongPress) { 13215 // This is a tap, so remove the longpress check 13216 removeLongPressCallback(); 13217 if (!event.isCanceled()) { 13218 return performClickInternal(); 13219 } 13220 } 13221 } 13222 } 13223 return false; 13224 } 13225 13226 /** 13227 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 13228 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 13229 * the event). 13230 * <p>Key presses in software keyboards will generally NOT trigger this listener, 13231 * although some may elect to do so in some situations. Do not rely on this to 13232 * catch software key presses. 13233 * 13234 * @param keyCode A key code that represents the button pressed, from 13235 * {@link android.view.KeyEvent}. 13236 * @param repeatCount The number of times the action was made. 13237 * @param event The KeyEvent object that defines the button action. 13238 */ 13239 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 13240 return false; 13241 } 13242 13243 /** 13244 * Called on the focused view when a key shortcut event is not handled. 13245 * Override this method to implement local key shortcuts for the View. 13246 * Key shortcuts can also be implemented by setting the 13247 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 13248 * 13249 * @param keyCode The value in event.getKeyCode(). 13250 * @param event Description of the key event. 13251 * @return If you handled the event, return true. If you want to allow the 13252 * event to be handled by the next receiver, return false. 13253 */ 13254 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 13255 return false; 13256 } 13257 13258 /** 13259 * Check whether the called view is a text editor, in which case it 13260 * would make sense to automatically display a soft input window for 13261 * it. Subclasses should override this if they implement 13262 * {@link #onCreateInputConnection(EditorInfo)} to return true if 13263 * a call on that method would return a non-null InputConnection, and 13264 * they are really a first-class editor that the user would normally 13265 * start typing on when the go into a window containing your view. 13266 * 13267 * <p>The default implementation always returns false. This does 13268 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 13269 * will not be called or the user can not otherwise perform edits on your 13270 * view; it is just a hint to the system that this is not the primary 13271 * purpose of this view. 13272 * 13273 * @return Returns true if this view is a text editor, else false. 13274 */ 13275 public boolean onCheckIsTextEditor() { 13276 return false; 13277 } 13278 13279 /** 13280 * Create a new InputConnection for an InputMethod to interact 13281 * with the view. The default implementation returns null, since it doesn't 13282 * support input methods. You can override this to implement such support. 13283 * This is only needed for views that take focus and text input. 13284 * 13285 * <p>When implementing this, you probably also want to implement 13286 * {@link #onCheckIsTextEditor()} to indicate you will return a 13287 * non-null InputConnection.</p> 13288 * 13289 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 13290 * object correctly and in its entirety, so that the connected IME can rely 13291 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 13292 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 13293 * must be filled in with the correct cursor position for IMEs to work correctly 13294 * with your application.</p> 13295 * 13296 * @param outAttrs Fill in with attribute information about the connection. 13297 */ 13298 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 13299 return null; 13300 } 13301 13302 /** 13303 * Called by the {@link android.view.inputmethod.InputMethodManager} 13304 * when a view who is not the current 13305 * input connection target is trying to make a call on the manager. The 13306 * default implementation returns false; you can override this to return 13307 * true for certain views if you are performing InputConnection proxying 13308 * to them. 13309 * @param view The View that is making the InputMethodManager call. 13310 * @return Return true to allow the call, false to reject. 13311 */ 13312 public boolean checkInputConnectionProxy(View view) { 13313 return false; 13314 } 13315 13316 /** 13317 * Show the context menu for this view. It is not safe to hold on to the 13318 * menu after returning from this method. 13319 * 13320 * You should normally not overload this method. Overload 13321 * {@link #onCreateContextMenu(ContextMenu)} or define an 13322 * {@link OnCreateContextMenuListener} to add items to the context menu. 13323 * 13324 * @param menu The context menu to populate 13325 */ 13326 public void createContextMenu(ContextMenu menu) { 13327 ContextMenuInfo menuInfo = getContextMenuInfo(); 13328 13329 // Sets the current menu info so all items added to menu will have 13330 // my extra info set. 13331 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 13332 13333 onCreateContextMenu(menu); 13334 ListenerInfo li = mListenerInfo; 13335 if (li != null && li.mOnCreateContextMenuListener != null) { 13336 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 13337 } 13338 13339 // Clear the extra information so subsequent items that aren't mine don't 13340 // have my extra info. 13341 ((MenuBuilder)menu).setCurrentMenuInfo(null); 13342 13343 if (mParent != null) { 13344 mParent.createContextMenu(menu); 13345 } 13346 } 13347 13348 /** 13349 * Views should implement this if they have extra information to associate 13350 * with the context menu. The return result is supplied as a parameter to 13351 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 13352 * callback. 13353 * 13354 * @return Extra information about the item for which the context menu 13355 * should be shown. This information will vary across different 13356 * subclasses of View. 13357 */ 13358 protected ContextMenuInfo getContextMenuInfo() { 13359 return null; 13360 } 13361 13362 /** 13363 * Views should implement this if the view itself is going to add items to 13364 * the context menu. 13365 * 13366 * @param menu the context menu to populate 13367 */ 13368 protected void onCreateContextMenu(ContextMenu menu) { 13369 } 13370 13371 /** 13372 * Implement this method to handle trackball motion events. The 13373 * <em>relative</em> movement of the trackball since the last event 13374 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 13375 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 13376 * that a movement of 1 corresponds to the user pressing one DPAD key (so 13377 * they will often be fractional values, representing the more fine-grained 13378 * movement information available from a trackball). 13379 * 13380 * @param event The motion event. 13381 * @return True if the event was handled, false otherwise. 13382 */ 13383 public boolean onTrackballEvent(MotionEvent event) { 13384 return false; 13385 } 13386 13387 /** 13388 * Implement this method to handle generic motion events. 13389 * <p> 13390 * Generic motion events describe joystick movements, mouse hovers, track pad 13391 * touches, scroll wheel movements and other input events. The 13392 * {@link MotionEvent#getSource() source} of the motion event specifies 13393 * the class of input that was received. Implementations of this method 13394 * must examine the bits in the source before processing the event. 13395 * The following code example shows how this is done. 13396 * </p><p> 13397 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 13398 * are delivered to the view under the pointer. All other generic motion events are 13399 * delivered to the focused view. 13400 * </p> 13401 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 13402 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 13403 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 13404 * // process the joystick movement... 13405 * return true; 13406 * } 13407 * } 13408 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 13409 * switch (event.getAction()) { 13410 * case MotionEvent.ACTION_HOVER_MOVE: 13411 * // process the mouse hover movement... 13412 * return true; 13413 * case MotionEvent.ACTION_SCROLL: 13414 * // process the scroll wheel movement... 13415 * return true; 13416 * } 13417 * } 13418 * return super.onGenericMotionEvent(event); 13419 * }</pre> 13420 * 13421 * @param event The generic motion event being processed. 13422 * @return True if the event was handled, false otherwise. 13423 */ 13424 public boolean onGenericMotionEvent(MotionEvent event) { 13425 return false; 13426 } 13427 13428 /** 13429 * Implement this method to handle hover events. 13430 * <p> 13431 * This method is called whenever a pointer is hovering into, over, or out of the 13432 * bounds of a view and the view is not currently being touched. 13433 * Hover events are represented as pointer events with action 13434 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 13435 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 13436 * </p> 13437 * <ul> 13438 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 13439 * when the pointer enters the bounds of the view.</li> 13440 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 13441 * when the pointer has already entered the bounds of the view and has moved.</li> 13442 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 13443 * when the pointer has exited the bounds of the view or when the pointer is 13444 * about to go down due to a button click, tap, or similar user action that 13445 * causes the view to be touched.</li> 13446 * </ul> 13447 * <p> 13448 * The view should implement this method to return true to indicate that it is 13449 * handling the hover event, such as by changing its drawable state. 13450 * </p><p> 13451 * The default implementation calls {@link #setHovered} to update the hovered state 13452 * of the view when a hover enter or hover exit event is received, if the view 13453 * is enabled and is clickable. The default implementation also sends hover 13454 * accessibility events. 13455 * </p> 13456 * 13457 * @param event The motion event that describes the hover. 13458 * @return True if the view handled the hover event. 13459 * 13460 * @see #isHovered 13461 * @see #setHovered 13462 * @see #onHoverChanged 13463 */ 13464 public boolean onHoverEvent(MotionEvent event) { 13465 // The root view may receive hover (or touch) events that are outside the bounds of 13466 // the window. This code ensures that we only send accessibility events for 13467 // hovers that are actually within the bounds of the root view. 13468 final int action = event.getActionMasked(); 13469 if (!mSendingHoverAccessibilityEvents) { 13470 if ((action == MotionEvent.ACTION_HOVER_ENTER 13471 || action == MotionEvent.ACTION_HOVER_MOVE) 13472 && !hasHoveredChild() 13473 && pointInView(event.getX(), event.getY())) { 13474 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 13475 mSendingHoverAccessibilityEvents = true; 13476 } 13477 } else { 13478 if (action == MotionEvent.ACTION_HOVER_EXIT 13479 || (action == MotionEvent.ACTION_MOVE 13480 && !pointInView(event.getX(), event.getY()))) { 13481 mSendingHoverAccessibilityEvents = false; 13482 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 13483 } 13484 } 13485 13486 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 13487 && event.isFromSource(InputDevice.SOURCE_MOUSE) 13488 && isOnScrollbar(event.getX(), event.getY())) { 13489 awakenScrollBars(); 13490 } 13491 13492 // If we consider ourself hoverable, or if we we're already hovered, 13493 // handle changing state in response to ENTER and EXIT events. 13494 if (isHoverable() || isHovered()) { 13495 switch (action) { 13496 case MotionEvent.ACTION_HOVER_ENTER: 13497 setHovered(true); 13498 break; 13499 case MotionEvent.ACTION_HOVER_EXIT: 13500 setHovered(false); 13501 break; 13502 } 13503 13504 // Dispatch the event to onGenericMotionEvent before returning true. 13505 // This is to provide compatibility with existing applications that 13506 // handled HOVER_MOVE events in onGenericMotionEvent and that would 13507 // break because of the new default handling for hoverable views 13508 // in onHoverEvent. 13509 // Note that onGenericMotionEvent will be called by default when 13510 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 13511 dispatchGenericMotionEventInternal(event); 13512 // The event was already handled by calling setHovered(), so always 13513 // return true. 13514 return true; 13515 } 13516 13517 return false; 13518 } 13519 13520 /** 13521 * Returns true if the view should handle {@link #onHoverEvent} 13522 * by calling {@link #setHovered} to change its hovered state. 13523 * 13524 * @return True if the view is hoverable. 13525 */ 13526 private boolean isHoverable() { 13527 final int viewFlags = mViewFlags; 13528 if ((viewFlags & ENABLED_MASK) == DISABLED) { 13529 return false; 13530 } 13531 13532 return (viewFlags & CLICKABLE) == CLICKABLE 13533 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 13534 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 13535 } 13536 13537 /** 13538 * Returns true if the view is currently hovered. 13539 * 13540 * @return True if the view is currently hovered. 13541 * 13542 * @see #setHovered 13543 * @see #onHoverChanged 13544 */ 13545 @ViewDebug.ExportedProperty 13546 public boolean isHovered() { 13547 return (mPrivateFlags & PFLAG_HOVERED) != 0; 13548 } 13549 13550 /** 13551 * Sets whether the view is currently hovered. 13552 * <p> 13553 * Calling this method also changes the drawable state of the view. This 13554 * enables the view to react to hover by using different drawable resources 13555 * to change its appearance. 13556 * </p><p> 13557 * The {@link #onHoverChanged} method is called when the hovered state changes. 13558 * </p> 13559 * 13560 * @param hovered True if the view is hovered. 13561 * 13562 * @see #isHovered 13563 * @see #onHoverChanged 13564 */ 13565 public void setHovered(boolean hovered) { 13566 if (hovered) { 13567 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 13568 mPrivateFlags |= PFLAG_HOVERED; 13569 refreshDrawableState(); 13570 onHoverChanged(true); 13571 } 13572 } else { 13573 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 13574 mPrivateFlags &= ~PFLAG_HOVERED; 13575 refreshDrawableState(); 13576 onHoverChanged(false); 13577 } 13578 } 13579 } 13580 13581 /** 13582 * Implement this method to handle hover state changes. 13583 * <p> 13584 * This method is called whenever the hover state changes as a result of a 13585 * call to {@link #setHovered}. 13586 * </p> 13587 * 13588 * @param hovered The current hover state, as returned by {@link #isHovered}. 13589 * 13590 * @see #isHovered 13591 * @see #setHovered 13592 */ 13593 public void onHoverChanged(boolean hovered) { 13594 } 13595 13596 /** 13597 * Handles scroll bar dragging by mouse input. 13598 * 13599 * @hide 13600 * @param event The motion event. 13601 * 13602 * @return true if the event was handled as a scroll bar dragging, false otherwise. 13603 */ 13604 protected boolean handleScrollBarDragging(MotionEvent event) { 13605 if (mScrollCache == null) { 13606 return false; 13607 } 13608 final float x = event.getX(); 13609 final float y = event.getY(); 13610 final int action = event.getAction(); 13611 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 13612 && action != MotionEvent.ACTION_DOWN) 13613 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 13614 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 13615 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 13616 return false; 13617 } 13618 13619 switch (action) { 13620 case MotionEvent.ACTION_MOVE: 13621 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 13622 return false; 13623 } 13624 if (mScrollCache.mScrollBarDraggingState 13625 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 13626 final Rect bounds = mScrollCache.mScrollBarBounds; 13627 getVerticalScrollBarBounds(bounds, null); 13628 final int range = computeVerticalScrollRange(); 13629 final int offset = computeVerticalScrollOffset(); 13630 final int extent = computeVerticalScrollExtent(); 13631 13632 final int thumbLength = ScrollBarUtils.getThumbLength( 13633 bounds.height(), bounds.width(), extent, range); 13634 final int thumbOffset = ScrollBarUtils.getThumbOffset( 13635 bounds.height(), thumbLength, extent, range, offset); 13636 13637 final float diff = y - mScrollCache.mScrollBarDraggingPos; 13638 final float maxThumbOffset = bounds.height() - thumbLength; 13639 final float newThumbOffset = 13640 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 13641 final int height = getHeight(); 13642 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 13643 && height > 0 && extent > 0) { 13644 final int newY = Math.round((range - extent) 13645 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 13646 if (newY != getScrollY()) { 13647 mScrollCache.mScrollBarDraggingPos = y; 13648 setScrollY(newY); 13649 } 13650 } 13651 return true; 13652 } 13653 if (mScrollCache.mScrollBarDraggingState 13654 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 13655 final Rect bounds = mScrollCache.mScrollBarBounds; 13656 getHorizontalScrollBarBounds(bounds, null); 13657 final int range = computeHorizontalScrollRange(); 13658 final int offset = computeHorizontalScrollOffset(); 13659 final int extent = computeHorizontalScrollExtent(); 13660 13661 final int thumbLength = ScrollBarUtils.getThumbLength( 13662 bounds.width(), bounds.height(), extent, range); 13663 final int thumbOffset = ScrollBarUtils.getThumbOffset( 13664 bounds.width(), thumbLength, extent, range, offset); 13665 13666 final float diff = x - mScrollCache.mScrollBarDraggingPos; 13667 final float maxThumbOffset = bounds.width() - thumbLength; 13668 final float newThumbOffset = 13669 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 13670 final int width = getWidth(); 13671 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 13672 && width > 0 && extent > 0) { 13673 final int newX = Math.round((range - extent) 13674 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 13675 if (newX != getScrollX()) { 13676 mScrollCache.mScrollBarDraggingPos = x; 13677 setScrollX(newX); 13678 } 13679 } 13680 return true; 13681 } 13682 case MotionEvent.ACTION_DOWN: 13683 if (mScrollCache.state == ScrollabilityCache.OFF) { 13684 return false; 13685 } 13686 if (isOnVerticalScrollbarThumb(x, y)) { 13687 mScrollCache.mScrollBarDraggingState = 13688 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 13689 mScrollCache.mScrollBarDraggingPos = y; 13690 return true; 13691 } 13692 if (isOnHorizontalScrollbarThumb(x, y)) { 13693 mScrollCache.mScrollBarDraggingState = 13694 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 13695 mScrollCache.mScrollBarDraggingPos = x; 13696 return true; 13697 } 13698 } 13699 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 13700 return false; 13701 } 13702 13703 /** 13704 * Implement this method to handle touch screen motion events. 13705 * <p> 13706 * If this method is used to detect click actions, it is recommended that 13707 * the actions be performed by implementing and calling 13708 * {@link #performClick()}. This will ensure consistent system behavior, 13709 * including: 13710 * <ul> 13711 * <li>obeying click sound preferences 13712 * <li>dispatching OnClickListener calls 13713 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 13714 * accessibility features are enabled 13715 * </ul> 13716 * 13717 * @param event The motion event. 13718 * @return True if the event was handled, false otherwise. 13719 */ 13720 public boolean onTouchEvent(MotionEvent event) { 13721 final float x = event.getX(); 13722 final float y = event.getY(); 13723 final int viewFlags = mViewFlags; 13724 final int action = event.getAction(); 13725 13726 final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE 13727 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 13728 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 13729 13730 if ((viewFlags & ENABLED_MASK) == DISABLED) { 13731 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 13732 setPressed(false); 13733 } 13734 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 13735 // A disabled view that is clickable still consumes the touch 13736 // events, it just doesn't respond to them. 13737 return clickable; 13738 } 13739 if (mTouchDelegate != null) { 13740 if (mTouchDelegate.onTouchEvent(event)) { 13741 return true; 13742 } 13743 } 13744 13745 if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { 13746 switch (action) { 13747 case MotionEvent.ACTION_UP: 13748 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 13749 if ((viewFlags & TOOLTIP) == TOOLTIP) { 13750 handleTooltipUp(); 13751 } 13752 if (!clickable) { 13753 removeTapCallback(); 13754 removeLongPressCallback(); 13755 mInContextButtonPress = false; 13756 mHasPerformedLongPress = false; 13757 mIgnoreNextUpEvent = false; 13758 break; 13759 } 13760 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 13761 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 13762 // take focus if we don't have it already and we should in 13763 // touch mode. 13764 boolean focusTaken = false; 13765 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 13766 focusTaken = requestFocus(); 13767 } 13768 13769 if (prepressed) { 13770 // The button is being released before we actually 13771 // showed it as pressed. Make it show the pressed 13772 // state now (before scheduling the click) to ensure 13773 // the user sees it. 13774 setPressed(true, x, y); 13775 } 13776 13777 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 13778 // This is a tap, so remove the longpress check 13779 removeLongPressCallback(); 13780 13781 // Only perform take click actions if we were in the pressed state 13782 if (!focusTaken) { 13783 // Use a Runnable and post this rather than calling 13784 // performClick directly. This lets other visual state 13785 // of the view update before click actions start. 13786 if (mPerformClick == null) { 13787 mPerformClick = new PerformClick(); 13788 } 13789 if (!post(mPerformClick)) { 13790 performClickInternal(); 13791 } 13792 } 13793 } 13794 13795 if (mUnsetPressedState == null) { 13796 mUnsetPressedState = new UnsetPressedState(); 13797 } 13798 13799 if (prepressed) { 13800 postDelayed(mUnsetPressedState, 13801 ViewConfiguration.getPressedStateDuration()); 13802 } else if (!post(mUnsetPressedState)) { 13803 // If the post failed, unpress right now 13804 mUnsetPressedState.run(); 13805 } 13806 13807 removeTapCallback(); 13808 } 13809 mIgnoreNextUpEvent = false; 13810 break; 13811 13812 case MotionEvent.ACTION_DOWN: 13813 if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) { 13814 mPrivateFlags3 |= PFLAG3_FINGER_DOWN; 13815 } 13816 mHasPerformedLongPress = false; 13817 13818 if (!clickable) { 13819 checkForLongClick(0, x, y); 13820 break; 13821 } 13822 13823 if (performButtonActionOnTouchDown(event)) { 13824 break; 13825 } 13826 13827 // Walk up the hierarchy to determine if we're inside a scrolling container. 13828 boolean isInScrollingContainer = isInScrollingContainer(); 13829 13830 // For views inside a scrolling container, delay the pressed feedback for 13831 // a short period in case this is a scroll. 13832 if (isInScrollingContainer) { 13833 mPrivateFlags |= PFLAG_PREPRESSED; 13834 if (mPendingCheckForTap == null) { 13835 mPendingCheckForTap = new CheckForTap(); 13836 } 13837 mPendingCheckForTap.x = event.getX(); 13838 mPendingCheckForTap.y = event.getY(); 13839 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 13840 } else { 13841 // Not inside a scrolling container, so show the feedback right away 13842 setPressed(true, x, y); 13843 checkForLongClick(0, x, y); 13844 } 13845 break; 13846 13847 case MotionEvent.ACTION_CANCEL: 13848 if (clickable) { 13849 setPressed(false); 13850 } 13851 removeTapCallback(); 13852 removeLongPressCallback(); 13853 mInContextButtonPress = false; 13854 mHasPerformedLongPress = false; 13855 mIgnoreNextUpEvent = false; 13856 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 13857 break; 13858 13859 case MotionEvent.ACTION_MOVE: 13860 if (clickable) { 13861 drawableHotspotChanged(x, y); 13862 } 13863 13864 // Be lenient about moving outside of buttons 13865 if (!pointInView(x, y, mTouchSlop)) { 13866 // Outside button 13867 // Remove any future long press/tap checks 13868 removeTapCallback(); 13869 removeLongPressCallback(); 13870 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 13871 setPressed(false); 13872 } 13873 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 13874 } 13875 break; 13876 } 13877 13878 return true; 13879 } 13880 13881 return false; 13882 } 13883 13884 /** 13885 * @hide 13886 */ 13887 public boolean isInScrollingContainer() { 13888 ViewParent p = getParent(); 13889 while (p != null && p instanceof ViewGroup) { 13890 if (((ViewGroup) p).shouldDelayChildPressedState()) { 13891 return true; 13892 } 13893 p = p.getParent(); 13894 } 13895 return false; 13896 } 13897 13898 /** 13899 * Remove the longpress detection timer. 13900 */ 13901 private void removeLongPressCallback() { 13902 if (mPendingCheckForLongPress != null) { 13903 removeCallbacks(mPendingCheckForLongPress); 13904 } 13905 } 13906 13907 /** 13908 * Remove the pending click action 13909 */ 13910 private void removePerformClickCallback() { 13911 if (mPerformClick != null) { 13912 removeCallbacks(mPerformClick); 13913 } 13914 } 13915 13916 /** 13917 * Remove the prepress detection timer. 13918 */ 13919 private void removeUnsetPressCallback() { 13920 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 13921 setPressed(false); 13922 removeCallbacks(mUnsetPressedState); 13923 } 13924 } 13925 13926 /** 13927 * Remove the tap detection timer. 13928 */ 13929 private void removeTapCallback() { 13930 if (mPendingCheckForTap != null) { 13931 mPrivateFlags &= ~PFLAG_PREPRESSED; 13932 removeCallbacks(mPendingCheckForTap); 13933 } 13934 } 13935 13936 /** 13937 * Cancels a pending long press. Your subclass can use this if you 13938 * want the context menu to come up if the user presses and holds 13939 * at the same place, but you don't want it to come up if they press 13940 * and then move around enough to cause scrolling. 13941 */ 13942 public void cancelLongPress() { 13943 removeLongPressCallback(); 13944 13945 /* 13946 * The prepressed state handled by the tap callback is a display 13947 * construct, but the tap callback will post a long press callback 13948 * less its own timeout. Remove it here. 13949 */ 13950 removeTapCallback(); 13951 } 13952 13953 /** 13954 * Sets the TouchDelegate for this View. 13955 */ 13956 public void setTouchDelegate(TouchDelegate delegate) { 13957 mTouchDelegate = delegate; 13958 } 13959 13960 /** 13961 * Gets the TouchDelegate for this View. 13962 */ 13963 public TouchDelegate getTouchDelegate() { 13964 return mTouchDelegate; 13965 } 13966 13967 /** 13968 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 13969 * 13970 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 13971 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 13972 * available. This method should only be called for touch events. 13973 * 13974 * <p class="note">This api is not intended for most applications. Buffered dispatch 13975 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 13976 * streams will not improve your input latency. Side effects include: increased latency, 13977 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 13978 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 13979 * you.</p> 13980 */ 13981 public final void requestUnbufferedDispatch(MotionEvent event) { 13982 final int action = event.getAction(); 13983 if (mAttachInfo == null 13984 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 13985 || !event.isTouchEvent()) { 13986 return; 13987 } 13988 mAttachInfo.mUnbufferedDispatchRequested = true; 13989 } 13990 13991 private boolean hasSize() { 13992 return (mBottom > mTop) && (mRight > mLeft); 13993 } 13994 13995 private boolean canTakeFocus() { 13996 return ((mViewFlags & VISIBILITY_MASK) == VISIBLE) 13997 && ((mViewFlags & FOCUSABLE) == FOCUSABLE) 13998 && ((mViewFlags & ENABLED_MASK) == ENABLED) 13999 && (sCanFocusZeroSized || !isLayoutValid() || hasSize()); 14000 } 14001 14002 /** 14003 * Set flags controlling behavior of this view. 14004 * 14005 * @param flags Constant indicating the value which should be set 14006 * @param mask Constant indicating the bit range that should be changed 14007 */ 14008 void setFlags(int flags, int mask) { 14009 final boolean accessibilityEnabled = 14010 AccessibilityManager.getInstance(mContext).isEnabled(); 14011 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 14012 14013 int old = mViewFlags; 14014 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 14015 14016 int changed = mViewFlags ^ old; 14017 if (changed == 0) { 14018 return; 14019 } 14020 int privateFlags = mPrivateFlags; 14021 boolean shouldNotifyFocusableAvailable = false; 14022 14023 // If focusable is auto, update the FOCUSABLE bit. 14024 int focusableChangedByAuto = 0; 14025 if (((mViewFlags & FOCUSABLE_AUTO) != 0) 14026 && (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) { 14027 // Heuristic only takes into account whether view is clickable. 14028 final int newFocus; 14029 if ((mViewFlags & CLICKABLE) != 0) { 14030 newFocus = FOCUSABLE; 14031 } else { 14032 newFocus = NOT_FOCUSABLE; 14033 } 14034 mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus; 14035 focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE); 14036 changed = (changed & ~FOCUSABLE) | focusableChangedByAuto; 14037 } 14038 14039 /* Check if the FOCUSABLE bit has changed */ 14040 if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) { 14041 if (((old & FOCUSABLE) == FOCUSABLE) 14042 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 14043 /* Give up focus if we are no longer focusable */ 14044 clearFocus(); 14045 if (mParent instanceof ViewGroup) { 14046 ((ViewGroup) mParent).clearFocusedInCluster(); 14047 } 14048 } else if (((old & FOCUSABLE) == NOT_FOCUSABLE) 14049 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 14050 /* 14051 * Tell the view system that we are now available to take focus 14052 * if no one else already has it. 14053 */ 14054 if (mParent != null) { 14055 ViewRootImpl viewRootImpl = getViewRootImpl(); 14056 if (!sAutoFocusableOffUIThreadWontNotifyParents 14057 || focusableChangedByAuto == 0 14058 || viewRootImpl == null 14059 || viewRootImpl.mThread == Thread.currentThread()) { 14060 shouldNotifyFocusableAvailable = canTakeFocus(); 14061 } 14062 } 14063 } 14064 } 14065 14066 final int newVisibility = flags & VISIBILITY_MASK; 14067 if (newVisibility == VISIBLE) { 14068 if ((changed & VISIBILITY_MASK) != 0) { 14069 /* 14070 * If this view is becoming visible, invalidate it in case it changed while 14071 * it was not visible. Marking it drawn ensures that the invalidation will 14072 * go through. 14073 */ 14074 mPrivateFlags |= PFLAG_DRAWN; 14075 invalidate(true); 14076 14077 needGlobalAttributesUpdate(true); 14078 14079 // a view becoming visible is worth notifying the parent about in case nothing has 14080 // focus. Even if this specific view isn't focusable, it may contain something that 14081 // is, so let the root view try to give this focus if nothing else does. 14082 shouldNotifyFocusableAvailable = hasSize(); 14083 } 14084 } 14085 14086 if ((changed & ENABLED_MASK) != 0) { 14087 if ((mViewFlags & ENABLED_MASK) == ENABLED) { 14088 // a view becoming enabled should notify the parent as long as the view is also 14089 // visible and the parent wasn't already notified by becoming visible during this 14090 // setFlags invocation. 14091 shouldNotifyFocusableAvailable = canTakeFocus(); 14092 } else { 14093 if (isFocused()) clearFocus(); 14094 } 14095 } 14096 14097 if (shouldNotifyFocusableAvailable && mParent != null) { 14098 mParent.focusableViewAvailable(this); 14099 } 14100 14101 /* Check if the GONE bit has changed */ 14102 if ((changed & GONE) != 0) { 14103 needGlobalAttributesUpdate(false); 14104 requestLayout(); 14105 14106 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 14107 if (hasFocus()) { 14108 clearFocus(); 14109 if (mParent instanceof ViewGroup) { 14110 ((ViewGroup) mParent).clearFocusedInCluster(); 14111 } 14112 } 14113 clearAccessibilityFocus(); 14114 destroyDrawingCache(); 14115 if (mParent instanceof View) { 14116 // GONE views noop invalidation, so invalidate the parent 14117 ((View) mParent).invalidate(true); 14118 } 14119 // Mark the view drawn to ensure that it gets invalidated properly the next 14120 // time it is visible and gets invalidated 14121 mPrivateFlags |= PFLAG_DRAWN; 14122 } 14123 if (mAttachInfo != null) { 14124 mAttachInfo.mViewVisibilityChanged = true; 14125 } 14126 } 14127 14128 /* Check if the VISIBLE bit has changed */ 14129 if ((changed & INVISIBLE) != 0) { 14130 needGlobalAttributesUpdate(false); 14131 /* 14132 * If this view is becoming invisible, set the DRAWN flag so that 14133 * the next invalidate() will not be skipped. 14134 */ 14135 mPrivateFlags |= PFLAG_DRAWN; 14136 14137 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 14138 // root view becoming invisible shouldn't clear focus and accessibility focus 14139 if (getRootView() != this) { 14140 if (hasFocus()) { 14141 clearFocus(); 14142 if (mParent instanceof ViewGroup) { 14143 ((ViewGroup) mParent).clearFocusedInCluster(); 14144 } 14145 } 14146 clearAccessibilityFocus(); 14147 } 14148 } 14149 if (mAttachInfo != null) { 14150 mAttachInfo.mViewVisibilityChanged = true; 14151 } 14152 } 14153 14154 if ((changed & VISIBILITY_MASK) != 0) { 14155 // If the view is invisible, cleanup its display list to free up resources 14156 if (newVisibility != VISIBLE && mAttachInfo != null) { 14157 cleanupDraw(); 14158 } 14159 14160 if (mParent instanceof ViewGroup) { 14161 ((ViewGroup) mParent).onChildVisibilityChanged(this, 14162 (changed & VISIBILITY_MASK), newVisibility); 14163 ((View) mParent).invalidate(true); 14164 } else if (mParent != null) { 14165 mParent.invalidateChild(this, null); 14166 } 14167 14168 if (mAttachInfo != null) { 14169 dispatchVisibilityChanged(this, newVisibility); 14170 14171 // Aggregated visibility changes are dispatched to attached views 14172 // in visible windows where the parent is currently shown/drawn 14173 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 14174 // discounting clipping or overlapping. This makes it a good place 14175 // to change animation states. 14176 if (mParent != null && getWindowVisibility() == VISIBLE && 14177 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 14178 dispatchVisibilityAggregated(newVisibility == VISIBLE); 14179 } 14180 notifySubtreeAccessibilityStateChangedIfNeeded(); 14181 } 14182 } 14183 14184 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 14185 destroyDrawingCache(); 14186 } 14187 14188 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 14189 destroyDrawingCache(); 14190 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14191 invalidateParentCaches(); 14192 } 14193 14194 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 14195 destroyDrawingCache(); 14196 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14197 } 14198 14199 if ((changed & DRAW_MASK) != 0) { 14200 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 14201 if (mBackground != null 14202 || mDefaultFocusHighlight != null 14203 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 14204 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 14205 } else { 14206 mPrivateFlags |= PFLAG_SKIP_DRAW; 14207 } 14208 } else { 14209 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 14210 } 14211 requestLayout(); 14212 invalidate(true); 14213 } 14214 14215 if ((changed & KEEP_SCREEN_ON) != 0) { 14216 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 14217 mParent.recomputeViewAttributes(this); 14218 } 14219 } 14220 14221 if (accessibilityEnabled) { 14222 // If we're an accessibility pane and the visibility changed, we already have sent 14223 // a state change, so we really don't need to report other changes. 14224 if (isAccessibilityPane()) { 14225 changed &= ~VISIBILITY_MASK; 14226 } 14227 if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0 14228 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 14229 || (changed & CONTEXT_CLICKABLE) != 0) { 14230 if (oldIncludeForAccessibility != includeForAccessibility()) { 14231 notifySubtreeAccessibilityStateChangedIfNeeded(); 14232 } else { 14233 notifyViewAccessibilityStateChangedIfNeeded( 14234 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 14235 } 14236 } else if ((changed & ENABLED_MASK) != 0) { 14237 notifyViewAccessibilityStateChangedIfNeeded( 14238 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 14239 } 14240 } 14241 } 14242 14243 /** 14244 * Change the view's z order in the tree, so it's on top of other sibling 14245 * views. This ordering change may affect layout, if the parent container 14246 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 14247 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 14248 * method should be followed by calls to {@link #requestLayout()} and 14249 * {@link View#invalidate()} on the view's parent to force the parent to redraw 14250 * with the new child ordering. 14251 * 14252 * @see ViewGroup#bringChildToFront(View) 14253 */ 14254 public void bringToFront() { 14255 if (mParent != null) { 14256 mParent.bringChildToFront(this); 14257 } 14258 } 14259 14260 /** 14261 * This is called in response to an internal scroll in this view (i.e., the 14262 * view scrolled its own contents). This is typically as a result of 14263 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 14264 * called. 14265 * 14266 * @param l Current horizontal scroll origin. 14267 * @param t Current vertical scroll origin. 14268 * @param oldl Previous horizontal scroll origin. 14269 * @param oldt Previous vertical scroll origin. 14270 */ 14271 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 14272 notifySubtreeAccessibilityStateChangedIfNeeded(); 14273 14274 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 14275 postSendViewScrolledAccessibilityEventCallback(l - oldl, t - oldt); 14276 } 14277 14278 mBackgroundSizeChanged = true; 14279 mDefaultFocusHighlightSizeChanged = true; 14280 if (mForegroundInfo != null) { 14281 mForegroundInfo.mBoundsChanged = true; 14282 } 14283 14284 final AttachInfo ai = mAttachInfo; 14285 if (ai != null) { 14286 ai.mViewScrollChanged = true; 14287 } 14288 14289 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 14290 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 14291 } 14292 } 14293 14294 /** 14295 * Interface definition for a callback to be invoked when the scroll 14296 * X or Y positions of a view change. 14297 * <p> 14298 * <b>Note:</b> Some views handle scrolling independently from View and may 14299 * have their own separate listeners for scroll-type events. For example, 14300 * {@link android.widget.ListView ListView} allows clients to register an 14301 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 14302 * to listen for changes in list scroll position. 14303 * 14304 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 14305 */ 14306 public interface OnScrollChangeListener { 14307 /** 14308 * Called when the scroll position of a view changes. 14309 * 14310 * @param v The view whose scroll position has changed. 14311 * @param scrollX Current horizontal scroll origin. 14312 * @param scrollY Current vertical scroll origin. 14313 * @param oldScrollX Previous horizontal scroll origin. 14314 * @param oldScrollY Previous vertical scroll origin. 14315 */ 14316 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 14317 } 14318 14319 /** 14320 * Interface definition for a callback to be invoked when the layout bounds of a view 14321 * changes due to layout processing. 14322 */ 14323 public interface OnLayoutChangeListener { 14324 /** 14325 * Called when the layout bounds of a view changes due to layout processing. 14326 * 14327 * @param v The view whose bounds have changed. 14328 * @param left The new value of the view's left property. 14329 * @param top The new value of the view's top property. 14330 * @param right The new value of the view's right property. 14331 * @param bottom The new value of the view's bottom property. 14332 * @param oldLeft The previous value of the view's left property. 14333 * @param oldTop The previous value of the view's top property. 14334 * @param oldRight The previous value of the view's right property. 14335 * @param oldBottom The previous value of the view's bottom property. 14336 */ 14337 void onLayoutChange(View v, int left, int top, int right, int bottom, 14338 int oldLeft, int oldTop, int oldRight, int oldBottom); 14339 } 14340 14341 /** 14342 * This is called during layout when the size of this view has changed. If 14343 * you were just added to the view hierarchy, you're called with the old 14344 * values of 0. 14345 * 14346 * @param w Current width of this view. 14347 * @param h Current height of this view. 14348 * @param oldw Old width of this view. 14349 * @param oldh Old height of this view. 14350 */ 14351 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 14352 } 14353 14354 /** 14355 * Called by draw to draw the child views. This may be overridden 14356 * by derived classes to gain control just before its children are drawn 14357 * (but after its own view has been drawn). 14358 * @param canvas the canvas on which to draw the view 14359 */ 14360 protected void dispatchDraw(Canvas canvas) { 14361 14362 } 14363 14364 /** 14365 * Gets the parent of this view. Note that the parent is a 14366 * ViewParent and not necessarily a View. 14367 * 14368 * @return Parent of this view. 14369 */ 14370 public final ViewParent getParent() { 14371 return mParent; 14372 } 14373 14374 /** 14375 * Set the horizontal scrolled position of your view. This will cause a call to 14376 * {@link #onScrollChanged(int, int, int, int)} and the view will be 14377 * invalidated. 14378 * @param value the x position to scroll to 14379 */ 14380 public void setScrollX(int value) { 14381 scrollTo(value, mScrollY); 14382 } 14383 14384 /** 14385 * Set the vertical scrolled position of your view. This will cause a call to 14386 * {@link #onScrollChanged(int, int, int, int)} and the view will be 14387 * invalidated. 14388 * @param value the y position to scroll to 14389 */ 14390 public void setScrollY(int value) { 14391 scrollTo(mScrollX, value); 14392 } 14393 14394 /** 14395 * Return the scrolled left position of this view. This is the left edge of 14396 * the displayed part of your view. You do not need to draw any pixels 14397 * farther left, since those are outside of the frame of your view on 14398 * screen. 14399 * 14400 * @return The left edge of the displayed part of your view, in pixels. 14401 */ 14402 public final int getScrollX() { 14403 return mScrollX; 14404 } 14405 14406 /** 14407 * Return the scrolled top position of this view. This is the top edge of 14408 * the displayed part of your view. You do not need to draw any pixels above 14409 * it, since those are outside of the frame of your view on screen. 14410 * 14411 * @return The top edge of the displayed part of your view, in pixels. 14412 */ 14413 public final int getScrollY() { 14414 return mScrollY; 14415 } 14416 14417 /** 14418 * Return the width of your view. 14419 * 14420 * @return The width of your view, in pixels. 14421 */ 14422 @ViewDebug.ExportedProperty(category = "layout") 14423 public final int getWidth() { 14424 return mRight - mLeft; 14425 } 14426 14427 /** 14428 * Return the height of your view. 14429 * 14430 * @return The height of your view, in pixels. 14431 */ 14432 @ViewDebug.ExportedProperty(category = "layout") 14433 public final int getHeight() { 14434 return mBottom - mTop; 14435 } 14436 14437 /** 14438 * Return the visible drawing bounds of your view. Fills in the output 14439 * rectangle with the values from getScrollX(), getScrollY(), 14440 * getWidth(), and getHeight(). These bounds do not account for any 14441 * transformation properties currently set on the view, such as 14442 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 14443 * 14444 * @param outRect The (scrolled) drawing bounds of the view. 14445 */ 14446 public void getDrawingRect(Rect outRect) { 14447 outRect.left = mScrollX; 14448 outRect.top = mScrollY; 14449 outRect.right = mScrollX + (mRight - mLeft); 14450 outRect.bottom = mScrollY + (mBottom - mTop); 14451 } 14452 14453 /** 14454 * Like {@link #getMeasuredWidthAndState()}, but only returns the 14455 * raw width component (that is the result is masked by 14456 * {@link #MEASURED_SIZE_MASK}). 14457 * 14458 * @return The raw measured width of this view. 14459 */ 14460 public final int getMeasuredWidth() { 14461 return mMeasuredWidth & MEASURED_SIZE_MASK; 14462 } 14463 14464 /** 14465 * Return the full width measurement information for this view as computed 14466 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 14467 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 14468 * This should be used during measurement and layout calculations only. Use 14469 * {@link #getWidth()} to see how wide a view is after layout. 14470 * 14471 * @return The measured width of this view as a bit mask. 14472 */ 14473 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 14474 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 14475 name = "MEASURED_STATE_TOO_SMALL"), 14476 }) 14477 public final int getMeasuredWidthAndState() { 14478 return mMeasuredWidth; 14479 } 14480 14481 /** 14482 * Like {@link #getMeasuredHeightAndState()}, but only returns the 14483 * raw height component (that is the result is masked by 14484 * {@link #MEASURED_SIZE_MASK}). 14485 * 14486 * @return The raw measured height of this view. 14487 */ 14488 public final int getMeasuredHeight() { 14489 return mMeasuredHeight & MEASURED_SIZE_MASK; 14490 } 14491 14492 /** 14493 * Return the full height measurement information for this view as computed 14494 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 14495 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 14496 * This should be used during measurement and layout calculations only. Use 14497 * {@link #getHeight()} to see how wide a view is after layout. 14498 * 14499 * @return The measured height of this view as a bit mask. 14500 */ 14501 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 14502 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 14503 name = "MEASURED_STATE_TOO_SMALL"), 14504 }) 14505 public final int getMeasuredHeightAndState() { 14506 return mMeasuredHeight; 14507 } 14508 14509 /** 14510 * Return only the state bits of {@link #getMeasuredWidthAndState()} 14511 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 14512 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 14513 * and the height component is at the shifted bits 14514 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 14515 */ 14516 public final int getMeasuredState() { 14517 return (mMeasuredWidth&MEASURED_STATE_MASK) 14518 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 14519 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 14520 } 14521 14522 /** 14523 * The transform matrix of this view, which is calculated based on the current 14524 * rotation, scale, and pivot properties. 14525 * 14526 * @see #getRotation() 14527 * @see #getScaleX() 14528 * @see #getScaleY() 14529 * @see #getPivotX() 14530 * @see #getPivotY() 14531 * @return The current transform matrix for the view 14532 */ 14533 public Matrix getMatrix() { 14534 ensureTransformationInfo(); 14535 final Matrix matrix = mTransformationInfo.mMatrix; 14536 mRenderNode.getMatrix(matrix); 14537 return matrix; 14538 } 14539 14540 /** 14541 * Returns true if the transform matrix is the identity matrix. 14542 * Recomputes the matrix if necessary. 14543 * 14544 * @return True if the transform matrix is the identity matrix, false otherwise. 14545 */ 14546 final boolean hasIdentityMatrix() { 14547 return mRenderNode.hasIdentityMatrix(); 14548 } 14549 14550 void ensureTransformationInfo() { 14551 if (mTransformationInfo == null) { 14552 mTransformationInfo = new TransformationInfo(); 14553 } 14554 } 14555 14556 /** 14557 * Utility method to retrieve the inverse of the current mMatrix property. 14558 * We cache the matrix to avoid recalculating it when transform properties 14559 * have not changed. 14560 * 14561 * @return The inverse of the current matrix of this view. 14562 * @hide 14563 */ 14564 public final Matrix getInverseMatrix() { 14565 ensureTransformationInfo(); 14566 if (mTransformationInfo.mInverseMatrix == null) { 14567 mTransformationInfo.mInverseMatrix = new Matrix(); 14568 } 14569 final Matrix matrix = mTransformationInfo.mInverseMatrix; 14570 mRenderNode.getInverseMatrix(matrix); 14571 return matrix; 14572 } 14573 14574 /** 14575 * Gets the distance along the Z axis from the camera to this view. 14576 * 14577 * @see #setCameraDistance(float) 14578 * 14579 * @return The distance along the Z axis. 14580 */ 14581 public float getCameraDistance() { 14582 final float dpi = mResources.getDisplayMetrics().densityDpi; 14583 return -(mRenderNode.getCameraDistance() * dpi); 14584 } 14585 14586 /** 14587 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 14588 * views are drawn) from the camera to this view. The camera's distance 14589 * affects 3D transformations, for instance rotations around the X and Y 14590 * axis. If the rotationX or rotationY properties are changed and this view is 14591 * large (more than half the size of the screen), it is recommended to always 14592 * use a camera distance that's greater than the height (X axis rotation) or 14593 * the width (Y axis rotation) of this view.</p> 14594 * 14595 * <p>The distance of the camera from the view plane can have an affect on the 14596 * perspective distortion of the view when it is rotated around the x or y axis. 14597 * For example, a large distance will result in a large viewing angle, and there 14598 * will not be much perspective distortion of the view as it rotates. A short 14599 * distance may cause much more perspective distortion upon rotation, and can 14600 * also result in some drawing artifacts if the rotated view ends up partially 14601 * behind the camera (which is why the recommendation is to use a distance at 14602 * least as far as the size of the view, if the view is to be rotated.)</p> 14603 * 14604 * <p>The distance is expressed in "depth pixels." The default distance depends 14605 * on the screen density. For instance, on a medium density display, the 14606 * default distance is 1280. On a high density display, the default distance 14607 * is 1920.</p> 14608 * 14609 * <p>If you want to specify a distance that leads to visually consistent 14610 * results across various densities, use the following formula:</p> 14611 * <pre> 14612 * float scale = context.getResources().getDisplayMetrics().density; 14613 * view.setCameraDistance(distance * scale); 14614 * </pre> 14615 * 14616 * <p>The density scale factor of a high density display is 1.5, 14617 * and 1920 = 1280 * 1.5.</p> 14618 * 14619 * @param distance The distance in "depth pixels", if negative the opposite 14620 * value is used 14621 * 14622 * @see #setRotationX(float) 14623 * @see #setRotationY(float) 14624 */ 14625 public void setCameraDistance(float distance) { 14626 final float dpi = mResources.getDisplayMetrics().densityDpi; 14627 14628 invalidateViewProperty(true, false); 14629 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 14630 invalidateViewProperty(false, false); 14631 14632 invalidateParentIfNeededAndWasQuickRejected(); 14633 } 14634 14635 /** 14636 * The degrees that the view is rotated around the pivot point. 14637 * 14638 * @see #setRotation(float) 14639 * @see #getPivotX() 14640 * @see #getPivotY() 14641 * 14642 * @return The degrees of rotation. 14643 */ 14644 @ViewDebug.ExportedProperty(category = "drawing") 14645 public float getRotation() { 14646 return mRenderNode.getRotation(); 14647 } 14648 14649 /** 14650 * Sets the degrees that the view is rotated around the pivot point. Increasing values 14651 * result in clockwise rotation. 14652 * 14653 * @param rotation The degrees of rotation. 14654 * 14655 * @see #getRotation() 14656 * @see #getPivotX() 14657 * @see #getPivotY() 14658 * @see #setRotationX(float) 14659 * @see #setRotationY(float) 14660 * 14661 * @attr ref android.R.styleable#View_rotation 14662 */ 14663 public void setRotation(float rotation) { 14664 if (rotation != getRotation()) { 14665 // Double-invalidation is necessary to capture view's old and new areas 14666 invalidateViewProperty(true, false); 14667 mRenderNode.setRotation(rotation); 14668 invalidateViewProperty(false, true); 14669 14670 invalidateParentIfNeededAndWasQuickRejected(); 14671 notifySubtreeAccessibilityStateChangedIfNeeded(); 14672 } 14673 } 14674 14675 /** 14676 * The degrees that the view is rotated around the vertical axis through the pivot point. 14677 * 14678 * @see #getPivotX() 14679 * @see #getPivotY() 14680 * @see #setRotationY(float) 14681 * 14682 * @return The degrees of Y rotation. 14683 */ 14684 @ViewDebug.ExportedProperty(category = "drawing") 14685 public float getRotationY() { 14686 return mRenderNode.getRotationY(); 14687 } 14688 14689 /** 14690 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 14691 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 14692 * down the y axis. 14693 * 14694 * When rotating large views, it is recommended to adjust the camera distance 14695 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 14696 * 14697 * @param rotationY The degrees of Y rotation. 14698 * 14699 * @see #getRotationY() 14700 * @see #getPivotX() 14701 * @see #getPivotY() 14702 * @see #setRotation(float) 14703 * @see #setRotationX(float) 14704 * @see #setCameraDistance(float) 14705 * 14706 * @attr ref android.R.styleable#View_rotationY 14707 */ 14708 public void setRotationY(float rotationY) { 14709 if (rotationY != getRotationY()) { 14710 invalidateViewProperty(true, false); 14711 mRenderNode.setRotationY(rotationY); 14712 invalidateViewProperty(false, true); 14713 14714 invalidateParentIfNeededAndWasQuickRejected(); 14715 notifySubtreeAccessibilityStateChangedIfNeeded(); 14716 } 14717 } 14718 14719 /** 14720 * The degrees that the view is rotated around the horizontal axis through the pivot point. 14721 * 14722 * @see #getPivotX() 14723 * @see #getPivotY() 14724 * @see #setRotationX(float) 14725 * 14726 * @return The degrees of X rotation. 14727 */ 14728 @ViewDebug.ExportedProperty(category = "drawing") 14729 public float getRotationX() { 14730 return mRenderNode.getRotationX(); 14731 } 14732 14733 /** 14734 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 14735 * Increasing values result in clockwise rotation from the viewpoint of looking down the 14736 * x axis. 14737 * 14738 * When rotating large views, it is recommended to adjust the camera distance 14739 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 14740 * 14741 * @param rotationX The degrees of X rotation. 14742 * 14743 * @see #getRotationX() 14744 * @see #getPivotX() 14745 * @see #getPivotY() 14746 * @see #setRotation(float) 14747 * @see #setRotationY(float) 14748 * @see #setCameraDistance(float) 14749 * 14750 * @attr ref android.R.styleable#View_rotationX 14751 */ 14752 public void setRotationX(float rotationX) { 14753 if (rotationX != getRotationX()) { 14754 invalidateViewProperty(true, false); 14755 mRenderNode.setRotationX(rotationX); 14756 invalidateViewProperty(false, true); 14757 14758 invalidateParentIfNeededAndWasQuickRejected(); 14759 notifySubtreeAccessibilityStateChangedIfNeeded(); 14760 } 14761 } 14762 14763 /** 14764 * The amount that the view is scaled in x around the pivot point, as a proportion of 14765 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 14766 * 14767 * <p>By default, this is 1.0f. 14768 * 14769 * @see #getPivotX() 14770 * @see #getPivotY() 14771 * @return The scaling factor. 14772 */ 14773 @ViewDebug.ExportedProperty(category = "drawing") 14774 public float getScaleX() { 14775 return mRenderNode.getScaleX(); 14776 } 14777 14778 /** 14779 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 14780 * the view's unscaled width. A value of 1 means that no scaling is applied. 14781 * 14782 * @param scaleX The scaling factor. 14783 * @see #getPivotX() 14784 * @see #getPivotY() 14785 * 14786 * @attr ref android.R.styleable#View_scaleX 14787 */ 14788 public void setScaleX(float scaleX) { 14789 if (scaleX != getScaleX()) { 14790 scaleX = sanitizeFloatPropertyValue(scaleX, "scaleX"); 14791 invalidateViewProperty(true, false); 14792 mRenderNode.setScaleX(scaleX); 14793 invalidateViewProperty(false, true); 14794 14795 invalidateParentIfNeededAndWasQuickRejected(); 14796 notifySubtreeAccessibilityStateChangedIfNeeded(); 14797 } 14798 } 14799 14800 /** 14801 * The amount that the view is scaled in y around the pivot point, as a proportion of 14802 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 14803 * 14804 * <p>By default, this is 1.0f. 14805 * 14806 * @see #getPivotX() 14807 * @see #getPivotY() 14808 * @return The scaling factor. 14809 */ 14810 @ViewDebug.ExportedProperty(category = "drawing") 14811 public float getScaleY() { 14812 return mRenderNode.getScaleY(); 14813 } 14814 14815 /** 14816 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 14817 * the view's unscaled width. A value of 1 means that no scaling is applied. 14818 * 14819 * @param scaleY The scaling factor. 14820 * @see #getPivotX() 14821 * @see #getPivotY() 14822 * 14823 * @attr ref android.R.styleable#View_scaleY 14824 */ 14825 public void setScaleY(float scaleY) { 14826 if (scaleY != getScaleY()) { 14827 scaleY = sanitizeFloatPropertyValue(scaleY, "scaleY"); 14828 invalidateViewProperty(true, false); 14829 mRenderNode.setScaleY(scaleY); 14830 invalidateViewProperty(false, true); 14831 14832 invalidateParentIfNeededAndWasQuickRejected(); 14833 notifySubtreeAccessibilityStateChangedIfNeeded(); 14834 } 14835 } 14836 14837 /** 14838 * The x location of the point around which the view is {@link #setRotation(float) rotated} 14839 * and {@link #setScaleX(float) scaled}. 14840 * 14841 * @see #getRotation() 14842 * @see #getScaleX() 14843 * @see #getScaleY() 14844 * @see #getPivotY() 14845 * @return The x location of the pivot point. 14846 * 14847 * @attr ref android.R.styleable#View_transformPivotX 14848 */ 14849 @ViewDebug.ExportedProperty(category = "drawing") 14850 public float getPivotX() { 14851 return mRenderNode.getPivotX(); 14852 } 14853 14854 /** 14855 * Sets the x location of the point around which the view is 14856 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 14857 * By default, the pivot point is centered on the object. 14858 * Setting this property disables this behavior and causes the view to use only the 14859 * explicitly set pivotX and pivotY values. 14860 * 14861 * @param pivotX The x location of the pivot point. 14862 * @see #getRotation() 14863 * @see #getScaleX() 14864 * @see #getScaleY() 14865 * @see #getPivotY() 14866 * 14867 * @attr ref android.R.styleable#View_transformPivotX 14868 */ 14869 public void setPivotX(float pivotX) { 14870 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 14871 invalidateViewProperty(true, false); 14872 mRenderNode.setPivotX(pivotX); 14873 invalidateViewProperty(false, true); 14874 14875 invalidateParentIfNeededAndWasQuickRejected(); 14876 } 14877 } 14878 14879 /** 14880 * The y location of the point around which the view is {@link #setRotation(float) rotated} 14881 * and {@link #setScaleY(float) scaled}. 14882 * 14883 * @see #getRotation() 14884 * @see #getScaleX() 14885 * @see #getScaleY() 14886 * @see #getPivotY() 14887 * @return The y location of the pivot point. 14888 * 14889 * @attr ref android.R.styleable#View_transformPivotY 14890 */ 14891 @ViewDebug.ExportedProperty(category = "drawing") 14892 public float getPivotY() { 14893 return mRenderNode.getPivotY(); 14894 } 14895 14896 /** 14897 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 14898 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 14899 * Setting this property disables this behavior and causes the view to use only the 14900 * explicitly set pivotX and pivotY values. 14901 * 14902 * @param pivotY The y location of the pivot point. 14903 * @see #getRotation() 14904 * @see #getScaleX() 14905 * @see #getScaleY() 14906 * @see #getPivotY() 14907 * 14908 * @attr ref android.R.styleable#View_transformPivotY 14909 */ 14910 public void setPivotY(float pivotY) { 14911 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 14912 invalidateViewProperty(true, false); 14913 mRenderNode.setPivotY(pivotY); 14914 invalidateViewProperty(false, true); 14915 14916 invalidateParentIfNeededAndWasQuickRejected(); 14917 } 14918 } 14919 14920 /** 14921 * Returns whether or not a pivot has been set by a call to {@link #setPivotX(float)} or 14922 * {@link #setPivotY(float)}. If no pivot has been set then the pivot will be the center 14923 * of the view. 14924 * 14925 * @return True if a pivot has been set, false if the default pivot is being used 14926 */ 14927 public boolean isPivotSet() { 14928 return mRenderNode.isPivotExplicitlySet(); 14929 } 14930 14931 /** 14932 * Clears any pivot previously set by a call to {@link #setPivotX(float)} or 14933 * {@link #setPivotY(float)}. After calling this {@link #isPivotSet()} will be false 14934 * and the pivot used for rotation will return to default of being centered on the view. 14935 */ 14936 public void resetPivot() { 14937 if (mRenderNode.resetPivot()) { 14938 invalidateViewProperty(false, false); 14939 } 14940 } 14941 14942 /** 14943 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 14944 * completely transparent and 1 means the view is completely opaque. 14945 * 14946 * <p>By default this is 1.0f. 14947 * @return The opacity of the view. 14948 */ 14949 @ViewDebug.ExportedProperty(category = "drawing") 14950 public float getAlpha() { 14951 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 14952 } 14953 14954 /** 14955 * Sets the behavior for overlapping rendering for this view (see {@link 14956 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 14957 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 14958 * providing the value which is then used internally. That is, when {@link 14959 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 14960 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 14961 * instead. 14962 * 14963 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 14964 * instead of that returned by {@link #hasOverlappingRendering()}. 14965 * 14966 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 14967 */ 14968 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 14969 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 14970 if (hasOverlappingRendering) { 14971 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 14972 } else { 14973 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 14974 } 14975 } 14976 14977 /** 14978 * Returns the value for overlapping rendering that is used internally. This is either 14979 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 14980 * the return value of {@link #hasOverlappingRendering()}, otherwise. 14981 * 14982 * @return The value for overlapping rendering being used internally. 14983 */ 14984 public final boolean getHasOverlappingRendering() { 14985 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 14986 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 14987 hasOverlappingRendering(); 14988 } 14989 14990 /** 14991 * Returns whether this View has content which overlaps. 14992 * 14993 * <p>This function, intended to be overridden by specific View types, is an optimization when 14994 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 14995 * an offscreen buffer and then composited into place, which can be expensive. If the view has 14996 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 14997 * directly. An example of overlapping rendering is a TextView with a background image, such as 14998 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 14999 * ImageView with only the foreground image. The default implementation returns true; subclasses 15000 * should override if they have cases which can be optimized.</p> 15001 * 15002 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 15003 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 15004 * 15005 * @return true if the content in this view might overlap, false otherwise. 15006 */ 15007 @ViewDebug.ExportedProperty(category = "drawing") 15008 public boolean hasOverlappingRendering() { 15009 return true; 15010 } 15011 15012 /** 15013 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 15014 * completely transparent and 1 means the view is completely opaque. 15015 * 15016 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 15017 * can have significant performance implications, especially for large views. It is best to use 15018 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 15019 * 15020 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 15021 * strongly recommended for performance reasons to either override 15022 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 15023 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 15024 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 15025 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 15026 * of rendering cost, even for simple or small views. Starting with 15027 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 15028 * applied to the view at the rendering level.</p> 15029 * 15030 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 15031 * responsible for applying the opacity itself.</p> 15032 * 15033 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 15034 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 15035 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 15036 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 15037 * 15038 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 15039 * value will clip a View to its bounds, unless the View returns <code>false</code> from 15040 * {@link #hasOverlappingRendering}.</p> 15041 * 15042 * @param alpha The opacity of the view. 15043 * 15044 * @see #hasOverlappingRendering() 15045 * @see #setLayerType(int, android.graphics.Paint) 15046 * 15047 * @attr ref android.R.styleable#View_alpha 15048 */ 15049 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 15050 ensureTransformationInfo(); 15051 if (mTransformationInfo.mAlpha != alpha) { 15052 float oldAlpha = mTransformationInfo.mAlpha; 15053 mTransformationInfo.mAlpha = alpha; 15054 if (onSetAlpha((int) (alpha * 255))) { 15055 mPrivateFlags |= PFLAG_ALPHA_SET; 15056 // subclass is handling alpha - don't optimize rendering cache invalidation 15057 invalidateParentCaches(); 15058 invalidate(true); 15059 } else { 15060 mPrivateFlags &= ~PFLAG_ALPHA_SET; 15061 invalidateViewProperty(true, false); 15062 mRenderNode.setAlpha(getFinalAlpha()); 15063 } 15064 // Report visibility changes, which can affect children, to accessibility 15065 if ((alpha == 0) ^ (oldAlpha == 0)) { 15066 notifySubtreeAccessibilityStateChangedIfNeeded(); 15067 } 15068 } 15069 } 15070 15071 /** 15072 * Faster version of setAlpha() which performs the same steps except there are 15073 * no calls to invalidate(). The caller of this function should perform proper invalidation 15074 * on the parent and this object. The return value indicates whether the subclass handles 15075 * alpha (the return value for onSetAlpha()). 15076 * 15077 * @param alpha The new value for the alpha property 15078 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 15079 * the new value for the alpha property is different from the old value 15080 */ 15081 boolean setAlphaNoInvalidation(float alpha) { 15082 ensureTransformationInfo(); 15083 if (mTransformationInfo.mAlpha != alpha) { 15084 mTransformationInfo.mAlpha = alpha; 15085 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 15086 if (subclassHandlesAlpha) { 15087 mPrivateFlags |= PFLAG_ALPHA_SET; 15088 return true; 15089 } else { 15090 mPrivateFlags &= ~PFLAG_ALPHA_SET; 15091 mRenderNode.setAlpha(getFinalAlpha()); 15092 } 15093 } 15094 return false; 15095 } 15096 15097 /** 15098 * This property is hidden and intended only for use by the Fade transition, which 15099 * animates it to produce a visual translucency that does not side-effect (or get 15100 * affected by) the real alpha property. This value is composited with the other 15101 * alpha value (and the AlphaAnimation value, when that is present) to produce 15102 * a final visual translucency result, which is what is passed into the DisplayList. 15103 * 15104 * @hide 15105 */ 15106 public void setTransitionAlpha(float alpha) { 15107 ensureTransformationInfo(); 15108 if (mTransformationInfo.mTransitionAlpha != alpha) { 15109 mTransformationInfo.mTransitionAlpha = alpha; 15110 mPrivateFlags &= ~PFLAG_ALPHA_SET; 15111 invalidateViewProperty(true, false); 15112 mRenderNode.setAlpha(getFinalAlpha()); 15113 } 15114 } 15115 15116 /** 15117 * Calculates the visual alpha of this view, which is a combination of the actual 15118 * alpha value and the transitionAlpha value (if set). 15119 */ 15120 private float getFinalAlpha() { 15121 if (mTransformationInfo != null) { 15122 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 15123 } 15124 return 1; 15125 } 15126 15127 /** 15128 * This property is hidden and intended only for use by the Fade transition, which 15129 * animates it to produce a visual translucency that does not side-effect (or get 15130 * affected by) the real alpha property. This value is composited with the other 15131 * alpha value (and the AlphaAnimation value, when that is present) to produce 15132 * a final visual translucency result, which is what is passed into the DisplayList. 15133 * 15134 * @hide 15135 */ 15136 @ViewDebug.ExportedProperty(category = "drawing") 15137 public float getTransitionAlpha() { 15138 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 15139 } 15140 15141 /** 15142 * Top position of this view relative to its parent. 15143 * 15144 * @return The top of this view, in pixels. 15145 */ 15146 @ViewDebug.CapturedViewProperty 15147 public final int getTop() { 15148 return mTop; 15149 } 15150 15151 /** 15152 * Sets the top position of this view relative to its parent. This method is meant to be called 15153 * by the layout system and should not generally be called otherwise, because the property 15154 * may be changed at any time by the layout. 15155 * 15156 * @param top The top of this view, in pixels. 15157 */ 15158 public final void setTop(int top) { 15159 if (top != mTop) { 15160 final boolean matrixIsIdentity = hasIdentityMatrix(); 15161 if (matrixIsIdentity) { 15162 if (mAttachInfo != null) { 15163 int minTop; 15164 int yLoc; 15165 if (top < mTop) { 15166 minTop = top; 15167 yLoc = top - mTop; 15168 } else { 15169 minTop = mTop; 15170 yLoc = 0; 15171 } 15172 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 15173 } 15174 } else { 15175 // Double-invalidation is necessary to capture view's old and new areas 15176 invalidate(true); 15177 } 15178 15179 int width = mRight - mLeft; 15180 int oldHeight = mBottom - mTop; 15181 15182 mTop = top; 15183 mRenderNode.setTop(mTop); 15184 15185 sizeChange(width, mBottom - mTop, width, oldHeight); 15186 15187 if (!matrixIsIdentity) { 15188 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 15189 invalidate(true); 15190 } 15191 mBackgroundSizeChanged = true; 15192 mDefaultFocusHighlightSizeChanged = true; 15193 if (mForegroundInfo != null) { 15194 mForegroundInfo.mBoundsChanged = true; 15195 } 15196 invalidateParentIfNeeded(); 15197 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 15198 // View was rejected last time it was drawn by its parent; this may have changed 15199 invalidateParentIfNeeded(); 15200 } 15201 } 15202 } 15203 15204 /** 15205 * Bottom position of this view relative to its parent. 15206 * 15207 * @return The bottom of this view, in pixels. 15208 */ 15209 @ViewDebug.CapturedViewProperty 15210 public final int getBottom() { 15211 return mBottom; 15212 } 15213 15214 /** 15215 * True if this view has changed since the last time being drawn. 15216 * 15217 * @return The dirty state of this view. 15218 */ 15219 public boolean isDirty() { 15220 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 15221 } 15222 15223 /** 15224 * Sets the bottom position of this view relative to its parent. This method is meant to be 15225 * called by the layout system and should not generally be called otherwise, because the 15226 * property may be changed at any time by the layout. 15227 * 15228 * @param bottom The bottom of this view, in pixels. 15229 */ 15230 public final void setBottom(int bottom) { 15231 if (bottom != mBottom) { 15232 final boolean matrixIsIdentity = hasIdentityMatrix(); 15233 if (matrixIsIdentity) { 15234 if (mAttachInfo != null) { 15235 int maxBottom; 15236 if (bottom < mBottom) { 15237 maxBottom = mBottom; 15238 } else { 15239 maxBottom = bottom; 15240 } 15241 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 15242 } 15243 } else { 15244 // Double-invalidation is necessary to capture view's old and new areas 15245 invalidate(true); 15246 } 15247 15248 int width = mRight - mLeft; 15249 int oldHeight = mBottom - mTop; 15250 15251 mBottom = bottom; 15252 mRenderNode.setBottom(mBottom); 15253 15254 sizeChange(width, mBottom - mTop, width, oldHeight); 15255 15256 if (!matrixIsIdentity) { 15257 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 15258 invalidate(true); 15259 } 15260 mBackgroundSizeChanged = true; 15261 mDefaultFocusHighlightSizeChanged = true; 15262 if (mForegroundInfo != null) { 15263 mForegroundInfo.mBoundsChanged = true; 15264 } 15265 invalidateParentIfNeeded(); 15266 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 15267 // View was rejected last time it was drawn by its parent; this may have changed 15268 invalidateParentIfNeeded(); 15269 } 15270 } 15271 } 15272 15273 /** 15274 * Left position of this view relative to its parent. 15275 * 15276 * @return The left edge of this view, in pixels. 15277 */ 15278 @ViewDebug.CapturedViewProperty 15279 public final int getLeft() { 15280 return mLeft; 15281 } 15282 15283 /** 15284 * Sets the left position of this view relative to its parent. This method is meant to be called 15285 * by the layout system and should not generally be called otherwise, because the property 15286 * may be changed at any time by the layout. 15287 * 15288 * @param left The left of this view, in pixels. 15289 */ 15290 public final void setLeft(int left) { 15291 if (left != mLeft) { 15292 final boolean matrixIsIdentity = hasIdentityMatrix(); 15293 if (matrixIsIdentity) { 15294 if (mAttachInfo != null) { 15295 int minLeft; 15296 int xLoc; 15297 if (left < mLeft) { 15298 minLeft = left; 15299 xLoc = left - mLeft; 15300 } else { 15301 minLeft = mLeft; 15302 xLoc = 0; 15303 } 15304 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 15305 } 15306 } else { 15307 // Double-invalidation is necessary to capture view's old and new areas 15308 invalidate(true); 15309 } 15310 15311 int oldWidth = mRight - mLeft; 15312 int height = mBottom - mTop; 15313 15314 mLeft = left; 15315 mRenderNode.setLeft(left); 15316 15317 sizeChange(mRight - mLeft, height, oldWidth, height); 15318 15319 if (!matrixIsIdentity) { 15320 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 15321 invalidate(true); 15322 } 15323 mBackgroundSizeChanged = true; 15324 mDefaultFocusHighlightSizeChanged = true; 15325 if (mForegroundInfo != null) { 15326 mForegroundInfo.mBoundsChanged = true; 15327 } 15328 invalidateParentIfNeeded(); 15329 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 15330 // View was rejected last time it was drawn by its parent; this may have changed 15331 invalidateParentIfNeeded(); 15332 } 15333 } 15334 } 15335 15336 /** 15337 * Right position of this view relative to its parent. 15338 * 15339 * @return The right edge of this view, in pixels. 15340 */ 15341 @ViewDebug.CapturedViewProperty 15342 public final int getRight() { 15343 return mRight; 15344 } 15345 15346 /** 15347 * Sets the right position of this view relative to its parent. This method is meant to be called 15348 * by the layout system and should not generally be called otherwise, because the property 15349 * may be changed at any time by the layout. 15350 * 15351 * @param right The right of this view, in pixels. 15352 */ 15353 public final void setRight(int right) { 15354 if (right != mRight) { 15355 final boolean matrixIsIdentity = hasIdentityMatrix(); 15356 if (matrixIsIdentity) { 15357 if (mAttachInfo != null) { 15358 int maxRight; 15359 if (right < mRight) { 15360 maxRight = mRight; 15361 } else { 15362 maxRight = right; 15363 } 15364 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 15365 } 15366 } else { 15367 // Double-invalidation is necessary to capture view's old and new areas 15368 invalidate(true); 15369 } 15370 15371 int oldWidth = mRight - mLeft; 15372 int height = mBottom - mTop; 15373 15374 mRight = right; 15375 mRenderNode.setRight(mRight); 15376 15377 sizeChange(mRight - mLeft, height, oldWidth, height); 15378 15379 if (!matrixIsIdentity) { 15380 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 15381 invalidate(true); 15382 } 15383 mBackgroundSizeChanged = true; 15384 mDefaultFocusHighlightSizeChanged = true; 15385 if (mForegroundInfo != null) { 15386 mForegroundInfo.mBoundsChanged = true; 15387 } 15388 invalidateParentIfNeeded(); 15389 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 15390 // View was rejected last time it was drawn by its parent; this may have changed 15391 invalidateParentIfNeeded(); 15392 } 15393 } 15394 } 15395 15396 private static float sanitizeFloatPropertyValue(float value, String propertyName) { 15397 return sanitizeFloatPropertyValue(value, propertyName, -Float.MAX_VALUE, Float.MAX_VALUE); 15398 } 15399 15400 private static float sanitizeFloatPropertyValue(float value, String propertyName, 15401 float min, float max) { 15402 // The expected "nothing bad happened" path 15403 if (value >= min && value <= max) return value; 15404 15405 if (value < min || value == Float.NEGATIVE_INFINITY) { 15406 if (sThrowOnInvalidFloatProperties) { 15407 throw new IllegalArgumentException("Cannot set '" + propertyName + "' to " 15408 + value + ", the value must be >= " + min); 15409 } 15410 return min; 15411 } 15412 15413 if (value > max || value == Float.POSITIVE_INFINITY) { 15414 if (sThrowOnInvalidFloatProperties) { 15415 throw new IllegalArgumentException("Cannot set '" + propertyName + "' to " 15416 + value + ", the value must be <= " + max); 15417 } 15418 return max; 15419 } 15420 15421 if (Float.isNaN(value)) { 15422 if (sThrowOnInvalidFloatProperties) { 15423 throw new IllegalArgumentException( 15424 "Cannot set '" + propertyName + "' to Float.NaN"); 15425 } 15426 return 0; // Unclear which direction this NaN went so... 0? 15427 } 15428 15429 // Shouldn't be possible to reach this. 15430 throw new IllegalStateException("How do you get here?? " + value); 15431 } 15432 15433 /** 15434 * The visual x position of this view, in pixels. This is equivalent to the 15435 * {@link #setTranslationX(float) translationX} property plus the current 15436 * {@link #getLeft() left} property. 15437 * 15438 * @return The visual x position of this view, in pixels. 15439 */ 15440 @ViewDebug.ExportedProperty(category = "drawing") 15441 public float getX() { 15442 return mLeft + getTranslationX(); 15443 } 15444 15445 /** 15446 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 15447 * {@link #setTranslationX(float) translationX} property to be the difference between 15448 * the x value passed in and the current {@link #getLeft() left} property. 15449 * 15450 * @param x The visual x position of this view, in pixels. 15451 */ 15452 public void setX(float x) { 15453 setTranslationX(x - mLeft); 15454 } 15455 15456 /** 15457 * The visual y position of this view, in pixels. This is equivalent to the 15458 * {@link #setTranslationY(float) translationY} property plus the current 15459 * {@link #getTop() top} property. 15460 * 15461 * @return The visual y position of this view, in pixels. 15462 */ 15463 @ViewDebug.ExportedProperty(category = "drawing") 15464 public float getY() { 15465 return mTop + getTranslationY(); 15466 } 15467 15468 /** 15469 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 15470 * {@link #setTranslationY(float) translationY} property to be the difference between 15471 * the y value passed in and the current {@link #getTop() top} property. 15472 * 15473 * @param y The visual y position of this view, in pixels. 15474 */ 15475 public void setY(float y) { 15476 setTranslationY(y - mTop); 15477 } 15478 15479 /** 15480 * The visual z position of this view, in pixels. This is equivalent to the 15481 * {@link #setTranslationZ(float) translationZ} property plus the current 15482 * {@link #getElevation() elevation} property. 15483 * 15484 * @return The visual z position of this view, in pixels. 15485 */ 15486 @ViewDebug.ExportedProperty(category = "drawing") 15487 public float getZ() { 15488 return getElevation() + getTranslationZ(); 15489 } 15490 15491 /** 15492 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 15493 * {@link #setTranslationZ(float) translationZ} property to be the difference between 15494 * the x value passed in and the current {@link #getElevation() elevation} property. 15495 * 15496 * @param z The visual z position of this view, in pixels. 15497 */ 15498 public void setZ(float z) { 15499 setTranslationZ(z - getElevation()); 15500 } 15501 15502 /** 15503 * The base elevation of this view relative to its parent, in pixels. 15504 * 15505 * @return The base depth position of the view, in pixels. 15506 */ 15507 @ViewDebug.ExportedProperty(category = "drawing") 15508 public float getElevation() { 15509 return mRenderNode.getElevation(); 15510 } 15511 15512 /** 15513 * Sets the base elevation of this view, in pixels. 15514 * 15515 * @attr ref android.R.styleable#View_elevation 15516 */ 15517 public void setElevation(float elevation) { 15518 if (elevation != getElevation()) { 15519 elevation = sanitizeFloatPropertyValue(elevation, "elevation"); 15520 invalidateViewProperty(true, false); 15521 mRenderNode.setElevation(elevation); 15522 invalidateViewProperty(false, true); 15523 15524 invalidateParentIfNeededAndWasQuickRejected(); 15525 } 15526 } 15527 15528 /** 15529 * The horizontal location of this view relative to its {@link #getLeft() left} position. 15530 * This position is post-layout, in addition to wherever the object's 15531 * layout placed it. 15532 * 15533 * @return The horizontal position of this view relative to its left position, in pixels. 15534 */ 15535 @ViewDebug.ExportedProperty(category = "drawing") 15536 public float getTranslationX() { 15537 return mRenderNode.getTranslationX(); 15538 } 15539 15540 /** 15541 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 15542 * This effectively positions the object post-layout, in addition to wherever the object's 15543 * layout placed it. 15544 * 15545 * @param translationX The horizontal position of this view relative to its left position, 15546 * in pixels. 15547 * 15548 * @attr ref android.R.styleable#View_translationX 15549 */ 15550 public void setTranslationX(float translationX) { 15551 if (translationX != getTranslationX()) { 15552 invalidateViewProperty(true, false); 15553 mRenderNode.setTranslationX(translationX); 15554 invalidateViewProperty(false, true); 15555 15556 invalidateParentIfNeededAndWasQuickRejected(); 15557 notifySubtreeAccessibilityStateChangedIfNeeded(); 15558 } 15559 } 15560 15561 /** 15562 * The vertical location of this view relative to its {@link #getTop() top} position. 15563 * This position is post-layout, in addition to wherever the object's 15564 * layout placed it. 15565 * 15566 * @return The vertical position of this view relative to its top position, 15567 * in pixels. 15568 */ 15569 @ViewDebug.ExportedProperty(category = "drawing") 15570 public float getTranslationY() { 15571 return mRenderNode.getTranslationY(); 15572 } 15573 15574 /** 15575 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 15576 * This effectively positions the object post-layout, in addition to wherever the object's 15577 * layout placed it. 15578 * 15579 * @param translationY The vertical position of this view relative to its top position, 15580 * in pixels. 15581 * 15582 * @attr ref android.R.styleable#View_translationY 15583 */ 15584 public void setTranslationY(float translationY) { 15585 if (translationY != getTranslationY()) { 15586 invalidateViewProperty(true, false); 15587 mRenderNode.setTranslationY(translationY); 15588 invalidateViewProperty(false, true); 15589 15590 invalidateParentIfNeededAndWasQuickRejected(); 15591 notifySubtreeAccessibilityStateChangedIfNeeded(); 15592 } 15593 } 15594 15595 /** 15596 * The depth location of this view relative to its {@link #getElevation() elevation}. 15597 * 15598 * @return The depth of this view relative to its elevation. 15599 */ 15600 @ViewDebug.ExportedProperty(category = "drawing") 15601 public float getTranslationZ() { 15602 return mRenderNode.getTranslationZ(); 15603 } 15604 15605 /** 15606 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 15607 * 15608 * @attr ref android.R.styleable#View_translationZ 15609 */ 15610 public void setTranslationZ(float translationZ) { 15611 if (translationZ != getTranslationZ()) { 15612 translationZ = sanitizeFloatPropertyValue(translationZ, "translationZ"); 15613 invalidateViewProperty(true, false); 15614 mRenderNode.setTranslationZ(translationZ); 15615 invalidateViewProperty(false, true); 15616 15617 invalidateParentIfNeededAndWasQuickRejected(); 15618 } 15619 } 15620 15621 /** @hide */ 15622 public void setAnimationMatrix(Matrix matrix) { 15623 invalidateViewProperty(true, false); 15624 mRenderNode.setAnimationMatrix(matrix); 15625 invalidateViewProperty(false, true); 15626 15627 invalidateParentIfNeededAndWasQuickRejected(); 15628 } 15629 15630 /** 15631 * Returns the current StateListAnimator if exists. 15632 * 15633 * @return StateListAnimator or null if it does not exists 15634 * @see #setStateListAnimator(android.animation.StateListAnimator) 15635 */ 15636 public StateListAnimator getStateListAnimator() { 15637 return mStateListAnimator; 15638 } 15639 15640 /** 15641 * Attaches the provided StateListAnimator to this View. 15642 * <p> 15643 * Any previously attached StateListAnimator will be detached. 15644 * 15645 * @param stateListAnimator The StateListAnimator to update the view 15646 * @see android.animation.StateListAnimator 15647 */ 15648 public void setStateListAnimator(StateListAnimator stateListAnimator) { 15649 if (mStateListAnimator == stateListAnimator) { 15650 return; 15651 } 15652 if (mStateListAnimator != null) { 15653 mStateListAnimator.setTarget(null); 15654 } 15655 mStateListAnimator = stateListAnimator; 15656 if (stateListAnimator != null) { 15657 stateListAnimator.setTarget(this); 15658 if (isAttachedToWindow()) { 15659 stateListAnimator.setState(getDrawableState()); 15660 } 15661 } 15662 } 15663 15664 /** 15665 * Returns whether the Outline should be used to clip the contents of the View. 15666 * <p> 15667 * Note that this flag will only be respected if the View's Outline returns true from 15668 * {@link Outline#canClip()}. 15669 * 15670 * @see #setOutlineProvider(ViewOutlineProvider) 15671 * @see #setClipToOutline(boolean) 15672 */ 15673 public final boolean getClipToOutline() { 15674 return mRenderNode.getClipToOutline(); 15675 } 15676 15677 /** 15678 * Sets whether the View's Outline should be used to clip the contents of the View. 15679 * <p> 15680 * Only a single non-rectangular clip can be applied on a View at any time. 15681 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 15682 * circular reveal} animation take priority over Outline clipping, and 15683 * child Outline clipping takes priority over Outline clipping done by a 15684 * parent. 15685 * <p> 15686 * Note that this flag will only be respected if the View's Outline returns true from 15687 * {@link Outline#canClip()}. 15688 * 15689 * @see #setOutlineProvider(ViewOutlineProvider) 15690 * @see #getClipToOutline() 15691 */ 15692 public void setClipToOutline(boolean clipToOutline) { 15693 damageInParent(); 15694 if (getClipToOutline() != clipToOutline) { 15695 mRenderNode.setClipToOutline(clipToOutline); 15696 } 15697 } 15698 15699 // correspond to the enum values of View_outlineProvider 15700 private static final int PROVIDER_BACKGROUND = 0; 15701 private static final int PROVIDER_NONE = 1; 15702 private static final int PROVIDER_BOUNDS = 2; 15703 private static final int PROVIDER_PADDED_BOUNDS = 3; 15704 private void setOutlineProviderFromAttribute(int providerInt) { 15705 switch (providerInt) { 15706 case PROVIDER_BACKGROUND: 15707 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 15708 break; 15709 case PROVIDER_NONE: 15710 setOutlineProvider(null); 15711 break; 15712 case PROVIDER_BOUNDS: 15713 setOutlineProvider(ViewOutlineProvider.BOUNDS); 15714 break; 15715 case PROVIDER_PADDED_BOUNDS: 15716 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 15717 break; 15718 } 15719 } 15720 15721 /** 15722 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 15723 * the shape of the shadow it casts, and enables outline clipping. 15724 * <p> 15725 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 15726 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 15727 * outline provider with this method allows this behavior to be overridden. 15728 * <p> 15729 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 15730 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 15731 * <p> 15732 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 15733 * 15734 * @see #setClipToOutline(boolean) 15735 * @see #getClipToOutline() 15736 * @see #getOutlineProvider() 15737 */ 15738 public void setOutlineProvider(ViewOutlineProvider provider) { 15739 mOutlineProvider = provider; 15740 invalidateOutline(); 15741 } 15742 15743 /** 15744 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 15745 * that defines the shape of the shadow it casts, and enables outline clipping. 15746 * 15747 * @see #setOutlineProvider(ViewOutlineProvider) 15748 */ 15749 public ViewOutlineProvider getOutlineProvider() { 15750 return mOutlineProvider; 15751 } 15752 15753 /** 15754 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 15755 * 15756 * @see #setOutlineProvider(ViewOutlineProvider) 15757 */ 15758 public void invalidateOutline() { 15759 rebuildOutline(); 15760 15761 notifySubtreeAccessibilityStateChangedIfNeeded(); 15762 invalidateViewProperty(false, false); 15763 } 15764 15765 /** 15766 * Internal version of {@link #invalidateOutline()} which invalidates the 15767 * outline without invalidating the view itself. This is intended to be called from 15768 * within methods in the View class itself which are the result of the view being 15769 * invalidated already. For example, when we are drawing the background of a View, 15770 * we invalidate the outline in case it changed in the meantime, but we do not 15771 * need to invalidate the view because we're already drawing the background as part 15772 * of drawing the view in response to an earlier invalidation of the view. 15773 */ 15774 private void rebuildOutline() { 15775 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 15776 if (mAttachInfo == null) return; 15777 15778 if (mOutlineProvider == null) { 15779 // no provider, remove outline 15780 mRenderNode.setOutline(null); 15781 } else { 15782 final Outline outline = mAttachInfo.mTmpOutline; 15783 outline.setEmpty(); 15784 outline.setAlpha(1.0f); 15785 15786 mOutlineProvider.getOutline(this, outline); 15787 mRenderNode.setOutline(outline); 15788 } 15789 } 15790 15791 /** 15792 * HierarchyViewer only 15793 * 15794 * @hide 15795 */ 15796 @ViewDebug.ExportedProperty(category = "drawing") 15797 public boolean hasShadow() { 15798 return mRenderNode.hasShadow(); 15799 } 15800 15801 /** 15802 * Sets the color of the spot shadow that is drawn when the view has a positive Z or 15803 * elevation value. 15804 * <p> 15805 * By default the shadow color is black. Generally, this color will be opaque so the intensity 15806 * of the shadow is consistent between different views with different colors. 15807 * <p> 15808 * The opacity of the final spot shadow is a function of the shadow caster height, the 15809 * alpha channel of the outlineSpotShadowColor (typically opaque), and the 15810 * {@link android.R.attr#spotShadowAlpha} theme attribute. 15811 * 15812 * @attr ref android.R.styleable#View_outlineSpotShadowColor 15813 * @param color The color this View will cast for its elevation spot shadow. 15814 */ 15815 public void setOutlineSpotShadowColor(@ColorInt int color) { 15816 if (mRenderNode.setSpotShadowColor(color)) { 15817 invalidateViewProperty(true, true); 15818 } 15819 } 15820 15821 /** 15822 * @return The shadow color set by {@link #setOutlineSpotShadowColor(int)}, or black if nothing 15823 * was set 15824 */ 15825 public @ColorInt int getOutlineSpotShadowColor() { 15826 return mRenderNode.getSpotShadowColor(); 15827 } 15828 15829 /** 15830 * Sets the color of the ambient shadow that is drawn when the view has a positive Z or 15831 * elevation value. 15832 * <p> 15833 * By default the shadow color is black. Generally, this color will be opaque so the intensity 15834 * of the shadow is consistent between different views with different colors. 15835 * <p> 15836 * The opacity of the final ambient shadow is a function of the shadow caster height, the 15837 * alpha channel of the outlineAmbientShadowColor (typically opaque), and the 15838 * {@link android.R.attr#ambientShadowAlpha} theme attribute. 15839 * 15840 * @attr ref android.R.styleable#View_outlineAmbientShadowColor 15841 * @param color The color this View will cast for its elevation shadow. 15842 */ 15843 public void setOutlineAmbientShadowColor(@ColorInt int color) { 15844 if (mRenderNode.setAmbientShadowColor(color)) { 15845 invalidateViewProperty(true, true); 15846 } 15847 } 15848 15849 /** 15850 * @return The shadow color set by {@link #setOutlineAmbientShadowColor(int)}, or black if 15851 * nothing was set 15852 */ 15853 public @ColorInt int getOutlineAmbientShadowColor() { 15854 return mRenderNode.getAmbientShadowColor(); 15855 } 15856 15857 15858 /** @hide */ 15859 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 15860 mRenderNode.setRevealClip(shouldClip, x, y, radius); 15861 invalidateViewProperty(false, false); 15862 } 15863 15864 /** 15865 * Hit rectangle in parent's coordinates 15866 * 15867 * @param outRect The hit rectangle of the view. 15868 */ 15869 public void getHitRect(Rect outRect) { 15870 if (hasIdentityMatrix() || mAttachInfo == null) { 15871 outRect.set(mLeft, mTop, mRight, mBottom); 15872 } else { 15873 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 15874 tmpRect.set(0, 0, getWidth(), getHeight()); 15875 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 15876 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 15877 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 15878 } 15879 } 15880 15881 /** 15882 * Determines whether the given point, in local coordinates is inside the view. 15883 */ 15884 /*package*/ final boolean pointInView(float localX, float localY) { 15885 return pointInView(localX, localY, 0); 15886 } 15887 15888 /** 15889 * Utility method to determine whether the given point, in local coordinates, 15890 * is inside the view, where the area of the view is expanded by the slop factor. 15891 * This method is called while processing touch-move events to determine if the event 15892 * is still within the view. 15893 * 15894 * @hide 15895 */ 15896 public boolean pointInView(float localX, float localY, float slop) { 15897 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 15898 localY < ((mBottom - mTop) + slop); 15899 } 15900 15901 /** 15902 * When a view has focus and the user navigates away from it, the next view is searched for 15903 * starting from the rectangle filled in by this method. 15904 * 15905 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 15906 * of the view. However, if your view maintains some idea of internal selection, 15907 * such as a cursor, or a selected row or column, you should override this method and 15908 * fill in a more specific rectangle. 15909 * 15910 * @param r The rectangle to fill in, in this view's coordinates. 15911 */ 15912 public void getFocusedRect(Rect r) { 15913 getDrawingRect(r); 15914 } 15915 15916 /** 15917 * If some part of this view is not clipped by any of its parents, then 15918 * return that area in r in global (root) coordinates. To convert r to local 15919 * coordinates (without taking possible View rotations into account), offset 15920 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 15921 * If the view is completely clipped or translated out, return false. 15922 * 15923 * @param r If true is returned, r holds the global coordinates of the 15924 * visible portion of this view. 15925 * @param globalOffset If true is returned, globalOffset holds the dx,dy 15926 * between this view and its root. globalOffet may be null. 15927 * @return true if r is non-empty (i.e. part of the view is visible at the 15928 * root level. 15929 */ 15930 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 15931 int width = mRight - mLeft; 15932 int height = mBottom - mTop; 15933 if (width > 0 && height > 0) { 15934 r.set(0, 0, width, height); 15935 if (globalOffset != null) { 15936 globalOffset.set(-mScrollX, -mScrollY); 15937 } 15938 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 15939 } 15940 return false; 15941 } 15942 15943 public final boolean getGlobalVisibleRect(Rect r) { 15944 return getGlobalVisibleRect(r, null); 15945 } 15946 15947 public final boolean getLocalVisibleRect(Rect r) { 15948 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 15949 if (getGlobalVisibleRect(r, offset)) { 15950 r.offset(-offset.x, -offset.y); // make r local 15951 return true; 15952 } 15953 return false; 15954 } 15955 15956 /** 15957 * Offset this view's vertical location by the specified number of pixels. 15958 * 15959 * @param offset the number of pixels to offset the view by 15960 */ 15961 public void offsetTopAndBottom(int offset) { 15962 if (offset != 0) { 15963 final boolean matrixIsIdentity = hasIdentityMatrix(); 15964 if (matrixIsIdentity) { 15965 if (isHardwareAccelerated()) { 15966 invalidateViewProperty(false, false); 15967 } else { 15968 final ViewParent p = mParent; 15969 if (p != null && mAttachInfo != null) { 15970 final Rect r = mAttachInfo.mTmpInvalRect; 15971 int minTop; 15972 int maxBottom; 15973 int yLoc; 15974 if (offset < 0) { 15975 minTop = mTop + offset; 15976 maxBottom = mBottom; 15977 yLoc = offset; 15978 } else { 15979 minTop = mTop; 15980 maxBottom = mBottom + offset; 15981 yLoc = 0; 15982 } 15983 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 15984 p.invalidateChild(this, r); 15985 } 15986 } 15987 } else { 15988 invalidateViewProperty(false, false); 15989 } 15990 15991 mTop += offset; 15992 mBottom += offset; 15993 mRenderNode.offsetTopAndBottom(offset); 15994 if (isHardwareAccelerated()) { 15995 invalidateViewProperty(false, false); 15996 invalidateParentIfNeededAndWasQuickRejected(); 15997 } else { 15998 if (!matrixIsIdentity) { 15999 invalidateViewProperty(false, true); 16000 } 16001 invalidateParentIfNeeded(); 16002 } 16003 notifySubtreeAccessibilityStateChangedIfNeeded(); 16004 } 16005 } 16006 16007 /** 16008 * Offset this view's horizontal location by the specified amount of pixels. 16009 * 16010 * @param offset the number of pixels to offset the view by 16011 */ 16012 public void offsetLeftAndRight(int offset) { 16013 if (offset != 0) { 16014 final boolean matrixIsIdentity = hasIdentityMatrix(); 16015 if (matrixIsIdentity) { 16016 if (isHardwareAccelerated()) { 16017 invalidateViewProperty(false, false); 16018 } else { 16019 final ViewParent p = mParent; 16020 if (p != null && mAttachInfo != null) { 16021 final Rect r = mAttachInfo.mTmpInvalRect; 16022 int minLeft; 16023 int maxRight; 16024 if (offset < 0) { 16025 minLeft = mLeft + offset; 16026 maxRight = mRight; 16027 } else { 16028 minLeft = mLeft; 16029 maxRight = mRight + offset; 16030 } 16031 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 16032 p.invalidateChild(this, r); 16033 } 16034 } 16035 } else { 16036 invalidateViewProperty(false, false); 16037 } 16038 16039 mLeft += offset; 16040 mRight += offset; 16041 mRenderNode.offsetLeftAndRight(offset); 16042 if (isHardwareAccelerated()) { 16043 invalidateViewProperty(false, false); 16044 invalidateParentIfNeededAndWasQuickRejected(); 16045 } else { 16046 if (!matrixIsIdentity) { 16047 invalidateViewProperty(false, true); 16048 } 16049 invalidateParentIfNeeded(); 16050 } 16051 notifySubtreeAccessibilityStateChangedIfNeeded(); 16052 } 16053 } 16054 16055 /** 16056 * Get the LayoutParams associated with this view. All views should have 16057 * layout parameters. These supply parameters to the <i>parent</i> of this 16058 * view specifying how it should be arranged. There are many subclasses of 16059 * ViewGroup.LayoutParams, and these correspond to the different subclasses 16060 * of ViewGroup that are responsible for arranging their children. 16061 * 16062 * This method may return null if this View is not attached to a parent 16063 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 16064 * was not invoked successfully. When a View is attached to a parent 16065 * ViewGroup, this method must not return null. 16066 * 16067 * @return The LayoutParams associated with this view, or null if no 16068 * parameters have been set yet 16069 */ 16070 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 16071 public ViewGroup.LayoutParams getLayoutParams() { 16072 return mLayoutParams; 16073 } 16074 16075 /** 16076 * Set the layout parameters associated with this view. These supply 16077 * parameters to the <i>parent</i> of this view specifying how it should be 16078 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 16079 * correspond to the different subclasses of ViewGroup that are responsible 16080 * for arranging their children. 16081 * 16082 * @param params The layout parameters for this view, cannot be null 16083 */ 16084 public void setLayoutParams(ViewGroup.LayoutParams params) { 16085 if (params == null) { 16086 throw new NullPointerException("Layout parameters cannot be null"); 16087 } 16088 mLayoutParams = params; 16089 resolveLayoutParams(); 16090 if (mParent instanceof ViewGroup) { 16091 ((ViewGroup) mParent).onSetLayoutParams(this, params); 16092 } 16093 requestLayout(); 16094 } 16095 16096 /** 16097 * Resolve the layout parameters depending on the resolved layout direction 16098 * 16099 * @hide 16100 */ 16101 public void resolveLayoutParams() { 16102 if (mLayoutParams != null) { 16103 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 16104 } 16105 } 16106 16107 /** 16108 * Set the scrolled position of your view. This will cause a call to 16109 * {@link #onScrollChanged(int, int, int, int)} and the view will be 16110 * invalidated. 16111 * @param x the x position to scroll to 16112 * @param y the y position to scroll to 16113 */ 16114 public void scrollTo(int x, int y) { 16115 if (mScrollX != x || mScrollY != y) { 16116 int oldX = mScrollX; 16117 int oldY = mScrollY; 16118 mScrollX = x; 16119 mScrollY = y; 16120 invalidateParentCaches(); 16121 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 16122 if (!awakenScrollBars()) { 16123 postInvalidateOnAnimation(); 16124 } 16125 } 16126 } 16127 16128 /** 16129 * Move the scrolled position of your view. This will cause a call to 16130 * {@link #onScrollChanged(int, int, int, int)} and the view will be 16131 * invalidated. 16132 * @param x the amount of pixels to scroll by horizontally 16133 * @param y the amount of pixels to scroll by vertically 16134 */ 16135 public void scrollBy(int x, int y) { 16136 scrollTo(mScrollX + x, mScrollY + y); 16137 } 16138 16139 /** 16140 * <p>Trigger the scrollbars to draw. When invoked this method starts an 16141 * animation to fade the scrollbars out after a default delay. If a subclass 16142 * provides animated scrolling, the start delay should equal the duration 16143 * of the scrolling animation.</p> 16144 * 16145 * <p>The animation starts only if at least one of the scrollbars is 16146 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 16147 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 16148 * this method returns true, and false otherwise. If the animation is 16149 * started, this method calls {@link #invalidate()}; in that case the 16150 * caller should not call {@link #invalidate()}.</p> 16151 * 16152 * <p>This method should be invoked every time a subclass directly updates 16153 * the scroll parameters.</p> 16154 * 16155 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 16156 * and {@link #scrollTo(int, int)}.</p> 16157 * 16158 * @return true if the animation is played, false otherwise 16159 * 16160 * @see #awakenScrollBars(int) 16161 * @see #scrollBy(int, int) 16162 * @see #scrollTo(int, int) 16163 * @see #isHorizontalScrollBarEnabled() 16164 * @see #isVerticalScrollBarEnabled() 16165 * @see #setHorizontalScrollBarEnabled(boolean) 16166 * @see #setVerticalScrollBarEnabled(boolean) 16167 */ 16168 protected boolean awakenScrollBars() { 16169 return mScrollCache != null && 16170 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 16171 } 16172 16173 /** 16174 * Trigger the scrollbars to draw. 16175 * This method differs from awakenScrollBars() only in its default duration. 16176 * initialAwakenScrollBars() will show the scroll bars for longer than 16177 * usual to give the user more of a chance to notice them. 16178 * 16179 * @return true if the animation is played, false otherwise. 16180 */ 16181 private boolean initialAwakenScrollBars() { 16182 return mScrollCache != null && 16183 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 16184 } 16185 16186 /** 16187 * <p> 16188 * Trigger the scrollbars to draw. When invoked this method starts an 16189 * animation to fade the scrollbars out after a fixed delay. If a subclass 16190 * provides animated scrolling, the start delay should equal the duration of 16191 * the scrolling animation. 16192 * </p> 16193 * 16194 * <p> 16195 * The animation starts only if at least one of the scrollbars is enabled, 16196 * as specified by {@link #isHorizontalScrollBarEnabled()} and 16197 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 16198 * this method returns true, and false otherwise. If the animation is 16199 * started, this method calls {@link #invalidate()}; in that case the caller 16200 * should not call {@link #invalidate()}. 16201 * </p> 16202 * 16203 * <p> 16204 * This method should be invoked every time a subclass directly updates the 16205 * scroll parameters. 16206 * </p> 16207 * 16208 * @param startDelay the delay, in milliseconds, after which the animation 16209 * should start; when the delay is 0, the animation starts 16210 * immediately 16211 * @return true if the animation is played, false otherwise 16212 * 16213 * @see #scrollBy(int, int) 16214 * @see #scrollTo(int, int) 16215 * @see #isHorizontalScrollBarEnabled() 16216 * @see #isVerticalScrollBarEnabled() 16217 * @see #setHorizontalScrollBarEnabled(boolean) 16218 * @see #setVerticalScrollBarEnabled(boolean) 16219 */ 16220 protected boolean awakenScrollBars(int startDelay) { 16221 return awakenScrollBars(startDelay, true); 16222 } 16223 16224 /** 16225 * <p> 16226 * Trigger the scrollbars to draw. When invoked this method starts an 16227 * animation to fade the scrollbars out after a fixed delay. If a subclass 16228 * provides animated scrolling, the start delay should equal the duration of 16229 * the scrolling animation. 16230 * </p> 16231 * 16232 * <p> 16233 * The animation starts only if at least one of the scrollbars is enabled, 16234 * as specified by {@link #isHorizontalScrollBarEnabled()} and 16235 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 16236 * this method returns true, and false otherwise. If the animation is 16237 * started, this method calls {@link #invalidate()} if the invalidate parameter 16238 * is set to true; in that case the caller 16239 * should not call {@link #invalidate()}. 16240 * </p> 16241 * 16242 * <p> 16243 * This method should be invoked every time a subclass directly updates the 16244 * scroll parameters. 16245 * </p> 16246 * 16247 * @param startDelay the delay, in milliseconds, after which the animation 16248 * should start; when the delay is 0, the animation starts 16249 * immediately 16250 * 16251 * @param invalidate Whether this method should call invalidate 16252 * 16253 * @return true if the animation is played, false otherwise 16254 * 16255 * @see #scrollBy(int, int) 16256 * @see #scrollTo(int, int) 16257 * @see #isHorizontalScrollBarEnabled() 16258 * @see #isVerticalScrollBarEnabled() 16259 * @see #setHorizontalScrollBarEnabled(boolean) 16260 * @see #setVerticalScrollBarEnabled(boolean) 16261 */ 16262 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 16263 final ScrollabilityCache scrollCache = mScrollCache; 16264 16265 if (scrollCache == null || !scrollCache.fadeScrollBars) { 16266 return false; 16267 } 16268 16269 if (scrollCache.scrollBar == null) { 16270 scrollCache.scrollBar = new ScrollBarDrawable(); 16271 scrollCache.scrollBar.setState(getDrawableState()); 16272 scrollCache.scrollBar.setCallback(this); 16273 } 16274 16275 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 16276 16277 if (invalidate) { 16278 // Invalidate to show the scrollbars 16279 postInvalidateOnAnimation(); 16280 } 16281 16282 if (scrollCache.state == ScrollabilityCache.OFF) { 16283 // FIXME: this is copied from WindowManagerService. 16284 // We should get this value from the system when it 16285 // is possible to do so. 16286 final int KEY_REPEAT_FIRST_DELAY = 750; 16287 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 16288 } 16289 16290 // Tell mScrollCache when we should start fading. This may 16291 // extend the fade start time if one was already scheduled 16292 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 16293 scrollCache.fadeStartTime = fadeStartTime; 16294 scrollCache.state = ScrollabilityCache.ON; 16295 16296 // Schedule our fader to run, unscheduling any old ones first 16297 if (mAttachInfo != null) { 16298 mAttachInfo.mHandler.removeCallbacks(scrollCache); 16299 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 16300 } 16301 16302 return true; 16303 } 16304 16305 return false; 16306 } 16307 16308 /** 16309 * Do not invalidate views which are not visible and which are not running an animation. They 16310 * will not get drawn and they should not set dirty flags as if they will be drawn 16311 */ 16312 private boolean skipInvalidate() { 16313 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 16314 (!(mParent instanceof ViewGroup) || 16315 !((ViewGroup) mParent).isViewTransitioning(this)); 16316 } 16317 16318 /** 16319 * Mark the area defined by dirty as needing to be drawn. If the view is 16320 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 16321 * point in the future. 16322 * <p> 16323 * This must be called from a UI thread. To call from a non-UI thread, call 16324 * {@link #postInvalidate()}. 16325 * <p> 16326 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 16327 * {@code dirty}. 16328 * 16329 * @param dirty the rectangle representing the bounds of the dirty region 16330 * 16331 * @deprecated The switch to hardware accelerated rendering in API 14 reduced 16332 * the importance of the dirty rectangle. In API 21 the given rectangle is 16333 * ignored entirely in favor of an internally-calculated area instead. 16334 * Because of this, clients are encouraged to just call {@link #invalidate()}. 16335 */ 16336 @Deprecated 16337 public void invalidate(Rect dirty) { 16338 final int scrollX = mScrollX; 16339 final int scrollY = mScrollY; 16340 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 16341 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 16342 } 16343 16344 /** 16345 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 16346 * coordinates of the dirty rect are relative to the view. If the view is 16347 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 16348 * point in the future. 16349 * <p> 16350 * This must be called from a UI thread. To call from a non-UI thread, call 16351 * {@link #postInvalidate()}. 16352 * 16353 * @param l the left position of the dirty region 16354 * @param t the top position of the dirty region 16355 * @param r the right position of the dirty region 16356 * @param b the bottom position of the dirty region 16357 * 16358 * @deprecated The switch to hardware accelerated rendering in API 14 reduced 16359 * the importance of the dirty rectangle. In API 21 the given rectangle is 16360 * ignored entirely in favor of an internally-calculated area instead. 16361 * Because of this, clients are encouraged to just call {@link #invalidate()}. 16362 */ 16363 @Deprecated 16364 public void invalidate(int l, int t, int r, int b) { 16365 final int scrollX = mScrollX; 16366 final int scrollY = mScrollY; 16367 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 16368 } 16369 16370 /** 16371 * Invalidate the whole view. If the view is visible, 16372 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 16373 * the future. 16374 * <p> 16375 * This must be called from a UI thread. To call from a non-UI thread, call 16376 * {@link #postInvalidate()}. 16377 */ 16378 public void invalidate() { 16379 invalidate(true); 16380 } 16381 16382 /** 16383 * This is where the invalidate() work actually happens. A full invalidate() 16384 * causes the drawing cache to be invalidated, but this function can be 16385 * called with invalidateCache set to false to skip that invalidation step 16386 * for cases that do not need it (for example, a component that remains at 16387 * the same dimensions with the same content). 16388 * 16389 * @param invalidateCache Whether the drawing cache for this view should be 16390 * invalidated as well. This is usually true for a full 16391 * invalidate, but may be set to false if the View's contents or 16392 * dimensions have not changed. 16393 * @hide 16394 */ 16395 public void invalidate(boolean invalidateCache) { 16396 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 16397 } 16398 16399 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 16400 boolean fullInvalidate) { 16401 if (mGhostView != null) { 16402 mGhostView.invalidate(true); 16403 return; 16404 } 16405 16406 if (skipInvalidate()) { 16407 return; 16408 } 16409 16410 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 16411 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 16412 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 16413 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 16414 if (fullInvalidate) { 16415 mLastIsOpaque = isOpaque(); 16416 mPrivateFlags &= ~PFLAG_DRAWN; 16417 } 16418 16419 mPrivateFlags |= PFLAG_DIRTY; 16420 16421 if (invalidateCache) { 16422 mPrivateFlags |= PFLAG_INVALIDATED; 16423 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 16424 } 16425 16426 // Propagate the damage rectangle to the parent view. 16427 final AttachInfo ai = mAttachInfo; 16428 final ViewParent p = mParent; 16429 if (p != null && ai != null && l < r && t < b) { 16430 final Rect damage = ai.mTmpInvalRect; 16431 damage.set(l, t, r, b); 16432 p.invalidateChild(this, damage); 16433 } 16434 16435 // Damage the entire projection receiver, if necessary. 16436 if (mBackground != null && mBackground.isProjected()) { 16437 final View receiver = getProjectionReceiver(); 16438 if (receiver != null) { 16439 receiver.damageInParent(); 16440 } 16441 } 16442 } 16443 } 16444 16445 /** 16446 * @return this view's projection receiver, or {@code null} if none exists 16447 */ 16448 private View getProjectionReceiver() { 16449 ViewParent p = getParent(); 16450 while (p != null && p instanceof View) { 16451 final View v = (View) p; 16452 if (v.isProjectionReceiver()) { 16453 return v; 16454 } 16455 p = p.getParent(); 16456 } 16457 16458 return null; 16459 } 16460 16461 /** 16462 * @return whether the view is a projection receiver 16463 */ 16464 private boolean isProjectionReceiver() { 16465 return mBackground != null; 16466 } 16467 16468 /** 16469 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 16470 * set any flags or handle all of the cases handled by the default invalidation methods. 16471 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 16472 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 16473 * walk up the hierarchy, transforming the dirty rect as necessary. 16474 * 16475 * The method also handles normal invalidation logic if display list properties are not 16476 * being used in this view. The invalidateParent and forceRedraw flags are used by that 16477 * backup approach, to handle these cases used in the various property-setting methods. 16478 * 16479 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 16480 * are not being used in this view 16481 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 16482 * list properties are not being used in this view 16483 */ 16484 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 16485 if (!isHardwareAccelerated() 16486 || !mRenderNode.isValid() 16487 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 16488 if (invalidateParent) { 16489 invalidateParentCaches(); 16490 } 16491 if (forceRedraw) { 16492 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 16493 } 16494 invalidate(false); 16495 } else { 16496 damageInParent(); 16497 } 16498 } 16499 16500 /** 16501 * Tells the parent view to damage this view's bounds. 16502 * 16503 * @hide 16504 */ 16505 protected void damageInParent() { 16506 if (mParent != null && mAttachInfo != null) { 16507 mParent.onDescendantInvalidated(this, this); 16508 } 16509 } 16510 16511 /** 16512 * Utility method to transform a given Rect by the current matrix of this view. 16513 */ 16514 void transformRect(final Rect rect) { 16515 if (!getMatrix().isIdentity()) { 16516 RectF boundingRect = mAttachInfo.mTmpTransformRect; 16517 boundingRect.set(rect); 16518 getMatrix().mapRect(boundingRect); 16519 rect.set((int) Math.floor(boundingRect.left), 16520 (int) Math.floor(boundingRect.top), 16521 (int) Math.ceil(boundingRect.right), 16522 (int) Math.ceil(boundingRect.bottom)); 16523 } 16524 } 16525 16526 /** 16527 * Used to indicate that the parent of this view should clear its caches. This functionality 16528 * is used to force the parent to rebuild its display list (when hardware-accelerated), 16529 * which is necessary when various parent-managed properties of the view change, such as 16530 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 16531 * clears the parent caches and does not causes an invalidate event. 16532 * 16533 * @hide 16534 */ 16535 protected void invalidateParentCaches() { 16536 if (mParent instanceof View) { 16537 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 16538 } 16539 } 16540 16541 /** 16542 * Used to indicate that the parent of this view should be invalidated. This functionality 16543 * is used to force the parent to rebuild its display list (when hardware-accelerated), 16544 * which is necessary when various parent-managed properties of the view change, such as 16545 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 16546 * an invalidation event to the parent. 16547 * 16548 * @hide 16549 */ 16550 protected void invalidateParentIfNeeded() { 16551 if (isHardwareAccelerated() && mParent instanceof View) { 16552 ((View) mParent).invalidate(true); 16553 } 16554 } 16555 16556 /** 16557 * @hide 16558 */ 16559 protected void invalidateParentIfNeededAndWasQuickRejected() { 16560 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 16561 // View was rejected last time it was drawn by its parent; this may have changed 16562 invalidateParentIfNeeded(); 16563 } 16564 } 16565 16566 /** 16567 * Indicates whether this View is opaque. An opaque View guarantees that it will 16568 * draw all the pixels overlapping its bounds using a fully opaque color. 16569 * 16570 * Subclasses of View should override this method whenever possible to indicate 16571 * whether an instance is opaque. Opaque Views are treated in a special way by 16572 * the View hierarchy, possibly allowing it to perform optimizations during 16573 * invalidate/draw passes. 16574 * 16575 * @return True if this View is guaranteed to be fully opaque, false otherwise. 16576 */ 16577 @ViewDebug.ExportedProperty(category = "drawing") 16578 public boolean isOpaque() { 16579 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 16580 getFinalAlpha() >= 1.0f; 16581 } 16582 16583 /** 16584 * @hide 16585 */ 16586 protected void computeOpaqueFlags() { 16587 // Opaque if: 16588 // - Has a background 16589 // - Background is opaque 16590 // - Doesn't have scrollbars or scrollbars overlay 16591 16592 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 16593 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 16594 } else { 16595 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 16596 } 16597 16598 final int flags = mViewFlags; 16599 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 16600 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 16601 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 16602 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 16603 } else { 16604 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 16605 } 16606 } 16607 16608 /** 16609 * @hide 16610 */ 16611 protected boolean hasOpaqueScrollbars() { 16612 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 16613 } 16614 16615 /** 16616 * @return A handler associated with the thread running the View. This 16617 * handler can be used to pump events in the UI events queue. 16618 */ 16619 public Handler getHandler() { 16620 final AttachInfo attachInfo = mAttachInfo; 16621 if (attachInfo != null) { 16622 return attachInfo.mHandler; 16623 } 16624 return null; 16625 } 16626 16627 /** 16628 * Returns the queue of runnable for this view. 16629 * 16630 * @return the queue of runnables for this view 16631 */ 16632 private HandlerActionQueue getRunQueue() { 16633 if (mRunQueue == null) { 16634 mRunQueue = new HandlerActionQueue(); 16635 } 16636 return mRunQueue; 16637 } 16638 16639 /** 16640 * Gets the view root associated with the View. 16641 * @return The view root, or null if none. 16642 * @hide 16643 */ 16644 public ViewRootImpl getViewRootImpl() { 16645 if (mAttachInfo != null) { 16646 return mAttachInfo.mViewRootImpl; 16647 } 16648 return null; 16649 } 16650 16651 /** 16652 * @hide 16653 */ 16654 public ThreadedRenderer getThreadedRenderer() { 16655 return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null; 16656 } 16657 16658 /** 16659 * <p>Causes the Runnable to be added to the message queue. 16660 * The runnable will be run on the user interface thread.</p> 16661 * 16662 * @param action The Runnable that will be executed. 16663 * 16664 * @return Returns true if the Runnable was successfully placed in to the 16665 * message queue. Returns false on failure, usually because the 16666 * looper processing the message queue is exiting. 16667 * 16668 * @see #postDelayed 16669 * @see #removeCallbacks 16670 */ 16671 public boolean post(Runnable action) { 16672 final AttachInfo attachInfo = mAttachInfo; 16673 if (attachInfo != null) { 16674 return attachInfo.mHandler.post(action); 16675 } 16676 16677 // Postpone the runnable until we know on which thread it needs to run. 16678 // Assume that the runnable will be successfully placed after attach. 16679 getRunQueue().post(action); 16680 return true; 16681 } 16682 16683 /** 16684 * <p>Causes the Runnable to be added to the message queue, to be run 16685 * after the specified amount of time elapses. 16686 * The runnable will be run on the user interface thread.</p> 16687 * 16688 * @param action The Runnable that will be executed. 16689 * @param delayMillis The delay (in milliseconds) until the Runnable 16690 * will be executed. 16691 * 16692 * @return true if the Runnable was successfully placed in to the 16693 * message queue. Returns false on failure, usually because the 16694 * looper processing the message queue is exiting. Note that a 16695 * result of true does not mean the Runnable will be processed -- 16696 * if the looper is quit before the delivery time of the message 16697 * occurs then the message will be dropped. 16698 * 16699 * @see #post 16700 * @see #removeCallbacks 16701 */ 16702 public boolean postDelayed(Runnable action, long delayMillis) { 16703 final AttachInfo attachInfo = mAttachInfo; 16704 if (attachInfo != null) { 16705 return attachInfo.mHandler.postDelayed(action, delayMillis); 16706 } 16707 16708 // Postpone the runnable until we know on which thread it needs to run. 16709 // Assume that the runnable will be successfully placed after attach. 16710 getRunQueue().postDelayed(action, delayMillis); 16711 return true; 16712 } 16713 16714 /** 16715 * <p>Causes the Runnable to execute on the next animation time step. 16716 * The runnable will be run on the user interface thread.</p> 16717 * 16718 * @param action The Runnable that will be executed. 16719 * 16720 * @see #postOnAnimationDelayed 16721 * @see #removeCallbacks 16722 */ 16723 public void postOnAnimation(Runnable action) { 16724 final AttachInfo attachInfo = mAttachInfo; 16725 if (attachInfo != null) { 16726 attachInfo.mViewRootImpl.mChoreographer.postCallback( 16727 Choreographer.CALLBACK_ANIMATION, action, null); 16728 } else { 16729 // Postpone the runnable until we know 16730 // on which thread it needs to run. 16731 getRunQueue().post(action); 16732 } 16733 } 16734 16735 /** 16736 * <p>Causes the Runnable to execute on the next animation time step, 16737 * after the specified amount of time elapses. 16738 * The runnable will be run on the user interface thread.</p> 16739 * 16740 * @param action The Runnable that will be executed. 16741 * @param delayMillis The delay (in milliseconds) until the Runnable 16742 * will be executed. 16743 * 16744 * @see #postOnAnimation 16745 * @see #removeCallbacks 16746 */ 16747 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 16748 final AttachInfo attachInfo = mAttachInfo; 16749 if (attachInfo != null) { 16750 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 16751 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 16752 } else { 16753 // Postpone the runnable until we know 16754 // on which thread it needs to run. 16755 getRunQueue().postDelayed(action, delayMillis); 16756 } 16757 } 16758 16759 /** 16760 * <p>Removes the specified Runnable from the message queue.</p> 16761 * 16762 * @param action The Runnable to remove from the message handling queue 16763 * 16764 * @return true if this view could ask the Handler to remove the Runnable, 16765 * false otherwise. When the returned value is true, the Runnable 16766 * may or may not have been actually removed from the message queue 16767 * (for instance, if the Runnable was not in the queue already.) 16768 * 16769 * @see #post 16770 * @see #postDelayed 16771 * @see #postOnAnimation 16772 * @see #postOnAnimationDelayed 16773 */ 16774 public boolean removeCallbacks(Runnable action) { 16775 if (action != null) { 16776 final AttachInfo attachInfo = mAttachInfo; 16777 if (attachInfo != null) { 16778 attachInfo.mHandler.removeCallbacks(action); 16779 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 16780 Choreographer.CALLBACK_ANIMATION, action, null); 16781 } 16782 getRunQueue().removeCallbacks(action); 16783 } 16784 return true; 16785 } 16786 16787 /** 16788 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 16789 * Use this to invalidate the View from a non-UI thread.</p> 16790 * 16791 * <p>This method can be invoked from outside of the UI thread 16792 * only when this View is attached to a window.</p> 16793 * 16794 * @see #invalidate() 16795 * @see #postInvalidateDelayed(long) 16796 */ 16797 public void postInvalidate() { 16798 postInvalidateDelayed(0); 16799 } 16800 16801 /** 16802 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 16803 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 16804 * 16805 * <p>This method can be invoked from outside of the UI thread 16806 * only when this View is attached to a window.</p> 16807 * 16808 * @param left The left coordinate of the rectangle to invalidate. 16809 * @param top The top coordinate of the rectangle to invalidate. 16810 * @param right The right coordinate of the rectangle to invalidate. 16811 * @param bottom The bottom coordinate of the rectangle to invalidate. 16812 * 16813 * @see #invalidate(int, int, int, int) 16814 * @see #invalidate(Rect) 16815 * @see #postInvalidateDelayed(long, int, int, int, int) 16816 */ 16817 public void postInvalidate(int left, int top, int right, int bottom) { 16818 postInvalidateDelayed(0, left, top, right, bottom); 16819 } 16820 16821 /** 16822 * <p>Cause an invalidate to happen on a subsequent cycle through the event 16823 * loop. Waits for the specified amount of time.</p> 16824 * 16825 * <p>This method can be invoked from outside of the UI thread 16826 * only when this View is attached to a window.</p> 16827 * 16828 * @param delayMilliseconds the duration in milliseconds to delay the 16829 * invalidation by 16830 * 16831 * @see #invalidate() 16832 * @see #postInvalidate() 16833 */ 16834 public void postInvalidateDelayed(long delayMilliseconds) { 16835 // We try only with the AttachInfo because there's no point in invalidating 16836 // if we are not attached to our window 16837 final AttachInfo attachInfo = mAttachInfo; 16838 if (attachInfo != null) { 16839 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 16840 } 16841 } 16842 16843 /** 16844 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 16845 * through the event loop. Waits for the specified amount of time.</p> 16846 * 16847 * <p>This method can be invoked from outside of the UI thread 16848 * only when this View is attached to a window.</p> 16849 * 16850 * @param delayMilliseconds the duration in milliseconds to delay the 16851 * invalidation by 16852 * @param left The left coordinate of the rectangle to invalidate. 16853 * @param top The top coordinate of the rectangle to invalidate. 16854 * @param right The right coordinate of the rectangle to invalidate. 16855 * @param bottom The bottom coordinate of the rectangle to invalidate. 16856 * 16857 * @see #invalidate(int, int, int, int) 16858 * @see #invalidate(Rect) 16859 * @see #postInvalidate(int, int, int, int) 16860 */ 16861 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 16862 int right, int bottom) { 16863 16864 // We try only with the AttachInfo because there's no point in invalidating 16865 // if we are not attached to our window 16866 final AttachInfo attachInfo = mAttachInfo; 16867 if (attachInfo != null) { 16868 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 16869 info.target = this; 16870 info.left = left; 16871 info.top = top; 16872 info.right = right; 16873 info.bottom = bottom; 16874 16875 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 16876 } 16877 } 16878 16879 /** 16880 * <p>Cause an invalidate to happen on the next animation time step, typically the 16881 * next display frame.</p> 16882 * 16883 * <p>This method can be invoked from outside of the UI thread 16884 * only when this View is attached to a window.</p> 16885 * 16886 * @see #invalidate() 16887 */ 16888 public void postInvalidateOnAnimation() { 16889 // We try only with the AttachInfo because there's no point in invalidating 16890 // if we are not attached to our window 16891 final AttachInfo attachInfo = mAttachInfo; 16892 if (attachInfo != null) { 16893 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 16894 } 16895 } 16896 16897 /** 16898 * <p>Cause an invalidate of the specified area to happen on the next animation 16899 * time step, typically the next display frame.</p> 16900 * 16901 * <p>This method can be invoked from outside of the UI thread 16902 * only when this View is attached to a window.</p> 16903 * 16904 * @param left The left coordinate of the rectangle to invalidate. 16905 * @param top The top coordinate of the rectangle to invalidate. 16906 * @param right The right coordinate of the rectangle to invalidate. 16907 * @param bottom The bottom coordinate of the rectangle to invalidate. 16908 * 16909 * @see #invalidate(int, int, int, int) 16910 * @see #invalidate(Rect) 16911 */ 16912 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 16913 // We try only with the AttachInfo because there's no point in invalidating 16914 // if we are not attached to our window 16915 final AttachInfo attachInfo = mAttachInfo; 16916 if (attachInfo != null) { 16917 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 16918 info.target = this; 16919 info.left = left; 16920 info.top = top; 16921 info.right = right; 16922 info.bottom = bottom; 16923 16924 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 16925 } 16926 } 16927 16928 /** 16929 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 16930 * This event is sent at most once every 16931 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 16932 */ 16933 private void postSendViewScrolledAccessibilityEventCallback(int dx, int dy) { 16934 if (mSendViewScrolledAccessibilityEvent == null) { 16935 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 16936 } 16937 mSendViewScrolledAccessibilityEvent.post(dx, dy); 16938 } 16939 16940 /** 16941 * Called by a parent to request that a child update its values for mScrollX 16942 * and mScrollY if necessary. This will typically be done if the child is 16943 * animating a scroll using a {@link android.widget.Scroller Scroller} 16944 * object. 16945 */ 16946 public void computeScroll() { 16947 } 16948 16949 /** 16950 * <p>Indicate whether the horizontal edges are faded when the view is 16951 * scrolled horizontally.</p> 16952 * 16953 * @return true if the horizontal edges should are faded on scroll, false 16954 * otherwise 16955 * 16956 * @see #setHorizontalFadingEdgeEnabled(boolean) 16957 * 16958 * @attr ref android.R.styleable#View_requiresFadingEdge 16959 */ 16960 public boolean isHorizontalFadingEdgeEnabled() { 16961 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 16962 } 16963 16964 /** 16965 * <p>Define whether the horizontal edges should be faded when this view 16966 * is scrolled horizontally.</p> 16967 * 16968 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 16969 * be faded when the view is scrolled 16970 * horizontally 16971 * 16972 * @see #isHorizontalFadingEdgeEnabled() 16973 * 16974 * @attr ref android.R.styleable#View_requiresFadingEdge 16975 */ 16976 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 16977 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 16978 if (horizontalFadingEdgeEnabled) { 16979 initScrollCache(); 16980 } 16981 16982 mViewFlags ^= FADING_EDGE_HORIZONTAL; 16983 } 16984 } 16985 16986 /** 16987 * <p>Indicate whether the vertical edges are faded when the view is 16988 * scrolled horizontally.</p> 16989 * 16990 * @return true if the vertical edges should are faded on scroll, false 16991 * otherwise 16992 * 16993 * @see #setVerticalFadingEdgeEnabled(boolean) 16994 * 16995 * @attr ref android.R.styleable#View_requiresFadingEdge 16996 */ 16997 public boolean isVerticalFadingEdgeEnabled() { 16998 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 16999 } 17000 17001 /** 17002 * <p>Define whether the vertical edges should be faded when this view 17003 * is scrolled vertically.</p> 17004 * 17005 * @param verticalFadingEdgeEnabled true if the vertical edges should 17006 * be faded when the view is scrolled 17007 * vertically 17008 * 17009 * @see #isVerticalFadingEdgeEnabled() 17010 * 17011 * @attr ref android.R.styleable#View_requiresFadingEdge 17012 */ 17013 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 17014 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 17015 if (verticalFadingEdgeEnabled) { 17016 initScrollCache(); 17017 } 17018 17019 mViewFlags ^= FADING_EDGE_VERTICAL; 17020 } 17021 } 17022 17023 /** 17024 * Returns the strength, or intensity, of the top faded edge. The strength is 17025 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 17026 * returns 0.0 or 1.0 but no value in between. 17027 * 17028 * Subclasses should override this method to provide a smoother fade transition 17029 * when scrolling occurs. 17030 * 17031 * @return the intensity of the top fade as a float between 0.0f and 1.0f 17032 */ 17033 protected float getTopFadingEdgeStrength() { 17034 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 17035 } 17036 17037 /** 17038 * Returns the strength, or intensity, of the bottom faded edge. The strength is 17039 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 17040 * returns 0.0 or 1.0 but no value in between. 17041 * 17042 * Subclasses should override this method to provide a smoother fade transition 17043 * when scrolling occurs. 17044 * 17045 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 17046 */ 17047 protected float getBottomFadingEdgeStrength() { 17048 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 17049 computeVerticalScrollRange() ? 1.0f : 0.0f; 17050 } 17051 17052 /** 17053 * Returns the strength, or intensity, of the left faded edge. The strength is 17054 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 17055 * returns 0.0 or 1.0 but no value in between. 17056 * 17057 * Subclasses should override this method to provide a smoother fade transition 17058 * when scrolling occurs. 17059 * 17060 * @return the intensity of the left fade as a float between 0.0f and 1.0f 17061 */ 17062 protected float getLeftFadingEdgeStrength() { 17063 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 17064 } 17065 17066 /** 17067 * Returns the strength, or intensity, of the right faded edge. The strength is 17068 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 17069 * returns 0.0 or 1.0 but no value in between. 17070 * 17071 * Subclasses should override this method to provide a smoother fade transition 17072 * when scrolling occurs. 17073 * 17074 * @return the intensity of the right fade as a float between 0.0f and 1.0f 17075 */ 17076 protected float getRightFadingEdgeStrength() { 17077 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 17078 computeHorizontalScrollRange() ? 1.0f : 0.0f; 17079 } 17080 17081 /** 17082 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 17083 * scrollbar is not drawn by default.</p> 17084 * 17085 * @return true if the horizontal scrollbar should be painted, false 17086 * otherwise 17087 * 17088 * @see #setHorizontalScrollBarEnabled(boolean) 17089 */ 17090 public boolean isHorizontalScrollBarEnabled() { 17091 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 17092 } 17093 17094 /** 17095 * <p>Define whether the horizontal scrollbar should be drawn or not. The 17096 * scrollbar is not drawn by default.</p> 17097 * 17098 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 17099 * be painted 17100 * 17101 * @see #isHorizontalScrollBarEnabled() 17102 */ 17103 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 17104 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 17105 mViewFlags ^= SCROLLBARS_HORIZONTAL; 17106 computeOpaqueFlags(); 17107 resolvePadding(); 17108 } 17109 } 17110 17111 /** 17112 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 17113 * scrollbar is not drawn by default.</p> 17114 * 17115 * @return true if the vertical scrollbar should be painted, false 17116 * otherwise 17117 * 17118 * @see #setVerticalScrollBarEnabled(boolean) 17119 */ 17120 public boolean isVerticalScrollBarEnabled() { 17121 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 17122 } 17123 17124 /** 17125 * <p>Define whether the vertical scrollbar should be drawn or not. The 17126 * scrollbar is not drawn by default.</p> 17127 * 17128 * @param verticalScrollBarEnabled true if the vertical scrollbar should 17129 * be painted 17130 * 17131 * @see #isVerticalScrollBarEnabled() 17132 */ 17133 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 17134 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 17135 mViewFlags ^= SCROLLBARS_VERTICAL; 17136 computeOpaqueFlags(); 17137 resolvePadding(); 17138 } 17139 } 17140 17141 /** 17142 * @hide 17143 */ 17144 protected void recomputePadding() { 17145 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 17146 } 17147 17148 /** 17149 * Define whether scrollbars will fade when the view is not scrolling. 17150 * 17151 * @param fadeScrollbars whether to enable fading 17152 * 17153 * @attr ref android.R.styleable#View_fadeScrollbars 17154 */ 17155 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 17156 initScrollCache(); 17157 final ScrollabilityCache scrollabilityCache = mScrollCache; 17158 scrollabilityCache.fadeScrollBars = fadeScrollbars; 17159 if (fadeScrollbars) { 17160 scrollabilityCache.state = ScrollabilityCache.OFF; 17161 } else { 17162 scrollabilityCache.state = ScrollabilityCache.ON; 17163 } 17164 } 17165 17166 /** 17167 * 17168 * Returns true if scrollbars will fade when this view is not scrolling 17169 * 17170 * @return true if scrollbar fading is enabled 17171 * 17172 * @attr ref android.R.styleable#View_fadeScrollbars 17173 */ 17174 public boolean isScrollbarFadingEnabled() { 17175 return mScrollCache != null && mScrollCache.fadeScrollBars; 17176 } 17177 17178 /** 17179 * 17180 * Returns the delay before scrollbars fade. 17181 * 17182 * @return the delay before scrollbars fade 17183 * 17184 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 17185 */ 17186 public int getScrollBarDefaultDelayBeforeFade() { 17187 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 17188 mScrollCache.scrollBarDefaultDelayBeforeFade; 17189 } 17190 17191 /** 17192 * Define the delay before scrollbars fade. 17193 * 17194 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 17195 * 17196 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 17197 */ 17198 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 17199 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 17200 } 17201 17202 /** 17203 * 17204 * Returns the scrollbar fade duration. 17205 * 17206 * @return the scrollbar fade duration, in milliseconds 17207 * 17208 * @attr ref android.R.styleable#View_scrollbarFadeDuration 17209 */ 17210 public int getScrollBarFadeDuration() { 17211 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 17212 mScrollCache.scrollBarFadeDuration; 17213 } 17214 17215 /** 17216 * Define the scrollbar fade duration. 17217 * 17218 * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds 17219 * 17220 * @attr ref android.R.styleable#View_scrollbarFadeDuration 17221 */ 17222 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 17223 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 17224 } 17225 17226 /** 17227 * 17228 * Returns the scrollbar size. 17229 * 17230 * @return the scrollbar size 17231 * 17232 * @attr ref android.R.styleable#View_scrollbarSize 17233 */ 17234 public int getScrollBarSize() { 17235 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 17236 mScrollCache.scrollBarSize; 17237 } 17238 17239 /** 17240 * Define the scrollbar size. 17241 * 17242 * @param scrollBarSize - the scrollbar size 17243 * 17244 * @attr ref android.R.styleable#View_scrollbarSize 17245 */ 17246 public void setScrollBarSize(int scrollBarSize) { 17247 getScrollCache().scrollBarSize = scrollBarSize; 17248 } 17249 17250 /** 17251 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 17252 * inset. When inset, they add to the padding of the view. And the scrollbars 17253 * can be drawn inside the padding area or on the edge of the view. For example, 17254 * if a view has a background drawable and you want to draw the scrollbars 17255 * inside the padding specified by the drawable, you can use 17256 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 17257 * appear at the edge of the view, ignoring the padding, then you can use 17258 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 17259 * @param style the style of the scrollbars. Should be one of 17260 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 17261 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 17262 * @see #SCROLLBARS_INSIDE_OVERLAY 17263 * @see #SCROLLBARS_INSIDE_INSET 17264 * @see #SCROLLBARS_OUTSIDE_OVERLAY 17265 * @see #SCROLLBARS_OUTSIDE_INSET 17266 * 17267 * @attr ref android.R.styleable#View_scrollbarStyle 17268 */ 17269 public void setScrollBarStyle(@ScrollBarStyle int style) { 17270 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 17271 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 17272 computeOpaqueFlags(); 17273 resolvePadding(); 17274 } 17275 } 17276 17277 /** 17278 * <p>Returns the current scrollbar style.</p> 17279 * @return the current scrollbar style 17280 * @see #SCROLLBARS_INSIDE_OVERLAY 17281 * @see #SCROLLBARS_INSIDE_INSET 17282 * @see #SCROLLBARS_OUTSIDE_OVERLAY 17283 * @see #SCROLLBARS_OUTSIDE_INSET 17284 * 17285 * @attr ref android.R.styleable#View_scrollbarStyle 17286 */ 17287 @ViewDebug.ExportedProperty(mapping = { 17288 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 17289 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 17290 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 17291 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 17292 }) 17293 @ScrollBarStyle 17294 public int getScrollBarStyle() { 17295 return mViewFlags & SCROLLBARS_STYLE_MASK; 17296 } 17297 17298 /** 17299 * <p>Compute the horizontal range that the horizontal scrollbar 17300 * represents.</p> 17301 * 17302 * <p>The range is expressed in arbitrary units that must be the same as the 17303 * units used by {@link #computeHorizontalScrollExtent()} and 17304 * {@link #computeHorizontalScrollOffset()}.</p> 17305 * 17306 * <p>The default range is the drawing width of this view.</p> 17307 * 17308 * @return the total horizontal range represented by the horizontal 17309 * scrollbar 17310 * 17311 * @see #computeHorizontalScrollExtent() 17312 * @see #computeHorizontalScrollOffset() 17313 * @see android.widget.ScrollBarDrawable 17314 */ 17315 protected int computeHorizontalScrollRange() { 17316 return getWidth(); 17317 } 17318 17319 /** 17320 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 17321 * within the horizontal range. This value is used to compute the position 17322 * of the thumb within the scrollbar's track.</p> 17323 * 17324 * <p>The range is expressed in arbitrary units that must be the same as the 17325 * units used by {@link #computeHorizontalScrollRange()} and 17326 * {@link #computeHorizontalScrollExtent()}.</p> 17327 * 17328 * <p>The default offset is the scroll offset of this view.</p> 17329 * 17330 * @return the horizontal offset of the scrollbar's thumb 17331 * 17332 * @see #computeHorizontalScrollRange() 17333 * @see #computeHorizontalScrollExtent() 17334 * @see android.widget.ScrollBarDrawable 17335 */ 17336 protected int computeHorizontalScrollOffset() { 17337 return mScrollX; 17338 } 17339 17340 /** 17341 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 17342 * within the horizontal range. This value is used to compute the length 17343 * of the thumb within the scrollbar's track.</p> 17344 * 17345 * <p>The range is expressed in arbitrary units that must be the same as the 17346 * units used by {@link #computeHorizontalScrollRange()} and 17347 * {@link #computeHorizontalScrollOffset()}.</p> 17348 * 17349 * <p>The default extent is the drawing width of this view.</p> 17350 * 17351 * @return the horizontal extent of the scrollbar's thumb 17352 * 17353 * @see #computeHorizontalScrollRange() 17354 * @see #computeHorizontalScrollOffset() 17355 * @see android.widget.ScrollBarDrawable 17356 */ 17357 protected int computeHorizontalScrollExtent() { 17358 return getWidth(); 17359 } 17360 17361 /** 17362 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 17363 * 17364 * <p>The range is expressed in arbitrary units that must be the same as the 17365 * units used by {@link #computeVerticalScrollExtent()} and 17366 * {@link #computeVerticalScrollOffset()}.</p> 17367 * 17368 * @return the total vertical range represented by the vertical scrollbar 17369 * 17370 * <p>The default range is the drawing height of this view.</p> 17371 * 17372 * @see #computeVerticalScrollExtent() 17373 * @see #computeVerticalScrollOffset() 17374 * @see android.widget.ScrollBarDrawable 17375 */ 17376 protected int computeVerticalScrollRange() { 17377 return getHeight(); 17378 } 17379 17380 /** 17381 * <p>Compute the vertical offset of the vertical scrollbar's thumb 17382 * within the horizontal range. This value is used to compute the position 17383 * of the thumb within the scrollbar's track.</p> 17384 * 17385 * <p>The range is expressed in arbitrary units that must be the same as the 17386 * units used by {@link #computeVerticalScrollRange()} and 17387 * {@link #computeVerticalScrollExtent()}.</p> 17388 * 17389 * <p>The default offset is the scroll offset of this view.</p> 17390 * 17391 * @return the vertical offset of the scrollbar's thumb 17392 * 17393 * @see #computeVerticalScrollRange() 17394 * @see #computeVerticalScrollExtent() 17395 * @see android.widget.ScrollBarDrawable 17396 */ 17397 protected int computeVerticalScrollOffset() { 17398 return mScrollY; 17399 } 17400 17401 /** 17402 * <p>Compute the vertical extent of the vertical scrollbar's thumb 17403 * within the vertical range. This value is used to compute the length 17404 * of the thumb within the scrollbar's track.</p> 17405 * 17406 * <p>The range is expressed in arbitrary units that must be the same as the 17407 * units used by {@link #computeVerticalScrollRange()} and 17408 * {@link #computeVerticalScrollOffset()}.</p> 17409 * 17410 * <p>The default extent is the drawing height of this view.</p> 17411 * 17412 * @return the vertical extent of the scrollbar's thumb 17413 * 17414 * @see #computeVerticalScrollRange() 17415 * @see #computeVerticalScrollOffset() 17416 * @see android.widget.ScrollBarDrawable 17417 */ 17418 protected int computeVerticalScrollExtent() { 17419 return getHeight(); 17420 } 17421 17422 /** 17423 * Check if this view can be scrolled horizontally in a certain direction. 17424 * 17425 * @param direction Negative to check scrolling left, positive to check scrolling right. 17426 * @return true if this view can be scrolled in the specified direction, false otherwise. 17427 */ 17428 public boolean canScrollHorizontally(int direction) { 17429 final int offset = computeHorizontalScrollOffset(); 17430 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 17431 if (range == 0) return false; 17432 if (direction < 0) { 17433 return offset > 0; 17434 } else { 17435 return offset < range - 1; 17436 } 17437 } 17438 17439 /** 17440 * Check if this view can be scrolled vertically in a certain direction. 17441 * 17442 * @param direction Negative to check scrolling up, positive to check scrolling down. 17443 * @return true if this view can be scrolled in the specified direction, false otherwise. 17444 */ 17445 public boolean canScrollVertically(int direction) { 17446 final int offset = computeVerticalScrollOffset(); 17447 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 17448 if (range == 0) return false; 17449 if (direction < 0) { 17450 return offset > 0; 17451 } else { 17452 return offset < range - 1; 17453 } 17454 } 17455 17456 void getScrollIndicatorBounds(@NonNull Rect out) { 17457 out.left = mScrollX; 17458 out.right = mScrollX + mRight - mLeft; 17459 out.top = mScrollY; 17460 out.bottom = mScrollY + mBottom - mTop; 17461 } 17462 17463 private void onDrawScrollIndicators(Canvas c) { 17464 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 17465 // No scroll indicators enabled. 17466 return; 17467 } 17468 17469 final Drawable dr = mScrollIndicatorDrawable; 17470 if (dr == null) { 17471 // Scroll indicators aren't supported here. 17472 return; 17473 } 17474 17475 final int h = dr.getIntrinsicHeight(); 17476 final int w = dr.getIntrinsicWidth(); 17477 final Rect rect = mAttachInfo.mTmpInvalRect; 17478 getScrollIndicatorBounds(rect); 17479 17480 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 17481 final boolean canScrollUp = canScrollVertically(-1); 17482 if (canScrollUp) { 17483 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 17484 dr.draw(c); 17485 } 17486 } 17487 17488 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 17489 final boolean canScrollDown = canScrollVertically(1); 17490 if (canScrollDown) { 17491 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 17492 dr.draw(c); 17493 } 17494 } 17495 17496 final int leftRtl; 17497 final int rightRtl; 17498 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 17499 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 17500 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 17501 } else { 17502 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 17503 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 17504 } 17505 17506 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 17507 if ((mPrivateFlags3 & leftMask) != 0) { 17508 final boolean canScrollLeft = canScrollHorizontally(-1); 17509 if (canScrollLeft) { 17510 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 17511 dr.draw(c); 17512 } 17513 } 17514 17515 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 17516 if ((mPrivateFlags3 & rightMask) != 0) { 17517 final boolean canScrollRight = canScrollHorizontally(1); 17518 if (canScrollRight) { 17519 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 17520 dr.draw(c); 17521 } 17522 } 17523 } 17524 17525 private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds, 17526 @Nullable Rect touchBounds) { 17527 final Rect bounds = drawBounds != null ? drawBounds : touchBounds; 17528 if (bounds == null) { 17529 return; 17530 } 17531 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 17532 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 17533 && !isVerticalScrollBarHidden(); 17534 final int size = getHorizontalScrollbarHeight(); 17535 final int verticalScrollBarGap = drawVerticalScrollBar ? 17536 getVerticalScrollbarWidth() : 0; 17537 final int width = mRight - mLeft; 17538 final int height = mBottom - mTop; 17539 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 17540 bounds.left = mScrollX + (mPaddingLeft & inside); 17541 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 17542 bounds.bottom = bounds.top + size; 17543 17544 if (touchBounds == null) { 17545 return; 17546 } 17547 if (touchBounds != bounds) { 17548 touchBounds.set(bounds); 17549 } 17550 final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget; 17551 if (touchBounds.height() < minTouchTarget) { 17552 final int adjust = (minTouchTarget - touchBounds.height()) / 2; 17553 touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height); 17554 touchBounds.top = touchBounds.bottom - minTouchTarget; 17555 } 17556 if (touchBounds.width() < minTouchTarget) { 17557 final int adjust = (minTouchTarget - touchBounds.width()) / 2; 17558 touchBounds.left -= adjust; 17559 touchBounds.right = touchBounds.left + minTouchTarget; 17560 } 17561 } 17562 17563 private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) { 17564 if (mRoundScrollbarRenderer == null) { 17565 getStraightVerticalScrollBarBounds(bounds, touchBounds); 17566 } else { 17567 getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds); 17568 } 17569 } 17570 17571 private void getRoundVerticalScrollBarBounds(Rect bounds) { 17572 final int width = mRight - mLeft; 17573 final int height = mBottom - mTop; 17574 // Do not take padding into account as we always want the scrollbars 17575 // to hug the screen for round wearable devices. 17576 bounds.left = mScrollX; 17577 bounds.top = mScrollY; 17578 bounds.right = bounds.left + width; 17579 bounds.bottom = mScrollY + height; 17580 } 17581 17582 private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds, 17583 @Nullable Rect touchBounds) { 17584 final Rect bounds = drawBounds != null ? drawBounds : touchBounds; 17585 if (bounds == null) { 17586 return; 17587 } 17588 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 17589 final int size = getVerticalScrollbarWidth(); 17590 int verticalScrollbarPosition = mVerticalScrollbarPosition; 17591 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 17592 verticalScrollbarPosition = isLayoutRtl() ? 17593 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 17594 } 17595 final int width = mRight - mLeft; 17596 final int height = mBottom - mTop; 17597 switch (verticalScrollbarPosition) { 17598 default: 17599 case SCROLLBAR_POSITION_RIGHT: 17600 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 17601 break; 17602 case SCROLLBAR_POSITION_LEFT: 17603 bounds.left = mScrollX + (mUserPaddingLeft & inside); 17604 break; 17605 } 17606 bounds.top = mScrollY + (mPaddingTop & inside); 17607 bounds.right = bounds.left + size; 17608 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 17609 17610 if (touchBounds == null) { 17611 return; 17612 } 17613 if (touchBounds != bounds) { 17614 touchBounds.set(bounds); 17615 } 17616 final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget; 17617 if (touchBounds.width() < minTouchTarget) { 17618 final int adjust = (minTouchTarget - touchBounds.width()) / 2; 17619 if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) { 17620 touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width); 17621 touchBounds.left = touchBounds.right - minTouchTarget; 17622 } else { 17623 touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX); 17624 touchBounds.right = touchBounds.left + minTouchTarget; 17625 } 17626 } 17627 if (touchBounds.height() < minTouchTarget) { 17628 final int adjust = (minTouchTarget - touchBounds.height()) / 2; 17629 touchBounds.top -= adjust; 17630 touchBounds.bottom = touchBounds.top + minTouchTarget; 17631 } 17632 } 17633 17634 /** 17635 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 17636 * scrollbars are painted only if they have been awakened first.</p> 17637 * 17638 * @param canvas the canvas on which to draw the scrollbars 17639 * 17640 * @see #awakenScrollBars(int) 17641 */ 17642 protected final void onDrawScrollBars(Canvas canvas) { 17643 // scrollbars are drawn only when the animation is running 17644 final ScrollabilityCache cache = mScrollCache; 17645 17646 if (cache != null) { 17647 17648 int state = cache.state; 17649 17650 if (state == ScrollabilityCache.OFF) { 17651 return; 17652 } 17653 17654 boolean invalidate = false; 17655 17656 if (state == ScrollabilityCache.FADING) { 17657 // We're fading -- get our fade interpolation 17658 if (cache.interpolatorValues == null) { 17659 cache.interpolatorValues = new float[1]; 17660 } 17661 17662 float[] values = cache.interpolatorValues; 17663 17664 // Stops the animation if we're done 17665 if (cache.scrollBarInterpolator.timeToValues(values) == 17666 Interpolator.Result.FREEZE_END) { 17667 cache.state = ScrollabilityCache.OFF; 17668 } else { 17669 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 17670 } 17671 17672 // This will make the scroll bars inval themselves after 17673 // drawing. We only want this when we're fading so that 17674 // we prevent excessive redraws 17675 invalidate = true; 17676 } else { 17677 // We're just on -- but we may have been fading before so 17678 // reset alpha 17679 cache.scrollBar.mutate().setAlpha(255); 17680 } 17681 17682 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 17683 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 17684 && !isVerticalScrollBarHidden(); 17685 17686 // Fork out the scroll bar drawing for round wearable devices. 17687 if (mRoundScrollbarRenderer != null) { 17688 if (drawVerticalScrollBar) { 17689 final Rect bounds = cache.mScrollBarBounds; 17690 getVerticalScrollBarBounds(bounds, null); 17691 mRoundScrollbarRenderer.drawRoundScrollbars( 17692 canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds); 17693 if (invalidate) { 17694 invalidate(); 17695 } 17696 } 17697 // Do not draw horizontal scroll bars for round wearable devices. 17698 } else if (drawVerticalScrollBar || drawHorizontalScrollBar) { 17699 final ScrollBarDrawable scrollBar = cache.scrollBar; 17700 17701 if (drawHorizontalScrollBar) { 17702 scrollBar.setParameters(computeHorizontalScrollRange(), 17703 computeHorizontalScrollOffset(), 17704 computeHorizontalScrollExtent(), false); 17705 final Rect bounds = cache.mScrollBarBounds; 17706 getHorizontalScrollBarBounds(bounds, null); 17707 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 17708 bounds.right, bounds.bottom); 17709 if (invalidate) { 17710 invalidate(bounds); 17711 } 17712 } 17713 17714 if (drawVerticalScrollBar) { 17715 scrollBar.setParameters(computeVerticalScrollRange(), 17716 computeVerticalScrollOffset(), 17717 computeVerticalScrollExtent(), true); 17718 final Rect bounds = cache.mScrollBarBounds; 17719 getVerticalScrollBarBounds(bounds, null); 17720 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 17721 bounds.right, bounds.bottom); 17722 if (invalidate) { 17723 invalidate(bounds); 17724 } 17725 } 17726 } 17727 } 17728 } 17729 17730 /** 17731 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 17732 * FastScroller is visible. 17733 * @return whether to temporarily hide the vertical scrollbar 17734 * @hide 17735 */ 17736 protected boolean isVerticalScrollBarHidden() { 17737 return false; 17738 } 17739 17740 /** 17741 * <p>Draw the horizontal scrollbar if 17742 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 17743 * 17744 * @param canvas the canvas on which to draw the scrollbar 17745 * @param scrollBar the scrollbar's drawable 17746 * 17747 * @see #isHorizontalScrollBarEnabled() 17748 * @see #computeHorizontalScrollRange() 17749 * @see #computeHorizontalScrollExtent() 17750 * @see #computeHorizontalScrollOffset() 17751 * @see android.widget.ScrollBarDrawable 17752 * @hide 17753 */ 17754 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 17755 int l, int t, int r, int b) { 17756 scrollBar.setBounds(l, t, r, b); 17757 scrollBar.draw(canvas); 17758 } 17759 17760 /** 17761 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 17762 * returns true.</p> 17763 * 17764 * @param canvas the canvas on which to draw the scrollbar 17765 * @param scrollBar the scrollbar's drawable 17766 * 17767 * @see #isVerticalScrollBarEnabled() 17768 * @see #computeVerticalScrollRange() 17769 * @see #computeVerticalScrollExtent() 17770 * @see #computeVerticalScrollOffset() 17771 * @see android.widget.ScrollBarDrawable 17772 * @hide 17773 */ 17774 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 17775 int l, int t, int r, int b) { 17776 scrollBar.setBounds(l, t, r, b); 17777 scrollBar.draw(canvas); 17778 } 17779 17780 /** 17781 * Implement this to do your drawing. 17782 * 17783 * @param canvas the canvas on which the background will be drawn 17784 */ 17785 protected void onDraw(Canvas canvas) { 17786 } 17787 17788 /* 17789 * Caller is responsible for calling requestLayout if necessary. 17790 * (This allows addViewInLayout to not request a new layout.) 17791 */ 17792 void assignParent(ViewParent parent) { 17793 if (mParent == null) { 17794 mParent = parent; 17795 } else if (parent == null) { 17796 mParent = null; 17797 } else { 17798 throw new RuntimeException("view " + this + " being added, but" 17799 + " it already has a parent"); 17800 } 17801 } 17802 17803 /** 17804 * This is called when the view is attached to a window. At this point it 17805 * has a Surface and will start drawing. Note that this function is 17806 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 17807 * however it may be called any time before the first onDraw -- including 17808 * before or after {@link #onMeasure(int, int)}. 17809 * 17810 * @see #onDetachedFromWindow() 17811 */ 17812 @CallSuper 17813 protected void onAttachedToWindow() { 17814 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 17815 mParent.requestTransparentRegion(this); 17816 } 17817 17818 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 17819 17820 jumpDrawablesToCurrentState(); 17821 17822 resetSubtreeAccessibilityStateChanged(); 17823 17824 // rebuild, since Outline not maintained while View is detached 17825 rebuildOutline(); 17826 17827 if (isFocused()) { 17828 InputMethodManager imm = InputMethodManager.peekInstance(); 17829 if (imm != null) { 17830 imm.focusIn(this); 17831 } 17832 } 17833 } 17834 17835 /** 17836 * Resolve all RTL related properties. 17837 * 17838 * @return true if resolution of RTL properties has been done 17839 * 17840 * @hide 17841 */ 17842 public boolean resolveRtlPropertiesIfNeeded() { 17843 if (!needRtlPropertiesResolution()) return false; 17844 17845 // Order is important here: LayoutDirection MUST be resolved first 17846 if (!isLayoutDirectionResolved()) { 17847 resolveLayoutDirection(); 17848 resolveLayoutParams(); 17849 } 17850 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 17851 if (!isTextDirectionResolved()) { 17852 resolveTextDirection(); 17853 } 17854 if (!isTextAlignmentResolved()) { 17855 resolveTextAlignment(); 17856 } 17857 // Should resolve Drawables before Padding because we need the layout direction of the 17858 // Drawable to correctly resolve Padding. 17859 if (!areDrawablesResolved()) { 17860 resolveDrawables(); 17861 } 17862 if (!isPaddingResolved()) { 17863 resolvePadding(); 17864 } 17865 onRtlPropertiesChanged(getLayoutDirection()); 17866 return true; 17867 } 17868 17869 /** 17870 * Reset resolution of all RTL related properties. 17871 * 17872 * @hide 17873 */ 17874 public void resetRtlProperties() { 17875 resetResolvedLayoutDirection(); 17876 resetResolvedTextDirection(); 17877 resetResolvedTextAlignment(); 17878 resetResolvedPadding(); 17879 resetResolvedDrawables(); 17880 } 17881 17882 /** 17883 * @see #onScreenStateChanged(int) 17884 */ 17885 void dispatchScreenStateChanged(int screenState) { 17886 onScreenStateChanged(screenState); 17887 } 17888 17889 /** 17890 * This method is called whenever the state of the screen this view is 17891 * attached to changes. A state change will usually occurs when the screen 17892 * turns on or off (whether it happens automatically or the user does it 17893 * manually.) 17894 * 17895 * @param screenState The new state of the screen. Can be either 17896 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 17897 */ 17898 public void onScreenStateChanged(int screenState) { 17899 } 17900 17901 /** 17902 * @see #onMovedToDisplay(int, Configuration) 17903 */ 17904 void dispatchMovedToDisplay(Display display, Configuration config) { 17905 mAttachInfo.mDisplay = display; 17906 mAttachInfo.mDisplayState = display.getState(); 17907 onMovedToDisplay(display.getDisplayId(), config); 17908 } 17909 17910 /** 17911 * Called by the system when the hosting activity is moved from one display to another without 17912 * recreation. This means that the activity is declared to handle all changes to configuration 17913 * that happened when it was switched to another display, so it wasn't destroyed and created 17914 * again. 17915 * 17916 * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the 17917 * applied configuration actually changed. It is up to app developer to choose whether to handle 17918 * the change in this method or in the following {@link #onConfigurationChanged(Configuration)} 17919 * call. 17920 * 17921 * <p>Use this callback to track changes to the displays if some functionality relies on an 17922 * association with some display properties. 17923 * 17924 * @param displayId The id of the display to which the view was moved. 17925 * @param config Configuration of the resources on new display after move. 17926 * 17927 * @see #onConfigurationChanged(Configuration) 17928 * @hide 17929 */ 17930 public void onMovedToDisplay(int displayId, Configuration config) { 17931 } 17932 17933 /** 17934 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 17935 */ 17936 private boolean hasRtlSupport() { 17937 return mContext.getApplicationInfo().hasRtlSupport(); 17938 } 17939 17940 /** 17941 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 17942 * RTL not supported) 17943 */ 17944 private boolean isRtlCompatibilityMode() { 17945 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 17946 return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport(); 17947 } 17948 17949 /** 17950 * @return true if RTL properties need resolution. 17951 * 17952 */ 17953 private boolean needRtlPropertiesResolution() { 17954 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 17955 } 17956 17957 /** 17958 * Called when any RTL property (layout direction or text direction or text alignment) has 17959 * been changed. 17960 * 17961 * Subclasses need to override this method to take care of cached information that depends on the 17962 * resolved layout direction, or to inform child views that inherit their layout direction. 17963 * 17964 * The default implementation does nothing. 17965 * 17966 * @param layoutDirection the direction of the layout 17967 * 17968 * @see #LAYOUT_DIRECTION_LTR 17969 * @see #LAYOUT_DIRECTION_RTL 17970 */ 17971 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 17972 } 17973 17974 /** 17975 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 17976 * that the parent directionality can and will be resolved before its children. 17977 * 17978 * @return true if resolution has been done, false otherwise. 17979 * 17980 * @hide 17981 */ 17982 public boolean resolveLayoutDirection() { 17983 // Clear any previous layout direction resolution 17984 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 17985 17986 if (hasRtlSupport()) { 17987 // Set resolved depending on layout direction 17988 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 17989 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 17990 case LAYOUT_DIRECTION_INHERIT: 17991 // We cannot resolve yet. LTR is by default and let the resolution happen again 17992 // later to get the correct resolved value 17993 if (!canResolveLayoutDirection()) return false; 17994 17995 // Parent has not yet resolved, LTR is still the default 17996 try { 17997 if (!mParent.isLayoutDirectionResolved()) return false; 17998 17999 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 18000 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 18001 } 18002 } catch (AbstractMethodError e) { 18003 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18004 " does not fully implement ViewParent", e); 18005 } 18006 break; 18007 case LAYOUT_DIRECTION_RTL: 18008 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 18009 break; 18010 case LAYOUT_DIRECTION_LOCALE: 18011 if((LAYOUT_DIRECTION_RTL == 18012 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 18013 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 18014 } 18015 break; 18016 default: 18017 // Nothing to do, LTR by default 18018 } 18019 } 18020 18021 // Set to resolved 18022 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 18023 return true; 18024 } 18025 18026 /** 18027 * Check if layout direction resolution can be done. 18028 * 18029 * @return true if layout direction resolution can be done otherwise return false. 18030 */ 18031 public boolean canResolveLayoutDirection() { 18032 switch (getRawLayoutDirection()) { 18033 case LAYOUT_DIRECTION_INHERIT: 18034 if (mParent != null) { 18035 try { 18036 return mParent.canResolveLayoutDirection(); 18037 } catch (AbstractMethodError e) { 18038 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18039 " does not fully implement ViewParent", e); 18040 } 18041 } 18042 return false; 18043 18044 default: 18045 return true; 18046 } 18047 } 18048 18049 /** 18050 * Reset the resolved layout direction. Layout direction will be resolved during a call to 18051 * {@link #onMeasure(int, int)}. 18052 * 18053 * @hide 18054 */ 18055 public void resetResolvedLayoutDirection() { 18056 // Reset the current resolved bits 18057 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 18058 } 18059 18060 /** 18061 * @return true if the layout direction is inherited. 18062 * 18063 * @hide 18064 */ 18065 public boolean isLayoutDirectionInherited() { 18066 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 18067 } 18068 18069 /** 18070 * @return true if layout direction has been resolved. 18071 */ 18072 public boolean isLayoutDirectionResolved() { 18073 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 18074 } 18075 18076 /** 18077 * Return if padding has been resolved 18078 * 18079 * @hide 18080 */ 18081 boolean isPaddingResolved() { 18082 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 18083 } 18084 18085 /** 18086 * Resolves padding depending on layout direction, if applicable, and 18087 * recomputes internal padding values to adjust for scroll bars. 18088 * 18089 * @hide 18090 */ 18091 public void resolvePadding() { 18092 final int resolvedLayoutDirection = getLayoutDirection(); 18093 18094 if (!isRtlCompatibilityMode()) { 18095 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 18096 // If start / end padding are defined, they will be resolved (hence overriding) to 18097 // left / right or right / left depending on the resolved layout direction. 18098 // If start / end padding are not defined, use the left / right ones. 18099 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 18100 Rect padding = sThreadLocal.get(); 18101 if (padding == null) { 18102 padding = new Rect(); 18103 sThreadLocal.set(padding); 18104 } 18105 mBackground.getPadding(padding); 18106 if (!mLeftPaddingDefined) { 18107 mUserPaddingLeftInitial = padding.left; 18108 } 18109 if (!mRightPaddingDefined) { 18110 mUserPaddingRightInitial = padding.right; 18111 } 18112 } 18113 switch (resolvedLayoutDirection) { 18114 case LAYOUT_DIRECTION_RTL: 18115 if (mUserPaddingStart != UNDEFINED_PADDING) { 18116 mUserPaddingRight = mUserPaddingStart; 18117 } else { 18118 mUserPaddingRight = mUserPaddingRightInitial; 18119 } 18120 if (mUserPaddingEnd != UNDEFINED_PADDING) { 18121 mUserPaddingLeft = mUserPaddingEnd; 18122 } else { 18123 mUserPaddingLeft = mUserPaddingLeftInitial; 18124 } 18125 break; 18126 case LAYOUT_DIRECTION_LTR: 18127 default: 18128 if (mUserPaddingStart != UNDEFINED_PADDING) { 18129 mUserPaddingLeft = mUserPaddingStart; 18130 } else { 18131 mUserPaddingLeft = mUserPaddingLeftInitial; 18132 } 18133 if (mUserPaddingEnd != UNDEFINED_PADDING) { 18134 mUserPaddingRight = mUserPaddingEnd; 18135 } else { 18136 mUserPaddingRight = mUserPaddingRightInitial; 18137 } 18138 } 18139 18140 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 18141 } 18142 18143 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 18144 onRtlPropertiesChanged(resolvedLayoutDirection); 18145 18146 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 18147 } 18148 18149 /** 18150 * Reset the resolved layout direction. 18151 * 18152 * @hide 18153 */ 18154 public void resetResolvedPadding() { 18155 resetResolvedPaddingInternal(); 18156 } 18157 18158 /** 18159 * Used when we only want to reset *this* view's padding and not trigger overrides 18160 * in ViewGroup that reset children too. 18161 */ 18162 void resetResolvedPaddingInternal() { 18163 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 18164 } 18165 18166 /** 18167 * This is called when the view is detached from a window. At this point it 18168 * no longer has a surface for drawing. 18169 * 18170 * @see #onAttachedToWindow() 18171 */ 18172 @CallSuper 18173 protected void onDetachedFromWindow() { 18174 } 18175 18176 /** 18177 * This is a framework-internal mirror of onDetachedFromWindow() that's called 18178 * after onDetachedFromWindow(). 18179 * 18180 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 18181 * The super method should be called at the end of the overridden method to ensure 18182 * subclasses are destroyed first 18183 * 18184 * @hide 18185 */ 18186 @CallSuper 18187 protected void onDetachedFromWindowInternal() { 18188 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 18189 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 18190 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 18191 18192 removeUnsetPressCallback(); 18193 removeLongPressCallback(); 18194 removePerformClickCallback(); 18195 cancel(mSendViewScrolledAccessibilityEvent); 18196 stopNestedScroll(); 18197 18198 // Anything that started animating right before detach should already 18199 // be in its final state when re-attached. 18200 jumpDrawablesToCurrentState(); 18201 18202 destroyDrawingCache(); 18203 18204 cleanupDraw(); 18205 mCurrentAnimation = null; 18206 18207 if ((mViewFlags & TOOLTIP) == TOOLTIP) { 18208 hideTooltip(); 18209 } 18210 } 18211 18212 private void cleanupDraw() { 18213 resetDisplayList(); 18214 if (mAttachInfo != null) { 18215 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 18216 } 18217 } 18218 18219 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 18220 } 18221 18222 /** 18223 * @return The number of times this view has been attached to a window 18224 */ 18225 protected int getWindowAttachCount() { 18226 return mWindowAttachCount; 18227 } 18228 18229 /** 18230 * Retrieve a unique token identifying the window this view is attached to. 18231 * @return Return the window's token for use in 18232 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 18233 */ 18234 public IBinder getWindowToken() { 18235 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 18236 } 18237 18238 /** 18239 * Retrieve the {@link WindowId} for the window this view is 18240 * currently attached to. 18241 */ 18242 public WindowId getWindowId() { 18243 AttachInfo ai = mAttachInfo; 18244 if (ai == null) { 18245 return null; 18246 } 18247 if (ai.mWindowId == null) { 18248 try { 18249 ai.mIWindowId = ai.mSession.getWindowId(ai.mWindowToken); 18250 if (ai.mIWindowId != null) { 18251 ai.mWindowId = new WindowId(ai.mIWindowId); 18252 } 18253 } catch (RemoteException e) { 18254 } 18255 } 18256 return ai.mWindowId; 18257 } 18258 18259 /** 18260 * Retrieve a unique token identifying the top-level "real" window of 18261 * the window that this view is attached to. That is, this is like 18262 * {@link #getWindowToken}, except if the window this view in is a panel 18263 * window (attached to another containing window), then the token of 18264 * the containing window is returned instead. 18265 * 18266 * @return Returns the associated window token, either 18267 * {@link #getWindowToken()} or the containing window's token. 18268 */ 18269 public IBinder getApplicationWindowToken() { 18270 AttachInfo ai = mAttachInfo; 18271 if (ai != null) { 18272 IBinder appWindowToken = ai.mPanelParentWindowToken; 18273 if (appWindowToken == null) { 18274 appWindowToken = ai.mWindowToken; 18275 } 18276 return appWindowToken; 18277 } 18278 return null; 18279 } 18280 18281 /** 18282 * Gets the logical display to which the view's window has been attached. 18283 * 18284 * @return The logical display, or null if the view is not currently attached to a window. 18285 */ 18286 public Display getDisplay() { 18287 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 18288 } 18289 18290 /** 18291 * Retrieve private session object this view hierarchy is using to 18292 * communicate with the window manager. 18293 * @return the session object to communicate with the window manager 18294 */ 18295 /*package*/ IWindowSession getWindowSession() { 18296 return mAttachInfo != null ? mAttachInfo.mSession : null; 18297 } 18298 18299 /** 18300 * Return the window this view is currently attached to. Used in 18301 * {@link android.app.ActivityView} to communicate with WM. 18302 * @hide 18303 */ 18304 protected IWindow getWindow() { 18305 return mAttachInfo != null ? mAttachInfo.mWindow : null; 18306 } 18307 18308 /** 18309 * Return the visibility value of the least visible component passed. 18310 */ 18311 int combineVisibility(int vis1, int vis2) { 18312 // This works because VISIBLE < INVISIBLE < GONE. 18313 return Math.max(vis1, vis2); 18314 } 18315 18316 /** 18317 * @param info the {@link android.view.View.AttachInfo} to associated with 18318 * this view 18319 */ 18320 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 18321 mAttachInfo = info; 18322 if (mOverlay != null) { 18323 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 18324 } 18325 mWindowAttachCount++; 18326 // We will need to evaluate the drawable state at least once. 18327 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 18328 if (mFloatingTreeObserver != null) { 18329 info.mTreeObserver.merge(mFloatingTreeObserver); 18330 mFloatingTreeObserver = null; 18331 } 18332 18333 registerPendingFrameMetricsObservers(); 18334 18335 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 18336 mAttachInfo.mScrollContainers.add(this); 18337 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 18338 } 18339 // Transfer all pending runnables. 18340 if (mRunQueue != null) { 18341 mRunQueue.executeActions(info.mHandler); 18342 mRunQueue = null; 18343 } 18344 performCollectViewAttributes(mAttachInfo, visibility); 18345 onAttachedToWindow(); 18346 18347 ListenerInfo li = mListenerInfo; 18348 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 18349 li != null ? li.mOnAttachStateChangeListeners : null; 18350 if (listeners != null && listeners.size() > 0) { 18351 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 18352 // perform the dispatching. The iterator is a safe guard against listeners that 18353 // could mutate the list by calling the various add/remove methods. This prevents 18354 // the array from being modified while we iterate it. 18355 for (OnAttachStateChangeListener listener : listeners) { 18356 listener.onViewAttachedToWindow(this); 18357 } 18358 } 18359 18360 int vis = info.mWindowVisibility; 18361 if (vis != GONE) { 18362 onWindowVisibilityChanged(vis); 18363 if (isShown()) { 18364 // Calling onVisibilityAggregated directly here since the subtree will also 18365 // receive dispatchAttachedToWindow and this same call 18366 onVisibilityAggregated(vis == VISIBLE); 18367 } 18368 } 18369 18370 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 18371 // As all views in the subtree will already receive dispatchAttachedToWindow 18372 // traversing the subtree again here is not desired. 18373 onVisibilityChanged(this, visibility); 18374 18375 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 18376 // If nobody has evaluated the drawable state yet, then do it now. 18377 refreshDrawableState(); 18378 } 18379 needGlobalAttributesUpdate(false); 18380 18381 notifyEnterOrExitForAutoFillIfNeeded(true); 18382 } 18383 18384 void dispatchDetachedFromWindow() { 18385 AttachInfo info = mAttachInfo; 18386 if (info != null) { 18387 int vis = info.mWindowVisibility; 18388 if (vis != GONE) { 18389 onWindowVisibilityChanged(GONE); 18390 if (isShown()) { 18391 // Invoking onVisibilityAggregated directly here since the subtree 18392 // will also receive detached from window 18393 onVisibilityAggregated(false); 18394 } 18395 } 18396 } 18397 18398 onDetachedFromWindow(); 18399 onDetachedFromWindowInternal(); 18400 18401 InputMethodManager imm = InputMethodManager.peekInstance(); 18402 if (imm != null) { 18403 imm.onViewDetachedFromWindow(this); 18404 } 18405 18406 ListenerInfo li = mListenerInfo; 18407 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 18408 li != null ? li.mOnAttachStateChangeListeners : null; 18409 if (listeners != null && listeners.size() > 0) { 18410 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 18411 // perform the dispatching. The iterator is a safe guard against listeners that 18412 // could mutate the list by calling the various add/remove methods. This prevents 18413 // the array from being modified while we iterate it. 18414 for (OnAttachStateChangeListener listener : listeners) { 18415 listener.onViewDetachedFromWindow(this); 18416 } 18417 } 18418 18419 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 18420 mAttachInfo.mScrollContainers.remove(this); 18421 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 18422 } 18423 18424 mAttachInfo = null; 18425 if (mOverlay != null) { 18426 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 18427 } 18428 18429 notifyEnterOrExitForAutoFillIfNeeded(false); 18430 } 18431 18432 /** 18433 * Cancel any deferred high-level input events that were previously posted to the event queue. 18434 * 18435 * <p>Many views post high-level events such as click handlers to the event queue 18436 * to run deferred in order to preserve a desired user experience - clearing visible 18437 * pressed states before executing, etc. This method will abort any events of this nature 18438 * that are currently in flight.</p> 18439 * 18440 * <p>Custom views that generate their own high-level deferred input events should override 18441 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 18442 * 18443 * <p>This will also cancel pending input events for any child views.</p> 18444 * 18445 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 18446 * This will not impact newer events posted after this call that may occur as a result of 18447 * lower-level input events still waiting in the queue. If you are trying to prevent 18448 * double-submitted events for the duration of some sort of asynchronous transaction 18449 * you should also take other steps to protect against unexpected double inputs e.g. calling 18450 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 18451 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 18452 */ 18453 public final void cancelPendingInputEvents() { 18454 dispatchCancelPendingInputEvents(); 18455 } 18456 18457 /** 18458 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 18459 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 18460 */ 18461 void dispatchCancelPendingInputEvents() { 18462 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 18463 onCancelPendingInputEvents(); 18464 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 18465 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 18466 " did not call through to super.onCancelPendingInputEvents()"); 18467 } 18468 } 18469 18470 /** 18471 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 18472 * a parent view. 18473 * 18474 * <p>This method is responsible for removing any pending high-level input events that were 18475 * posted to the event queue to run later. Custom view classes that post their own deferred 18476 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 18477 * {@link android.os.Handler} should override this method, call 18478 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 18479 * </p> 18480 */ 18481 public void onCancelPendingInputEvents() { 18482 removePerformClickCallback(); 18483 cancelLongPress(); 18484 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 18485 } 18486 18487 /** 18488 * Store this view hierarchy's frozen state into the given container. 18489 * 18490 * @param container The SparseArray in which to save the view's state. 18491 * 18492 * @see #restoreHierarchyState(android.util.SparseArray) 18493 * @see #dispatchSaveInstanceState(android.util.SparseArray) 18494 * @see #onSaveInstanceState() 18495 */ 18496 public void saveHierarchyState(SparseArray<Parcelable> container) { 18497 dispatchSaveInstanceState(container); 18498 } 18499 18500 /** 18501 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 18502 * this view and its children. May be overridden to modify how freezing happens to a 18503 * view's children; for example, some views may want to not store state for their children. 18504 * 18505 * @param container The SparseArray in which to save the view's state. 18506 * 18507 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 18508 * @see #saveHierarchyState(android.util.SparseArray) 18509 * @see #onSaveInstanceState() 18510 */ 18511 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 18512 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 18513 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 18514 Parcelable state = onSaveInstanceState(); 18515 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 18516 throw new IllegalStateException( 18517 "Derived class did not call super.onSaveInstanceState()"); 18518 } 18519 if (state != null) { 18520 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 18521 // + ": " + state); 18522 container.put(mID, state); 18523 } 18524 } 18525 } 18526 18527 /** 18528 * Hook allowing a view to generate a representation of its internal state 18529 * that can later be used to create a new instance with that same state. 18530 * This state should only contain information that is not persistent or can 18531 * not be reconstructed later. For example, you will never store your 18532 * current position on screen because that will be computed again when a 18533 * new instance of the view is placed in its view hierarchy. 18534 * <p> 18535 * Some examples of things you may store here: the current cursor position 18536 * in a text view (but usually not the text itself since that is stored in a 18537 * content provider or other persistent storage), the currently selected 18538 * item in a list view. 18539 * 18540 * @return Returns a Parcelable object containing the view's current dynamic 18541 * state, or null if there is nothing interesting to save. 18542 * @see #onRestoreInstanceState(Parcelable) 18543 * @see #saveHierarchyState(SparseArray) 18544 * @see #dispatchSaveInstanceState(SparseArray) 18545 * @see #setSaveEnabled(boolean) 18546 */ 18547 @CallSuper 18548 @Nullable protected Parcelable onSaveInstanceState() { 18549 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 18550 if (mStartActivityRequestWho != null || isAutofilled() 18551 || mAutofillViewId > LAST_APP_AUTOFILL_ID) { 18552 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 18553 18554 if (mStartActivityRequestWho != null) { 18555 state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED; 18556 } 18557 18558 if (isAutofilled()) { 18559 state.mSavedData |= BaseSavedState.IS_AUTOFILLED; 18560 } 18561 18562 if (mAutofillViewId > LAST_APP_AUTOFILL_ID) { 18563 state.mSavedData |= BaseSavedState.AUTOFILL_ID; 18564 } 18565 18566 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 18567 state.mIsAutofilled = isAutofilled(); 18568 state.mAutofillViewId = mAutofillViewId; 18569 return state; 18570 } 18571 return BaseSavedState.EMPTY_STATE; 18572 } 18573 18574 /** 18575 * Restore this view hierarchy's frozen state from the given container. 18576 * 18577 * @param container The SparseArray which holds previously frozen states. 18578 * 18579 * @see #saveHierarchyState(android.util.SparseArray) 18580 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 18581 * @see #onRestoreInstanceState(android.os.Parcelable) 18582 */ 18583 public void restoreHierarchyState(SparseArray<Parcelable> container) { 18584 dispatchRestoreInstanceState(container); 18585 } 18586 18587 /** 18588 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 18589 * state for this view and its children. May be overridden to modify how restoring 18590 * happens to a view's children; for example, some views may want to not store state 18591 * for their children. 18592 * 18593 * @param container The SparseArray which holds previously saved state. 18594 * 18595 * @see #dispatchSaveInstanceState(android.util.SparseArray) 18596 * @see #restoreHierarchyState(android.util.SparseArray) 18597 * @see #onRestoreInstanceState(android.os.Parcelable) 18598 */ 18599 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 18600 if (mID != NO_ID) { 18601 Parcelable state = container.get(mID); 18602 if (state != null) { 18603 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 18604 // + ": " + state); 18605 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 18606 onRestoreInstanceState(state); 18607 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 18608 throw new IllegalStateException( 18609 "Derived class did not call super.onRestoreInstanceState()"); 18610 } 18611 } 18612 } 18613 } 18614 18615 /** 18616 * Hook allowing a view to re-apply a representation of its internal state that had previously 18617 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 18618 * null state. 18619 * 18620 * @param state The frozen state that had previously been returned by 18621 * {@link #onSaveInstanceState}. 18622 * 18623 * @see #onSaveInstanceState() 18624 * @see #restoreHierarchyState(android.util.SparseArray) 18625 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 18626 */ 18627 @CallSuper 18628 protected void onRestoreInstanceState(Parcelable state) { 18629 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 18630 if (state != null && !(state instanceof AbsSavedState)) { 18631 throw new IllegalArgumentException("Wrong state class, expecting View State but " 18632 + "received " + state.getClass().toString() + " instead. This usually happens " 18633 + "when two views of different type have the same id in the same hierarchy. " 18634 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 18635 + "other views do not use the same id."); 18636 } 18637 if (state != null && state instanceof BaseSavedState) { 18638 BaseSavedState baseState = (BaseSavedState) state; 18639 18640 if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) { 18641 mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved; 18642 } 18643 if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) { 18644 setAutofilled(baseState.mIsAutofilled); 18645 } 18646 if ((baseState.mSavedData & BaseSavedState.AUTOFILL_ID) != 0) { 18647 // It can happen that views have the same view id and the restoration path will not 18648 // be able to distinguish between them. The autofill id needs to be unique though. 18649 // Hence prevent the same autofill view id from being restored multiple times. 18650 ((BaseSavedState) state).mSavedData &= ~BaseSavedState.AUTOFILL_ID; 18651 18652 if ((mPrivateFlags3 & PFLAG3_AUTOFILLID_EXPLICITLY_SET) != 0) { 18653 // Ignore when view already set it through setAutofillId(); 18654 if (android.view.autofill.Helper.sDebug) { 18655 Log.d(VIEW_LOG_TAG, "onRestoreInstanceState(): not setting autofillId to " 18656 + baseState.mAutofillViewId + " because view explicitly set it to " 18657 + mAutofillId); 18658 } 18659 } else { 18660 mAutofillViewId = baseState.mAutofillViewId; 18661 mAutofillId = null; // will be set on demand by getAutofillId() 18662 } 18663 } 18664 } 18665 } 18666 18667 /** 18668 * <p>Return the time at which the drawing of the view hierarchy started.</p> 18669 * 18670 * @return the drawing start time in milliseconds 18671 */ 18672 public long getDrawingTime() { 18673 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 18674 } 18675 18676 /** 18677 * <p>Enables or disables the duplication of the parent's state into this view. When 18678 * duplication is enabled, this view gets its drawable state from its parent rather 18679 * than from its own internal properties.</p> 18680 * 18681 * <p>Note: in the current implementation, setting this property to true after the 18682 * view was added to a ViewGroup might have no effect at all. This property should 18683 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 18684 * 18685 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 18686 * property is enabled, an exception will be thrown.</p> 18687 * 18688 * <p>Note: if the child view uses and updates additional states which are unknown to the 18689 * parent, these states should not be affected by this method.</p> 18690 * 18691 * @param enabled True to enable duplication of the parent's drawable state, false 18692 * to disable it. 18693 * 18694 * @see #getDrawableState() 18695 * @see #isDuplicateParentStateEnabled() 18696 */ 18697 public void setDuplicateParentStateEnabled(boolean enabled) { 18698 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 18699 } 18700 18701 /** 18702 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 18703 * 18704 * @return True if this view's drawable state is duplicated from the parent, 18705 * false otherwise 18706 * 18707 * @see #getDrawableState() 18708 * @see #setDuplicateParentStateEnabled(boolean) 18709 */ 18710 public boolean isDuplicateParentStateEnabled() { 18711 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 18712 } 18713 18714 /** 18715 * <p>Specifies the type of layer backing this view. The layer can be 18716 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 18717 * {@link #LAYER_TYPE_HARDWARE}.</p> 18718 * 18719 * <p>A layer is associated with an optional {@link android.graphics.Paint} 18720 * instance that controls how the layer is composed on screen. The following 18721 * properties of the paint are taken into account when composing the layer:</p> 18722 * <ul> 18723 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 18724 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 18725 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 18726 * </ul> 18727 * 18728 * <p>If this view has an alpha value set to < 1.0 by calling 18729 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 18730 * by this view's alpha value.</p> 18731 * 18732 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 18733 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 18734 * for more information on when and how to use layers.</p> 18735 * 18736 * @param layerType The type of layer to use with this view, must be one of 18737 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 18738 * {@link #LAYER_TYPE_HARDWARE} 18739 * @param paint The paint used to compose the layer. This argument is optional 18740 * and can be null. It is ignored when the layer type is 18741 * {@link #LAYER_TYPE_NONE} 18742 * 18743 * @see #getLayerType() 18744 * @see #LAYER_TYPE_NONE 18745 * @see #LAYER_TYPE_SOFTWARE 18746 * @see #LAYER_TYPE_HARDWARE 18747 * @see #setAlpha(float) 18748 * 18749 * @attr ref android.R.styleable#View_layerType 18750 */ 18751 public void setLayerType(int layerType, @Nullable Paint paint) { 18752 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 18753 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 18754 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 18755 } 18756 18757 boolean typeChanged = mRenderNode.setLayerType(layerType); 18758 18759 if (!typeChanged) { 18760 setLayerPaint(paint); 18761 return; 18762 } 18763 18764 if (layerType != LAYER_TYPE_SOFTWARE) { 18765 // Destroy any previous software drawing cache if present 18766 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 18767 // drawing cache created in View#draw when drawing to a SW canvas. 18768 destroyDrawingCache(); 18769 } 18770 18771 mLayerType = layerType; 18772 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 18773 mRenderNode.setLayerPaint(mLayerPaint); 18774 18775 // draw() behaves differently if we are on a layer, so we need to 18776 // invalidate() here 18777 invalidateParentCaches(); 18778 invalidate(true); 18779 } 18780 18781 /** 18782 * Updates the {@link Paint} object used with the current layer (used only if the current 18783 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 18784 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 18785 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 18786 * ensure that the view gets redrawn immediately. 18787 * 18788 * <p>A layer is associated with an optional {@link android.graphics.Paint} 18789 * instance that controls how the layer is composed on screen. The following 18790 * properties of the paint are taken into account when composing the layer:</p> 18791 * <ul> 18792 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 18793 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 18794 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 18795 * </ul> 18796 * 18797 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 18798 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 18799 * 18800 * @param paint The paint used to compose the layer. This argument is optional 18801 * and can be null. It is ignored when the layer type is 18802 * {@link #LAYER_TYPE_NONE} 18803 * 18804 * @see #setLayerType(int, android.graphics.Paint) 18805 */ 18806 public void setLayerPaint(@Nullable Paint paint) { 18807 int layerType = getLayerType(); 18808 if (layerType != LAYER_TYPE_NONE) { 18809 mLayerPaint = paint; 18810 if (layerType == LAYER_TYPE_HARDWARE) { 18811 if (mRenderNode.setLayerPaint(paint)) { 18812 invalidateViewProperty(false, false); 18813 } 18814 } else { 18815 invalidate(); 18816 } 18817 } 18818 } 18819 18820 /** 18821 * Indicates what type of layer is currently associated with this view. By default 18822 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 18823 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 18824 * for more information on the different types of layers. 18825 * 18826 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 18827 * {@link #LAYER_TYPE_HARDWARE} 18828 * 18829 * @see #setLayerType(int, android.graphics.Paint) 18830 * @see #buildLayer() 18831 * @see #LAYER_TYPE_NONE 18832 * @see #LAYER_TYPE_SOFTWARE 18833 * @see #LAYER_TYPE_HARDWARE 18834 */ 18835 public int getLayerType() { 18836 return mLayerType; 18837 } 18838 18839 /** 18840 * Forces this view's layer to be created and this view to be rendered 18841 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 18842 * invoking this method will have no effect. 18843 * 18844 * This method can for instance be used to render a view into its layer before 18845 * starting an animation. If this view is complex, rendering into the layer 18846 * before starting the animation will avoid skipping frames. 18847 * 18848 * @throws IllegalStateException If this view is not attached to a window 18849 * 18850 * @see #setLayerType(int, android.graphics.Paint) 18851 */ 18852 public void buildLayer() { 18853 if (mLayerType == LAYER_TYPE_NONE) return; 18854 18855 final AttachInfo attachInfo = mAttachInfo; 18856 if (attachInfo == null) { 18857 throw new IllegalStateException("This view must be attached to a window first"); 18858 } 18859 18860 if (getWidth() == 0 || getHeight() == 0) { 18861 return; 18862 } 18863 18864 switch (mLayerType) { 18865 case LAYER_TYPE_HARDWARE: 18866 updateDisplayListIfDirty(); 18867 if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) { 18868 attachInfo.mThreadedRenderer.buildLayer(mRenderNode); 18869 } 18870 break; 18871 case LAYER_TYPE_SOFTWARE: 18872 buildDrawingCache(true); 18873 break; 18874 } 18875 } 18876 18877 /** 18878 * Destroys all hardware rendering resources. This method is invoked 18879 * when the system needs to reclaim resources. Upon execution of this 18880 * method, you should free any OpenGL resources created by the view. 18881 * 18882 * Note: you <strong>must</strong> call 18883 * <code>super.destroyHardwareResources()</code> when overriding 18884 * this method. 18885 * 18886 * @hide 18887 */ 18888 @CallSuper 18889 protected void destroyHardwareResources() { 18890 if (mOverlay != null) { 18891 mOverlay.getOverlayView().destroyHardwareResources(); 18892 } 18893 if (mGhostView != null) { 18894 mGhostView.destroyHardwareResources(); 18895 } 18896 } 18897 18898 /** 18899 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 18900 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 18901 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 18902 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 18903 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 18904 * null.</p> 18905 * 18906 * <p>Enabling the drawing cache is similar to 18907 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 18908 * acceleration is turned off. When hardware acceleration is turned on, enabling the 18909 * drawing cache has no effect on rendering because the system uses a different mechanism 18910 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 18911 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 18912 * for information on how to enable software and hardware layers.</p> 18913 * 18914 * <p>This API can be used to manually generate 18915 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 18916 * {@link #getDrawingCache()}.</p> 18917 * 18918 * @param enabled true to enable the drawing cache, false otherwise 18919 * 18920 * @see #isDrawingCacheEnabled() 18921 * @see #getDrawingCache() 18922 * @see #buildDrawingCache() 18923 * @see #setLayerType(int, android.graphics.Paint) 18924 * 18925 * @deprecated The view drawing cache was largely made obsolete with the introduction of 18926 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 18927 * layers are largely unnecessary and can easily result in a net loss in performance due to the 18928 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 18929 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 18930 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 18931 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 18932 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 18933 * software-rendered usages are discouraged and have compatibility issues with hardware-only 18934 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 18935 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 18936 * reports or unit testing the {@link PixelCopy} API is recommended. 18937 */ 18938 @Deprecated 18939 public void setDrawingCacheEnabled(boolean enabled) { 18940 mCachingFailed = false; 18941 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 18942 } 18943 18944 /** 18945 * <p>Indicates whether the drawing cache is enabled for this view.</p> 18946 * 18947 * @return true if the drawing cache is enabled 18948 * 18949 * @see #setDrawingCacheEnabled(boolean) 18950 * @see #getDrawingCache() 18951 * 18952 * @deprecated The view drawing cache was largely made obsolete with the introduction of 18953 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 18954 * layers are largely unnecessary and can easily result in a net loss in performance due to the 18955 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 18956 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 18957 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 18958 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 18959 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 18960 * software-rendered usages are discouraged and have compatibility issues with hardware-only 18961 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 18962 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 18963 * reports or unit testing the {@link PixelCopy} API is recommended. 18964 */ 18965 @Deprecated 18966 @ViewDebug.ExportedProperty(category = "drawing") 18967 public boolean isDrawingCacheEnabled() { 18968 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 18969 } 18970 18971 /** 18972 * Debugging utility which recursively outputs the dirty state of a view and its 18973 * descendants. 18974 * 18975 * @hide 18976 */ 18977 @SuppressWarnings({"UnusedDeclaration"}) 18978 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 18979 Log.d(VIEW_LOG_TAG, indent + this + " DIRTY(" 18980 + (mPrivateFlags & View.PFLAG_DIRTY_MASK) 18981 + ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" 18982 + (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) 18983 + ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 18984 if (clear) { 18985 mPrivateFlags &= clearMask; 18986 } 18987 if (this instanceof ViewGroup) { 18988 ViewGroup parent = (ViewGroup) this; 18989 final int count = parent.getChildCount(); 18990 for (int i = 0; i < count; i++) { 18991 final View child = parent.getChildAt(i); 18992 child.outputDirtyFlags(indent + " ", clear, clearMask); 18993 } 18994 } 18995 } 18996 18997 /** 18998 * This method is used by ViewGroup to cause its children to restore or recreate their 18999 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 19000 * to recreate its own display list, which would happen if it went through the normal 19001 * draw/dispatchDraw mechanisms. 19002 * 19003 * @hide 19004 */ 19005 protected void dispatchGetDisplayList() {} 19006 19007 /** 19008 * A view that is not attached or hardware accelerated cannot create a display list. 19009 * This method checks these conditions and returns the appropriate result. 19010 * 19011 * @return true if view has the ability to create a display list, false otherwise. 19012 * 19013 * @hide 19014 */ 19015 public boolean canHaveDisplayList() { 19016 return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null); 19017 } 19018 19019 /** 19020 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 19021 * @hide 19022 */ 19023 @NonNull 19024 public RenderNode updateDisplayListIfDirty() { 19025 final RenderNode renderNode = mRenderNode; 19026 if (!canHaveDisplayList()) { 19027 // can't populate RenderNode, don't try 19028 return renderNode; 19029 } 19030 19031 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 19032 || !renderNode.isValid() 19033 || (mRecreateDisplayList)) { 19034 // Don't need to recreate the display list, just need to tell our 19035 // children to restore/recreate theirs 19036 if (renderNode.isValid() 19037 && !mRecreateDisplayList) { 19038 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 19039 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 19040 dispatchGetDisplayList(); 19041 19042 return renderNode; // no work needed 19043 } 19044 19045 // If we got here, we're recreating it. Mark it as such to ensure that 19046 // we copy in child display lists into ours in drawChild() 19047 mRecreateDisplayList = true; 19048 19049 int width = mRight - mLeft; 19050 int height = mBottom - mTop; 19051 int layerType = getLayerType(); 19052 19053 final DisplayListCanvas canvas = renderNode.start(width, height); 19054 19055 try { 19056 if (layerType == LAYER_TYPE_SOFTWARE) { 19057 buildDrawingCache(true); 19058 Bitmap cache = getDrawingCache(true); 19059 if (cache != null) { 19060 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 19061 } 19062 } else { 19063 computeScroll(); 19064 19065 canvas.translate(-mScrollX, -mScrollY); 19066 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 19067 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 19068 19069 // Fast path for layouts with no backgrounds 19070 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 19071 dispatchDraw(canvas); 19072 drawAutofilledHighlight(canvas); 19073 if (mOverlay != null && !mOverlay.isEmpty()) { 19074 mOverlay.getOverlayView().draw(canvas); 19075 } 19076 if (debugDraw()) { 19077 debugDrawFocus(canvas); 19078 } 19079 } else { 19080 draw(canvas); 19081 } 19082 } 19083 } finally { 19084 renderNode.end(canvas); 19085 setDisplayListProperties(renderNode); 19086 } 19087 } else { 19088 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 19089 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 19090 } 19091 return renderNode; 19092 } 19093 19094 private void resetDisplayList() { 19095 mRenderNode.discardDisplayList(); 19096 if (mBackgroundRenderNode != null) { 19097 mBackgroundRenderNode.discardDisplayList(); 19098 } 19099 } 19100 19101 /** 19102 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 19103 * 19104 * @return A non-scaled bitmap representing this view or null if cache is disabled. 19105 * 19106 * @see #getDrawingCache(boolean) 19107 * 19108 * @deprecated The view drawing cache was largely made obsolete with the introduction of 19109 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 19110 * layers are largely unnecessary and can easily result in a net loss in performance due to the 19111 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 19112 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 19113 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 19114 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 19115 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 19116 * software-rendered usages are discouraged and have compatibility issues with hardware-only 19117 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 19118 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 19119 * reports or unit testing the {@link PixelCopy} API is recommended. 19120 */ 19121 @Deprecated 19122 public Bitmap getDrawingCache() { 19123 return getDrawingCache(false); 19124 } 19125 19126 /** 19127 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 19128 * is null when caching is disabled. If caching is enabled and the cache is not ready, 19129 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 19130 * draw from the cache when the cache is enabled. To benefit from the cache, you must 19131 * request the drawing cache by calling this method and draw it on screen if the 19132 * returned bitmap is not null.</p> 19133 * 19134 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 19135 * this method will create a bitmap of the same size as this view. Because this bitmap 19136 * will be drawn scaled by the parent ViewGroup, the result on screen might show 19137 * scaling artifacts. To avoid such artifacts, you should call this method by setting 19138 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 19139 * size than the view. This implies that your application must be able to handle this 19140 * size.</p> 19141 * 19142 * @param autoScale Indicates whether the generated bitmap should be scaled based on 19143 * the current density of the screen when the application is in compatibility 19144 * mode. 19145 * 19146 * @return A bitmap representing this view or null if cache is disabled. 19147 * 19148 * @see #setDrawingCacheEnabled(boolean) 19149 * @see #isDrawingCacheEnabled() 19150 * @see #buildDrawingCache(boolean) 19151 * @see #destroyDrawingCache() 19152 * 19153 * @deprecated The view drawing cache was largely made obsolete with the introduction of 19154 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 19155 * layers are largely unnecessary and can easily result in a net loss in performance due to the 19156 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 19157 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 19158 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 19159 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 19160 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 19161 * software-rendered usages are discouraged and have compatibility issues with hardware-only 19162 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 19163 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 19164 * reports or unit testing the {@link PixelCopy} API is recommended. 19165 */ 19166 @Deprecated 19167 public Bitmap getDrawingCache(boolean autoScale) { 19168 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 19169 return null; 19170 } 19171 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 19172 buildDrawingCache(autoScale); 19173 } 19174 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 19175 } 19176 19177 /** 19178 * <p>Frees the resources used by the drawing cache. If you call 19179 * {@link #buildDrawingCache()} manually without calling 19180 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 19181 * should cleanup the cache with this method afterwards.</p> 19182 * 19183 * @see #setDrawingCacheEnabled(boolean) 19184 * @see #buildDrawingCache() 19185 * @see #getDrawingCache() 19186 * 19187 * @deprecated The view drawing cache was largely made obsolete with the introduction of 19188 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 19189 * layers are largely unnecessary and can easily result in a net loss in performance due to the 19190 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 19191 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 19192 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 19193 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 19194 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 19195 * software-rendered usages are discouraged and have compatibility issues with hardware-only 19196 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 19197 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 19198 * reports or unit testing the {@link PixelCopy} API is recommended. 19199 */ 19200 @Deprecated 19201 public void destroyDrawingCache() { 19202 if (mDrawingCache != null) { 19203 mDrawingCache.recycle(); 19204 mDrawingCache = null; 19205 } 19206 if (mUnscaledDrawingCache != null) { 19207 mUnscaledDrawingCache.recycle(); 19208 mUnscaledDrawingCache = null; 19209 } 19210 } 19211 19212 /** 19213 * Setting a solid background color for the drawing cache's bitmaps will improve 19214 * performance and memory usage. Note, though that this should only be used if this 19215 * view will always be drawn on top of a solid color. 19216 * 19217 * @param color The background color to use for the drawing cache's bitmap 19218 * 19219 * @see #setDrawingCacheEnabled(boolean) 19220 * @see #buildDrawingCache() 19221 * @see #getDrawingCache() 19222 * 19223 * @deprecated The view drawing cache was largely made obsolete with the introduction of 19224 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 19225 * layers are largely unnecessary and can easily result in a net loss in performance due to the 19226 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 19227 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 19228 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 19229 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 19230 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 19231 * software-rendered usages are discouraged and have compatibility issues with hardware-only 19232 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 19233 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 19234 * reports or unit testing the {@link PixelCopy} API is recommended. 19235 */ 19236 @Deprecated 19237 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 19238 if (color != mDrawingCacheBackgroundColor) { 19239 mDrawingCacheBackgroundColor = color; 19240 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 19241 } 19242 } 19243 19244 /** 19245 * @see #setDrawingCacheBackgroundColor(int) 19246 * 19247 * @return The background color to used for the drawing cache's bitmap 19248 * 19249 * @deprecated The view drawing cache was largely made obsolete with the introduction of 19250 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 19251 * layers are largely unnecessary and can easily result in a net loss in performance due to the 19252 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 19253 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 19254 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 19255 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 19256 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 19257 * software-rendered usages are discouraged and have compatibility issues with hardware-only 19258 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 19259 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 19260 * reports or unit testing the {@link PixelCopy} API is recommended. 19261 */ 19262 @Deprecated 19263 @ColorInt 19264 public int getDrawingCacheBackgroundColor() { 19265 return mDrawingCacheBackgroundColor; 19266 } 19267 19268 /** 19269 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 19270 * 19271 * @see #buildDrawingCache(boolean) 19272 * 19273 * @deprecated The view drawing cache was largely made obsolete with the introduction of 19274 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 19275 * layers are largely unnecessary and can easily result in a net loss in performance due to the 19276 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 19277 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 19278 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 19279 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 19280 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 19281 * software-rendered usages are discouraged and have compatibility issues with hardware-only 19282 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 19283 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 19284 * reports or unit testing the {@link PixelCopy} API is recommended. 19285 */ 19286 @Deprecated 19287 public void buildDrawingCache() { 19288 buildDrawingCache(false); 19289 } 19290 19291 /** 19292 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 19293 * 19294 * <p>If you call {@link #buildDrawingCache()} manually without calling 19295 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 19296 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 19297 * 19298 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 19299 * this method will create a bitmap of the same size as this view. Because this bitmap 19300 * will be drawn scaled by the parent ViewGroup, the result on screen might show 19301 * scaling artifacts. To avoid such artifacts, you should call this method by setting 19302 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 19303 * size than the view. This implies that your application must be able to handle this 19304 * size.</p> 19305 * 19306 * <p>You should avoid calling this method when hardware acceleration is enabled. If 19307 * you do not need the drawing cache bitmap, calling this method will increase memory 19308 * usage and cause the view to be rendered in software once, thus negatively impacting 19309 * performance.</p> 19310 * 19311 * @see #getDrawingCache() 19312 * @see #destroyDrawingCache() 19313 * 19314 * @deprecated The view drawing cache was largely made obsolete with the introduction of 19315 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache 19316 * layers are largely unnecessary and can easily result in a net loss in performance due to the 19317 * cost of creating and updating the layer. In the rare cases where caching layers are useful, 19318 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware 19319 * rendering. For software-rendered snapshots of a small part of the View hierarchy or 19320 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or 19321 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these 19322 * software-rendered usages are discouraged and have compatibility issues with hardware-only 19323 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} 19324 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback 19325 * reports or unit testing the {@link PixelCopy} API is recommended. 19326 */ 19327 @Deprecated 19328 public void buildDrawingCache(boolean autoScale) { 19329 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 19330 mDrawingCache == null : mUnscaledDrawingCache == null)) { 19331 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 19332 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 19333 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 19334 } 19335 try { 19336 buildDrawingCacheImpl(autoScale); 19337 } finally { 19338 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 19339 } 19340 } 19341 } 19342 19343 /** 19344 * private, internal implementation of buildDrawingCache, used to enable tracing 19345 */ 19346 private void buildDrawingCacheImpl(boolean autoScale) { 19347 mCachingFailed = false; 19348 19349 int width = mRight - mLeft; 19350 int height = mBottom - mTop; 19351 19352 final AttachInfo attachInfo = mAttachInfo; 19353 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 19354 19355 if (autoScale && scalingRequired) { 19356 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 19357 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 19358 } 19359 19360 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 19361 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 19362 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 19363 19364 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 19365 final long drawingCacheSize = 19366 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 19367 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 19368 if (width > 0 && height > 0) { 19369 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 19370 + " too large to fit into a software layer (or drawing cache), needs " 19371 + projectedBitmapSize + " bytes, only " 19372 + drawingCacheSize + " available"); 19373 } 19374 destroyDrawingCache(); 19375 mCachingFailed = true; 19376 return; 19377 } 19378 19379 boolean clear = true; 19380 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 19381 19382 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 19383 Bitmap.Config quality; 19384 if (!opaque) { 19385 // Never pick ARGB_4444 because it looks awful 19386 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 19387 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 19388 case DRAWING_CACHE_QUALITY_AUTO: 19389 case DRAWING_CACHE_QUALITY_LOW: 19390 case DRAWING_CACHE_QUALITY_HIGH: 19391 default: 19392 quality = Bitmap.Config.ARGB_8888; 19393 break; 19394 } 19395 } else { 19396 // Optimization for translucent windows 19397 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 19398 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 19399 } 19400 19401 // Try to cleanup memory 19402 if (bitmap != null) bitmap.recycle(); 19403 19404 try { 19405 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 19406 width, height, quality); 19407 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 19408 if (autoScale) { 19409 mDrawingCache = bitmap; 19410 } else { 19411 mUnscaledDrawingCache = bitmap; 19412 } 19413 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 19414 } catch (OutOfMemoryError e) { 19415 // If there is not enough memory to create the bitmap cache, just 19416 // ignore the issue as bitmap caches are not required to draw the 19417 // view hierarchy 19418 if (autoScale) { 19419 mDrawingCache = null; 19420 } else { 19421 mUnscaledDrawingCache = null; 19422 } 19423 mCachingFailed = true; 19424 return; 19425 } 19426 19427 clear = drawingCacheBackgroundColor != 0; 19428 } 19429 19430 Canvas canvas; 19431 if (attachInfo != null) { 19432 canvas = attachInfo.mCanvas; 19433 if (canvas == null) { 19434 canvas = new Canvas(); 19435 } 19436 canvas.setBitmap(bitmap); 19437 // Temporarily clobber the cached Canvas in case one of our children 19438 // is also using a drawing cache. Without this, the children would 19439 // steal the canvas by attaching their own bitmap to it and bad, bad 19440 // thing would happen (invisible views, corrupted drawings, etc.) 19441 attachInfo.mCanvas = null; 19442 } else { 19443 // This case should hopefully never or seldom happen 19444 canvas = new Canvas(bitmap); 19445 } 19446 19447 if (clear) { 19448 bitmap.eraseColor(drawingCacheBackgroundColor); 19449 } 19450 19451 computeScroll(); 19452 final int restoreCount = canvas.save(); 19453 19454 if (autoScale && scalingRequired) { 19455 final float scale = attachInfo.mApplicationScale; 19456 canvas.scale(scale, scale); 19457 } 19458 19459 canvas.translate(-mScrollX, -mScrollY); 19460 19461 mPrivateFlags |= PFLAG_DRAWN; 19462 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 19463 mLayerType != LAYER_TYPE_NONE) { 19464 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 19465 } 19466 19467 // Fast path for layouts with no backgrounds 19468 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 19469 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 19470 dispatchDraw(canvas); 19471 drawAutofilledHighlight(canvas); 19472 if (mOverlay != null && !mOverlay.isEmpty()) { 19473 mOverlay.getOverlayView().draw(canvas); 19474 } 19475 } else { 19476 draw(canvas); 19477 } 19478 19479 canvas.restoreToCount(restoreCount); 19480 canvas.setBitmap(null); 19481 19482 if (attachInfo != null) { 19483 // Restore the cached Canvas for our siblings 19484 attachInfo.mCanvas = canvas; 19485 } 19486 } 19487 19488 /** 19489 * Create a snapshot of the view into a bitmap. We should probably make 19490 * some form of this public, but should think about the API. 19491 * 19492 * @hide 19493 */ 19494 public Bitmap createSnapshot(ViewDebug.CanvasProvider canvasProvider, boolean skipChildren) { 19495 int width = mRight - mLeft; 19496 int height = mBottom - mTop; 19497 19498 final AttachInfo attachInfo = mAttachInfo; 19499 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 19500 width = (int) ((width * scale) + 0.5f); 19501 height = (int) ((height * scale) + 0.5f); 19502 19503 Canvas oldCanvas = null; 19504 try { 19505 Canvas canvas = canvasProvider.getCanvas(this, 19506 width > 0 ? width : 1, height > 0 ? height : 1); 19507 19508 if (attachInfo != null) { 19509 oldCanvas = attachInfo.mCanvas; 19510 // Temporarily clobber the cached Canvas in case one of our children 19511 // is also using a drawing cache. Without this, the children would 19512 // steal the canvas by attaching their own bitmap to it and bad, bad 19513 // things would happen (invisible views, corrupted drawings, etc.) 19514 attachInfo.mCanvas = null; 19515 } 19516 19517 computeScroll(); 19518 final int restoreCount = canvas.save(); 19519 canvas.scale(scale, scale); 19520 canvas.translate(-mScrollX, -mScrollY); 19521 19522 // Temporarily remove the dirty mask 19523 int flags = mPrivateFlags; 19524 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 19525 19526 // Fast path for layouts with no backgrounds 19527 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 19528 dispatchDraw(canvas); 19529 drawAutofilledHighlight(canvas); 19530 if (mOverlay != null && !mOverlay.isEmpty()) { 19531 mOverlay.getOverlayView().draw(canvas); 19532 } 19533 } else { 19534 draw(canvas); 19535 } 19536 19537 mPrivateFlags = flags; 19538 canvas.restoreToCount(restoreCount); 19539 return canvasProvider.createBitmap(); 19540 } finally { 19541 if (oldCanvas != null) { 19542 attachInfo.mCanvas = oldCanvas; 19543 } 19544 } 19545 } 19546 19547 /** 19548 * Indicates whether this View is currently in edit mode. A View is usually 19549 * in edit mode when displayed within a developer tool. For instance, if 19550 * this View is being drawn by a visual user interface builder, this method 19551 * should return true. 19552 * 19553 * Subclasses should check the return value of this method to provide 19554 * different behaviors if their normal behavior might interfere with the 19555 * host environment. For instance: the class spawns a thread in its 19556 * constructor, the drawing code relies on device-specific features, etc. 19557 * 19558 * This method is usually checked in the drawing code of custom widgets. 19559 * 19560 * @return True if this View is in edit mode, false otherwise. 19561 */ 19562 public boolean isInEditMode() { 19563 return false; 19564 } 19565 19566 /** 19567 * If the View draws content inside its padding and enables fading edges, 19568 * it needs to support padding offsets. Padding offsets are added to the 19569 * fading edges to extend the length of the fade so that it covers pixels 19570 * drawn inside the padding. 19571 * 19572 * Subclasses of this class should override this method if they need 19573 * to draw content inside the padding. 19574 * 19575 * @return True if padding offset must be applied, false otherwise. 19576 * 19577 * @see #getLeftPaddingOffset() 19578 * @see #getRightPaddingOffset() 19579 * @see #getTopPaddingOffset() 19580 * @see #getBottomPaddingOffset() 19581 * 19582 * @since CURRENT 19583 */ 19584 protected boolean isPaddingOffsetRequired() { 19585 return false; 19586 } 19587 19588 /** 19589 * Amount by which to extend the left fading region. Called only when 19590 * {@link #isPaddingOffsetRequired()} returns true. 19591 * 19592 * @return The left padding offset in pixels. 19593 * 19594 * @see #isPaddingOffsetRequired() 19595 * 19596 * @since CURRENT 19597 */ 19598 protected int getLeftPaddingOffset() { 19599 return 0; 19600 } 19601 19602 /** 19603 * Amount by which to extend the right fading region. Called only when 19604 * {@link #isPaddingOffsetRequired()} returns true. 19605 * 19606 * @return The right padding offset in pixels. 19607 * 19608 * @see #isPaddingOffsetRequired() 19609 * 19610 * @since CURRENT 19611 */ 19612 protected int getRightPaddingOffset() { 19613 return 0; 19614 } 19615 19616 /** 19617 * Amount by which to extend the top fading region. Called only when 19618 * {@link #isPaddingOffsetRequired()} returns true. 19619 * 19620 * @return The top padding offset in pixels. 19621 * 19622 * @see #isPaddingOffsetRequired() 19623 * 19624 * @since CURRENT 19625 */ 19626 protected int getTopPaddingOffset() { 19627 return 0; 19628 } 19629 19630 /** 19631 * Amount by which to extend the bottom fading region. Called only when 19632 * {@link #isPaddingOffsetRequired()} returns true. 19633 * 19634 * @return The bottom padding offset in pixels. 19635 * 19636 * @see #isPaddingOffsetRequired() 19637 * 19638 * @since CURRENT 19639 */ 19640 protected int getBottomPaddingOffset() { 19641 return 0; 19642 } 19643 19644 /** 19645 * @hide 19646 * @param offsetRequired 19647 */ 19648 protected int getFadeTop(boolean offsetRequired) { 19649 int top = mPaddingTop; 19650 if (offsetRequired) top += getTopPaddingOffset(); 19651 return top; 19652 } 19653 19654 /** 19655 * @hide 19656 * @param offsetRequired 19657 */ 19658 protected int getFadeHeight(boolean offsetRequired) { 19659 int padding = mPaddingTop; 19660 if (offsetRequired) padding += getTopPaddingOffset(); 19661 return mBottom - mTop - mPaddingBottom - padding; 19662 } 19663 19664 /** 19665 * <p>Indicates whether this view is attached to a hardware accelerated 19666 * window or not.</p> 19667 * 19668 * <p>Even if this method returns true, it does not mean that every call 19669 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 19670 * accelerated {@link android.graphics.Canvas}. For instance, if this view 19671 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 19672 * window is hardware accelerated, 19673 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 19674 * return false, and this method will return true.</p> 19675 * 19676 * @return True if the view is attached to a window and the window is 19677 * hardware accelerated; false in any other case. 19678 */ 19679 @ViewDebug.ExportedProperty(category = "drawing") 19680 public boolean isHardwareAccelerated() { 19681 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 19682 } 19683 19684 /** 19685 * Sets a rectangular area on this view to which the view will be clipped 19686 * when it is drawn. Setting the value to null will remove the clip bounds 19687 * and the view will draw normally, using its full bounds. 19688 * 19689 * @param clipBounds The rectangular area, in the local coordinates of 19690 * this view, to which future drawing operations will be clipped. 19691 */ 19692 public void setClipBounds(Rect clipBounds) { 19693 if (clipBounds == mClipBounds 19694 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 19695 return; 19696 } 19697 if (clipBounds != null) { 19698 if (mClipBounds == null) { 19699 mClipBounds = new Rect(clipBounds); 19700 } else { 19701 mClipBounds.set(clipBounds); 19702 } 19703 } else { 19704 mClipBounds = null; 19705 } 19706 mRenderNode.setClipBounds(mClipBounds); 19707 invalidateViewProperty(false, false); 19708 } 19709 19710 /** 19711 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 19712 * 19713 * @return A copy of the current clip bounds if clip bounds are set, 19714 * otherwise null. 19715 */ 19716 public Rect getClipBounds() { 19717 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 19718 } 19719 19720 19721 /** 19722 * Populates an output rectangle with the clip bounds of the view, 19723 * returning {@code true} if successful or {@code false} if the view's 19724 * clip bounds are {@code null}. 19725 * 19726 * @param outRect rectangle in which to place the clip bounds of the view 19727 * @return {@code true} if successful or {@code false} if the view's 19728 * clip bounds are {@code null} 19729 */ 19730 public boolean getClipBounds(Rect outRect) { 19731 if (mClipBounds != null) { 19732 outRect.set(mClipBounds); 19733 return true; 19734 } 19735 return false; 19736 } 19737 19738 /** 19739 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 19740 * case of an active Animation being run on the view. 19741 */ 19742 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 19743 Animation a, boolean scalingRequired) { 19744 Transformation invalidationTransform; 19745 final int flags = parent.mGroupFlags; 19746 final boolean initialized = a.isInitialized(); 19747 if (!initialized) { 19748 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 19749 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 19750 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 19751 onAnimationStart(); 19752 } 19753 19754 final Transformation t = parent.getChildTransformation(); 19755 boolean more = a.getTransformation(drawingTime, t, 1f); 19756 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 19757 if (parent.mInvalidationTransformation == null) { 19758 parent.mInvalidationTransformation = new Transformation(); 19759 } 19760 invalidationTransform = parent.mInvalidationTransformation; 19761 a.getTransformation(drawingTime, invalidationTransform, 1f); 19762 } else { 19763 invalidationTransform = t; 19764 } 19765 19766 if (more) { 19767 if (!a.willChangeBounds()) { 19768 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 19769 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 19770 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 19771 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 19772 // The child need to draw an animation, potentially offscreen, so 19773 // make sure we do not cancel invalidate requests 19774 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 19775 parent.invalidate(mLeft, mTop, mRight, mBottom); 19776 } 19777 } else { 19778 if (parent.mInvalidateRegion == null) { 19779 parent.mInvalidateRegion = new RectF(); 19780 } 19781 final RectF region = parent.mInvalidateRegion; 19782 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 19783 invalidationTransform); 19784 19785 // The child need to draw an animation, potentially offscreen, so 19786 // make sure we do not cancel invalidate requests 19787 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 19788 19789 final int left = mLeft + (int) region.left; 19790 final int top = mTop + (int) region.top; 19791 parent.invalidate(left, top, left + (int) (region.width() + .5f), 19792 top + (int) (region.height() + .5f)); 19793 } 19794 } 19795 return more; 19796 } 19797 19798 /** 19799 * This method is called by getDisplayList() when a display list is recorded for a View. 19800 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 19801 */ 19802 void setDisplayListProperties(RenderNode renderNode) { 19803 if (renderNode != null) { 19804 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 19805 renderNode.setClipToBounds(mParent instanceof ViewGroup 19806 && ((ViewGroup) mParent).getClipChildren()); 19807 19808 float alpha = 1; 19809 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 19810 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 19811 ViewGroup parentVG = (ViewGroup) mParent; 19812 final Transformation t = parentVG.getChildTransformation(); 19813 if (parentVG.getChildStaticTransformation(this, t)) { 19814 final int transformType = t.getTransformationType(); 19815 if (transformType != Transformation.TYPE_IDENTITY) { 19816 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 19817 alpha = t.getAlpha(); 19818 } 19819 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 19820 renderNode.setStaticMatrix(t.getMatrix()); 19821 } 19822 } 19823 } 19824 } 19825 if (mTransformationInfo != null) { 19826 alpha *= getFinalAlpha(); 19827 if (alpha < 1) { 19828 final int multipliedAlpha = (int) (255 * alpha); 19829 if (onSetAlpha(multipliedAlpha)) { 19830 alpha = 1; 19831 } 19832 } 19833 renderNode.setAlpha(alpha); 19834 } else if (alpha < 1) { 19835 renderNode.setAlpha(alpha); 19836 } 19837 } 19838 } 19839 19840 /** 19841 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 19842 * 19843 * This is where the View specializes rendering behavior based on layer type, 19844 * and hardware acceleration. 19845 */ 19846 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 19847 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 19848 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 19849 * 19850 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 19851 * HW accelerated, it can't handle drawing RenderNodes. 19852 */ 19853 boolean drawingWithRenderNode = mAttachInfo != null 19854 && mAttachInfo.mHardwareAccelerated 19855 && hardwareAcceleratedCanvas; 19856 19857 boolean more = false; 19858 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 19859 final int parentFlags = parent.mGroupFlags; 19860 19861 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 19862 parent.getChildTransformation().clear(); 19863 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 19864 } 19865 19866 Transformation transformToApply = null; 19867 boolean concatMatrix = false; 19868 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 19869 final Animation a = getAnimation(); 19870 if (a != null) { 19871 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 19872 concatMatrix = a.willChangeTransformationMatrix(); 19873 if (concatMatrix) { 19874 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 19875 } 19876 transformToApply = parent.getChildTransformation(); 19877 } else { 19878 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 19879 // No longer animating: clear out old animation matrix 19880 mRenderNode.setAnimationMatrix(null); 19881 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 19882 } 19883 if (!drawingWithRenderNode 19884 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 19885 final Transformation t = parent.getChildTransformation(); 19886 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 19887 if (hasTransform) { 19888 final int transformType = t.getTransformationType(); 19889 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 19890 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 19891 } 19892 } 19893 } 19894 19895 concatMatrix |= !childHasIdentityMatrix; 19896 19897 // Sets the flag as early as possible to allow draw() implementations 19898 // to call invalidate() successfully when doing animations 19899 mPrivateFlags |= PFLAG_DRAWN; 19900 19901 if (!concatMatrix && 19902 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 19903 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 19904 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 19905 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 19906 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 19907 return more; 19908 } 19909 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 19910 19911 if (hardwareAcceleratedCanvas) { 19912 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 19913 // retain the flag's value temporarily in the mRecreateDisplayList flag 19914 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 19915 mPrivateFlags &= ~PFLAG_INVALIDATED; 19916 } 19917 19918 RenderNode renderNode = null; 19919 Bitmap cache = null; 19920 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 19921 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 19922 if (layerType != LAYER_TYPE_NONE) { 19923 // If not drawing with RenderNode, treat HW layers as SW 19924 layerType = LAYER_TYPE_SOFTWARE; 19925 buildDrawingCache(true); 19926 } 19927 cache = getDrawingCache(true); 19928 } 19929 19930 if (drawingWithRenderNode) { 19931 // Delay getting the display list until animation-driven alpha values are 19932 // set up and possibly passed on to the view 19933 renderNode = updateDisplayListIfDirty(); 19934 if (!renderNode.isValid()) { 19935 // Uncommon, but possible. If a view is removed from the hierarchy during the call 19936 // to getDisplayList(), the display list will be marked invalid and we should not 19937 // try to use it again. 19938 renderNode = null; 19939 drawingWithRenderNode = false; 19940 } 19941 } 19942 19943 int sx = 0; 19944 int sy = 0; 19945 if (!drawingWithRenderNode) { 19946 computeScroll(); 19947 sx = mScrollX; 19948 sy = mScrollY; 19949 } 19950 19951 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 19952 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 19953 19954 int restoreTo = -1; 19955 if (!drawingWithRenderNode || transformToApply != null) { 19956 restoreTo = canvas.save(); 19957 } 19958 if (offsetForScroll) { 19959 canvas.translate(mLeft - sx, mTop - sy); 19960 } else { 19961 if (!drawingWithRenderNode) { 19962 canvas.translate(mLeft, mTop); 19963 } 19964 if (scalingRequired) { 19965 if (drawingWithRenderNode) { 19966 // TODO: Might not need this if we put everything inside the DL 19967 restoreTo = canvas.save(); 19968 } 19969 // mAttachInfo cannot be null, otherwise scalingRequired == false 19970 final float scale = 1.0f / mAttachInfo.mApplicationScale; 19971 canvas.scale(scale, scale); 19972 } 19973 } 19974 19975 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 19976 if (transformToApply != null 19977 || alpha < 1 19978 || !hasIdentityMatrix() 19979 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 19980 if (transformToApply != null || !childHasIdentityMatrix) { 19981 int transX = 0; 19982 int transY = 0; 19983 19984 if (offsetForScroll) { 19985 transX = -sx; 19986 transY = -sy; 19987 } 19988 19989 if (transformToApply != null) { 19990 if (concatMatrix) { 19991 if (drawingWithRenderNode) { 19992 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 19993 } else { 19994 // Undo the scroll translation, apply the transformation matrix, 19995 // then redo the scroll translate to get the correct result. 19996 canvas.translate(-transX, -transY); 19997 canvas.concat(transformToApply.getMatrix()); 19998 canvas.translate(transX, transY); 19999 } 20000 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 20001 } 20002 20003 float transformAlpha = transformToApply.getAlpha(); 20004 if (transformAlpha < 1) { 20005 alpha *= transformAlpha; 20006 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 20007 } 20008 } 20009 20010 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 20011 canvas.translate(-transX, -transY); 20012 canvas.concat(getMatrix()); 20013 canvas.translate(transX, transY); 20014 } 20015 } 20016 20017 // Deal with alpha if it is or used to be <1 20018 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 20019 if (alpha < 1) { 20020 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 20021 } else { 20022 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 20023 } 20024 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 20025 if (!drawingWithDrawingCache) { 20026 final int multipliedAlpha = (int) (255 * alpha); 20027 if (!onSetAlpha(multipliedAlpha)) { 20028 if (drawingWithRenderNode) { 20029 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 20030 } else if (layerType == LAYER_TYPE_NONE) { 20031 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 20032 multipliedAlpha); 20033 } 20034 } else { 20035 // Alpha is handled by the child directly, clobber the layer's alpha 20036 mPrivateFlags |= PFLAG_ALPHA_SET; 20037 } 20038 } 20039 } 20040 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 20041 onSetAlpha(255); 20042 mPrivateFlags &= ~PFLAG_ALPHA_SET; 20043 } 20044 20045 if (!drawingWithRenderNode) { 20046 // apply clips directly, since RenderNode won't do it for this draw 20047 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 20048 if (offsetForScroll) { 20049 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 20050 } else { 20051 if (!scalingRequired || cache == null) { 20052 canvas.clipRect(0, 0, getWidth(), getHeight()); 20053 } else { 20054 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 20055 } 20056 } 20057 } 20058 20059 if (mClipBounds != null) { 20060 // clip bounds ignore scroll 20061 canvas.clipRect(mClipBounds); 20062 } 20063 } 20064 20065 if (!drawingWithDrawingCache) { 20066 if (drawingWithRenderNode) { 20067 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 20068 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 20069 } else { 20070 // Fast path for layouts with no backgrounds 20071 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 20072 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 20073 dispatchDraw(canvas); 20074 } else { 20075 draw(canvas); 20076 } 20077 } 20078 } else if (cache != null) { 20079 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 20080 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 20081 // no layer paint, use temporary paint to draw bitmap 20082 Paint cachePaint = parent.mCachePaint; 20083 if (cachePaint == null) { 20084 cachePaint = new Paint(); 20085 cachePaint.setDither(false); 20086 parent.mCachePaint = cachePaint; 20087 } 20088 cachePaint.setAlpha((int) (alpha * 255)); 20089 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 20090 } else { 20091 // use layer paint to draw the bitmap, merging the two alphas, but also restore 20092 int layerPaintAlpha = mLayerPaint.getAlpha(); 20093 if (alpha < 1) { 20094 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 20095 } 20096 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 20097 if (alpha < 1) { 20098 mLayerPaint.setAlpha(layerPaintAlpha); 20099 } 20100 } 20101 } 20102 20103 if (restoreTo >= 0) { 20104 canvas.restoreToCount(restoreTo); 20105 } 20106 20107 if (a != null && !more) { 20108 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 20109 onSetAlpha(255); 20110 } 20111 parent.finishAnimatingView(this, a); 20112 } 20113 20114 if (more && hardwareAcceleratedCanvas) { 20115 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 20116 // alpha animations should cause the child to recreate its display list 20117 invalidate(true); 20118 } 20119 } 20120 20121 mRecreateDisplayList = false; 20122 20123 return more; 20124 } 20125 20126 static Paint getDebugPaint() { 20127 if (sDebugPaint == null) { 20128 sDebugPaint = new Paint(); 20129 sDebugPaint.setAntiAlias(false); 20130 } 20131 return sDebugPaint; 20132 } 20133 20134 final int dipsToPixels(int dips) { 20135 float scale = getContext().getResources().getDisplayMetrics().density; 20136 return (int) (dips * scale + 0.5f); 20137 } 20138 20139 final private void debugDrawFocus(Canvas canvas) { 20140 if (isFocused()) { 20141 final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP); 20142 final int l = mScrollX; 20143 final int r = l + mRight - mLeft; 20144 final int t = mScrollY; 20145 final int b = t + mBottom - mTop; 20146 20147 final Paint paint = getDebugPaint(); 20148 paint.setColor(DEBUG_CORNERS_COLOR); 20149 20150 // Draw squares in corners. 20151 paint.setStyle(Paint.Style.FILL); 20152 canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint); 20153 canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint); 20154 canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint); 20155 canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint); 20156 20157 // Draw big X across the view. 20158 paint.setStyle(Paint.Style.STROKE); 20159 canvas.drawLine(l, t, r, b, paint); 20160 canvas.drawLine(l, b, r, t, paint); 20161 } 20162 } 20163 20164 /** 20165 * Manually render this view (and all of its children) to the given Canvas. 20166 * The view must have already done a full layout before this function is 20167 * called. When implementing a view, implement 20168 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 20169 * If you do need to override this method, call the superclass version. 20170 * 20171 * @param canvas The Canvas to which the View is rendered. 20172 */ 20173 @CallSuper 20174 public void draw(Canvas canvas) { 20175 final int privateFlags = mPrivateFlags; 20176 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 20177 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 20178 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 20179 20180 /* 20181 * Draw traversal performs several drawing steps which must be executed 20182 * in the appropriate order: 20183 * 20184 * 1. Draw the background 20185 * 2. If necessary, save the canvas' layers to prepare for fading 20186 * 3. Draw view's content 20187 * 4. Draw children 20188 * 5. If necessary, draw the fading edges and restore layers 20189 * 6. Draw decorations (scrollbars for instance) 20190 */ 20191 20192 // Step 1, draw the background, if needed 20193 int saveCount; 20194 20195 if (!dirtyOpaque) { 20196 drawBackground(canvas); 20197 } 20198 20199 // skip step 2 & 5 if possible (common case) 20200 final int viewFlags = mViewFlags; 20201 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 20202 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 20203 if (!verticalEdges && !horizontalEdges) { 20204 // Step 3, draw the content 20205 if (!dirtyOpaque) onDraw(canvas); 20206 20207 // Step 4, draw the children 20208 dispatchDraw(canvas); 20209 20210 drawAutofilledHighlight(canvas); 20211 20212 // Overlay is part of the content and draws beneath Foreground 20213 if (mOverlay != null && !mOverlay.isEmpty()) { 20214 mOverlay.getOverlayView().dispatchDraw(canvas); 20215 } 20216 20217 // Step 6, draw decorations (foreground, scrollbars) 20218 onDrawForeground(canvas); 20219 20220 // Step 7, draw the default focus highlight 20221 drawDefaultFocusHighlight(canvas); 20222 20223 if (debugDraw()) { 20224 debugDrawFocus(canvas); 20225 } 20226 20227 // we're done... 20228 return; 20229 } 20230 20231 /* 20232 * Here we do the full fledged routine... 20233 * (this is an uncommon case where speed matters less, 20234 * this is why we repeat some of the tests that have been 20235 * done above) 20236 */ 20237 20238 boolean drawTop = false; 20239 boolean drawBottom = false; 20240 boolean drawLeft = false; 20241 boolean drawRight = false; 20242 20243 float topFadeStrength = 0.0f; 20244 float bottomFadeStrength = 0.0f; 20245 float leftFadeStrength = 0.0f; 20246 float rightFadeStrength = 0.0f; 20247 20248 // Step 2, save the canvas' layers 20249 int paddingLeft = mPaddingLeft; 20250 20251 final boolean offsetRequired = isPaddingOffsetRequired(); 20252 if (offsetRequired) { 20253 paddingLeft += getLeftPaddingOffset(); 20254 } 20255 20256 int left = mScrollX + paddingLeft; 20257 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 20258 int top = mScrollY + getFadeTop(offsetRequired); 20259 int bottom = top + getFadeHeight(offsetRequired); 20260 20261 if (offsetRequired) { 20262 right += getRightPaddingOffset(); 20263 bottom += getBottomPaddingOffset(); 20264 } 20265 20266 final ScrollabilityCache scrollabilityCache = mScrollCache; 20267 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 20268 int length = (int) fadeHeight; 20269 20270 // clip the fade length if top and bottom fades overlap 20271 // overlapping fades produce odd-looking artifacts 20272 if (verticalEdges && (top + length > bottom - length)) { 20273 length = (bottom - top) / 2; 20274 } 20275 20276 // also clip horizontal fades if necessary 20277 if (horizontalEdges && (left + length > right - length)) { 20278 length = (right - left) / 2; 20279 } 20280 20281 if (verticalEdges) { 20282 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 20283 drawTop = topFadeStrength * fadeHeight > 1.0f; 20284 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 20285 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 20286 } 20287 20288 if (horizontalEdges) { 20289 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 20290 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 20291 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 20292 drawRight = rightFadeStrength * fadeHeight > 1.0f; 20293 } 20294 20295 saveCount = canvas.getSaveCount(); 20296 20297 int solidColor = getSolidColor(); 20298 if (solidColor == 0) { 20299 if (drawTop) { 20300 canvas.saveUnclippedLayer(left, top, right, top + length); 20301 } 20302 20303 if (drawBottom) { 20304 canvas.saveUnclippedLayer(left, bottom - length, right, bottom); 20305 } 20306 20307 if (drawLeft) { 20308 canvas.saveUnclippedLayer(left, top, left + length, bottom); 20309 } 20310 20311 if (drawRight) { 20312 canvas.saveUnclippedLayer(right - length, top, right, bottom); 20313 } 20314 } else { 20315 scrollabilityCache.setFadeColor(solidColor); 20316 } 20317 20318 // Step 3, draw the content 20319 if (!dirtyOpaque) onDraw(canvas); 20320 20321 // Step 4, draw the children 20322 dispatchDraw(canvas); 20323 20324 // Step 5, draw the fade effect and restore layers 20325 final Paint p = scrollabilityCache.paint; 20326 final Matrix matrix = scrollabilityCache.matrix; 20327 final Shader fade = scrollabilityCache.shader; 20328 20329 if (drawTop) { 20330 matrix.setScale(1, fadeHeight * topFadeStrength); 20331 matrix.postTranslate(left, top); 20332 fade.setLocalMatrix(matrix); 20333 p.setShader(fade); 20334 canvas.drawRect(left, top, right, top + length, p); 20335 } 20336 20337 if (drawBottom) { 20338 matrix.setScale(1, fadeHeight * bottomFadeStrength); 20339 matrix.postRotate(180); 20340 matrix.postTranslate(left, bottom); 20341 fade.setLocalMatrix(matrix); 20342 p.setShader(fade); 20343 canvas.drawRect(left, bottom - length, right, bottom, p); 20344 } 20345 20346 if (drawLeft) { 20347 matrix.setScale(1, fadeHeight * leftFadeStrength); 20348 matrix.postRotate(-90); 20349 matrix.postTranslate(left, top); 20350 fade.setLocalMatrix(matrix); 20351 p.setShader(fade); 20352 canvas.drawRect(left, top, left + length, bottom, p); 20353 } 20354 20355 if (drawRight) { 20356 matrix.setScale(1, fadeHeight * rightFadeStrength); 20357 matrix.postRotate(90); 20358 matrix.postTranslate(right, top); 20359 fade.setLocalMatrix(matrix); 20360 p.setShader(fade); 20361 canvas.drawRect(right - length, top, right, bottom, p); 20362 } 20363 20364 canvas.restoreToCount(saveCount); 20365 20366 drawAutofilledHighlight(canvas); 20367 20368 // Overlay is part of the content and draws beneath Foreground 20369 if (mOverlay != null && !mOverlay.isEmpty()) { 20370 mOverlay.getOverlayView().dispatchDraw(canvas); 20371 } 20372 20373 // Step 6, draw decorations (foreground, scrollbars) 20374 onDrawForeground(canvas); 20375 20376 if (debugDraw()) { 20377 debugDrawFocus(canvas); 20378 } 20379 } 20380 20381 /** 20382 * Draws the background onto the specified canvas. 20383 * 20384 * @param canvas Canvas on which to draw the background 20385 */ 20386 private void drawBackground(Canvas canvas) { 20387 final Drawable background = mBackground; 20388 if (background == null) { 20389 return; 20390 } 20391 20392 setBackgroundBounds(); 20393 20394 // Attempt to use a display list if requested. 20395 if (canvas.isHardwareAccelerated() && mAttachInfo != null 20396 && mAttachInfo.mThreadedRenderer != null) { 20397 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 20398 20399 final RenderNode renderNode = mBackgroundRenderNode; 20400 if (renderNode != null && renderNode.isValid()) { 20401 setBackgroundRenderNodeProperties(renderNode); 20402 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 20403 return; 20404 } 20405 } 20406 20407 final int scrollX = mScrollX; 20408 final int scrollY = mScrollY; 20409 if ((scrollX | scrollY) == 0) { 20410 background.draw(canvas); 20411 } else { 20412 canvas.translate(scrollX, scrollY); 20413 background.draw(canvas); 20414 canvas.translate(-scrollX, -scrollY); 20415 } 20416 } 20417 20418 /** 20419 * Sets the correct background bounds and rebuilds the outline, if needed. 20420 * <p/> 20421 * This is called by LayoutLib. 20422 */ 20423 void setBackgroundBounds() { 20424 if (mBackgroundSizeChanged && mBackground != null) { 20425 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 20426 mBackgroundSizeChanged = false; 20427 rebuildOutline(); 20428 } 20429 } 20430 20431 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 20432 renderNode.setTranslationX(mScrollX); 20433 renderNode.setTranslationY(mScrollY); 20434 } 20435 20436 /** 20437 * Creates a new display list or updates the existing display list for the 20438 * specified Drawable. 20439 * 20440 * @param drawable Drawable for which to create a display list 20441 * @param renderNode Existing RenderNode, or {@code null} 20442 * @return A valid display list for the specified drawable 20443 */ 20444 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 20445 if (renderNode == null) { 20446 renderNode = RenderNode.create(drawable.getClass().getName(), this); 20447 } 20448 20449 final Rect bounds = drawable.getBounds(); 20450 final int width = bounds.width(); 20451 final int height = bounds.height(); 20452 final DisplayListCanvas canvas = renderNode.start(width, height); 20453 20454 // Reverse left/top translation done by drawable canvas, which will 20455 // instead be applied by rendernode's LTRB bounds below. This way, the 20456 // drawable's bounds match with its rendernode bounds and its content 20457 // will lie within those bounds in the rendernode tree. 20458 canvas.translate(-bounds.left, -bounds.top); 20459 20460 try { 20461 drawable.draw(canvas); 20462 } finally { 20463 renderNode.end(canvas); 20464 } 20465 20466 // Set up drawable properties that are view-independent. 20467 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 20468 renderNode.setProjectBackwards(drawable.isProjected()); 20469 renderNode.setProjectionReceiver(true); 20470 renderNode.setClipToBounds(false); 20471 return renderNode; 20472 } 20473 20474 /** 20475 * Returns the overlay for this view, creating it if it does not yet exist. 20476 * Adding drawables to the overlay will cause them to be displayed whenever 20477 * the view itself is redrawn. Objects in the overlay should be actively 20478 * managed: remove them when they should not be displayed anymore. The 20479 * overlay will always have the same size as its host view. 20480 * 20481 * <p>Note: Overlays do not currently work correctly with {@link 20482 * SurfaceView} or {@link TextureView}; contents in overlays for these 20483 * types of views may not display correctly.</p> 20484 * 20485 * @return The ViewOverlay object for this view. 20486 * @see ViewOverlay 20487 */ 20488 public ViewOverlay getOverlay() { 20489 if (mOverlay == null) { 20490 mOverlay = new ViewOverlay(mContext, this); 20491 } 20492 return mOverlay; 20493 } 20494 20495 /** 20496 * Override this if your view is known to always be drawn on top of a solid color background, 20497 * and needs to draw fading edges. Returning a non-zero color enables the view system to 20498 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 20499 * should be set to 0xFF. 20500 * 20501 * @see #setVerticalFadingEdgeEnabled(boolean) 20502 * @see #setHorizontalFadingEdgeEnabled(boolean) 20503 * 20504 * @return The known solid color background for this view, or 0 if the color may vary 20505 */ 20506 @ViewDebug.ExportedProperty(category = "drawing") 20507 @ColorInt 20508 public int getSolidColor() { 20509 return 0; 20510 } 20511 20512 /** 20513 * Build a human readable string representation of the specified view flags. 20514 * 20515 * @param flags the view flags to convert to a string 20516 * @return a String representing the supplied flags 20517 */ 20518 private static String printFlags(int flags) { 20519 String output = ""; 20520 int numFlags = 0; 20521 if ((flags & FOCUSABLE) == FOCUSABLE) { 20522 output += "TAKES_FOCUS"; 20523 numFlags++; 20524 } 20525 20526 switch (flags & VISIBILITY_MASK) { 20527 case INVISIBLE: 20528 if (numFlags > 0) { 20529 output += " "; 20530 } 20531 output += "INVISIBLE"; 20532 // USELESS HERE numFlags++; 20533 break; 20534 case GONE: 20535 if (numFlags > 0) { 20536 output += " "; 20537 } 20538 output += "GONE"; 20539 // USELESS HERE numFlags++; 20540 break; 20541 default: 20542 break; 20543 } 20544 return output; 20545 } 20546 20547 /** 20548 * Build a human readable string representation of the specified private 20549 * view flags. 20550 * 20551 * @param privateFlags the private view flags to convert to a string 20552 * @return a String representing the supplied flags 20553 */ 20554 private static String printPrivateFlags(int privateFlags) { 20555 String output = ""; 20556 int numFlags = 0; 20557 20558 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 20559 output += "WANTS_FOCUS"; 20560 numFlags++; 20561 } 20562 20563 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 20564 if (numFlags > 0) { 20565 output += " "; 20566 } 20567 output += "FOCUSED"; 20568 numFlags++; 20569 } 20570 20571 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 20572 if (numFlags > 0) { 20573 output += " "; 20574 } 20575 output += "SELECTED"; 20576 numFlags++; 20577 } 20578 20579 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 20580 if (numFlags > 0) { 20581 output += " "; 20582 } 20583 output += "IS_ROOT_NAMESPACE"; 20584 numFlags++; 20585 } 20586 20587 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 20588 if (numFlags > 0) { 20589 output += " "; 20590 } 20591 output += "HAS_BOUNDS"; 20592 numFlags++; 20593 } 20594 20595 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 20596 if (numFlags > 0) { 20597 output += " "; 20598 } 20599 output += "DRAWN"; 20600 // USELESS HERE numFlags++; 20601 } 20602 return output; 20603 } 20604 20605 /** 20606 * <p>Indicates whether or not this view's layout will be requested during 20607 * the next hierarchy layout pass.</p> 20608 * 20609 * @return true if the layout will be forced during next layout pass 20610 */ 20611 public boolean isLayoutRequested() { 20612 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 20613 } 20614 20615 /** 20616 * Return true if o is a ViewGroup that is laying out using optical bounds. 20617 * @hide 20618 */ 20619 public static boolean isLayoutModeOptical(Object o) { 20620 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 20621 } 20622 20623 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 20624 Insets parentInsets = mParent instanceof View ? 20625 ((View) mParent).getOpticalInsets() : Insets.NONE; 20626 Insets childInsets = getOpticalInsets(); 20627 return setFrame( 20628 left + parentInsets.left - childInsets.left, 20629 top + parentInsets.top - childInsets.top, 20630 right + parentInsets.left + childInsets.right, 20631 bottom + parentInsets.top + childInsets.bottom); 20632 } 20633 20634 /** 20635 * Assign a size and position to a view and all of its 20636 * descendants 20637 * 20638 * <p>This is the second phase of the layout mechanism. 20639 * (The first is measuring). In this phase, each parent calls 20640 * layout on all of its children to position them. 20641 * This is typically done using the child measurements 20642 * that were stored in the measure pass().</p> 20643 * 20644 * <p>Derived classes should not override this method. 20645 * Derived classes with children should override 20646 * onLayout. In that method, they should 20647 * call layout on each of their children.</p> 20648 * 20649 * @param l Left position, relative to parent 20650 * @param t Top position, relative to parent 20651 * @param r Right position, relative to parent 20652 * @param b Bottom position, relative to parent 20653 */ 20654 @SuppressWarnings({"unchecked"}) 20655 public void layout(int l, int t, int r, int b) { 20656 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 20657 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 20658 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 20659 } 20660 20661 int oldL = mLeft; 20662 int oldT = mTop; 20663 int oldB = mBottom; 20664 int oldR = mRight; 20665 20666 boolean changed = isLayoutModeOptical(mParent) ? 20667 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 20668 20669 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 20670 onLayout(changed, l, t, r, b); 20671 20672 if (shouldDrawRoundScrollbar()) { 20673 if(mRoundScrollbarRenderer == null) { 20674 mRoundScrollbarRenderer = new RoundScrollbarRenderer(this); 20675 } 20676 } else { 20677 mRoundScrollbarRenderer = null; 20678 } 20679 20680 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 20681 20682 ListenerInfo li = mListenerInfo; 20683 if (li != null && li.mOnLayoutChangeListeners != null) { 20684 ArrayList<OnLayoutChangeListener> listenersCopy = 20685 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 20686 int numListeners = listenersCopy.size(); 20687 for (int i = 0; i < numListeners; ++i) { 20688 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 20689 } 20690 } 20691 } 20692 20693 final boolean wasLayoutValid = isLayoutValid(); 20694 20695 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 20696 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 20697 20698 if (!wasLayoutValid && isFocused()) { 20699 mPrivateFlags &= ~PFLAG_WANTS_FOCUS; 20700 if (canTakeFocus()) { 20701 // We have a robust focus, so parents should no longer be wanting focus. 20702 clearParentsWantFocus(); 20703 } else if (getViewRootImpl() == null || !getViewRootImpl().isInLayout()) { 20704 // This is a weird case. Most-likely the user, rather than ViewRootImpl, called 20705 // layout. In this case, there's no guarantee that parent layouts will be evaluated 20706 // and thus the safest action is to clear focus here. 20707 clearFocusInternal(null, /* propagate */ true, /* refocus */ false); 20708 clearParentsWantFocus(); 20709 } else if (!hasParentWantsFocus()) { 20710 // original requestFocus was likely on this view directly, so just clear focus 20711 clearFocusInternal(null, /* propagate */ true, /* refocus */ false); 20712 } 20713 // otherwise, we let parents handle re-assigning focus during their layout passes. 20714 } else if ((mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) { 20715 mPrivateFlags &= ~PFLAG_WANTS_FOCUS; 20716 View focused = findFocus(); 20717 if (focused != null) { 20718 // Try to restore focus as close as possible to our starting focus. 20719 if (!restoreDefaultFocus() && !hasParentWantsFocus()) { 20720 // Give up and clear focus once we've reached the top-most parent which wants 20721 // focus. 20722 focused.clearFocusInternal(null, /* propagate */ true, /* refocus */ false); 20723 } 20724 } 20725 } 20726 20727 if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) { 20728 mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT; 20729 notifyEnterOrExitForAutoFillIfNeeded(true); 20730 } 20731 } 20732 20733 private boolean hasParentWantsFocus() { 20734 ViewParent parent = mParent; 20735 while (parent instanceof ViewGroup) { 20736 ViewGroup pv = (ViewGroup) parent; 20737 if ((pv.mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) { 20738 return true; 20739 } 20740 parent = pv.mParent; 20741 } 20742 return false; 20743 } 20744 20745 /** 20746 * Called from layout when this view should 20747 * assign a size and position to each of its children. 20748 * 20749 * Derived classes with children should override 20750 * this method and call layout on each of 20751 * their children. 20752 * @param changed This is a new size or position for this view 20753 * @param left Left position, relative to parent 20754 * @param top Top position, relative to parent 20755 * @param right Right position, relative to parent 20756 * @param bottom Bottom position, relative to parent 20757 */ 20758 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 20759 } 20760 20761 /** 20762 * Assign a size and position to this view. 20763 * 20764 * This is called from layout. 20765 * 20766 * @param left Left position, relative to parent 20767 * @param top Top position, relative to parent 20768 * @param right Right position, relative to parent 20769 * @param bottom Bottom position, relative to parent 20770 * @return true if the new size and position are different than the 20771 * previous ones 20772 * {@hide} 20773 */ 20774 protected boolean setFrame(int left, int top, int right, int bottom) { 20775 boolean changed = false; 20776 20777 if (DBG) { 20778 Log.d(VIEW_LOG_TAG, this + " View.setFrame(" + left + "," + top + "," 20779 + right + "," + bottom + ")"); 20780 } 20781 20782 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 20783 changed = true; 20784 20785 // Remember our drawn bit 20786 int drawn = mPrivateFlags & PFLAG_DRAWN; 20787 20788 int oldWidth = mRight - mLeft; 20789 int oldHeight = mBottom - mTop; 20790 int newWidth = right - left; 20791 int newHeight = bottom - top; 20792 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 20793 20794 // Invalidate our old position 20795 invalidate(sizeChanged); 20796 20797 mLeft = left; 20798 mTop = top; 20799 mRight = right; 20800 mBottom = bottom; 20801 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 20802 20803 mPrivateFlags |= PFLAG_HAS_BOUNDS; 20804 20805 20806 if (sizeChanged) { 20807 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 20808 } 20809 20810 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 20811 // If we are visible, force the DRAWN bit to on so that 20812 // this invalidate will go through (at least to our parent). 20813 // This is because someone may have invalidated this view 20814 // before this call to setFrame came in, thereby clearing 20815 // the DRAWN bit. 20816 mPrivateFlags |= PFLAG_DRAWN; 20817 invalidate(sizeChanged); 20818 // parent display list may need to be recreated based on a change in the bounds 20819 // of any child 20820 invalidateParentCaches(); 20821 } 20822 20823 // Reset drawn bit to original value (invalidate turns it off) 20824 mPrivateFlags |= drawn; 20825 20826 mBackgroundSizeChanged = true; 20827 mDefaultFocusHighlightSizeChanged = true; 20828 if (mForegroundInfo != null) { 20829 mForegroundInfo.mBoundsChanged = true; 20830 } 20831 20832 notifySubtreeAccessibilityStateChangedIfNeeded(); 20833 } 20834 return changed; 20835 } 20836 20837 /** 20838 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 20839 * @hide 20840 */ 20841 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 20842 setFrame(left, top, right, bottom); 20843 } 20844 20845 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 20846 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 20847 if (mOverlay != null) { 20848 mOverlay.getOverlayView().setRight(newWidth); 20849 mOverlay.getOverlayView().setBottom(newHeight); 20850 } 20851 // If this isn't laid out yet, focus assignment will be handled during the "deferment/ 20852 // backtracking" of requestFocus during layout, so don't touch focus here. 20853 if (!sCanFocusZeroSized && isLayoutValid()) { 20854 if (newWidth <= 0 || newHeight <= 0) { 20855 if (hasFocus()) { 20856 clearFocus(); 20857 if (mParent instanceof ViewGroup) { 20858 ((ViewGroup) mParent).clearFocusedInCluster(); 20859 } 20860 } 20861 clearAccessibilityFocus(); 20862 } else if (oldWidth <= 0 || oldHeight <= 0) { 20863 if (mParent != null && canTakeFocus()) { 20864 mParent.focusableViewAvailable(this); 20865 } 20866 } 20867 } 20868 rebuildOutline(); 20869 } 20870 20871 /** 20872 * Finalize inflating a view from XML. This is called as the last phase 20873 * of inflation, after all child views have been added. 20874 * 20875 * <p>Even if the subclass overrides onFinishInflate, they should always be 20876 * sure to call the super method, so that we get called. 20877 */ 20878 @CallSuper 20879 protected void onFinishInflate() { 20880 } 20881 20882 /** 20883 * Returns the resources associated with this view. 20884 * 20885 * @return Resources object. 20886 */ 20887 public Resources getResources() { 20888 return mResources; 20889 } 20890 20891 /** 20892 * Invalidates the specified Drawable. 20893 * 20894 * @param drawable the drawable to invalidate 20895 */ 20896 @Override 20897 public void invalidateDrawable(@NonNull Drawable drawable) { 20898 if (verifyDrawable(drawable)) { 20899 final Rect dirty = drawable.getDirtyBounds(); 20900 final int scrollX = mScrollX; 20901 final int scrollY = mScrollY; 20902 20903 invalidate(dirty.left + scrollX, dirty.top + scrollY, 20904 dirty.right + scrollX, dirty.bottom + scrollY); 20905 rebuildOutline(); 20906 } 20907 } 20908 20909 /** 20910 * Schedules an action on a drawable to occur at a specified time. 20911 * 20912 * @param who the recipient of the action 20913 * @param what the action to run on the drawable 20914 * @param when the time at which the action must occur. Uses the 20915 * {@link SystemClock#uptimeMillis} timebase. 20916 */ 20917 @Override 20918 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 20919 if (verifyDrawable(who) && what != null) { 20920 final long delay = when - SystemClock.uptimeMillis(); 20921 if (mAttachInfo != null) { 20922 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 20923 Choreographer.CALLBACK_ANIMATION, what, who, 20924 Choreographer.subtractFrameDelay(delay)); 20925 } else { 20926 // Postpone the runnable until we know 20927 // on which thread it needs to run. 20928 getRunQueue().postDelayed(what, delay); 20929 } 20930 } 20931 } 20932 20933 /** 20934 * Cancels a scheduled action on a drawable. 20935 * 20936 * @param who the recipient of the action 20937 * @param what the action to cancel 20938 */ 20939 @Override 20940 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 20941 if (verifyDrawable(who) && what != null) { 20942 if (mAttachInfo != null) { 20943 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 20944 Choreographer.CALLBACK_ANIMATION, what, who); 20945 } 20946 getRunQueue().removeCallbacks(what); 20947 } 20948 } 20949 20950 /** 20951 * Unschedule any events associated with the given Drawable. This can be 20952 * used when selecting a new Drawable into a view, so that the previous 20953 * one is completely unscheduled. 20954 * 20955 * @param who The Drawable to unschedule. 20956 * 20957 * @see #drawableStateChanged 20958 */ 20959 public void unscheduleDrawable(Drawable who) { 20960 if (mAttachInfo != null && who != null) { 20961 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 20962 Choreographer.CALLBACK_ANIMATION, null, who); 20963 } 20964 } 20965 20966 /** 20967 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 20968 * that the View directionality can and will be resolved before its Drawables. 20969 * 20970 * Will call {@link View#onResolveDrawables} when resolution is done. 20971 * 20972 * @hide 20973 */ 20974 protected void resolveDrawables() { 20975 // Drawables resolution may need to happen before resolving the layout direction (which is 20976 // done only during the measure() call). 20977 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 20978 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 20979 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 20980 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 20981 // direction to be resolved as its resolved value will be the same as its raw value. 20982 if (!isLayoutDirectionResolved() && 20983 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 20984 return; 20985 } 20986 20987 final int layoutDirection = isLayoutDirectionResolved() ? 20988 getLayoutDirection() : getRawLayoutDirection(); 20989 20990 if (mBackground != null) { 20991 mBackground.setLayoutDirection(layoutDirection); 20992 } 20993 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 20994 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 20995 } 20996 if (mDefaultFocusHighlight != null) { 20997 mDefaultFocusHighlight.setLayoutDirection(layoutDirection); 20998 } 20999 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 21000 onResolveDrawables(layoutDirection); 21001 } 21002 21003 boolean areDrawablesResolved() { 21004 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 21005 } 21006 21007 /** 21008 * Called when layout direction has been resolved. 21009 * 21010 * The default implementation does nothing. 21011 * 21012 * @param layoutDirection The resolved layout direction. 21013 * 21014 * @see #LAYOUT_DIRECTION_LTR 21015 * @see #LAYOUT_DIRECTION_RTL 21016 * 21017 * @hide 21018 */ 21019 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 21020 } 21021 21022 /** 21023 * @hide 21024 */ 21025 protected void resetResolvedDrawables() { 21026 resetResolvedDrawablesInternal(); 21027 } 21028 21029 void resetResolvedDrawablesInternal() { 21030 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 21031 } 21032 21033 /** 21034 * If your view subclass is displaying its own Drawable objects, it should 21035 * override this function and return true for any Drawable it is 21036 * displaying. This allows animations for those drawables to be 21037 * scheduled. 21038 * 21039 * <p>Be sure to call through to the super class when overriding this 21040 * function. 21041 * 21042 * @param who The Drawable to verify. Return true if it is one you are 21043 * displaying, else return the result of calling through to the 21044 * super class. 21045 * 21046 * @return boolean If true than the Drawable is being displayed in the 21047 * view; else false and it is not allowed to animate. 21048 * 21049 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 21050 * @see #drawableStateChanged() 21051 */ 21052 @CallSuper 21053 protected boolean verifyDrawable(@NonNull Drawable who) { 21054 // Avoid verifying the scroll bar drawable so that we don't end up in 21055 // an invalidation loop. This effectively prevents the scroll bar 21056 // drawable from triggering invalidations and scheduling runnables. 21057 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who) 21058 || (mDefaultFocusHighlight == who); 21059 } 21060 21061 /** 21062 * This function is called whenever the state of the view changes in such 21063 * a way that it impacts the state of drawables being shown. 21064 * <p> 21065 * If the View has a StateListAnimator, it will also be called to run necessary state 21066 * change animations. 21067 * <p> 21068 * Be sure to call through to the superclass when overriding this function. 21069 * 21070 * @see Drawable#setState(int[]) 21071 */ 21072 @CallSuper 21073 protected void drawableStateChanged() { 21074 final int[] state = getDrawableState(); 21075 boolean changed = false; 21076 21077 final Drawable bg = mBackground; 21078 if (bg != null && bg.isStateful()) { 21079 changed |= bg.setState(state); 21080 } 21081 21082 final Drawable hl = mDefaultFocusHighlight; 21083 if (hl != null && hl.isStateful()) { 21084 changed |= hl.setState(state); 21085 } 21086 21087 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 21088 if (fg != null && fg.isStateful()) { 21089 changed |= fg.setState(state); 21090 } 21091 21092 if (mScrollCache != null) { 21093 final Drawable scrollBar = mScrollCache.scrollBar; 21094 if (scrollBar != null && scrollBar.isStateful()) { 21095 changed |= scrollBar.setState(state) 21096 && mScrollCache.state != ScrollabilityCache.OFF; 21097 } 21098 } 21099 21100 if (mStateListAnimator != null) { 21101 mStateListAnimator.setState(state); 21102 } 21103 21104 if (changed) { 21105 invalidate(); 21106 } 21107 } 21108 21109 /** 21110 * This function is called whenever the view hotspot changes and needs to 21111 * be propagated to drawables or child views managed by the view. 21112 * <p> 21113 * Dispatching to child views is handled by 21114 * {@link #dispatchDrawableHotspotChanged(float, float)}. 21115 * <p> 21116 * Be sure to call through to the superclass when overriding this function. 21117 * 21118 * @param x hotspot x coordinate 21119 * @param y hotspot y coordinate 21120 */ 21121 @CallSuper 21122 public void drawableHotspotChanged(float x, float y) { 21123 if (mBackground != null) { 21124 mBackground.setHotspot(x, y); 21125 } 21126 if (mDefaultFocusHighlight != null) { 21127 mDefaultFocusHighlight.setHotspot(x, y); 21128 } 21129 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 21130 mForegroundInfo.mDrawable.setHotspot(x, y); 21131 } 21132 21133 dispatchDrawableHotspotChanged(x, y); 21134 } 21135 21136 /** 21137 * Dispatches drawableHotspotChanged to all of this View's children. 21138 * 21139 * @param x hotspot x coordinate 21140 * @param y hotspot y coordinate 21141 * @see #drawableHotspotChanged(float, float) 21142 */ 21143 public void dispatchDrawableHotspotChanged(float x, float y) { 21144 } 21145 21146 /** 21147 * Call this to force a view to update its drawable state. This will cause 21148 * drawableStateChanged to be called on this view. Views that are interested 21149 * in the new state should call getDrawableState. 21150 * 21151 * @see #drawableStateChanged 21152 * @see #getDrawableState 21153 */ 21154 public void refreshDrawableState() { 21155 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 21156 drawableStateChanged(); 21157 21158 ViewParent parent = mParent; 21159 if (parent != null) { 21160 parent.childDrawableStateChanged(this); 21161 } 21162 } 21163 21164 /** 21165 * Create a default focus highlight if it doesn't exist. 21166 * @return a default focus highlight. 21167 */ 21168 private Drawable getDefaultFocusHighlightDrawable() { 21169 if (mDefaultFocusHighlightCache == null) { 21170 if (mContext != null) { 21171 final int[] attrs = new int[] { android.R.attr.selectableItemBackground }; 21172 final TypedArray ta = mContext.obtainStyledAttributes(attrs); 21173 mDefaultFocusHighlightCache = ta.getDrawable(0); 21174 ta.recycle(); 21175 } 21176 } 21177 return mDefaultFocusHighlightCache; 21178 } 21179 21180 /** 21181 * Set the current default focus highlight. 21182 * @param highlight the highlight drawable, or {@code null} if it's no longer needed. 21183 */ 21184 private void setDefaultFocusHighlight(Drawable highlight) { 21185 mDefaultFocusHighlight = highlight; 21186 mDefaultFocusHighlightSizeChanged = true; 21187 if (highlight != null) { 21188 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 21189 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 21190 } 21191 highlight.setLayoutDirection(getLayoutDirection()); 21192 if (highlight.isStateful()) { 21193 highlight.setState(getDrawableState()); 21194 } 21195 if (isAttachedToWindow()) { 21196 highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 21197 } 21198 // Set callback last, since the view may still be initializing. 21199 highlight.setCallback(this); 21200 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null 21201 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 21202 mPrivateFlags |= PFLAG_SKIP_DRAW; 21203 } 21204 invalidate(); 21205 } 21206 21207 /** 21208 * Check whether we need to draw a default focus highlight when this view gets focused, 21209 * which requires: 21210 * <ul> 21211 * <li>In both background and foreground, {@link android.R.attr#state_focused} 21212 * is not defined.</li> 21213 * <li>This view is not in touch mode.</li> 21214 * <li>This view doesn't opt out for a default focus highlight, via 21215 * {@link #setDefaultFocusHighlightEnabled(boolean)}.</li> 21216 * <li>This view is attached to window.</li> 21217 * </ul> 21218 * @return {@code true} if a default focus highlight is needed. 21219 * @hide 21220 */ 21221 @TestApi 21222 public boolean isDefaultFocusHighlightNeeded(Drawable background, Drawable foreground) { 21223 final boolean lackFocusState = (background == null || !background.isStateful() 21224 || !background.hasFocusStateSpecified()) 21225 && (foreground == null || !foreground.isStateful() 21226 || !foreground.hasFocusStateSpecified()); 21227 return !isInTouchMode() && getDefaultFocusHighlightEnabled() && lackFocusState 21228 && isAttachedToWindow() && sUseDefaultFocusHighlight; 21229 } 21230 21231 /** 21232 * When this view is focused, switches on/off the default focused highlight. 21233 * <p> 21234 * This always happens when this view is focused, and only at this moment the default focus 21235 * highlight can be visible. 21236 */ 21237 private void switchDefaultFocusHighlight() { 21238 if (isFocused()) { 21239 final boolean needed = isDefaultFocusHighlightNeeded(mBackground, 21240 mForegroundInfo == null ? null : mForegroundInfo.mDrawable); 21241 final boolean active = mDefaultFocusHighlight != null; 21242 if (needed && !active) { 21243 setDefaultFocusHighlight(getDefaultFocusHighlightDrawable()); 21244 } else if (!needed && active) { 21245 // The highlight is no longer needed, so tear it down. 21246 setDefaultFocusHighlight(null); 21247 } 21248 } 21249 } 21250 21251 /** 21252 * Draw the default focus highlight onto the canvas. 21253 * @param canvas the canvas where we're drawing the highlight. 21254 */ 21255 private void drawDefaultFocusHighlight(Canvas canvas) { 21256 if (mDefaultFocusHighlight != null) { 21257 if (mDefaultFocusHighlightSizeChanged) { 21258 mDefaultFocusHighlightSizeChanged = false; 21259 final int l = mScrollX; 21260 final int r = l + mRight - mLeft; 21261 final int t = mScrollY; 21262 final int b = t + mBottom - mTop; 21263 mDefaultFocusHighlight.setBounds(l, t, r, b); 21264 } 21265 mDefaultFocusHighlight.draw(canvas); 21266 } 21267 } 21268 21269 /** 21270 * Return an array of resource IDs of the drawable states representing the 21271 * current state of the view. 21272 * 21273 * @return The current drawable state 21274 * 21275 * @see Drawable#setState(int[]) 21276 * @see #drawableStateChanged() 21277 * @see #onCreateDrawableState(int) 21278 */ 21279 public final int[] getDrawableState() { 21280 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 21281 return mDrawableState; 21282 } else { 21283 mDrawableState = onCreateDrawableState(0); 21284 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 21285 return mDrawableState; 21286 } 21287 } 21288 21289 /** 21290 * Generate the new {@link android.graphics.drawable.Drawable} state for 21291 * this view. This is called by the view 21292 * system when the cached Drawable state is determined to be invalid. To 21293 * retrieve the current state, you should use {@link #getDrawableState}. 21294 * 21295 * @param extraSpace if non-zero, this is the number of extra entries you 21296 * would like in the returned array in which you can place your own 21297 * states. 21298 * 21299 * @return Returns an array holding the current {@link Drawable} state of 21300 * the view. 21301 * 21302 * @see #mergeDrawableStates(int[], int[]) 21303 */ 21304 protected int[] onCreateDrawableState(int extraSpace) { 21305 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 21306 mParent instanceof View) { 21307 return ((View) mParent).onCreateDrawableState(extraSpace); 21308 } 21309 21310 int[] drawableState; 21311 21312 int privateFlags = mPrivateFlags; 21313 21314 int viewStateIndex = 0; 21315 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 21316 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 21317 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 21318 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 21319 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 21320 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 21321 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 21322 ThreadedRenderer.isAvailable()) { 21323 // This is set if HW acceleration is requested, even if the current 21324 // process doesn't allow it. This is just to allow app preview 21325 // windows to better match their app. 21326 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 21327 } 21328 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 21329 21330 final int privateFlags2 = mPrivateFlags2; 21331 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 21332 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 21333 } 21334 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 21335 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 21336 } 21337 21338 drawableState = StateSet.get(viewStateIndex); 21339 21340 //noinspection ConstantIfStatement 21341 if (false) { 21342 Log.i("View", "drawableStateIndex=" + viewStateIndex); 21343 Log.i("View", toString() 21344 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 21345 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 21346 + " fo=" + hasFocus() 21347 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 21348 + " wf=" + hasWindowFocus() 21349 + ": " + Arrays.toString(drawableState)); 21350 } 21351 21352 if (extraSpace == 0) { 21353 return drawableState; 21354 } 21355 21356 final int[] fullState; 21357 if (drawableState != null) { 21358 fullState = new int[drawableState.length + extraSpace]; 21359 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 21360 } else { 21361 fullState = new int[extraSpace]; 21362 } 21363 21364 return fullState; 21365 } 21366 21367 /** 21368 * Merge your own state values in <var>additionalState</var> into the base 21369 * state values <var>baseState</var> that were returned by 21370 * {@link #onCreateDrawableState(int)}. 21371 * 21372 * @param baseState The base state values returned by 21373 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 21374 * own additional state values. 21375 * 21376 * @param additionalState The additional state values you would like 21377 * added to <var>baseState</var>; this array is not modified. 21378 * 21379 * @return As a convenience, the <var>baseState</var> array you originally 21380 * passed into the function is returned. 21381 * 21382 * @see #onCreateDrawableState(int) 21383 */ 21384 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 21385 final int N = baseState.length; 21386 int i = N - 1; 21387 while (i >= 0 && baseState[i] == 0) { 21388 i--; 21389 } 21390 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 21391 return baseState; 21392 } 21393 21394 /** 21395 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 21396 * on all Drawable objects associated with this view. 21397 * <p> 21398 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 21399 * attached to this view. 21400 */ 21401 @CallSuper 21402 public void jumpDrawablesToCurrentState() { 21403 if (mBackground != null) { 21404 mBackground.jumpToCurrentState(); 21405 } 21406 if (mStateListAnimator != null) { 21407 mStateListAnimator.jumpToCurrentState(); 21408 } 21409 if (mDefaultFocusHighlight != null) { 21410 mDefaultFocusHighlight.jumpToCurrentState(); 21411 } 21412 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 21413 mForegroundInfo.mDrawable.jumpToCurrentState(); 21414 } 21415 } 21416 21417 /** 21418 * Sets the background color for this view. 21419 * @param color the color of the background 21420 */ 21421 @RemotableViewMethod 21422 public void setBackgroundColor(@ColorInt int color) { 21423 if (mBackground instanceof ColorDrawable) { 21424 ((ColorDrawable) mBackground.mutate()).setColor(color); 21425 computeOpaqueFlags(); 21426 mBackgroundResource = 0; 21427 } else { 21428 setBackground(new ColorDrawable(color)); 21429 } 21430 } 21431 21432 /** 21433 * Set the background to a given resource. The resource should refer to 21434 * a Drawable object or 0 to remove the background. 21435 * @param resid The identifier of the resource. 21436 * 21437 * @attr ref android.R.styleable#View_background 21438 */ 21439 @RemotableViewMethod 21440 public void setBackgroundResource(@DrawableRes int resid) { 21441 if (resid != 0 && resid == mBackgroundResource) { 21442 return; 21443 } 21444 21445 Drawable d = null; 21446 if (resid != 0) { 21447 d = mContext.getDrawable(resid); 21448 } 21449 setBackground(d); 21450 21451 mBackgroundResource = resid; 21452 } 21453 21454 /** 21455 * Set the background to a given Drawable, or remove the background. If the 21456 * background has padding, this View's padding is set to the background's 21457 * padding. However, when a background is removed, this View's padding isn't 21458 * touched. If setting the padding is desired, please use 21459 * {@link #setPadding(int, int, int, int)}. 21460 * 21461 * @param background The Drawable to use as the background, or null to remove the 21462 * background 21463 */ 21464 public void setBackground(Drawable background) { 21465 //noinspection deprecation 21466 setBackgroundDrawable(background); 21467 } 21468 21469 /** 21470 * @deprecated use {@link #setBackground(Drawable)} instead 21471 */ 21472 @Deprecated 21473 public void setBackgroundDrawable(Drawable background) { 21474 computeOpaqueFlags(); 21475 21476 if (background == mBackground) { 21477 return; 21478 } 21479 21480 boolean requestLayout = false; 21481 21482 mBackgroundResource = 0; 21483 21484 /* 21485 * Regardless of whether we're setting a new background or not, we want 21486 * to clear the previous drawable. setVisible first while we still have the callback set. 21487 */ 21488 if (mBackground != null) { 21489 if (isAttachedToWindow()) { 21490 mBackground.setVisible(false, false); 21491 } 21492 mBackground.setCallback(null); 21493 unscheduleDrawable(mBackground); 21494 } 21495 21496 if (background != null) { 21497 Rect padding = sThreadLocal.get(); 21498 if (padding == null) { 21499 padding = new Rect(); 21500 sThreadLocal.set(padding); 21501 } 21502 resetResolvedDrawablesInternal(); 21503 background.setLayoutDirection(getLayoutDirection()); 21504 if (background.getPadding(padding)) { 21505 resetResolvedPaddingInternal(); 21506 switch (background.getLayoutDirection()) { 21507 case LAYOUT_DIRECTION_RTL: 21508 mUserPaddingLeftInitial = padding.right; 21509 mUserPaddingRightInitial = padding.left; 21510 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 21511 break; 21512 case LAYOUT_DIRECTION_LTR: 21513 default: 21514 mUserPaddingLeftInitial = padding.left; 21515 mUserPaddingRightInitial = padding.right; 21516 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 21517 } 21518 mLeftPaddingDefined = false; 21519 mRightPaddingDefined = false; 21520 } 21521 21522 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 21523 // if it has a different minimum size, we should layout again 21524 if (mBackground == null 21525 || mBackground.getMinimumHeight() != background.getMinimumHeight() 21526 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 21527 requestLayout = true; 21528 } 21529 21530 // Set mBackground before we set this as the callback and start making other 21531 // background drawable state change calls. In particular, the setVisible call below 21532 // can result in drawables attempting to start animations or otherwise invalidate, 21533 // which requires the view set as the callback (us) to recognize the drawable as 21534 // belonging to it as per verifyDrawable. 21535 mBackground = background; 21536 if (background.isStateful()) { 21537 background.setState(getDrawableState()); 21538 } 21539 if (isAttachedToWindow()) { 21540 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 21541 } 21542 21543 applyBackgroundTint(); 21544 21545 // Set callback last, since the view may still be initializing. 21546 background.setCallback(this); 21547 21548 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 21549 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 21550 requestLayout = true; 21551 } 21552 } else { 21553 /* Remove the background */ 21554 mBackground = null; 21555 if ((mViewFlags & WILL_NOT_DRAW) != 0 21556 && (mDefaultFocusHighlight == null) 21557 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 21558 mPrivateFlags |= PFLAG_SKIP_DRAW; 21559 } 21560 21561 /* 21562 * When the background is set, we try to apply its padding to this 21563 * View. When the background is removed, we don't touch this View's 21564 * padding. This is noted in the Javadocs. Hence, we don't need to 21565 * requestLayout(), the invalidate() below is sufficient. 21566 */ 21567 21568 // The old background's minimum size could have affected this 21569 // View's layout, so let's requestLayout 21570 requestLayout = true; 21571 } 21572 21573 computeOpaqueFlags(); 21574 21575 if (requestLayout) { 21576 requestLayout(); 21577 } 21578 21579 mBackgroundSizeChanged = true; 21580 invalidate(true); 21581 invalidateOutline(); 21582 } 21583 21584 /** 21585 * Gets the background drawable 21586 * 21587 * @return The drawable used as the background for this view, if any. 21588 * 21589 * @see #setBackground(Drawable) 21590 * 21591 * @attr ref android.R.styleable#View_background 21592 */ 21593 public Drawable getBackground() { 21594 return mBackground; 21595 } 21596 21597 /** 21598 * Applies a tint to the background drawable. Does not modify the current tint 21599 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 21600 * <p> 21601 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 21602 * mutate the drawable and apply the specified tint and tint mode using 21603 * {@link Drawable#setTintList(ColorStateList)}. 21604 * 21605 * @param tint the tint to apply, may be {@code null} to clear tint 21606 * 21607 * @attr ref android.R.styleable#View_backgroundTint 21608 * @see #getBackgroundTintList() 21609 * @see Drawable#setTintList(ColorStateList) 21610 */ 21611 public void setBackgroundTintList(@Nullable ColorStateList tint) { 21612 if (mBackgroundTint == null) { 21613 mBackgroundTint = new TintInfo(); 21614 } 21615 mBackgroundTint.mTintList = tint; 21616 mBackgroundTint.mHasTintList = true; 21617 21618 applyBackgroundTint(); 21619 } 21620 21621 /** 21622 * Return the tint applied to the background drawable, if specified. 21623 * 21624 * @return the tint applied to the background drawable 21625 * @attr ref android.R.styleable#View_backgroundTint 21626 * @see #setBackgroundTintList(ColorStateList) 21627 */ 21628 @Nullable 21629 public ColorStateList getBackgroundTintList() { 21630 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 21631 } 21632 21633 /** 21634 * Specifies the blending mode used to apply the tint specified by 21635 * {@link #setBackgroundTintList(ColorStateList)}} to the background 21636 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 21637 * 21638 * @param tintMode the blending mode used to apply the tint, may be 21639 * {@code null} to clear tint 21640 * @attr ref android.R.styleable#View_backgroundTintMode 21641 * @see #getBackgroundTintMode() 21642 * @see Drawable#setTintMode(PorterDuff.Mode) 21643 */ 21644 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 21645 if (mBackgroundTint == null) { 21646 mBackgroundTint = new TintInfo(); 21647 } 21648 mBackgroundTint.mTintMode = tintMode; 21649 mBackgroundTint.mHasTintMode = true; 21650 21651 applyBackgroundTint(); 21652 } 21653 21654 /** 21655 * Return the blending mode used to apply the tint to the background 21656 * drawable, if specified. 21657 * 21658 * @return the blending mode used to apply the tint to the background 21659 * drawable 21660 * @attr ref android.R.styleable#View_backgroundTintMode 21661 * @see #setBackgroundTintMode(PorterDuff.Mode) 21662 */ 21663 @Nullable 21664 public PorterDuff.Mode getBackgroundTintMode() { 21665 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 21666 } 21667 21668 private void applyBackgroundTint() { 21669 if (mBackground != null && mBackgroundTint != null) { 21670 final TintInfo tintInfo = mBackgroundTint; 21671 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 21672 mBackground = mBackground.mutate(); 21673 21674 if (tintInfo.mHasTintList) { 21675 mBackground.setTintList(tintInfo.mTintList); 21676 } 21677 21678 if (tintInfo.mHasTintMode) { 21679 mBackground.setTintMode(tintInfo.mTintMode); 21680 } 21681 21682 // The drawable (or one of its children) may not have been 21683 // stateful before applying the tint, so let's try again. 21684 if (mBackground.isStateful()) { 21685 mBackground.setState(getDrawableState()); 21686 } 21687 } 21688 } 21689 } 21690 21691 /** 21692 * Returns the drawable used as the foreground of this View. The 21693 * foreground drawable, if non-null, is always drawn on top of the view's content. 21694 * 21695 * @return a Drawable or null if no foreground was set 21696 * 21697 * @see #onDrawForeground(Canvas) 21698 */ 21699 public Drawable getForeground() { 21700 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 21701 } 21702 21703 /** 21704 * Supply a Drawable that is to be rendered on top of all of the content in the view. 21705 * 21706 * @param foreground the Drawable to be drawn on top of the children 21707 * 21708 * @attr ref android.R.styleable#View_foreground 21709 */ 21710 public void setForeground(Drawable foreground) { 21711 if (mForegroundInfo == null) { 21712 if (foreground == null) { 21713 // Nothing to do. 21714 return; 21715 } 21716 mForegroundInfo = new ForegroundInfo(); 21717 } 21718 21719 if (foreground == mForegroundInfo.mDrawable) { 21720 // Nothing to do 21721 return; 21722 } 21723 21724 if (mForegroundInfo.mDrawable != null) { 21725 if (isAttachedToWindow()) { 21726 mForegroundInfo.mDrawable.setVisible(false, false); 21727 } 21728 mForegroundInfo.mDrawable.setCallback(null); 21729 unscheduleDrawable(mForegroundInfo.mDrawable); 21730 } 21731 21732 mForegroundInfo.mDrawable = foreground; 21733 mForegroundInfo.mBoundsChanged = true; 21734 if (foreground != null) { 21735 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 21736 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 21737 } 21738 foreground.setLayoutDirection(getLayoutDirection()); 21739 if (foreground.isStateful()) { 21740 foreground.setState(getDrawableState()); 21741 } 21742 applyForegroundTint(); 21743 if (isAttachedToWindow()) { 21744 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 21745 } 21746 // Set callback last, since the view may still be initializing. 21747 foreground.setCallback(this); 21748 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null 21749 && (mDefaultFocusHighlight == null)) { 21750 mPrivateFlags |= PFLAG_SKIP_DRAW; 21751 } 21752 requestLayout(); 21753 invalidate(); 21754 } 21755 21756 /** 21757 * Magic bit used to support features of framework-internal window decor implementation details. 21758 * This used to live exclusively in FrameLayout. 21759 * 21760 * @return true if the foreground should draw inside the padding region or false 21761 * if it should draw inset by the view's padding 21762 * @hide internal use only; only used by FrameLayout and internal screen layouts. 21763 */ 21764 public boolean isForegroundInsidePadding() { 21765 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 21766 } 21767 21768 /** 21769 * Describes how the foreground is positioned. 21770 * 21771 * @return foreground gravity. 21772 * 21773 * @see #setForegroundGravity(int) 21774 * 21775 * @attr ref android.R.styleable#View_foregroundGravity 21776 */ 21777 public int getForegroundGravity() { 21778 return mForegroundInfo != null ? mForegroundInfo.mGravity 21779 : Gravity.START | Gravity.TOP; 21780 } 21781 21782 /** 21783 * Describes how the foreground is positioned. Defaults to START and TOP. 21784 * 21785 * @param gravity see {@link android.view.Gravity} 21786 * 21787 * @see #getForegroundGravity() 21788 * 21789 * @attr ref android.R.styleable#View_foregroundGravity 21790 */ 21791 public void setForegroundGravity(int gravity) { 21792 if (mForegroundInfo == null) { 21793 mForegroundInfo = new ForegroundInfo(); 21794 } 21795 21796 if (mForegroundInfo.mGravity != gravity) { 21797 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 21798 gravity |= Gravity.START; 21799 } 21800 21801 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 21802 gravity |= Gravity.TOP; 21803 } 21804 21805 mForegroundInfo.mGravity = gravity; 21806 requestLayout(); 21807 } 21808 } 21809 21810 /** 21811 * Applies a tint to the foreground drawable. Does not modify the current tint 21812 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 21813 * <p> 21814 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 21815 * mutate the drawable and apply the specified tint and tint mode using 21816 * {@link Drawable#setTintList(ColorStateList)}. 21817 * 21818 * @param tint the tint to apply, may be {@code null} to clear tint 21819 * 21820 * @attr ref android.R.styleable#View_foregroundTint 21821 * @see #getForegroundTintList() 21822 * @see Drawable#setTintList(ColorStateList) 21823 */ 21824 public void setForegroundTintList(@Nullable ColorStateList tint) { 21825 if (mForegroundInfo == null) { 21826 mForegroundInfo = new ForegroundInfo(); 21827 } 21828 if (mForegroundInfo.mTintInfo == null) { 21829 mForegroundInfo.mTintInfo = new TintInfo(); 21830 } 21831 mForegroundInfo.mTintInfo.mTintList = tint; 21832 mForegroundInfo.mTintInfo.mHasTintList = true; 21833 21834 applyForegroundTint(); 21835 } 21836 21837 /** 21838 * Return the tint applied to the foreground drawable, if specified. 21839 * 21840 * @return the tint applied to the foreground drawable 21841 * @attr ref android.R.styleable#View_foregroundTint 21842 * @see #setForegroundTintList(ColorStateList) 21843 */ 21844 @Nullable 21845 public ColorStateList getForegroundTintList() { 21846 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 21847 ? mForegroundInfo.mTintInfo.mTintList : null; 21848 } 21849 21850 /** 21851 * Specifies the blending mode used to apply the tint specified by 21852 * {@link #setForegroundTintList(ColorStateList)}} to the background 21853 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 21854 * 21855 * @param tintMode the blending mode used to apply the tint, may be 21856 * {@code null} to clear tint 21857 * @attr ref android.R.styleable#View_foregroundTintMode 21858 * @see #getForegroundTintMode() 21859 * @see Drawable#setTintMode(PorterDuff.Mode) 21860 */ 21861 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 21862 if (mForegroundInfo == null) { 21863 mForegroundInfo = new ForegroundInfo(); 21864 } 21865 if (mForegroundInfo.mTintInfo == null) { 21866 mForegroundInfo.mTintInfo = new TintInfo(); 21867 } 21868 mForegroundInfo.mTintInfo.mTintMode = tintMode; 21869 mForegroundInfo.mTintInfo.mHasTintMode = true; 21870 21871 applyForegroundTint(); 21872 } 21873 21874 /** 21875 * Return the blending mode used to apply the tint to the foreground 21876 * drawable, if specified. 21877 * 21878 * @return the blending mode used to apply the tint to the foreground 21879 * drawable 21880 * @attr ref android.R.styleable#View_foregroundTintMode 21881 * @see #setForegroundTintMode(PorterDuff.Mode) 21882 */ 21883 @Nullable 21884 public PorterDuff.Mode getForegroundTintMode() { 21885 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 21886 ? mForegroundInfo.mTintInfo.mTintMode : null; 21887 } 21888 21889 private void applyForegroundTint() { 21890 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 21891 && mForegroundInfo.mTintInfo != null) { 21892 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 21893 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 21894 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 21895 21896 if (tintInfo.mHasTintList) { 21897 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 21898 } 21899 21900 if (tintInfo.mHasTintMode) { 21901 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 21902 } 21903 21904 // The drawable (or one of its children) may not have been 21905 // stateful before applying the tint, so let's try again. 21906 if (mForegroundInfo.mDrawable.isStateful()) { 21907 mForegroundInfo.mDrawable.setState(getDrawableState()); 21908 } 21909 } 21910 } 21911 } 21912 21913 /** 21914 * Get the drawable to be overlayed when a view is autofilled 21915 * 21916 * @return The drawable 21917 * 21918 * @throws IllegalStateException if the drawable could not be found. 21919 */ 21920 @Nullable private Drawable getAutofilledDrawable() { 21921 if (mAttachInfo == null) { 21922 return null; 21923 } 21924 // Lazily load the isAutofilled drawable. 21925 if (mAttachInfo.mAutofilledDrawable == null) { 21926 Context rootContext = getRootView().getContext(); 21927 TypedArray a = rootContext.getTheme().obtainStyledAttributes(AUTOFILL_HIGHLIGHT_ATTR); 21928 int attributeResourceId = a.getResourceId(0, 0); 21929 mAttachInfo.mAutofilledDrawable = rootContext.getDrawable(attributeResourceId); 21930 a.recycle(); 21931 } 21932 21933 return mAttachInfo.mAutofilledDrawable; 21934 } 21935 21936 /** 21937 * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled. 21938 * 21939 * @param canvas The canvas to draw on 21940 */ 21941 private void drawAutofilledHighlight(@NonNull Canvas canvas) { 21942 if (isAutofilled()) { 21943 Drawable autofilledHighlight = getAutofilledDrawable(); 21944 21945 if (autofilledHighlight != null) { 21946 autofilledHighlight.setBounds(0, 0, getWidth(), getHeight()); 21947 autofilledHighlight.draw(canvas); 21948 } 21949 } 21950 } 21951 21952 /** 21953 * Draw any foreground content for this view. 21954 * 21955 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 21956 * drawable or other view-specific decorations. The foreground is drawn on top of the 21957 * primary view content.</p> 21958 * 21959 * @param canvas canvas to draw into 21960 */ 21961 public void onDrawForeground(Canvas canvas) { 21962 onDrawScrollIndicators(canvas); 21963 onDrawScrollBars(canvas); 21964 21965 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 21966 if (foreground != null) { 21967 if (mForegroundInfo.mBoundsChanged) { 21968 mForegroundInfo.mBoundsChanged = false; 21969 final Rect selfBounds = mForegroundInfo.mSelfBounds; 21970 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 21971 21972 if (mForegroundInfo.mInsidePadding) { 21973 selfBounds.set(0, 0, getWidth(), getHeight()); 21974 } else { 21975 selfBounds.set(getPaddingLeft(), getPaddingTop(), 21976 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 21977 } 21978 21979 final int ld = getLayoutDirection(); 21980 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 21981 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 21982 foreground.setBounds(overlayBounds); 21983 } 21984 21985 foreground.draw(canvas); 21986 } 21987 } 21988 21989 /** 21990 * Sets the padding. The view may add on the space required to display 21991 * the scrollbars, depending on the style and visibility of the scrollbars. 21992 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 21993 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 21994 * from the values set in this call. 21995 * 21996 * @attr ref android.R.styleable#View_padding 21997 * @attr ref android.R.styleable#View_paddingBottom 21998 * @attr ref android.R.styleable#View_paddingLeft 21999 * @attr ref android.R.styleable#View_paddingRight 22000 * @attr ref android.R.styleable#View_paddingTop 22001 * @param left the left padding in pixels 22002 * @param top the top padding in pixels 22003 * @param right the right padding in pixels 22004 * @param bottom the bottom padding in pixels 22005 */ 22006 public void setPadding(int left, int top, int right, int bottom) { 22007 resetResolvedPaddingInternal(); 22008 22009 mUserPaddingStart = UNDEFINED_PADDING; 22010 mUserPaddingEnd = UNDEFINED_PADDING; 22011 22012 mUserPaddingLeftInitial = left; 22013 mUserPaddingRightInitial = right; 22014 22015 mLeftPaddingDefined = true; 22016 mRightPaddingDefined = true; 22017 22018 internalSetPadding(left, top, right, bottom); 22019 } 22020 22021 /** 22022 * @hide 22023 */ 22024 protected void internalSetPadding(int left, int top, int right, int bottom) { 22025 mUserPaddingLeft = left; 22026 mUserPaddingRight = right; 22027 mUserPaddingBottom = bottom; 22028 22029 final int viewFlags = mViewFlags; 22030 boolean changed = false; 22031 22032 // Common case is there are no scroll bars. 22033 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 22034 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 22035 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 22036 ? 0 : getVerticalScrollbarWidth(); 22037 switch (mVerticalScrollbarPosition) { 22038 case SCROLLBAR_POSITION_DEFAULT: 22039 if (isLayoutRtl()) { 22040 left += offset; 22041 } else { 22042 right += offset; 22043 } 22044 break; 22045 case SCROLLBAR_POSITION_RIGHT: 22046 right += offset; 22047 break; 22048 case SCROLLBAR_POSITION_LEFT: 22049 left += offset; 22050 break; 22051 } 22052 } 22053 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 22054 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 22055 ? 0 : getHorizontalScrollbarHeight(); 22056 } 22057 } 22058 22059 if (mPaddingLeft != left) { 22060 changed = true; 22061 mPaddingLeft = left; 22062 } 22063 if (mPaddingTop != top) { 22064 changed = true; 22065 mPaddingTop = top; 22066 } 22067 if (mPaddingRight != right) { 22068 changed = true; 22069 mPaddingRight = right; 22070 } 22071 if (mPaddingBottom != bottom) { 22072 changed = true; 22073 mPaddingBottom = bottom; 22074 } 22075 22076 if (changed) { 22077 requestLayout(); 22078 invalidateOutline(); 22079 } 22080 } 22081 22082 /** 22083 * Sets the relative padding. The view may add on the space required to display 22084 * the scrollbars, depending on the style and visibility of the scrollbars. 22085 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 22086 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 22087 * from the values set in this call. 22088 * 22089 * @attr ref android.R.styleable#View_padding 22090 * @attr ref android.R.styleable#View_paddingBottom 22091 * @attr ref android.R.styleable#View_paddingStart 22092 * @attr ref android.R.styleable#View_paddingEnd 22093 * @attr ref android.R.styleable#View_paddingTop 22094 * @param start the start padding in pixels 22095 * @param top the top padding in pixels 22096 * @param end the end padding in pixels 22097 * @param bottom the bottom padding in pixels 22098 */ 22099 public void setPaddingRelative(int start, int top, int end, int bottom) { 22100 resetResolvedPaddingInternal(); 22101 22102 mUserPaddingStart = start; 22103 mUserPaddingEnd = end; 22104 mLeftPaddingDefined = true; 22105 mRightPaddingDefined = true; 22106 22107 switch(getLayoutDirection()) { 22108 case LAYOUT_DIRECTION_RTL: 22109 mUserPaddingLeftInitial = end; 22110 mUserPaddingRightInitial = start; 22111 internalSetPadding(end, top, start, bottom); 22112 break; 22113 case LAYOUT_DIRECTION_LTR: 22114 default: 22115 mUserPaddingLeftInitial = start; 22116 mUserPaddingRightInitial = end; 22117 internalSetPadding(start, top, end, bottom); 22118 } 22119 } 22120 22121 /** 22122 * Returns the top padding of this view. 22123 * 22124 * @return the top padding in pixels 22125 */ 22126 public int getPaddingTop() { 22127 return mPaddingTop; 22128 } 22129 22130 /** 22131 * Returns the bottom padding of this view. If there are inset and enabled 22132 * scrollbars, this value may include the space required to display the 22133 * scrollbars as well. 22134 * 22135 * @return the bottom padding in pixels 22136 */ 22137 public int getPaddingBottom() { 22138 return mPaddingBottom; 22139 } 22140 22141 /** 22142 * Returns the left padding of this view. If there are inset and enabled 22143 * scrollbars, this value may include the space required to display the 22144 * scrollbars as well. 22145 * 22146 * @return the left padding in pixels 22147 */ 22148 public int getPaddingLeft() { 22149 if (!isPaddingResolved()) { 22150 resolvePadding(); 22151 } 22152 return mPaddingLeft; 22153 } 22154 22155 /** 22156 * Returns the start padding of this view depending on its resolved layout direction. 22157 * If there are inset and enabled scrollbars, this value may include the space 22158 * required to display the scrollbars as well. 22159 * 22160 * @return the start padding in pixels 22161 */ 22162 public int getPaddingStart() { 22163 if (!isPaddingResolved()) { 22164 resolvePadding(); 22165 } 22166 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 22167 mPaddingRight : mPaddingLeft; 22168 } 22169 22170 /** 22171 * Returns the right padding of this view. If there are inset and enabled 22172 * scrollbars, this value may include the space required to display the 22173 * scrollbars as well. 22174 * 22175 * @return the right padding in pixels 22176 */ 22177 public int getPaddingRight() { 22178 if (!isPaddingResolved()) { 22179 resolvePadding(); 22180 } 22181 return mPaddingRight; 22182 } 22183 22184 /** 22185 * Returns the end padding of this view depending on its resolved layout direction. 22186 * If there are inset and enabled scrollbars, this value may include the space 22187 * required to display the scrollbars as well. 22188 * 22189 * @return the end padding in pixels 22190 */ 22191 public int getPaddingEnd() { 22192 if (!isPaddingResolved()) { 22193 resolvePadding(); 22194 } 22195 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 22196 mPaddingLeft : mPaddingRight; 22197 } 22198 22199 /** 22200 * Return if the padding has been set through relative values 22201 * {@link #setPaddingRelative(int, int, int, int)} or through 22202 * @attr ref android.R.styleable#View_paddingStart or 22203 * @attr ref android.R.styleable#View_paddingEnd 22204 * 22205 * @return true if the padding is relative or false if it is not. 22206 */ 22207 public boolean isPaddingRelative() { 22208 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 22209 } 22210 22211 Insets computeOpticalInsets() { 22212 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 22213 } 22214 22215 /** 22216 * @hide 22217 */ 22218 public void resetPaddingToInitialValues() { 22219 if (isRtlCompatibilityMode()) { 22220 mPaddingLeft = mUserPaddingLeftInitial; 22221 mPaddingRight = mUserPaddingRightInitial; 22222 return; 22223 } 22224 if (isLayoutRtl()) { 22225 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 22226 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 22227 } else { 22228 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 22229 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 22230 } 22231 } 22232 22233 /** 22234 * @hide 22235 */ 22236 public Insets getOpticalInsets() { 22237 if (mLayoutInsets == null) { 22238 mLayoutInsets = computeOpticalInsets(); 22239 } 22240 return mLayoutInsets; 22241 } 22242 22243 /** 22244 * Set this view's optical insets. 22245 * 22246 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 22247 * property. Views that compute their own optical insets should call it as part of measurement. 22248 * This method does not request layout. If you are setting optical insets outside of 22249 * measure/layout itself you will want to call requestLayout() yourself. 22250 * </p> 22251 * @hide 22252 */ 22253 public void setOpticalInsets(Insets insets) { 22254 mLayoutInsets = insets; 22255 } 22256 22257 /** 22258 * Changes the selection state of this view. A view can be selected or not. 22259 * Note that selection is not the same as focus. Views are typically 22260 * selected in the context of an AdapterView like ListView or GridView; 22261 * the selected view is the view that is highlighted. 22262 * 22263 * @param selected true if the view must be selected, false otherwise 22264 */ 22265 public void setSelected(boolean selected) { 22266 //noinspection DoubleNegation 22267 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 22268 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 22269 if (!selected) resetPressedState(); 22270 invalidate(true); 22271 refreshDrawableState(); 22272 dispatchSetSelected(selected); 22273 if (selected) { 22274 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 22275 } else { 22276 notifyViewAccessibilityStateChangedIfNeeded( 22277 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 22278 } 22279 } 22280 } 22281 22282 /** 22283 * Dispatch setSelected to all of this View's children. 22284 * 22285 * @see #setSelected(boolean) 22286 * 22287 * @param selected The new selected state 22288 */ 22289 protected void dispatchSetSelected(boolean selected) { 22290 } 22291 22292 /** 22293 * Indicates the selection state of this view. 22294 * 22295 * @return true if the view is selected, false otherwise 22296 */ 22297 @ViewDebug.ExportedProperty 22298 public boolean isSelected() { 22299 return (mPrivateFlags & PFLAG_SELECTED) != 0; 22300 } 22301 22302 /** 22303 * Changes the activated state of this view. A view can be activated or not. 22304 * Note that activation is not the same as selection. Selection is 22305 * a transient property, representing the view (hierarchy) the user is 22306 * currently interacting with. Activation is a longer-term state that the 22307 * user can move views in and out of. For example, in a list view with 22308 * single or multiple selection enabled, the views in the current selection 22309 * set are activated. (Um, yeah, we are deeply sorry about the terminology 22310 * here.) The activated state is propagated down to children of the view it 22311 * is set on. 22312 * 22313 * @param activated true if the view must be activated, false otherwise 22314 */ 22315 public void setActivated(boolean activated) { 22316 //noinspection DoubleNegation 22317 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 22318 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 22319 invalidate(true); 22320 refreshDrawableState(); 22321 dispatchSetActivated(activated); 22322 } 22323 } 22324 22325 /** 22326 * Dispatch setActivated to all of this View's children. 22327 * 22328 * @see #setActivated(boolean) 22329 * 22330 * @param activated The new activated state 22331 */ 22332 protected void dispatchSetActivated(boolean activated) { 22333 } 22334 22335 /** 22336 * Indicates the activation state of this view. 22337 * 22338 * @return true if the view is activated, false otherwise 22339 */ 22340 @ViewDebug.ExportedProperty 22341 public boolean isActivated() { 22342 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 22343 } 22344 22345 /** 22346 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 22347 * observer can be used to get notifications when global events, like 22348 * layout, happen. 22349 * 22350 * The returned ViewTreeObserver observer is not guaranteed to remain 22351 * valid for the lifetime of this View. If the caller of this method keeps 22352 * a long-lived reference to ViewTreeObserver, it should always check for 22353 * the return value of {@link ViewTreeObserver#isAlive()}. 22354 * 22355 * @return The ViewTreeObserver for this view's hierarchy. 22356 */ 22357 public ViewTreeObserver getViewTreeObserver() { 22358 if (mAttachInfo != null) { 22359 return mAttachInfo.mTreeObserver; 22360 } 22361 if (mFloatingTreeObserver == null) { 22362 mFloatingTreeObserver = new ViewTreeObserver(mContext); 22363 } 22364 return mFloatingTreeObserver; 22365 } 22366 22367 /** 22368 * <p>Finds the topmost view in the current view hierarchy.</p> 22369 * 22370 * @return the topmost view containing this view 22371 */ 22372 public View getRootView() { 22373 if (mAttachInfo != null) { 22374 final View v = mAttachInfo.mRootView; 22375 if (v != null) { 22376 return v; 22377 } 22378 } 22379 22380 View parent = this; 22381 22382 while (parent.mParent != null && parent.mParent instanceof View) { 22383 parent = (View) parent.mParent; 22384 } 22385 22386 return parent; 22387 } 22388 22389 /** 22390 * Transforms a motion event from view-local coordinates to on-screen 22391 * coordinates. 22392 * 22393 * @param ev the view-local motion event 22394 * @return false if the transformation could not be applied 22395 * @hide 22396 */ 22397 public boolean toGlobalMotionEvent(MotionEvent ev) { 22398 final AttachInfo info = mAttachInfo; 22399 if (info == null) { 22400 return false; 22401 } 22402 22403 final Matrix m = info.mTmpMatrix; 22404 m.set(Matrix.IDENTITY_MATRIX); 22405 transformMatrixToGlobal(m); 22406 ev.transform(m); 22407 return true; 22408 } 22409 22410 /** 22411 * Transforms a motion event from on-screen coordinates to view-local 22412 * coordinates. 22413 * 22414 * @param ev the on-screen motion event 22415 * @return false if the transformation could not be applied 22416 * @hide 22417 */ 22418 public boolean toLocalMotionEvent(MotionEvent ev) { 22419 final AttachInfo info = mAttachInfo; 22420 if (info == null) { 22421 return false; 22422 } 22423 22424 final Matrix m = info.mTmpMatrix; 22425 m.set(Matrix.IDENTITY_MATRIX); 22426 transformMatrixToLocal(m); 22427 ev.transform(m); 22428 return true; 22429 } 22430 22431 /** 22432 * Modifies the input matrix such that it maps view-local coordinates to 22433 * on-screen coordinates. 22434 * 22435 * @param m input matrix to modify 22436 * @hide 22437 */ 22438 public void transformMatrixToGlobal(Matrix m) { 22439 final ViewParent parent = mParent; 22440 if (parent instanceof View) { 22441 final View vp = (View) parent; 22442 vp.transformMatrixToGlobal(m); 22443 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 22444 } else if (parent instanceof ViewRootImpl) { 22445 final ViewRootImpl vr = (ViewRootImpl) parent; 22446 vr.transformMatrixToGlobal(m); 22447 m.preTranslate(0, -vr.mCurScrollY); 22448 } 22449 22450 m.preTranslate(mLeft, mTop); 22451 22452 if (!hasIdentityMatrix()) { 22453 m.preConcat(getMatrix()); 22454 } 22455 } 22456 22457 /** 22458 * Modifies the input matrix such that it maps on-screen coordinates to 22459 * view-local coordinates. 22460 * 22461 * @param m input matrix to modify 22462 * @hide 22463 */ 22464 public void transformMatrixToLocal(Matrix m) { 22465 final ViewParent parent = mParent; 22466 if (parent instanceof View) { 22467 final View vp = (View) parent; 22468 vp.transformMatrixToLocal(m); 22469 m.postTranslate(vp.mScrollX, vp.mScrollY); 22470 } else if (parent instanceof ViewRootImpl) { 22471 final ViewRootImpl vr = (ViewRootImpl) parent; 22472 vr.transformMatrixToLocal(m); 22473 m.postTranslate(0, vr.mCurScrollY); 22474 } 22475 22476 m.postTranslate(-mLeft, -mTop); 22477 22478 if (!hasIdentityMatrix()) { 22479 m.postConcat(getInverseMatrix()); 22480 } 22481 } 22482 22483 /** 22484 * @hide 22485 */ 22486 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 22487 @ViewDebug.IntToString(from = 0, to = "x"), 22488 @ViewDebug.IntToString(from = 1, to = "y") 22489 }) 22490 public int[] getLocationOnScreen() { 22491 int[] location = new int[2]; 22492 getLocationOnScreen(location); 22493 return location; 22494 } 22495 22496 /** 22497 * <p>Computes the coordinates of this view on the screen. The argument 22498 * must be an array of two integers. After the method returns, the array 22499 * contains the x and y location in that order.</p> 22500 * 22501 * @param outLocation an array of two integers in which to hold the coordinates 22502 */ 22503 public void getLocationOnScreen(@Size(2) int[] outLocation) { 22504 getLocationInWindow(outLocation); 22505 22506 final AttachInfo info = mAttachInfo; 22507 if (info != null) { 22508 outLocation[0] += info.mWindowLeft; 22509 outLocation[1] += info.mWindowTop; 22510 } 22511 } 22512 22513 /** 22514 * <p>Computes the coordinates of this view in its window. The argument 22515 * must be an array of two integers. After the method returns, the array 22516 * contains the x and y location in that order.</p> 22517 * 22518 * @param outLocation an array of two integers in which to hold the coordinates 22519 */ 22520 public void getLocationInWindow(@Size(2) int[] outLocation) { 22521 if (outLocation == null || outLocation.length < 2) { 22522 throw new IllegalArgumentException("outLocation must be an array of two integers"); 22523 } 22524 22525 outLocation[0] = 0; 22526 outLocation[1] = 0; 22527 22528 transformFromViewToWindowSpace(outLocation); 22529 } 22530 22531 /** @hide */ 22532 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 22533 if (inOutLocation == null || inOutLocation.length < 2) { 22534 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 22535 } 22536 22537 if (mAttachInfo == null) { 22538 // When the view is not attached to a window, this method does not make sense 22539 inOutLocation[0] = inOutLocation[1] = 0; 22540 return; 22541 } 22542 22543 float position[] = mAttachInfo.mTmpTransformLocation; 22544 position[0] = inOutLocation[0]; 22545 position[1] = inOutLocation[1]; 22546 22547 if (!hasIdentityMatrix()) { 22548 getMatrix().mapPoints(position); 22549 } 22550 22551 position[0] += mLeft; 22552 position[1] += mTop; 22553 22554 ViewParent viewParent = mParent; 22555 while (viewParent instanceof View) { 22556 final View view = (View) viewParent; 22557 22558 position[0] -= view.mScrollX; 22559 position[1] -= view.mScrollY; 22560 22561 if (!view.hasIdentityMatrix()) { 22562 view.getMatrix().mapPoints(position); 22563 } 22564 22565 position[0] += view.mLeft; 22566 position[1] += view.mTop; 22567 22568 viewParent = view.mParent; 22569 } 22570 22571 if (viewParent instanceof ViewRootImpl) { 22572 // *cough* 22573 final ViewRootImpl vr = (ViewRootImpl) viewParent; 22574 position[1] -= vr.mCurScrollY; 22575 } 22576 22577 inOutLocation[0] = Math.round(position[0]); 22578 inOutLocation[1] = Math.round(position[1]); 22579 } 22580 22581 /** 22582 * @param id the id of the view to be found 22583 * @return the view of the specified id, null if cannot be found 22584 * @hide 22585 */ 22586 protected <T extends View> T findViewTraversal(@IdRes int id) { 22587 if (id == mID) { 22588 return (T) this; 22589 } 22590 return null; 22591 } 22592 22593 /** 22594 * @param tag the tag of the view to be found 22595 * @return the view of specified tag, null if cannot be found 22596 * @hide 22597 */ 22598 protected <T extends View> T findViewWithTagTraversal(Object tag) { 22599 if (tag != null && tag.equals(mTag)) { 22600 return (T) this; 22601 } 22602 return null; 22603 } 22604 22605 /** 22606 * @param predicate The predicate to evaluate. 22607 * @param childToSkip If not null, ignores this child during the recursive traversal. 22608 * @return The first view that matches the predicate or null. 22609 * @hide 22610 */ 22611 protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate, 22612 View childToSkip) { 22613 if (predicate.test(this)) { 22614 return (T) this; 22615 } 22616 return null; 22617 } 22618 22619 /** 22620 * Finds the first descendant view with the given ID, the view itself if 22621 * the ID matches {@link #getId()}, or {@code null} if the ID is invalid 22622 * (< 0) or there is no matching view in the hierarchy. 22623 * <p> 22624 * <strong>Note:</strong> In most cases -- depending on compiler support -- 22625 * the resulting view is automatically cast to the target class type. If 22626 * the target class type is unconstrained, an explicit cast may be 22627 * necessary. 22628 * 22629 * @param id the ID to search for 22630 * @return a view with given ID if found, or {@code null} otherwise 22631 * @see View#requireViewById(int) 22632 */ 22633 @Nullable 22634 public final <T extends View> T findViewById(@IdRes int id) { 22635 if (id == NO_ID) { 22636 return null; 22637 } 22638 return findViewTraversal(id); 22639 } 22640 22641 /** 22642 * Finds the first descendant view with the given ID, the view itself if the ID matches 22643 * {@link #getId()}, or throws an IllegalArgumentException if the ID is invalid or there is no 22644 * matching view in the hierarchy. 22645 * <p> 22646 * <strong>Note:</strong> In most cases -- depending on compiler support -- 22647 * the resulting view is automatically cast to the target class type. If 22648 * the target class type is unconstrained, an explicit cast may be 22649 * necessary. 22650 * 22651 * @param id the ID to search for 22652 * @return a view with given ID 22653 * @see View#findViewById(int) 22654 */ 22655 @NonNull 22656 public final <T extends View> T requireViewById(@IdRes int id) { 22657 T view = findViewById(id); 22658 if (view == null) { 22659 throw new IllegalArgumentException("ID does not reference a View inside this View"); 22660 } 22661 return view; 22662 } 22663 22664 /** 22665 * Finds a view by its unuque and stable accessibility id. 22666 * 22667 * @param accessibilityId The searched accessibility id. 22668 * @return The found view. 22669 */ 22670 final <T extends View> T findViewByAccessibilityId(int accessibilityId) { 22671 if (accessibilityId < 0) { 22672 return null; 22673 } 22674 T view = findViewByAccessibilityIdTraversal(accessibilityId); 22675 if (view != null) { 22676 return view.includeForAccessibility() ? view : null; 22677 } 22678 return null; 22679 } 22680 22681 /** 22682 * Performs the traversal to find a view by its unique and stable accessibility id. 22683 * 22684 * <strong>Note:</strong>This method does not stop at the root namespace 22685 * boundary since the user can touch the screen at an arbitrary location 22686 * potentially crossing the root namespace boundary which will send an 22687 * accessibility event to accessibility services and they should be able 22688 * to obtain the event source. Also accessibility ids are guaranteed to be 22689 * unique in the window. 22690 * 22691 * @param accessibilityId The accessibility id. 22692 * @return The found view. 22693 * @hide 22694 */ 22695 public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) { 22696 if (getAccessibilityViewId() == accessibilityId) { 22697 return (T) this; 22698 } 22699 return null; 22700 } 22701 22702 /** 22703 * Performs the traversal to find a view by its autofill id. 22704 * 22705 * <strong>Note:</strong>This method does not stop at the root namespace 22706 * boundary. 22707 * 22708 * @param autofillId The autofill id. 22709 * @return The found view. 22710 * @hide 22711 */ 22712 public <T extends View> T findViewByAutofillIdTraversal(int autofillId) { 22713 if (getAutofillViewId() == autofillId) { 22714 return (T) this; 22715 } 22716 return null; 22717 } 22718 22719 /** 22720 * Look for a child view with the given tag. If this view has the given 22721 * tag, return this view. 22722 * 22723 * @param tag The tag to search for, using "tag.equals(getTag())". 22724 * @return The View that has the given tag in the hierarchy or null 22725 */ 22726 public final <T extends View> T findViewWithTag(Object tag) { 22727 if (tag == null) { 22728 return null; 22729 } 22730 return findViewWithTagTraversal(tag); 22731 } 22732 22733 /** 22734 * Look for a child view that matches the specified predicate. 22735 * If this view matches the predicate, return this view. 22736 * 22737 * @param predicate The predicate to evaluate. 22738 * @return The first view that matches the predicate or null. 22739 * @hide 22740 */ 22741 public final <T extends View> T findViewByPredicate(Predicate<View> predicate) { 22742 return findViewByPredicateTraversal(predicate, null); 22743 } 22744 22745 /** 22746 * Look for a child view that matches the specified predicate, 22747 * starting with the specified view and its descendents and then 22748 * recusively searching the ancestors and siblings of that view 22749 * until this view is reached. 22750 * 22751 * This method is useful in cases where the predicate does not match 22752 * a single unique view (perhaps multiple views use the same id) 22753 * and we are trying to find the view that is "closest" in scope to the 22754 * starting view. 22755 * 22756 * @param start The view to start from. 22757 * @param predicate The predicate to evaluate. 22758 * @return The first view that matches the predicate or null. 22759 * @hide 22760 */ 22761 public final <T extends View> T findViewByPredicateInsideOut( 22762 View start, Predicate<View> predicate) { 22763 View childToSkip = null; 22764 for (;;) { 22765 T view = start.findViewByPredicateTraversal(predicate, childToSkip); 22766 if (view != null || start == this) { 22767 return view; 22768 } 22769 22770 ViewParent parent = start.getParent(); 22771 if (parent == null || !(parent instanceof View)) { 22772 return null; 22773 } 22774 22775 childToSkip = start; 22776 start = (View) parent; 22777 } 22778 } 22779 22780 /** 22781 * Sets the identifier for this view. The identifier does not have to be 22782 * unique in this view's hierarchy. The identifier should be a positive 22783 * number. 22784 * 22785 * @see #NO_ID 22786 * @see #getId() 22787 * @see #findViewById(int) 22788 * 22789 * @param id a number used to identify the view 22790 * 22791 * @attr ref android.R.styleable#View_id 22792 */ 22793 public void setId(@IdRes int id) { 22794 mID = id; 22795 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 22796 mID = generateViewId(); 22797 } 22798 } 22799 22800 /** 22801 * {@hide} 22802 * 22803 * @param isRoot true if the view belongs to the root namespace, false 22804 * otherwise 22805 */ 22806 public void setIsRootNamespace(boolean isRoot) { 22807 if (isRoot) { 22808 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 22809 } else { 22810 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 22811 } 22812 } 22813 22814 /** 22815 * {@hide} 22816 * 22817 * @return true if the view belongs to the root namespace, false otherwise 22818 */ 22819 public boolean isRootNamespace() { 22820 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 22821 } 22822 22823 /** 22824 * Returns this view's identifier. 22825 * 22826 * @return a positive integer used to identify the view or {@link #NO_ID} 22827 * if the view has no ID 22828 * 22829 * @see #setId(int) 22830 * @see #findViewById(int) 22831 * @attr ref android.R.styleable#View_id 22832 */ 22833 @IdRes 22834 @ViewDebug.CapturedViewProperty 22835 public int getId() { 22836 return mID; 22837 } 22838 22839 /** 22840 * Returns this view's tag. 22841 * 22842 * @return the Object stored in this view as a tag, or {@code null} if not 22843 * set 22844 * 22845 * @see #setTag(Object) 22846 * @see #getTag(int) 22847 */ 22848 @ViewDebug.ExportedProperty 22849 public Object getTag() { 22850 return mTag; 22851 } 22852 22853 /** 22854 * Sets the tag associated with this view. A tag can be used to mark 22855 * a view in its hierarchy and does not have to be unique within the 22856 * hierarchy. Tags can also be used to store data within a view without 22857 * resorting to another data structure. 22858 * 22859 * @param tag an Object to tag the view with 22860 * 22861 * @see #getTag() 22862 * @see #setTag(int, Object) 22863 */ 22864 public void setTag(final Object tag) { 22865 mTag = tag; 22866 } 22867 22868 /** 22869 * Returns the tag associated with this view and the specified key. 22870 * 22871 * @param key The key identifying the tag 22872 * 22873 * @return the Object stored in this view as a tag, or {@code null} if not 22874 * set 22875 * 22876 * @see #setTag(int, Object) 22877 * @see #getTag() 22878 */ 22879 public Object getTag(int key) { 22880 if (mKeyedTags != null) return mKeyedTags.get(key); 22881 return null; 22882 } 22883 22884 /** 22885 * Sets a tag associated with this view and a key. A tag can be used 22886 * to mark a view in its hierarchy and does not have to be unique within 22887 * the hierarchy. Tags can also be used to store data within a view 22888 * without resorting to another data structure. 22889 * 22890 * The specified key should be an id declared in the resources of the 22891 * application to ensure it is unique (see the <a 22892 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 22893 * Keys identified as belonging to 22894 * the Android framework or not associated with any package will cause 22895 * an {@link IllegalArgumentException} to be thrown. 22896 * 22897 * @param key The key identifying the tag 22898 * @param tag An Object to tag the view with 22899 * 22900 * @throws IllegalArgumentException If they specified key is not valid 22901 * 22902 * @see #setTag(Object) 22903 * @see #getTag(int) 22904 */ 22905 public void setTag(int key, final Object tag) { 22906 // If the package id is 0x00 or 0x01, it's either an undefined package 22907 // or a framework id 22908 if ((key >>> 24) < 2) { 22909 throw new IllegalArgumentException("The key must be an application-specific " 22910 + "resource id."); 22911 } 22912 22913 setKeyedTag(key, tag); 22914 } 22915 22916 /** 22917 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 22918 * framework id. 22919 * 22920 * @hide 22921 */ 22922 public void setTagInternal(int key, Object tag) { 22923 if ((key >>> 24) != 0x1) { 22924 throw new IllegalArgumentException("The key must be a framework-specific " 22925 + "resource id."); 22926 } 22927 22928 setKeyedTag(key, tag); 22929 } 22930 22931 private void setKeyedTag(int key, Object tag) { 22932 if (mKeyedTags == null) { 22933 mKeyedTags = new SparseArray<Object>(2); 22934 } 22935 22936 mKeyedTags.put(key, tag); 22937 } 22938 22939 /** 22940 * Prints information about this view in the log output, with the tag 22941 * {@link #VIEW_LOG_TAG}. 22942 * 22943 * @hide 22944 */ 22945 public void debug() { 22946 debug(0); 22947 } 22948 22949 /** 22950 * Prints information about this view in the log output, with the tag 22951 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 22952 * indentation defined by the <code>depth</code>. 22953 * 22954 * @param depth the indentation level 22955 * 22956 * @hide 22957 */ 22958 protected void debug(int depth) { 22959 String output = debugIndent(depth - 1); 22960 22961 output += "+ " + this; 22962 int id = getId(); 22963 if (id != -1) { 22964 output += " (id=" + id + ")"; 22965 } 22966 Object tag = getTag(); 22967 if (tag != null) { 22968 output += " (tag=" + tag + ")"; 22969 } 22970 Log.d(VIEW_LOG_TAG, output); 22971 22972 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 22973 output = debugIndent(depth) + " FOCUSED"; 22974 Log.d(VIEW_LOG_TAG, output); 22975 } 22976 22977 output = debugIndent(depth); 22978 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 22979 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 22980 + "} "; 22981 Log.d(VIEW_LOG_TAG, output); 22982 22983 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 22984 || mPaddingBottom != 0) { 22985 output = debugIndent(depth); 22986 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 22987 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 22988 Log.d(VIEW_LOG_TAG, output); 22989 } 22990 22991 output = debugIndent(depth); 22992 output += "mMeasureWidth=" + mMeasuredWidth + 22993 " mMeasureHeight=" + mMeasuredHeight; 22994 Log.d(VIEW_LOG_TAG, output); 22995 22996 output = debugIndent(depth); 22997 if (mLayoutParams == null) { 22998 output += "BAD! no layout params"; 22999 } else { 23000 output = mLayoutParams.debug(output); 23001 } 23002 Log.d(VIEW_LOG_TAG, output); 23003 23004 output = debugIndent(depth); 23005 output += "flags={"; 23006 output += View.printFlags(mViewFlags); 23007 output += "}"; 23008 Log.d(VIEW_LOG_TAG, output); 23009 23010 output = debugIndent(depth); 23011 output += "privateFlags={"; 23012 output += View.printPrivateFlags(mPrivateFlags); 23013 output += "}"; 23014 Log.d(VIEW_LOG_TAG, output); 23015 } 23016 23017 /** 23018 * Creates a string of whitespaces used for indentation. 23019 * 23020 * @param depth the indentation level 23021 * @return a String containing (depth * 2 + 3) * 2 white spaces 23022 * 23023 * @hide 23024 */ 23025 protected static String debugIndent(int depth) { 23026 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 23027 for (int i = 0; i < (depth * 2) + 3; i++) { 23028 spaces.append(' ').append(' '); 23029 } 23030 return spaces.toString(); 23031 } 23032 23033 /** 23034 * <p>Return the offset of the widget's text baseline from the widget's top 23035 * boundary. If this widget does not support baseline alignment, this 23036 * method returns -1. </p> 23037 * 23038 * @return the offset of the baseline within the widget's bounds or -1 23039 * if baseline alignment is not supported 23040 */ 23041 @ViewDebug.ExportedProperty(category = "layout") 23042 public int getBaseline() { 23043 return -1; 23044 } 23045 23046 /** 23047 * Returns whether the view hierarchy is currently undergoing a layout pass. This 23048 * information is useful to avoid situations such as calling {@link #requestLayout()} during 23049 * a layout pass. 23050 * 23051 * @return whether the view hierarchy is currently undergoing a layout pass 23052 */ 23053 public boolean isInLayout() { 23054 ViewRootImpl viewRoot = getViewRootImpl(); 23055 return (viewRoot != null && viewRoot.isInLayout()); 23056 } 23057 23058 /** 23059 * Call this when something has changed which has invalidated the 23060 * layout of this view. This will schedule a layout pass of the view 23061 * tree. This should not be called while the view hierarchy is currently in a layout 23062 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 23063 * end of the current layout pass (and then layout will run again) or after the current 23064 * frame is drawn and the next layout occurs. 23065 * 23066 * <p>Subclasses which override this method should call the superclass method to 23067 * handle possible request-during-layout errors correctly.</p> 23068 */ 23069 @CallSuper 23070 public void requestLayout() { 23071 if (mMeasureCache != null) mMeasureCache.clear(); 23072 23073 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 23074 // Only trigger request-during-layout logic if this is the view requesting it, 23075 // not the views in its parent hierarchy 23076 ViewRootImpl viewRoot = getViewRootImpl(); 23077 if (viewRoot != null && viewRoot.isInLayout()) { 23078 if (!viewRoot.requestLayoutDuringLayout(this)) { 23079 return; 23080 } 23081 } 23082 mAttachInfo.mViewRequestingLayout = this; 23083 } 23084 23085 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 23086 mPrivateFlags |= PFLAG_INVALIDATED; 23087 23088 if (mParent != null && !mParent.isLayoutRequested()) { 23089 mParent.requestLayout(); 23090 } 23091 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 23092 mAttachInfo.mViewRequestingLayout = null; 23093 } 23094 } 23095 23096 /** 23097 * Forces this view to be laid out during the next layout pass. 23098 * This method does not call requestLayout() or forceLayout() 23099 * on the parent. 23100 */ 23101 public void forceLayout() { 23102 if (mMeasureCache != null) mMeasureCache.clear(); 23103 23104 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 23105 mPrivateFlags |= PFLAG_INVALIDATED; 23106 } 23107 23108 /** 23109 * <p> 23110 * This is called to find out how big a view should be. The parent 23111 * supplies constraint information in the width and height parameters. 23112 * </p> 23113 * 23114 * <p> 23115 * The actual measurement work of a view is performed in 23116 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 23117 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 23118 * </p> 23119 * 23120 * 23121 * @param widthMeasureSpec Horizontal space requirements as imposed by the 23122 * parent 23123 * @param heightMeasureSpec Vertical space requirements as imposed by the 23124 * parent 23125 * 23126 * @see #onMeasure(int, int) 23127 */ 23128 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 23129 boolean optical = isLayoutModeOptical(this); 23130 if (optical != isLayoutModeOptical(mParent)) { 23131 Insets insets = getOpticalInsets(); 23132 int oWidth = insets.left + insets.right; 23133 int oHeight = insets.top + insets.bottom; 23134 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 23135 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 23136 } 23137 23138 // Suppress sign extension for the low bytes 23139 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 23140 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 23141 23142 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 23143 23144 // Optimize layout by avoiding an extra EXACTLY pass when the view is 23145 // already measured as the correct size. In API 23 and below, this 23146 // extra pass is required to make LinearLayout re-distribute weight. 23147 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 23148 || heightMeasureSpec != mOldHeightMeasureSpec; 23149 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 23150 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 23151 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 23152 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 23153 final boolean needsLayout = specChanged 23154 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 23155 23156 if (forceLayout || needsLayout) { 23157 // first clears the measured dimension flag 23158 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 23159 23160 resolveRtlPropertiesIfNeeded(); 23161 23162 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 23163 if (cacheIndex < 0 || sIgnoreMeasureCache) { 23164 // measure ourselves, this should set the measured dimension flag back 23165 onMeasure(widthMeasureSpec, heightMeasureSpec); 23166 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 23167 } else { 23168 long value = mMeasureCache.valueAt(cacheIndex); 23169 // Casting a long to int drops the high 32 bits, no mask needed 23170 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 23171 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 23172 } 23173 23174 // flag not set, setMeasuredDimension() was not invoked, we raise 23175 // an exception to warn the developer 23176 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 23177 throw new IllegalStateException("View with id " + getId() + ": " 23178 + getClass().getName() + "#onMeasure() did not set the" 23179 + " measured dimension by calling" 23180 + " setMeasuredDimension()"); 23181 } 23182 23183 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 23184 } 23185 23186 mOldWidthMeasureSpec = widthMeasureSpec; 23187 mOldHeightMeasureSpec = heightMeasureSpec; 23188 23189 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 23190 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 23191 } 23192 23193 /** 23194 * <p> 23195 * Measure the view and its content to determine the measured width and the 23196 * measured height. This method is invoked by {@link #measure(int, int)} and 23197 * should be overridden by subclasses to provide accurate and efficient 23198 * measurement of their contents. 23199 * </p> 23200 * 23201 * <p> 23202 * <strong>CONTRACT:</strong> When overriding this method, you 23203 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 23204 * measured width and height of this view. Failure to do so will trigger an 23205 * <code>IllegalStateException</code>, thrown by 23206 * {@link #measure(int, int)}. Calling the superclass' 23207 * {@link #onMeasure(int, int)} is a valid use. 23208 * </p> 23209 * 23210 * <p> 23211 * The base class implementation of measure defaults to the background size, 23212 * unless a larger size is allowed by the MeasureSpec. Subclasses should 23213 * override {@link #onMeasure(int, int)} to provide better measurements of 23214 * their content. 23215 * </p> 23216 * 23217 * <p> 23218 * If this method is overridden, it is the subclass's responsibility to make 23219 * sure the measured height and width are at least the view's minimum height 23220 * and width ({@link #getSuggestedMinimumHeight()} and 23221 * {@link #getSuggestedMinimumWidth()}). 23222 * </p> 23223 * 23224 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 23225 * The requirements are encoded with 23226 * {@link android.view.View.MeasureSpec}. 23227 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 23228 * The requirements are encoded with 23229 * {@link android.view.View.MeasureSpec}. 23230 * 23231 * @see #getMeasuredWidth() 23232 * @see #getMeasuredHeight() 23233 * @see #setMeasuredDimension(int, int) 23234 * @see #getSuggestedMinimumHeight() 23235 * @see #getSuggestedMinimumWidth() 23236 * @see android.view.View.MeasureSpec#getMode(int) 23237 * @see android.view.View.MeasureSpec#getSize(int) 23238 */ 23239 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 23240 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 23241 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 23242 } 23243 23244 /** 23245 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 23246 * measured width and measured height. Failing to do so will trigger an 23247 * exception at measurement time.</p> 23248 * 23249 * @param measuredWidth The measured width of this view. May be a complex 23250 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 23251 * {@link #MEASURED_STATE_TOO_SMALL}. 23252 * @param measuredHeight The measured height of this view. May be a complex 23253 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 23254 * {@link #MEASURED_STATE_TOO_SMALL}. 23255 */ 23256 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 23257 boolean optical = isLayoutModeOptical(this); 23258 if (optical != isLayoutModeOptical(mParent)) { 23259 Insets insets = getOpticalInsets(); 23260 int opticalWidth = insets.left + insets.right; 23261 int opticalHeight = insets.top + insets.bottom; 23262 23263 measuredWidth += optical ? opticalWidth : -opticalWidth; 23264 measuredHeight += optical ? opticalHeight : -opticalHeight; 23265 } 23266 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 23267 } 23268 23269 /** 23270 * Sets the measured dimension without extra processing for things like optical bounds. 23271 * Useful for reapplying consistent values that have already been cooked with adjustments 23272 * for optical bounds, etc. such as those from the measurement cache. 23273 * 23274 * @param measuredWidth The measured width of this view. May be a complex 23275 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 23276 * {@link #MEASURED_STATE_TOO_SMALL}. 23277 * @param measuredHeight The measured height of this view. May be a complex 23278 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 23279 * {@link #MEASURED_STATE_TOO_SMALL}. 23280 */ 23281 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 23282 mMeasuredWidth = measuredWidth; 23283 mMeasuredHeight = measuredHeight; 23284 23285 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 23286 } 23287 23288 /** 23289 * Merge two states as returned by {@link #getMeasuredState()}. 23290 * @param curState The current state as returned from a view or the result 23291 * of combining multiple views. 23292 * @param newState The new view state to combine. 23293 * @return Returns a new integer reflecting the combination of the two 23294 * states. 23295 */ 23296 public static int combineMeasuredStates(int curState, int newState) { 23297 return curState | newState; 23298 } 23299 23300 /** 23301 * Version of {@link #resolveSizeAndState(int, int, int)} 23302 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 23303 */ 23304 public static int resolveSize(int size, int measureSpec) { 23305 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 23306 } 23307 23308 /** 23309 * Utility to reconcile a desired size and state, with constraints imposed 23310 * by a MeasureSpec. Will take the desired size, unless a different size 23311 * is imposed by the constraints. The returned value is a compound integer, 23312 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 23313 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 23314 * resulting size is smaller than the size the view wants to be. 23315 * 23316 * @param size How big the view wants to be. 23317 * @param measureSpec Constraints imposed by the parent. 23318 * @param childMeasuredState Size information bit mask for the view's 23319 * children. 23320 * @return Size information bit mask as defined by 23321 * {@link #MEASURED_SIZE_MASK} and 23322 * {@link #MEASURED_STATE_TOO_SMALL}. 23323 */ 23324 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 23325 final int specMode = MeasureSpec.getMode(measureSpec); 23326 final int specSize = MeasureSpec.getSize(measureSpec); 23327 final int result; 23328 switch (specMode) { 23329 case MeasureSpec.AT_MOST: 23330 if (specSize < size) { 23331 result = specSize | MEASURED_STATE_TOO_SMALL; 23332 } else { 23333 result = size; 23334 } 23335 break; 23336 case MeasureSpec.EXACTLY: 23337 result = specSize; 23338 break; 23339 case MeasureSpec.UNSPECIFIED: 23340 default: 23341 result = size; 23342 } 23343 return result | (childMeasuredState & MEASURED_STATE_MASK); 23344 } 23345 23346 /** 23347 * Utility to return a default size. Uses the supplied size if the 23348 * MeasureSpec imposed no constraints. Will get larger if allowed 23349 * by the MeasureSpec. 23350 * 23351 * @param size Default size for this view 23352 * @param measureSpec Constraints imposed by the parent 23353 * @return The size this view should be. 23354 */ 23355 public static int getDefaultSize(int size, int measureSpec) { 23356 int result = size; 23357 int specMode = MeasureSpec.getMode(measureSpec); 23358 int specSize = MeasureSpec.getSize(measureSpec); 23359 23360 switch (specMode) { 23361 case MeasureSpec.UNSPECIFIED: 23362 result = size; 23363 break; 23364 case MeasureSpec.AT_MOST: 23365 case MeasureSpec.EXACTLY: 23366 result = specSize; 23367 break; 23368 } 23369 return result; 23370 } 23371 23372 /** 23373 * Returns the suggested minimum height that the view should use. This 23374 * returns the maximum of the view's minimum height 23375 * and the background's minimum height 23376 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 23377 * <p> 23378 * When being used in {@link #onMeasure(int, int)}, the caller should still 23379 * ensure the returned height is within the requirements of the parent. 23380 * 23381 * @return The suggested minimum height of the view. 23382 */ 23383 protected int getSuggestedMinimumHeight() { 23384 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 23385 23386 } 23387 23388 /** 23389 * Returns the suggested minimum width that the view should use. This 23390 * returns the maximum of the view's minimum width 23391 * and the background's minimum width 23392 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 23393 * <p> 23394 * When being used in {@link #onMeasure(int, int)}, the caller should still 23395 * ensure the returned width is within the requirements of the parent. 23396 * 23397 * @return The suggested minimum width of the view. 23398 */ 23399 protected int getSuggestedMinimumWidth() { 23400 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 23401 } 23402 23403 /** 23404 * Returns the minimum height of the view. 23405 * 23406 * @return the minimum height the view will try to be, in pixels 23407 * 23408 * @see #setMinimumHeight(int) 23409 * 23410 * @attr ref android.R.styleable#View_minHeight 23411 */ 23412 public int getMinimumHeight() { 23413 return mMinHeight; 23414 } 23415 23416 /** 23417 * Sets the minimum height of the view. It is not guaranteed the view will 23418 * be able to achieve this minimum height (for example, if its parent layout 23419 * constrains it with less available height). 23420 * 23421 * @param minHeight The minimum height the view will try to be, in pixels 23422 * 23423 * @see #getMinimumHeight() 23424 * 23425 * @attr ref android.R.styleable#View_minHeight 23426 */ 23427 @RemotableViewMethod 23428 public void setMinimumHeight(int minHeight) { 23429 mMinHeight = minHeight; 23430 requestLayout(); 23431 } 23432 23433 /** 23434 * Returns the minimum width of the view. 23435 * 23436 * @return the minimum width the view will try to be, in pixels 23437 * 23438 * @see #setMinimumWidth(int) 23439 * 23440 * @attr ref android.R.styleable#View_minWidth 23441 */ 23442 public int getMinimumWidth() { 23443 return mMinWidth; 23444 } 23445 23446 /** 23447 * Sets the minimum width of the view. It is not guaranteed the view will 23448 * be able to achieve this minimum width (for example, if its parent layout 23449 * constrains it with less available width). 23450 * 23451 * @param minWidth The minimum width the view will try to be, in pixels 23452 * 23453 * @see #getMinimumWidth() 23454 * 23455 * @attr ref android.R.styleable#View_minWidth 23456 */ 23457 public void setMinimumWidth(int minWidth) { 23458 mMinWidth = minWidth; 23459 requestLayout(); 23460 23461 } 23462 23463 /** 23464 * Get the animation currently associated with this view. 23465 * 23466 * @return The animation that is currently playing or 23467 * scheduled to play for this view. 23468 */ 23469 public Animation getAnimation() { 23470 return mCurrentAnimation; 23471 } 23472 23473 /** 23474 * Start the specified animation now. 23475 * 23476 * @param animation the animation to start now 23477 */ 23478 public void startAnimation(Animation animation) { 23479 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 23480 setAnimation(animation); 23481 invalidateParentCaches(); 23482 invalidate(true); 23483 } 23484 23485 /** 23486 * Cancels any animations for this view. 23487 */ 23488 public void clearAnimation() { 23489 if (mCurrentAnimation != null) { 23490 mCurrentAnimation.detach(); 23491 } 23492 mCurrentAnimation = null; 23493 invalidateParentIfNeeded(); 23494 } 23495 23496 /** 23497 * Sets the next animation to play for this view. 23498 * If you want the animation to play immediately, use 23499 * {@link #startAnimation(android.view.animation.Animation)} instead. 23500 * This method provides allows fine-grained 23501 * control over the start time and invalidation, but you 23502 * must make sure that 1) the animation has a start time set, and 23503 * 2) the view's parent (which controls animations on its children) 23504 * will be invalidated when the animation is supposed to 23505 * start. 23506 * 23507 * @param animation The next animation, or null. 23508 */ 23509 public void setAnimation(Animation animation) { 23510 mCurrentAnimation = animation; 23511 23512 if (animation != null) { 23513 // If the screen is off assume the animation start time is now instead of 23514 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 23515 // would cause the animation to start when the screen turns back on 23516 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 23517 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 23518 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 23519 } 23520 animation.reset(); 23521 } 23522 } 23523 23524 /** 23525 * Invoked by a parent ViewGroup to notify the start of the animation 23526 * currently associated with this view. If you override this method, 23527 * always call super.onAnimationStart(); 23528 * 23529 * @see #setAnimation(android.view.animation.Animation) 23530 * @see #getAnimation() 23531 */ 23532 @CallSuper 23533 protected void onAnimationStart() { 23534 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 23535 } 23536 23537 /** 23538 * Invoked by a parent ViewGroup to notify the end of the animation 23539 * currently associated with this view. If you override this method, 23540 * always call super.onAnimationEnd(); 23541 * 23542 * @see #setAnimation(android.view.animation.Animation) 23543 * @see #getAnimation() 23544 */ 23545 @CallSuper 23546 protected void onAnimationEnd() { 23547 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 23548 } 23549 23550 /** 23551 * Invoked if there is a Transform that involves alpha. Subclass that can 23552 * draw themselves with the specified alpha should return true, and then 23553 * respect that alpha when their onDraw() is called. If this returns false 23554 * then the view may be redirected to draw into an offscreen buffer to 23555 * fulfill the request, which will look fine, but may be slower than if the 23556 * subclass handles it internally. The default implementation returns false. 23557 * 23558 * @param alpha The alpha (0..255) to apply to the view's drawing 23559 * @return true if the view can draw with the specified alpha. 23560 */ 23561 protected boolean onSetAlpha(int alpha) { 23562 return false; 23563 } 23564 23565 /** 23566 * This is used by the RootView to perform an optimization when 23567 * the view hierarchy contains one or several SurfaceView. 23568 * SurfaceView is always considered transparent, but its children are not, 23569 * therefore all View objects remove themselves from the global transparent 23570 * region (passed as a parameter to this function). 23571 * 23572 * @param region The transparent region for this ViewAncestor (window). 23573 * 23574 * @return Returns true if the effective visibility of the view at this 23575 * point is opaque, regardless of the transparent region; returns false 23576 * if it is possible for underlying windows to be seen behind the view. 23577 * 23578 * {@hide} 23579 */ 23580 public boolean gatherTransparentRegion(Region region) { 23581 final AttachInfo attachInfo = mAttachInfo; 23582 if (region != null && attachInfo != null) { 23583 final int pflags = mPrivateFlags; 23584 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 23585 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 23586 // remove it from the transparent region. 23587 final int[] location = attachInfo.mTransparentLocation; 23588 getLocationInWindow(location); 23589 // When a view has Z value, then it will be better to leave some area below the view 23590 // for drawing shadow. The shadow outset is proportional to the Z value. Note that 23591 // the bottom part needs more offset than the left, top and right parts due to the 23592 // spot light effects. 23593 int shadowOffset = getZ() > 0 ? (int) getZ() : 0; 23594 region.op(location[0] - shadowOffset, location[1] - shadowOffset, 23595 location[0] + mRight - mLeft + shadowOffset, 23596 location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE); 23597 } else { 23598 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 23599 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 23600 // the background drawable's non-transparent parts from this transparent region. 23601 applyDrawableToTransparentRegion(mBackground, region); 23602 } 23603 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 23604 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 23605 // Similarly, we remove the foreground drawable's non-transparent parts. 23606 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 23607 } 23608 if (mDefaultFocusHighlight != null 23609 && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) { 23610 // Similarly, we remove the default focus highlight's non-transparent parts. 23611 applyDrawableToTransparentRegion(mDefaultFocusHighlight, region); 23612 } 23613 } 23614 } 23615 return true; 23616 } 23617 23618 /** 23619 * Play a sound effect for this view. 23620 * 23621 * <p>The framework will play sound effects for some built in actions, such as 23622 * clicking, but you may wish to play these effects in your widget, 23623 * for instance, for internal navigation. 23624 * 23625 * <p>The sound effect will only be played if sound effects are enabled by the user, and 23626 * {@link #isSoundEffectsEnabled()} is true. 23627 * 23628 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 23629 */ 23630 public void playSoundEffect(int soundConstant) { 23631 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 23632 return; 23633 } 23634 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 23635 } 23636 23637 /** 23638 * BZZZTT!!1! 23639 * 23640 * <p>Provide haptic feedback to the user for this view. 23641 * 23642 * <p>The framework will provide haptic feedback for some built in actions, 23643 * such as long presses, but you may wish to provide feedback for your 23644 * own widget. 23645 * 23646 * <p>The feedback will only be performed if 23647 * {@link #isHapticFeedbackEnabled()} is true. 23648 * 23649 * @param feedbackConstant One of the constants defined in 23650 * {@link HapticFeedbackConstants} 23651 */ 23652 public boolean performHapticFeedback(int feedbackConstant) { 23653 return performHapticFeedback(feedbackConstant, 0); 23654 } 23655 23656 /** 23657 * BZZZTT!!1! 23658 * 23659 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 23660 * 23661 * @param feedbackConstant One of the constants defined in 23662 * {@link HapticFeedbackConstants} 23663 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 23664 */ 23665 public boolean performHapticFeedback(int feedbackConstant, int flags) { 23666 if (mAttachInfo == null) { 23667 return false; 23668 } 23669 //noinspection SimplifiableIfStatement 23670 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 23671 && !isHapticFeedbackEnabled()) { 23672 return false; 23673 } 23674 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 23675 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 23676 } 23677 23678 /** 23679 * Request that the visibility of the status bar or other screen/window 23680 * decorations be changed. 23681 * 23682 * <p>This method is used to put the over device UI into temporary modes 23683 * where the user's attention is focused more on the application content, 23684 * by dimming or hiding surrounding system affordances. This is typically 23685 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 23686 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 23687 * to be placed behind the action bar (and with these flags other system 23688 * affordances) so that smooth transitions between hiding and showing them 23689 * can be done. 23690 * 23691 * <p>Two representative examples of the use of system UI visibility is 23692 * implementing a content browsing application (like a magazine reader) 23693 * and a video playing application. 23694 * 23695 * <p>The first code shows a typical implementation of a View in a content 23696 * browsing application. In this implementation, the application goes 23697 * into a content-oriented mode by hiding the status bar and action bar, 23698 * and putting the navigation elements into lights out mode. The user can 23699 * then interact with content while in this mode. Such an application should 23700 * provide an easy way for the user to toggle out of the mode (such as to 23701 * check information in the status bar or access notifications). In the 23702 * implementation here, this is done simply by tapping on the content. 23703 * 23704 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 23705 * content} 23706 * 23707 * <p>This second code sample shows a typical implementation of a View 23708 * in a video playing application. In this situation, while the video is 23709 * playing the application would like to go into a complete full-screen mode, 23710 * to use as much of the display as possible for the video. When in this state 23711 * the user can not interact with the application; the system intercepts 23712 * touching on the screen to pop the UI out of full screen mode. See 23713 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 23714 * 23715 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 23716 * content} 23717 * 23718 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 23719 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 23720 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 23721 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 23722 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 23723 */ 23724 public void setSystemUiVisibility(int visibility) { 23725 if (visibility != mSystemUiVisibility) { 23726 mSystemUiVisibility = visibility; 23727 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 23728 mParent.recomputeViewAttributes(this); 23729 } 23730 } 23731 } 23732 23733 /** 23734 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 23735 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 23736 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 23737 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 23738 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 23739 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 23740 */ 23741 public int getSystemUiVisibility() { 23742 return mSystemUiVisibility; 23743 } 23744 23745 /** 23746 * Returns the current system UI visibility that is currently set for 23747 * the entire window. This is the combination of the 23748 * {@link #setSystemUiVisibility(int)} values supplied by all of the 23749 * views in the window. 23750 */ 23751 public int getWindowSystemUiVisibility() { 23752 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 23753 } 23754 23755 /** 23756 * Override to find out when the window's requested system UI visibility 23757 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 23758 * This is different from the callbacks received through 23759 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 23760 * in that this is only telling you about the local request of the window, 23761 * not the actual values applied by the system. 23762 */ 23763 public void onWindowSystemUiVisibilityChanged(int visible) { 23764 } 23765 23766 /** 23767 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 23768 * the view hierarchy. 23769 */ 23770 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 23771 onWindowSystemUiVisibilityChanged(visible); 23772 } 23773 23774 /** 23775 * Set a listener to receive callbacks when the visibility of the system bar changes. 23776 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 23777 */ 23778 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 23779 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 23780 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 23781 mParent.recomputeViewAttributes(this); 23782 } 23783 } 23784 23785 /** 23786 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 23787 * the view hierarchy. 23788 */ 23789 public void dispatchSystemUiVisibilityChanged(int visibility) { 23790 ListenerInfo li = mListenerInfo; 23791 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 23792 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 23793 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 23794 } 23795 } 23796 23797 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 23798 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 23799 if (val != mSystemUiVisibility) { 23800 setSystemUiVisibility(val); 23801 return true; 23802 } 23803 return false; 23804 } 23805 23806 /** @hide */ 23807 public void setDisabledSystemUiVisibility(int flags) { 23808 if (mAttachInfo != null) { 23809 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 23810 mAttachInfo.mDisabledSystemUiVisibility = flags; 23811 if (mParent != null) { 23812 mParent.recomputeViewAttributes(this); 23813 } 23814 } 23815 } 23816 } 23817 23818 /** 23819 * Creates an image that the system displays during the drag and drop 23820 * operation. This is called a "drag shadow". The default implementation 23821 * for a DragShadowBuilder based on a View returns an image that has exactly the same 23822 * appearance as the given View. The default also positions the center of the drag shadow 23823 * directly under the touch point. If no View is provided (the constructor with no parameters 23824 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 23825 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 23826 * default is an invisible drag shadow. 23827 * <p> 23828 * You are not required to use the View you provide to the constructor as the basis of the 23829 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 23830 * anything you want as the drag shadow. 23831 * </p> 23832 * <p> 23833 * You pass a DragShadowBuilder object to the system when you start the drag. The system 23834 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 23835 * size and position of the drag shadow. It uses this data to construct a 23836 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 23837 * so that your application can draw the shadow image in the Canvas. 23838 * </p> 23839 * 23840 * <div class="special reference"> 23841 * <h3>Developer Guides</h3> 23842 * <p>For a guide to implementing drag and drop features, read the 23843 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 23844 * </div> 23845 */ 23846 public static class DragShadowBuilder { 23847 private final WeakReference<View> mView; 23848 23849 /** 23850 * Constructs a shadow image builder based on a View. By default, the resulting drag 23851 * shadow will have the same appearance and dimensions as the View, with the touch point 23852 * over the center of the View. 23853 * @param view A View. Any View in scope can be used. 23854 */ 23855 public DragShadowBuilder(View view) { 23856 mView = new WeakReference<View>(view); 23857 } 23858 23859 /** 23860 * Construct a shadow builder object with no associated View. This 23861 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 23862 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 23863 * to supply the drag shadow's dimensions and appearance without 23864 * reference to any View object. 23865 */ 23866 public DragShadowBuilder() { 23867 mView = new WeakReference<View>(null); 23868 } 23869 23870 /** 23871 * Returns the View object that had been passed to the 23872 * {@link #View.DragShadowBuilder(View)} 23873 * constructor. If that View parameter was {@code null} or if the 23874 * {@link #View.DragShadowBuilder()} 23875 * constructor was used to instantiate the builder object, this method will return 23876 * null. 23877 * 23878 * @return The View object associate with this builder object. 23879 */ 23880 @SuppressWarnings({"JavadocReference"}) 23881 final public View getView() { 23882 return mView.get(); 23883 } 23884 23885 /** 23886 * Provides the metrics for the shadow image. These include the dimensions of 23887 * the shadow image, and the point within that shadow that should 23888 * be centered under the touch location while dragging. 23889 * <p> 23890 * The default implementation sets the dimensions of the shadow to be the 23891 * same as the dimensions of the View itself and centers the shadow under 23892 * the touch point. 23893 * </p> 23894 * 23895 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 23896 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 23897 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 23898 * image. 23899 * 23900 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 23901 * shadow image that should be underneath the touch point during the drag and drop 23902 * operation. Your application must set {@link android.graphics.Point#x} to the 23903 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 23904 */ 23905 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 23906 final View view = mView.get(); 23907 if (view != null) { 23908 outShadowSize.set(view.getWidth(), view.getHeight()); 23909 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 23910 } else { 23911 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 23912 } 23913 } 23914 23915 /** 23916 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 23917 * based on the dimensions it received from the 23918 * {@link #onProvideShadowMetrics(Point, Point)} callback. 23919 * 23920 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 23921 */ 23922 public void onDrawShadow(Canvas canvas) { 23923 final View view = mView.get(); 23924 if (view != null) { 23925 view.draw(canvas); 23926 } else { 23927 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 23928 } 23929 } 23930 } 23931 23932 /** 23933 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 23934 * startDragAndDrop()} for newer platform versions. 23935 */ 23936 @Deprecated 23937 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 23938 Object myLocalState, int flags) { 23939 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 23940 } 23941 23942 /** 23943 * Starts a drag and drop operation. When your application calls this method, it passes a 23944 * {@link android.view.View.DragShadowBuilder} object to the system. The 23945 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 23946 * to get metrics for the drag shadow, and then calls the object's 23947 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 23948 * <p> 23949 * Once the system has the drag shadow, it begins the drag and drop operation by sending 23950 * drag events to all the View objects in your application that are currently visible. It does 23951 * this either by calling the View object's drag listener (an implementation of 23952 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 23953 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 23954 * Both are passed a {@link android.view.DragEvent} object that has a 23955 * {@link android.view.DragEvent#getAction()} value of 23956 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 23957 * </p> 23958 * <p> 23959 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 23960 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 23961 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 23962 * to the View the user selected for dragging. 23963 * </p> 23964 * @param data A {@link android.content.ClipData} object pointing to the data to be 23965 * transferred by the drag and drop operation. 23966 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 23967 * drag shadow. 23968 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 23969 * drop operation. When dispatching drag events to views in the same activity this object 23970 * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other 23971 * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()} 23972 * will return null). 23973 * <p> 23974 * myLocalState is a lightweight mechanism for the sending information from the dragged View 23975 * to the target Views. For example, it can contain flags that differentiate between a 23976 * a copy operation and a move operation. 23977 * </p> 23978 * @param flags Flags that control the drag and drop operation. This can be set to 0 for no 23979 * flags, or any combination of the following: 23980 * <ul> 23981 * <li>{@link #DRAG_FLAG_GLOBAL}</li> 23982 * <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li> 23983 * <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li> 23984 * <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li> 23985 * <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li> 23986 * <li>{@link #DRAG_FLAG_OPAQUE}</li> 23987 * </ul> 23988 * @return {@code true} if the method completes successfully, or 23989 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 23990 * do a drag, and so no drag operation is in progress. 23991 */ 23992 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 23993 Object myLocalState, int flags) { 23994 if (ViewDebug.DEBUG_DRAG) { 23995 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 23996 } 23997 if (mAttachInfo == null) { 23998 Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view."); 23999 return false; 24000 } 24001 24002 if (data != null) { 24003 data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0); 24004 } 24005 24006 Point shadowSize = new Point(); 24007 Point shadowTouchPoint = new Point(); 24008 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 24009 24010 if ((shadowSize.x < 0) || (shadowSize.y < 0) 24011 || (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 24012 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 24013 } 24014 24015 // Create 1x1 surface when zero surface size is specified because SurfaceControl.Builder 24016 // does not accept zero size surface. 24017 if (shadowSize.x == 0 || shadowSize.y == 0) { 24018 if (!sAcceptZeroSizeDragShadow) { 24019 throw new IllegalStateException("Drag shadow dimensions must be positive"); 24020 } 24021 shadowSize.x = 1; 24022 shadowSize.y = 1; 24023 } 24024 24025 if (ViewDebug.DEBUG_DRAG) { 24026 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 24027 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 24028 } 24029 if (mAttachInfo.mDragSurface != null) { 24030 mAttachInfo.mDragSurface.release(); 24031 } 24032 mAttachInfo.mDragSurface = new Surface(); 24033 mAttachInfo.mDragToken = null; 24034 24035 final ViewRootImpl root = mAttachInfo.mViewRootImpl; 24036 final SurfaceSession session = new SurfaceSession(root.mSurface); 24037 final SurfaceControl surface = new SurfaceControl.Builder(session) 24038 .setName("drag surface") 24039 .setSize(shadowSize.x, shadowSize.y) 24040 .setFormat(PixelFormat.TRANSLUCENT) 24041 .build(); 24042 try { 24043 mAttachInfo.mDragSurface.copyFrom(surface); 24044 final Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 24045 try { 24046 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 24047 shadowBuilder.onDrawShadow(canvas); 24048 } finally { 24049 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 24050 } 24051 24052 // Cache the local state object for delivery with DragEvents 24053 root.setLocalDragState(myLocalState); 24054 24055 // repurpose 'shadowSize' for the last touch point 24056 root.getLastTouchPoint(shadowSize); 24057 24058 mAttachInfo.mDragToken = mAttachInfo.mSession.performDrag( 24059 mAttachInfo.mWindow, flags, surface, root.getLastTouchSource(), 24060 shadowSize.x, shadowSize.y, shadowTouchPoint.x, shadowTouchPoint.y, data); 24061 if (ViewDebug.DEBUG_DRAG) { 24062 Log.d(VIEW_LOG_TAG, "performDrag returned " + mAttachInfo.mDragToken); 24063 } 24064 24065 return mAttachInfo.mDragToken != null; 24066 } catch (Exception e) { 24067 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 24068 return false; 24069 } finally { 24070 if (mAttachInfo.mDragToken == null) { 24071 mAttachInfo.mDragSurface.destroy(); 24072 mAttachInfo.mDragSurface = null; 24073 root.setLocalDragState(null); 24074 } 24075 session.kill(); 24076 } 24077 } 24078 24079 /** 24080 * Cancels an ongoing drag and drop operation. 24081 * <p> 24082 * A {@link android.view.DragEvent} object with 24083 * {@link android.view.DragEvent#getAction()} value of 24084 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 24085 * {@link android.view.DragEvent#getResult()} value of {@code false} 24086 * will be sent to every 24087 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 24088 * even if they are not currently visible. 24089 * </p> 24090 * <p> 24091 * This method can be called on any View in the same window as the View on which 24092 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 24093 * was called. 24094 * </p> 24095 */ 24096 public final void cancelDragAndDrop() { 24097 if (ViewDebug.DEBUG_DRAG) { 24098 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 24099 } 24100 if (mAttachInfo == null) { 24101 Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view."); 24102 return; 24103 } 24104 if (mAttachInfo.mDragToken != null) { 24105 try { 24106 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 24107 } catch (Exception e) { 24108 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 24109 } 24110 mAttachInfo.mDragToken = null; 24111 } else { 24112 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 24113 } 24114 } 24115 24116 /** 24117 * Updates the drag shadow for the ongoing drag and drop operation. 24118 * 24119 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 24120 * new drag shadow. 24121 */ 24122 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 24123 if (ViewDebug.DEBUG_DRAG) { 24124 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 24125 } 24126 if (mAttachInfo == null) { 24127 Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view."); 24128 return; 24129 } 24130 if (mAttachInfo.mDragToken != null) { 24131 try { 24132 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 24133 try { 24134 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 24135 shadowBuilder.onDrawShadow(canvas); 24136 } finally { 24137 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 24138 } 24139 } catch (Exception e) { 24140 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 24141 } 24142 } else { 24143 Log.e(VIEW_LOG_TAG, "No active drag"); 24144 } 24145 } 24146 24147 /** 24148 * Starts a move from {startX, startY}, the amount of the movement will be the offset 24149 * between {startX, startY} and the new cursor positon. 24150 * @param startX horizontal coordinate where the move started. 24151 * @param startY vertical coordinate where the move started. 24152 * @return whether moving was started successfully. 24153 * @hide 24154 */ 24155 public final boolean startMovingTask(float startX, float startY) { 24156 if (ViewDebug.DEBUG_POSITIONING) { 24157 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 24158 } 24159 try { 24160 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 24161 } catch (RemoteException e) { 24162 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 24163 } 24164 return false; 24165 } 24166 24167 /** 24168 * Handles drag events sent by the system following a call to 24169 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 24170 * startDragAndDrop()}. 24171 *<p> 24172 * When the system calls this method, it passes a 24173 * {@link android.view.DragEvent} object. A call to 24174 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 24175 * in DragEvent. The method uses these to determine what is happening in the drag and drop 24176 * operation. 24177 * @param event The {@link android.view.DragEvent} sent by the system. 24178 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 24179 * in DragEvent, indicating the type of drag event represented by this object. 24180 * @return {@code true} if the method was successful, otherwise {@code false}. 24181 * <p> 24182 * The method should return {@code true} in response to an action type of 24183 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 24184 * operation. 24185 * </p> 24186 * <p> 24187 * The method should also return {@code true} in response to an action type of 24188 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 24189 * {@code false} if it didn't. 24190 * </p> 24191 * <p> 24192 * For all other events, the return value is ignored. 24193 * </p> 24194 */ 24195 public boolean onDragEvent(DragEvent event) { 24196 return false; 24197 } 24198 24199 // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps. 24200 boolean dispatchDragEnterExitInPreN(DragEvent event) { 24201 return callDragEventHandler(event); 24202 } 24203 24204 /** 24205 * Detects if this View is enabled and has a drag event listener. 24206 * If both are true, then it calls the drag event listener with the 24207 * {@link android.view.DragEvent} it received. If the drag event listener returns 24208 * {@code true}, then dispatchDragEvent() returns {@code true}. 24209 * <p> 24210 * For all other cases, the method calls the 24211 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 24212 * method and returns its result. 24213 * </p> 24214 * <p> 24215 * This ensures that a drag event is always consumed, even if the View does not have a drag 24216 * event listener. However, if the View has a listener and the listener returns true, then 24217 * onDragEvent() is not called. 24218 * </p> 24219 */ 24220 public boolean dispatchDragEvent(DragEvent event) { 24221 event.mEventHandlerWasCalled = true; 24222 if (event.mAction == DragEvent.ACTION_DRAG_LOCATION || 24223 event.mAction == DragEvent.ACTION_DROP) { 24224 // About to deliver an event with coordinates to this view. Notify that now this view 24225 // has drag focus. This will send exit/enter events as needed. 24226 getViewRootImpl().setDragFocus(this, event); 24227 } 24228 return callDragEventHandler(event); 24229 } 24230 24231 final boolean callDragEventHandler(DragEvent event) { 24232 final boolean result; 24233 24234 ListenerInfo li = mListenerInfo; 24235 //noinspection SimplifiableIfStatement 24236 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 24237 && li.mOnDragListener.onDrag(this, event)) { 24238 result = true; 24239 } else { 24240 result = onDragEvent(event); 24241 } 24242 24243 switch (event.mAction) { 24244 case DragEvent.ACTION_DRAG_ENTERED: { 24245 mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED; 24246 refreshDrawableState(); 24247 } break; 24248 case DragEvent.ACTION_DRAG_EXITED: { 24249 mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED; 24250 refreshDrawableState(); 24251 } break; 24252 case DragEvent.ACTION_DRAG_ENDED: { 24253 mPrivateFlags2 &= ~View.DRAG_MASK; 24254 refreshDrawableState(); 24255 } break; 24256 } 24257 24258 return result; 24259 } 24260 24261 boolean canAcceptDrag() { 24262 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 24263 } 24264 24265 /** 24266 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 24267 * it is ever exposed at all. 24268 * @hide 24269 */ 24270 public void onCloseSystemDialogs(String reason) { 24271 } 24272 24273 /** 24274 * Given a Drawable whose bounds have been set to draw into this view, 24275 * update a Region being computed for 24276 * {@link #gatherTransparentRegion(android.graphics.Region)} so 24277 * that any non-transparent parts of the Drawable are removed from the 24278 * given transparent region. 24279 * 24280 * @param dr The Drawable whose transparency is to be applied to the region. 24281 * @param region A Region holding the current transparency information, 24282 * where any parts of the region that are set are considered to be 24283 * transparent. On return, this region will be modified to have the 24284 * transparency information reduced by the corresponding parts of the 24285 * Drawable that are not transparent. 24286 * {@hide} 24287 */ 24288 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 24289 if (DBG) { 24290 Log.i("View", "Getting transparent region for: " + this); 24291 } 24292 final Region r = dr.getTransparentRegion(); 24293 final Rect db = dr.getBounds(); 24294 final AttachInfo attachInfo = mAttachInfo; 24295 if (r != null && attachInfo != null) { 24296 final int w = getRight()-getLeft(); 24297 final int h = getBottom()-getTop(); 24298 if (db.left > 0) { 24299 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 24300 r.op(0, 0, db.left, h, Region.Op.UNION); 24301 } 24302 if (db.right < w) { 24303 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 24304 r.op(db.right, 0, w, h, Region.Op.UNION); 24305 } 24306 if (db.top > 0) { 24307 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 24308 r.op(0, 0, w, db.top, Region.Op.UNION); 24309 } 24310 if (db.bottom < h) { 24311 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 24312 r.op(0, db.bottom, w, h, Region.Op.UNION); 24313 } 24314 final int[] location = attachInfo.mTransparentLocation; 24315 getLocationInWindow(location); 24316 r.translate(location[0], location[1]); 24317 region.op(r, Region.Op.INTERSECT); 24318 } else { 24319 region.op(db, Region.Op.DIFFERENCE); 24320 } 24321 } 24322 24323 private void checkForLongClick(int delayOffset, float x, float y) { 24324 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) { 24325 mHasPerformedLongPress = false; 24326 24327 if (mPendingCheckForLongPress == null) { 24328 mPendingCheckForLongPress = new CheckForLongPress(); 24329 } 24330 mPendingCheckForLongPress.setAnchor(x, y); 24331 mPendingCheckForLongPress.rememberWindowAttachCount(); 24332 mPendingCheckForLongPress.rememberPressedState(); 24333 postDelayed(mPendingCheckForLongPress, 24334 ViewConfiguration.getLongPressTimeout() - delayOffset); 24335 } 24336 } 24337 24338 /** 24339 * Inflate a view from an XML resource. This convenience method wraps the {@link 24340 * LayoutInflater} class, which provides a full range of options for view inflation. 24341 * 24342 * @param context The Context object for your activity or application. 24343 * @param resource The resource ID to inflate 24344 * @param root A view group that will be the parent. Used to properly inflate the 24345 * layout_* parameters. 24346 * @see LayoutInflater 24347 */ 24348 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 24349 LayoutInflater factory = LayoutInflater.from(context); 24350 return factory.inflate(resource, root); 24351 } 24352 24353 /** 24354 * Scroll the view with standard behavior for scrolling beyond the normal 24355 * content boundaries. Views that call this method should override 24356 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 24357 * results of an over-scroll operation. 24358 * 24359 * Views can use this method to handle any touch or fling-based scrolling. 24360 * 24361 * @param deltaX Change in X in pixels 24362 * @param deltaY Change in Y in pixels 24363 * @param scrollX Current X scroll value in pixels before applying deltaX 24364 * @param scrollY Current Y scroll value in pixels before applying deltaY 24365 * @param scrollRangeX Maximum content scroll range along the X axis 24366 * @param scrollRangeY Maximum content scroll range along the Y axis 24367 * @param maxOverScrollX Number of pixels to overscroll by in either direction 24368 * along the X axis. 24369 * @param maxOverScrollY Number of pixels to overscroll by in either direction 24370 * along the Y axis. 24371 * @param isTouchEvent true if this scroll operation is the result of a touch event. 24372 * @return true if scrolling was clamped to an over-scroll boundary along either 24373 * axis, false otherwise. 24374 */ 24375 @SuppressWarnings({"UnusedParameters"}) 24376 protected boolean overScrollBy(int deltaX, int deltaY, 24377 int scrollX, int scrollY, 24378 int scrollRangeX, int scrollRangeY, 24379 int maxOverScrollX, int maxOverScrollY, 24380 boolean isTouchEvent) { 24381 final int overScrollMode = mOverScrollMode; 24382 final boolean canScrollHorizontal = 24383 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 24384 final boolean canScrollVertical = 24385 computeVerticalScrollRange() > computeVerticalScrollExtent(); 24386 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 24387 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 24388 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 24389 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 24390 24391 int newScrollX = scrollX + deltaX; 24392 if (!overScrollHorizontal) { 24393 maxOverScrollX = 0; 24394 } 24395 24396 int newScrollY = scrollY + deltaY; 24397 if (!overScrollVertical) { 24398 maxOverScrollY = 0; 24399 } 24400 24401 // Clamp values if at the limits and record 24402 final int left = -maxOverScrollX; 24403 final int right = maxOverScrollX + scrollRangeX; 24404 final int top = -maxOverScrollY; 24405 final int bottom = maxOverScrollY + scrollRangeY; 24406 24407 boolean clampedX = false; 24408 if (newScrollX > right) { 24409 newScrollX = right; 24410 clampedX = true; 24411 } else if (newScrollX < left) { 24412 newScrollX = left; 24413 clampedX = true; 24414 } 24415 24416 boolean clampedY = false; 24417 if (newScrollY > bottom) { 24418 newScrollY = bottom; 24419 clampedY = true; 24420 } else if (newScrollY < top) { 24421 newScrollY = top; 24422 clampedY = true; 24423 } 24424 24425 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 24426 24427 return clampedX || clampedY; 24428 } 24429 24430 /** 24431 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 24432 * respond to the results of an over-scroll operation. 24433 * 24434 * @param scrollX New X scroll value in pixels 24435 * @param scrollY New Y scroll value in pixels 24436 * @param clampedX True if scrollX was clamped to an over-scroll boundary 24437 * @param clampedY True if scrollY was clamped to an over-scroll boundary 24438 */ 24439 protected void onOverScrolled(int scrollX, int scrollY, 24440 boolean clampedX, boolean clampedY) { 24441 // Intentionally empty. 24442 } 24443 24444 /** 24445 * Returns the over-scroll mode for this view. The result will be 24446 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 24447 * (allow over-scrolling only if the view content is larger than the container), 24448 * or {@link #OVER_SCROLL_NEVER}. 24449 * 24450 * @return This view's over-scroll mode. 24451 */ 24452 public int getOverScrollMode() { 24453 return mOverScrollMode; 24454 } 24455 24456 /** 24457 * Set the over-scroll mode for this view. Valid over-scroll modes are 24458 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 24459 * (allow over-scrolling only if the view content is larger than the container), 24460 * or {@link #OVER_SCROLL_NEVER}. 24461 * 24462 * Setting the over-scroll mode of a view will have an effect only if the 24463 * view is capable of scrolling. 24464 * 24465 * @param overScrollMode The new over-scroll mode for this view. 24466 */ 24467 public void setOverScrollMode(int overScrollMode) { 24468 if (overScrollMode != OVER_SCROLL_ALWAYS && 24469 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 24470 overScrollMode != OVER_SCROLL_NEVER) { 24471 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 24472 } 24473 mOverScrollMode = overScrollMode; 24474 } 24475 24476 /** 24477 * Enable or disable nested scrolling for this view. 24478 * 24479 * <p>If this property is set to true the view will be permitted to initiate nested 24480 * scrolling operations with a compatible parent view in the current hierarchy. If this 24481 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 24482 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 24483 * the nested scroll.</p> 24484 * 24485 * @param enabled true to enable nested scrolling, false to disable 24486 * 24487 * @see #isNestedScrollingEnabled() 24488 */ 24489 public void setNestedScrollingEnabled(boolean enabled) { 24490 if (enabled) { 24491 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 24492 } else { 24493 stopNestedScroll(); 24494 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 24495 } 24496 } 24497 24498 /** 24499 * Returns true if nested scrolling is enabled for this view. 24500 * 24501 * <p>If nested scrolling is enabled and this View class implementation supports it, 24502 * this view will act as a nested scrolling child view when applicable, forwarding data 24503 * about the scroll operation in progress to a compatible and cooperating nested scrolling 24504 * parent.</p> 24505 * 24506 * @return true if nested scrolling is enabled 24507 * 24508 * @see #setNestedScrollingEnabled(boolean) 24509 */ 24510 public boolean isNestedScrollingEnabled() { 24511 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 24512 PFLAG3_NESTED_SCROLLING_ENABLED; 24513 } 24514 24515 /** 24516 * Begin a nestable scroll operation along the given axes. 24517 * 24518 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 24519 * 24520 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 24521 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 24522 * In the case of touch scrolling the nested scroll will be terminated automatically in 24523 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 24524 * In the event of programmatic scrolling the caller must explicitly call 24525 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 24526 * 24527 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 24528 * If it returns false the caller may ignore the rest of this contract until the next scroll. 24529 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 24530 * 24531 * <p>At each incremental step of the scroll the caller should invoke 24532 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 24533 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 24534 * parent at least partially consumed the scroll and the caller should adjust the amount it 24535 * scrolls by.</p> 24536 * 24537 * <p>After applying the remainder of the scroll delta the caller should invoke 24538 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 24539 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 24540 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 24541 * </p> 24542 * 24543 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 24544 * {@link #SCROLL_AXIS_VERTICAL}. 24545 * @return true if a cooperative parent was found and nested scrolling has been enabled for 24546 * the current gesture. 24547 * 24548 * @see #stopNestedScroll() 24549 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 24550 * @see #dispatchNestedScroll(int, int, int, int, int[]) 24551 */ 24552 public boolean startNestedScroll(int axes) { 24553 if (hasNestedScrollingParent()) { 24554 // Already in progress 24555 return true; 24556 } 24557 if (isNestedScrollingEnabled()) { 24558 ViewParent p = getParent(); 24559 View child = this; 24560 while (p != null) { 24561 try { 24562 if (p.onStartNestedScroll(child, this, axes)) { 24563 mNestedScrollingParent = p; 24564 p.onNestedScrollAccepted(child, this, axes); 24565 return true; 24566 } 24567 } catch (AbstractMethodError e) { 24568 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 24569 "method onStartNestedScroll", e); 24570 // Allow the search upward to continue 24571 } 24572 if (p instanceof View) { 24573 child = (View) p; 24574 } 24575 p = p.getParent(); 24576 } 24577 } 24578 return false; 24579 } 24580 24581 /** 24582 * Stop a nested scroll in progress. 24583 * 24584 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 24585 * 24586 * @see #startNestedScroll(int) 24587 */ 24588 public void stopNestedScroll() { 24589 if (mNestedScrollingParent != null) { 24590 mNestedScrollingParent.onStopNestedScroll(this); 24591 mNestedScrollingParent = null; 24592 } 24593 } 24594 24595 /** 24596 * Returns true if this view has a nested scrolling parent. 24597 * 24598 * <p>The presence of a nested scrolling parent indicates that this view has initiated 24599 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 24600 * 24601 * @return whether this view has a nested scrolling parent 24602 */ 24603 public boolean hasNestedScrollingParent() { 24604 return mNestedScrollingParent != null; 24605 } 24606 24607 /** 24608 * Dispatch one step of a nested scroll in progress. 24609 * 24610 * <p>Implementations of views that support nested scrolling should call this to report 24611 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 24612 * is not currently in progress or nested scrolling is not 24613 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 24614 * 24615 * <p>Compatible View implementations should also call 24616 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 24617 * consuming a component of the scroll event themselves.</p> 24618 * 24619 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 24620 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 24621 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 24622 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 24623 * @param offsetInWindow Optional. If not null, on return this will contain the offset 24624 * in local view coordinates of this view from before this operation 24625 * to after it completes. View implementations may use this to adjust 24626 * expected input coordinate tracking. 24627 * @return true if the event was dispatched, false if it could not be dispatched. 24628 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 24629 */ 24630 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 24631 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 24632 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 24633 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 24634 int startX = 0; 24635 int startY = 0; 24636 if (offsetInWindow != null) { 24637 getLocationInWindow(offsetInWindow); 24638 startX = offsetInWindow[0]; 24639 startY = offsetInWindow[1]; 24640 } 24641 24642 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 24643 dxUnconsumed, dyUnconsumed); 24644 24645 if (offsetInWindow != null) { 24646 getLocationInWindow(offsetInWindow); 24647 offsetInWindow[0] -= startX; 24648 offsetInWindow[1] -= startY; 24649 } 24650 return true; 24651 } else if (offsetInWindow != null) { 24652 // No motion, no dispatch. Keep offsetInWindow up to date. 24653 offsetInWindow[0] = 0; 24654 offsetInWindow[1] = 0; 24655 } 24656 } 24657 return false; 24658 } 24659 24660 /** 24661 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 24662 * 24663 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 24664 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 24665 * scrolling operation to consume some or all of the scroll operation before the child view 24666 * consumes it.</p> 24667 * 24668 * @param dx Horizontal scroll distance in pixels 24669 * @param dy Vertical scroll distance in pixels 24670 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 24671 * and consumed[1] the consumed dy. 24672 * @param offsetInWindow Optional. If not null, on return this will contain the offset 24673 * in local view coordinates of this view from before this operation 24674 * to after it completes. View implementations may use this to adjust 24675 * expected input coordinate tracking. 24676 * @return true if the parent consumed some or all of the scroll delta 24677 * @see #dispatchNestedScroll(int, int, int, int, int[]) 24678 */ 24679 public boolean dispatchNestedPreScroll(int dx, int dy, 24680 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 24681 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 24682 if (dx != 0 || dy != 0) { 24683 int startX = 0; 24684 int startY = 0; 24685 if (offsetInWindow != null) { 24686 getLocationInWindow(offsetInWindow); 24687 startX = offsetInWindow[0]; 24688 startY = offsetInWindow[1]; 24689 } 24690 24691 if (consumed == null) { 24692 if (mTempNestedScrollConsumed == null) { 24693 mTempNestedScrollConsumed = new int[2]; 24694 } 24695 consumed = mTempNestedScrollConsumed; 24696 } 24697 consumed[0] = 0; 24698 consumed[1] = 0; 24699 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 24700 24701 if (offsetInWindow != null) { 24702 getLocationInWindow(offsetInWindow); 24703 offsetInWindow[0] -= startX; 24704 offsetInWindow[1] -= startY; 24705 } 24706 return consumed[0] != 0 || consumed[1] != 0; 24707 } else if (offsetInWindow != null) { 24708 offsetInWindow[0] = 0; 24709 offsetInWindow[1] = 0; 24710 } 24711 } 24712 return false; 24713 } 24714 24715 /** 24716 * Dispatch a fling to a nested scrolling parent. 24717 * 24718 * <p>This method should be used to indicate that a nested scrolling child has detected 24719 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 24720 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 24721 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 24722 * along a scrollable axis.</p> 24723 * 24724 * <p>If a nested scrolling child view would normally fling but it is at the edge of 24725 * its own content, it can use this method to delegate the fling to its nested scrolling 24726 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 24727 * 24728 * @param velocityX Horizontal fling velocity in pixels per second 24729 * @param velocityY Vertical fling velocity in pixels per second 24730 * @param consumed true if the child consumed the fling, false otherwise 24731 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 24732 */ 24733 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 24734 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 24735 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 24736 } 24737 return false; 24738 } 24739 24740 /** 24741 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 24742 * 24743 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 24744 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 24745 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 24746 * before the child view consumes it. If this method returns <code>true</code>, a nested 24747 * parent view consumed the fling and this view should not scroll as a result.</p> 24748 * 24749 * <p>For a better user experience, only one view in a nested scrolling chain should consume 24750 * the fling at a time. If a parent view consumed the fling this method will return false. 24751 * Custom view implementations should account for this in two ways:</p> 24752 * 24753 * <ul> 24754 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 24755 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 24756 * position regardless.</li> 24757 * <li>If a nested parent does consume the fling, this view should not scroll at all, 24758 * even to settle back to a valid idle position.</li> 24759 * </ul> 24760 * 24761 * <p>Views should also not offer fling velocities to nested parent views along an axis 24762 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 24763 * should not offer a horizontal fling velocity to its parents since scrolling along that 24764 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 24765 * 24766 * @param velocityX Horizontal fling velocity in pixels per second 24767 * @param velocityY Vertical fling velocity in pixels per second 24768 * @return true if a nested scrolling parent consumed the fling 24769 */ 24770 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 24771 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 24772 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 24773 } 24774 return false; 24775 } 24776 24777 /** 24778 * Gets a scale factor that determines the distance the view should scroll 24779 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 24780 * @return The vertical scroll scale factor. 24781 * @hide 24782 */ 24783 protected float getVerticalScrollFactor() { 24784 if (mVerticalScrollFactor == 0) { 24785 TypedValue outValue = new TypedValue(); 24786 if (!mContext.getTheme().resolveAttribute( 24787 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 24788 throw new IllegalStateException( 24789 "Expected theme to define listPreferredItemHeight."); 24790 } 24791 mVerticalScrollFactor = outValue.getDimension( 24792 mContext.getResources().getDisplayMetrics()); 24793 } 24794 return mVerticalScrollFactor; 24795 } 24796 24797 /** 24798 * Gets a scale factor that determines the distance the view should scroll 24799 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 24800 * @return The horizontal scroll scale factor. 24801 * @hide 24802 */ 24803 protected float getHorizontalScrollFactor() { 24804 // TODO: Should use something else. 24805 return getVerticalScrollFactor(); 24806 } 24807 24808 /** 24809 * Return the value specifying the text direction or policy that was set with 24810 * {@link #setTextDirection(int)}. 24811 * 24812 * @return the defined text direction. It can be one of: 24813 * 24814 * {@link #TEXT_DIRECTION_INHERIT}, 24815 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 24816 * {@link #TEXT_DIRECTION_ANY_RTL}, 24817 * {@link #TEXT_DIRECTION_LTR}, 24818 * {@link #TEXT_DIRECTION_RTL}, 24819 * {@link #TEXT_DIRECTION_LOCALE}, 24820 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 24821 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 24822 * 24823 * @attr ref android.R.styleable#View_textDirection 24824 * 24825 * @hide 24826 */ 24827 @ViewDebug.ExportedProperty(category = "text", mapping = { 24828 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 24829 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 24830 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 24831 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 24832 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 24833 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 24834 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 24835 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 24836 }) 24837 public int getRawTextDirection() { 24838 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 24839 } 24840 24841 /** 24842 * Set the text direction. 24843 * 24844 * @param textDirection the direction to set. Should be one of: 24845 * 24846 * {@link #TEXT_DIRECTION_INHERIT}, 24847 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 24848 * {@link #TEXT_DIRECTION_ANY_RTL}, 24849 * {@link #TEXT_DIRECTION_LTR}, 24850 * {@link #TEXT_DIRECTION_RTL}, 24851 * {@link #TEXT_DIRECTION_LOCALE} 24852 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 24853 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 24854 * 24855 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 24856 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 24857 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 24858 * 24859 * @attr ref android.R.styleable#View_textDirection 24860 */ 24861 public void setTextDirection(int textDirection) { 24862 if (getRawTextDirection() != textDirection) { 24863 // Reset the current text direction and the resolved one 24864 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 24865 resetResolvedTextDirection(); 24866 // Set the new text direction 24867 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 24868 // Do resolution 24869 resolveTextDirection(); 24870 // Notify change 24871 onRtlPropertiesChanged(getLayoutDirection()); 24872 // Refresh 24873 requestLayout(); 24874 invalidate(true); 24875 } 24876 } 24877 24878 /** 24879 * Return the resolved text direction. 24880 * 24881 * @return the resolved text direction. Returns one of: 24882 * 24883 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 24884 * {@link #TEXT_DIRECTION_ANY_RTL}, 24885 * {@link #TEXT_DIRECTION_LTR}, 24886 * {@link #TEXT_DIRECTION_RTL}, 24887 * {@link #TEXT_DIRECTION_LOCALE}, 24888 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 24889 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 24890 * 24891 * @attr ref android.R.styleable#View_textDirection 24892 */ 24893 @ViewDebug.ExportedProperty(category = "text", mapping = { 24894 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 24895 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 24896 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 24897 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 24898 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 24899 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 24900 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 24901 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 24902 }) 24903 public int getTextDirection() { 24904 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 24905 } 24906 24907 /** 24908 * Resolve the text direction. 24909 * 24910 * @return true if resolution has been done, false otherwise. 24911 * 24912 * @hide 24913 */ 24914 public boolean resolveTextDirection() { 24915 // Reset any previous text direction resolution 24916 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 24917 24918 if (hasRtlSupport()) { 24919 // Set resolved text direction flag depending on text direction flag 24920 final int textDirection = getRawTextDirection(); 24921 switch(textDirection) { 24922 case TEXT_DIRECTION_INHERIT: 24923 if (!canResolveTextDirection()) { 24924 // We cannot do the resolution if there is no parent, so use the default one 24925 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 24926 // Resolution will need to happen again later 24927 return false; 24928 } 24929 24930 // Parent has not yet resolved, so we still return the default 24931 try { 24932 if (!mParent.isTextDirectionResolved()) { 24933 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 24934 // Resolution will need to happen again later 24935 return false; 24936 } 24937 } catch (AbstractMethodError e) { 24938 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 24939 " does not fully implement ViewParent", e); 24940 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 24941 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 24942 return true; 24943 } 24944 24945 // Set current resolved direction to the same value as the parent's one 24946 int parentResolvedDirection; 24947 try { 24948 parentResolvedDirection = mParent.getTextDirection(); 24949 } catch (AbstractMethodError e) { 24950 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 24951 " does not fully implement ViewParent", e); 24952 parentResolvedDirection = TEXT_DIRECTION_LTR; 24953 } 24954 switch (parentResolvedDirection) { 24955 case TEXT_DIRECTION_FIRST_STRONG: 24956 case TEXT_DIRECTION_ANY_RTL: 24957 case TEXT_DIRECTION_LTR: 24958 case TEXT_DIRECTION_RTL: 24959 case TEXT_DIRECTION_LOCALE: 24960 case TEXT_DIRECTION_FIRST_STRONG_LTR: 24961 case TEXT_DIRECTION_FIRST_STRONG_RTL: 24962 mPrivateFlags2 |= 24963 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 24964 break; 24965 default: 24966 // Default resolved direction is "first strong" heuristic 24967 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 24968 } 24969 break; 24970 case TEXT_DIRECTION_FIRST_STRONG: 24971 case TEXT_DIRECTION_ANY_RTL: 24972 case TEXT_DIRECTION_LTR: 24973 case TEXT_DIRECTION_RTL: 24974 case TEXT_DIRECTION_LOCALE: 24975 case TEXT_DIRECTION_FIRST_STRONG_LTR: 24976 case TEXT_DIRECTION_FIRST_STRONG_RTL: 24977 // Resolved direction is the same as text direction 24978 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 24979 break; 24980 default: 24981 // Default resolved direction is "first strong" heuristic 24982 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 24983 } 24984 } else { 24985 // Default resolved direction is "first strong" heuristic 24986 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 24987 } 24988 24989 // Set to resolved 24990 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 24991 return true; 24992 } 24993 24994 /** 24995 * Check if text direction resolution can be done. 24996 * 24997 * @return true if text direction resolution can be done otherwise return false. 24998 */ 24999 public boolean canResolveTextDirection() { 25000 switch (getRawTextDirection()) { 25001 case TEXT_DIRECTION_INHERIT: 25002 if (mParent != null) { 25003 try { 25004 return mParent.canResolveTextDirection(); 25005 } catch (AbstractMethodError e) { 25006 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 25007 " does not fully implement ViewParent", e); 25008 } 25009 } 25010 return false; 25011 25012 default: 25013 return true; 25014 } 25015 } 25016 25017 /** 25018 * Reset resolved text direction. Text direction will be resolved during a call to 25019 * {@link #onMeasure(int, int)}. 25020 * 25021 * @hide 25022 */ 25023 public void resetResolvedTextDirection() { 25024 // Reset any previous text direction resolution 25025 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 25026 // Set to default value 25027 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 25028 } 25029 25030 /** 25031 * @return true if text direction is inherited. 25032 * 25033 * @hide 25034 */ 25035 public boolean isTextDirectionInherited() { 25036 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 25037 } 25038 25039 /** 25040 * @return true if text direction is resolved. 25041 */ 25042 public boolean isTextDirectionResolved() { 25043 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 25044 } 25045 25046 /** 25047 * Return the value specifying the text alignment or policy that was set with 25048 * {@link #setTextAlignment(int)}. 25049 * 25050 * @return the defined text alignment. It can be one of: 25051 * 25052 * {@link #TEXT_ALIGNMENT_INHERIT}, 25053 * {@link #TEXT_ALIGNMENT_GRAVITY}, 25054 * {@link #TEXT_ALIGNMENT_CENTER}, 25055 * {@link #TEXT_ALIGNMENT_TEXT_START}, 25056 * {@link #TEXT_ALIGNMENT_TEXT_END}, 25057 * {@link #TEXT_ALIGNMENT_VIEW_START}, 25058 * {@link #TEXT_ALIGNMENT_VIEW_END} 25059 * 25060 * @attr ref android.R.styleable#View_textAlignment 25061 * 25062 * @hide 25063 */ 25064 @ViewDebug.ExportedProperty(category = "text", mapping = { 25065 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 25066 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 25067 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 25068 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 25069 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 25070 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 25071 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 25072 }) 25073 @TextAlignment 25074 public int getRawTextAlignment() { 25075 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 25076 } 25077 25078 /** 25079 * Set the text alignment. 25080 * 25081 * @param textAlignment The text alignment to set. Should be one of 25082 * 25083 * {@link #TEXT_ALIGNMENT_INHERIT}, 25084 * {@link #TEXT_ALIGNMENT_GRAVITY}, 25085 * {@link #TEXT_ALIGNMENT_CENTER}, 25086 * {@link #TEXT_ALIGNMENT_TEXT_START}, 25087 * {@link #TEXT_ALIGNMENT_TEXT_END}, 25088 * {@link #TEXT_ALIGNMENT_VIEW_START}, 25089 * {@link #TEXT_ALIGNMENT_VIEW_END} 25090 * 25091 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 25092 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 25093 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 25094 * 25095 * @attr ref android.R.styleable#View_textAlignment 25096 */ 25097 public void setTextAlignment(@TextAlignment int textAlignment) { 25098 if (textAlignment != getRawTextAlignment()) { 25099 // Reset the current and resolved text alignment 25100 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 25101 resetResolvedTextAlignment(); 25102 // Set the new text alignment 25103 mPrivateFlags2 |= 25104 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 25105 // Do resolution 25106 resolveTextAlignment(); 25107 // Notify change 25108 onRtlPropertiesChanged(getLayoutDirection()); 25109 // Refresh 25110 requestLayout(); 25111 invalidate(true); 25112 } 25113 } 25114 25115 /** 25116 * Return the resolved text alignment. 25117 * 25118 * @return the resolved text alignment. Returns one of: 25119 * 25120 * {@link #TEXT_ALIGNMENT_GRAVITY}, 25121 * {@link #TEXT_ALIGNMENT_CENTER}, 25122 * {@link #TEXT_ALIGNMENT_TEXT_START}, 25123 * {@link #TEXT_ALIGNMENT_TEXT_END}, 25124 * {@link #TEXT_ALIGNMENT_VIEW_START}, 25125 * {@link #TEXT_ALIGNMENT_VIEW_END} 25126 * 25127 * @attr ref android.R.styleable#View_textAlignment 25128 */ 25129 @ViewDebug.ExportedProperty(category = "text", mapping = { 25130 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 25131 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 25132 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 25133 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 25134 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 25135 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 25136 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 25137 }) 25138 @TextAlignment 25139 public int getTextAlignment() { 25140 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 25141 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 25142 } 25143 25144 /** 25145 * Resolve the text alignment. 25146 * 25147 * @return true if resolution has been done, false otherwise. 25148 * 25149 * @hide 25150 */ 25151 public boolean resolveTextAlignment() { 25152 // Reset any previous text alignment resolution 25153 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 25154 25155 if (hasRtlSupport()) { 25156 // Set resolved text alignment flag depending on text alignment flag 25157 final int textAlignment = getRawTextAlignment(); 25158 switch (textAlignment) { 25159 case TEXT_ALIGNMENT_INHERIT: 25160 // Check if we can resolve the text alignment 25161 if (!canResolveTextAlignment()) { 25162 // We cannot do the resolution if there is no parent so use the default 25163 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 25164 // Resolution will need to happen again later 25165 return false; 25166 } 25167 25168 // Parent has not yet resolved, so we still return the default 25169 try { 25170 if (!mParent.isTextAlignmentResolved()) { 25171 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 25172 // Resolution will need to happen again later 25173 return false; 25174 } 25175 } catch (AbstractMethodError e) { 25176 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 25177 " does not fully implement ViewParent", e); 25178 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 25179 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 25180 return true; 25181 } 25182 25183 int parentResolvedTextAlignment; 25184 try { 25185 parentResolvedTextAlignment = mParent.getTextAlignment(); 25186 } catch (AbstractMethodError e) { 25187 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 25188 " does not fully implement ViewParent", e); 25189 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 25190 } 25191 switch (parentResolvedTextAlignment) { 25192 case TEXT_ALIGNMENT_GRAVITY: 25193 case TEXT_ALIGNMENT_TEXT_START: 25194 case TEXT_ALIGNMENT_TEXT_END: 25195 case TEXT_ALIGNMENT_CENTER: 25196 case TEXT_ALIGNMENT_VIEW_START: 25197 case TEXT_ALIGNMENT_VIEW_END: 25198 // Resolved text alignment is the same as the parent resolved 25199 // text alignment 25200 mPrivateFlags2 |= 25201 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 25202 break; 25203 default: 25204 // Use default resolved text alignment 25205 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 25206 } 25207 break; 25208 case TEXT_ALIGNMENT_GRAVITY: 25209 case TEXT_ALIGNMENT_TEXT_START: 25210 case TEXT_ALIGNMENT_TEXT_END: 25211 case TEXT_ALIGNMENT_CENTER: 25212 case TEXT_ALIGNMENT_VIEW_START: 25213 case TEXT_ALIGNMENT_VIEW_END: 25214 // Resolved text alignment is the same as text alignment 25215 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 25216 break; 25217 default: 25218 // Use default resolved text alignment 25219 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 25220 } 25221 } else { 25222 // Use default resolved text alignment 25223 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 25224 } 25225 25226 // Set the resolved 25227 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 25228 return true; 25229 } 25230 25231 /** 25232 * Check if text alignment resolution can be done. 25233 * 25234 * @return true if text alignment resolution can be done otherwise return false. 25235 */ 25236 public boolean canResolveTextAlignment() { 25237 switch (getRawTextAlignment()) { 25238 case TEXT_DIRECTION_INHERIT: 25239 if (mParent != null) { 25240 try { 25241 return mParent.canResolveTextAlignment(); 25242 } catch (AbstractMethodError e) { 25243 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 25244 " does not fully implement ViewParent", e); 25245 } 25246 } 25247 return false; 25248 25249 default: 25250 return true; 25251 } 25252 } 25253 25254 /** 25255 * Reset resolved text alignment. Text alignment will be resolved during a call to 25256 * {@link #onMeasure(int, int)}. 25257 * 25258 * @hide 25259 */ 25260 public void resetResolvedTextAlignment() { 25261 // Reset any previous text alignment resolution 25262 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 25263 // Set to default 25264 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 25265 } 25266 25267 /** 25268 * @return true if text alignment is inherited. 25269 * 25270 * @hide 25271 */ 25272 public boolean isTextAlignmentInherited() { 25273 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 25274 } 25275 25276 /** 25277 * @return true if text alignment is resolved. 25278 */ 25279 public boolean isTextAlignmentResolved() { 25280 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 25281 } 25282 25283 /** 25284 * Generate a value suitable for use in {@link #setId(int)}. 25285 * This value will not collide with ID values generated at build time by aapt for R.id. 25286 * 25287 * @return a generated ID value 25288 */ 25289 public static int generateViewId() { 25290 for (;;) { 25291 final int result = sNextGeneratedId.get(); 25292 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 25293 int newValue = result + 1; 25294 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 25295 if (sNextGeneratedId.compareAndSet(result, newValue)) { 25296 return result; 25297 } 25298 } 25299 } 25300 25301 private static boolean isViewIdGenerated(int id) { 25302 return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0; 25303 } 25304 25305 /** 25306 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 25307 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 25308 * a normal View or a ViewGroup with 25309 * {@link android.view.ViewGroup#isTransitionGroup()} true. 25310 * @hide 25311 */ 25312 public void captureTransitioningViews(List<View> transitioningViews) { 25313 if (getVisibility() == View.VISIBLE) { 25314 transitioningViews.add(this); 25315 } 25316 } 25317 25318 /** 25319 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 25320 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 25321 * @hide 25322 */ 25323 public void findNamedViews(Map<String, View> namedElements) { 25324 if (getVisibility() == VISIBLE || mGhostView != null) { 25325 String transitionName = getTransitionName(); 25326 if (transitionName != null) { 25327 namedElements.put(transitionName, this); 25328 } 25329 } 25330 } 25331 25332 /** 25333 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 25334 * The default implementation does not care the location or event types, but some subclasses 25335 * may use it (such as WebViews). 25336 * @param event The MotionEvent from a mouse 25337 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}. 25338 * This will be between 0 and {@link MotionEvent#getPointerCount()}. 25339 * @see PointerIcon 25340 */ 25341 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 25342 final float x = event.getX(pointerIndex); 25343 final float y = event.getY(pointerIndex); 25344 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 25345 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW); 25346 } 25347 return mPointerIcon; 25348 } 25349 25350 /** 25351 * Set the pointer icon for the current view. 25352 * Passing {@code null} will restore the pointer icon to its default value. 25353 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 25354 */ 25355 public void setPointerIcon(PointerIcon pointerIcon) { 25356 mPointerIcon = pointerIcon; 25357 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 25358 return; 25359 } 25360 try { 25361 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 25362 } catch (RemoteException e) { 25363 } 25364 } 25365 25366 /** 25367 * Gets the pointer icon for the current view. 25368 */ 25369 public PointerIcon getPointerIcon() { 25370 return mPointerIcon; 25371 } 25372 25373 /** 25374 * Checks pointer capture status. 25375 * 25376 * @return true if the view has pointer capture. 25377 * @see #requestPointerCapture() 25378 * @see #hasPointerCapture() 25379 */ 25380 public boolean hasPointerCapture() { 25381 final ViewRootImpl viewRootImpl = getViewRootImpl(); 25382 if (viewRootImpl == null) { 25383 return false; 25384 } 25385 return viewRootImpl.hasPointerCapture(); 25386 } 25387 25388 /** 25389 * Requests pointer capture mode. 25390 * <p> 25391 * When the window has pointer capture, the mouse pointer icon will disappear and will not 25392 * change its position. Further mouse will be dispatched with the source 25393 * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available 25394 * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events 25395 * (touchscreens, or stylus) will not be affected. 25396 * <p> 25397 * If the window already has pointer capture, this call does nothing. 25398 * <p> 25399 * The capture may be released through {@link #releasePointerCapture()}, or will be lost 25400 * automatically when the window loses focus. 25401 * 25402 * @see #releasePointerCapture() 25403 * @see #hasPointerCapture() 25404 */ 25405 public void requestPointerCapture() { 25406 final ViewRootImpl viewRootImpl = getViewRootImpl(); 25407 if (viewRootImpl != null) { 25408 viewRootImpl.requestPointerCapture(true); 25409 } 25410 } 25411 25412 25413 /** 25414 * Releases the pointer capture. 25415 * <p> 25416 * If the window does not have pointer capture, this call will do nothing. 25417 * @see #requestPointerCapture() 25418 * @see #hasPointerCapture() 25419 */ 25420 public void releasePointerCapture() { 25421 final ViewRootImpl viewRootImpl = getViewRootImpl(); 25422 if (viewRootImpl != null) { 25423 viewRootImpl.requestPointerCapture(false); 25424 } 25425 } 25426 25427 /** 25428 * Called when the window has just acquired or lost pointer capture. 25429 * 25430 * @param hasCapture True if the view now has pointerCapture, false otherwise. 25431 */ 25432 @CallSuper 25433 public void onPointerCaptureChange(boolean hasCapture) { 25434 } 25435 25436 /** 25437 * @see #onPointerCaptureChange 25438 */ 25439 public void dispatchPointerCaptureChanged(boolean hasCapture) { 25440 onPointerCaptureChange(hasCapture); 25441 } 25442 25443 /** 25444 * Implement this method to handle captured pointer events 25445 * 25446 * @param event The captured pointer event. 25447 * @return True if the event was handled, false otherwise. 25448 * @see #requestPointerCapture() 25449 */ 25450 public boolean onCapturedPointerEvent(MotionEvent event) { 25451 return false; 25452 } 25453 25454 /** 25455 * Interface definition for a callback to be invoked when a captured pointer event 25456 * is being dispatched this view. The callback will be invoked before the event is 25457 * given to the view. 25458 */ 25459 public interface OnCapturedPointerListener { 25460 /** 25461 * Called when a captured pointer event is dispatched to a view. 25462 * @param view The view this event has been dispatched to. 25463 * @param event The captured event. 25464 * @return True if the listener has consumed the event, false otherwise. 25465 */ 25466 boolean onCapturedPointer(View view, MotionEvent event); 25467 } 25468 25469 /** 25470 * Set a listener to receive callbacks when the pointer capture state of a view changes. 25471 * @param l The {@link OnCapturedPointerListener} to receive callbacks. 25472 */ 25473 public void setOnCapturedPointerListener(OnCapturedPointerListener l) { 25474 getListenerInfo().mOnCapturedPointerListener = l; 25475 } 25476 25477 // Properties 25478 // 25479 /** 25480 * A Property wrapper around the <code>alpha</code> functionality handled by the 25481 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 25482 */ 25483 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 25484 @Override 25485 public void setValue(View object, float value) { 25486 object.setAlpha(value); 25487 } 25488 25489 @Override 25490 public Float get(View object) { 25491 return object.getAlpha(); 25492 } 25493 }; 25494 25495 /** 25496 * A Property wrapper around the <code>translationX</code> functionality handled by the 25497 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 25498 */ 25499 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 25500 @Override 25501 public void setValue(View object, float value) { 25502 object.setTranslationX(value); 25503 } 25504 25505 @Override 25506 public Float get(View object) { 25507 return object.getTranslationX(); 25508 } 25509 }; 25510 25511 /** 25512 * A Property wrapper around the <code>translationY</code> functionality handled by the 25513 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 25514 */ 25515 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 25516 @Override 25517 public void setValue(View object, float value) { 25518 object.setTranslationY(value); 25519 } 25520 25521 @Override 25522 public Float get(View object) { 25523 return object.getTranslationY(); 25524 } 25525 }; 25526 25527 /** 25528 * A Property wrapper around the <code>translationZ</code> functionality handled by the 25529 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 25530 */ 25531 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 25532 @Override 25533 public void setValue(View object, float value) { 25534 object.setTranslationZ(value); 25535 } 25536 25537 @Override 25538 public Float get(View object) { 25539 return object.getTranslationZ(); 25540 } 25541 }; 25542 25543 /** 25544 * A Property wrapper around the <code>x</code> functionality handled by the 25545 * {@link View#setX(float)} and {@link View#getX()} methods. 25546 */ 25547 public static final Property<View, Float> X = new FloatProperty<View>("x") { 25548 @Override 25549 public void setValue(View object, float value) { 25550 object.setX(value); 25551 } 25552 25553 @Override 25554 public Float get(View object) { 25555 return object.getX(); 25556 } 25557 }; 25558 25559 /** 25560 * A Property wrapper around the <code>y</code> functionality handled by the 25561 * {@link View#setY(float)} and {@link View#getY()} methods. 25562 */ 25563 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 25564 @Override 25565 public void setValue(View object, float value) { 25566 object.setY(value); 25567 } 25568 25569 @Override 25570 public Float get(View object) { 25571 return object.getY(); 25572 } 25573 }; 25574 25575 /** 25576 * A Property wrapper around the <code>z</code> functionality handled by the 25577 * {@link View#setZ(float)} and {@link View#getZ()} methods. 25578 */ 25579 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 25580 @Override 25581 public void setValue(View object, float value) { 25582 object.setZ(value); 25583 } 25584 25585 @Override 25586 public Float get(View object) { 25587 return object.getZ(); 25588 } 25589 }; 25590 25591 /** 25592 * A Property wrapper around the <code>rotation</code> functionality handled by the 25593 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 25594 */ 25595 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 25596 @Override 25597 public void setValue(View object, float value) { 25598 object.setRotation(value); 25599 } 25600 25601 @Override 25602 public Float get(View object) { 25603 return object.getRotation(); 25604 } 25605 }; 25606 25607 /** 25608 * A Property wrapper around the <code>rotationX</code> functionality handled by the 25609 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 25610 */ 25611 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 25612 @Override 25613 public void setValue(View object, float value) { 25614 object.setRotationX(value); 25615 } 25616 25617 @Override 25618 public Float get(View object) { 25619 return object.getRotationX(); 25620 } 25621 }; 25622 25623 /** 25624 * A Property wrapper around the <code>rotationY</code> functionality handled by the 25625 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 25626 */ 25627 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 25628 @Override 25629 public void setValue(View object, float value) { 25630 object.setRotationY(value); 25631 } 25632 25633 @Override 25634 public Float get(View object) { 25635 return object.getRotationY(); 25636 } 25637 }; 25638 25639 /** 25640 * A Property wrapper around the <code>scaleX</code> functionality handled by the 25641 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 25642 */ 25643 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 25644 @Override 25645 public void setValue(View object, float value) { 25646 object.setScaleX(value); 25647 } 25648 25649 @Override 25650 public Float get(View object) { 25651 return object.getScaleX(); 25652 } 25653 }; 25654 25655 /** 25656 * A Property wrapper around the <code>scaleY</code> functionality handled by the 25657 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 25658 */ 25659 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 25660 @Override 25661 public void setValue(View object, float value) { 25662 object.setScaleY(value); 25663 } 25664 25665 @Override 25666 public Float get(View object) { 25667 return object.getScaleY(); 25668 } 25669 }; 25670 25671 /** 25672 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 25673 * Each MeasureSpec represents a requirement for either the width or the height. 25674 * A MeasureSpec is comprised of a size and a mode. There are three possible 25675 * modes: 25676 * <dl> 25677 * <dt>UNSPECIFIED</dt> 25678 * <dd> 25679 * The parent has not imposed any constraint on the child. It can be whatever size 25680 * it wants. 25681 * </dd> 25682 * 25683 * <dt>EXACTLY</dt> 25684 * <dd> 25685 * The parent has determined an exact size for the child. The child is going to be 25686 * given those bounds regardless of how big it wants to be. 25687 * </dd> 25688 * 25689 * <dt>AT_MOST</dt> 25690 * <dd> 25691 * The child can be as large as it wants up to the specified size. 25692 * </dd> 25693 * </dl> 25694 * 25695 * MeasureSpecs are implemented as ints to reduce object allocation. This class 25696 * is provided to pack and unpack the <size, mode> tuple into the int. 25697 */ 25698 public static class MeasureSpec { 25699 private static final int MODE_SHIFT = 30; 25700 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 25701 25702 /** @hide */ 25703 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 25704 @Retention(RetentionPolicy.SOURCE) 25705 public @interface MeasureSpecMode {} 25706 25707 /** 25708 * Measure specification mode: The parent has not imposed any constraint 25709 * on the child. It can be whatever size it wants. 25710 */ 25711 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 25712 25713 /** 25714 * Measure specification mode: The parent has determined an exact size 25715 * for the child. The child is going to be given those bounds regardless 25716 * of how big it wants to be. 25717 */ 25718 public static final int EXACTLY = 1 << MODE_SHIFT; 25719 25720 /** 25721 * Measure specification mode: The child can be as large as it wants up 25722 * to the specified size. 25723 */ 25724 public static final int AT_MOST = 2 << MODE_SHIFT; 25725 25726 /** 25727 * Creates a measure specification based on the supplied size and mode. 25728 * 25729 * The mode must always be one of the following: 25730 * <ul> 25731 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 25732 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 25733 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 25734 * </ul> 25735 * 25736 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 25737 * implementation was such that the order of arguments did not matter 25738 * and overflow in either value could impact the resulting MeasureSpec. 25739 * {@link android.widget.RelativeLayout} was affected by this bug. 25740 * Apps targeting API levels greater than 17 will get the fixed, more strict 25741 * behavior.</p> 25742 * 25743 * @param size the size of the measure specification 25744 * @param mode the mode of the measure specification 25745 * @return the measure specification based on size and mode 25746 */ 25747 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 25748 @MeasureSpecMode int mode) { 25749 if (sUseBrokenMakeMeasureSpec) { 25750 return size + mode; 25751 } else { 25752 return (size & ~MODE_MASK) | (mode & MODE_MASK); 25753 } 25754 } 25755 25756 /** 25757 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 25758 * will automatically get a size of 0. Older apps expect this. 25759 * 25760 * @hide internal use only for compatibility with system widgets and older apps 25761 */ 25762 public static int makeSafeMeasureSpec(int size, int mode) { 25763 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 25764 return 0; 25765 } 25766 return makeMeasureSpec(size, mode); 25767 } 25768 25769 /** 25770 * Extracts the mode from the supplied measure specification. 25771 * 25772 * @param measureSpec the measure specification to extract the mode from 25773 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 25774 * {@link android.view.View.MeasureSpec#AT_MOST} or 25775 * {@link android.view.View.MeasureSpec#EXACTLY} 25776 */ 25777 @MeasureSpecMode 25778 public static int getMode(int measureSpec) { 25779 //noinspection ResourceType 25780 return (measureSpec & MODE_MASK); 25781 } 25782 25783 /** 25784 * Extracts the size from the supplied measure specification. 25785 * 25786 * @param measureSpec the measure specification to extract the size from 25787 * @return the size in pixels defined in the supplied measure specification 25788 */ 25789 public static int getSize(int measureSpec) { 25790 return (measureSpec & ~MODE_MASK); 25791 } 25792 25793 static int adjust(int measureSpec, int delta) { 25794 final int mode = getMode(measureSpec); 25795 int size = getSize(measureSpec); 25796 if (mode == UNSPECIFIED) { 25797 // No need to adjust size for UNSPECIFIED mode. 25798 return makeMeasureSpec(size, UNSPECIFIED); 25799 } 25800 size += delta; 25801 if (size < 0) { 25802 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 25803 ") spec: " + toString(measureSpec) + " delta: " + delta); 25804 size = 0; 25805 } 25806 return makeMeasureSpec(size, mode); 25807 } 25808 25809 /** 25810 * Returns a String representation of the specified measure 25811 * specification. 25812 * 25813 * @param measureSpec the measure specification to convert to a String 25814 * @return a String with the following format: "MeasureSpec: MODE SIZE" 25815 */ 25816 public static String toString(int measureSpec) { 25817 int mode = getMode(measureSpec); 25818 int size = getSize(measureSpec); 25819 25820 StringBuilder sb = new StringBuilder("MeasureSpec: "); 25821 25822 if (mode == UNSPECIFIED) 25823 sb.append("UNSPECIFIED "); 25824 else if (mode == EXACTLY) 25825 sb.append("EXACTLY "); 25826 else if (mode == AT_MOST) 25827 sb.append("AT_MOST "); 25828 else 25829 sb.append(mode).append(" "); 25830 25831 sb.append(size); 25832 return sb.toString(); 25833 } 25834 } 25835 25836 private final class CheckForLongPress implements Runnable { 25837 private int mOriginalWindowAttachCount; 25838 private float mX; 25839 private float mY; 25840 private boolean mOriginalPressedState; 25841 25842 @Override 25843 public void run() { 25844 if ((mOriginalPressedState == isPressed()) && (mParent != null) 25845 && mOriginalWindowAttachCount == mWindowAttachCount) { 25846 if (performLongClick(mX, mY)) { 25847 mHasPerformedLongPress = true; 25848 } 25849 } 25850 } 25851 25852 public void setAnchor(float x, float y) { 25853 mX = x; 25854 mY = y; 25855 } 25856 25857 public void rememberWindowAttachCount() { 25858 mOriginalWindowAttachCount = mWindowAttachCount; 25859 } 25860 25861 public void rememberPressedState() { 25862 mOriginalPressedState = isPressed(); 25863 } 25864 } 25865 25866 private final class CheckForTap implements Runnable { 25867 public float x; 25868 public float y; 25869 25870 @Override 25871 public void run() { 25872 mPrivateFlags &= ~PFLAG_PREPRESSED; 25873 setPressed(true, x, y); 25874 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 25875 } 25876 } 25877 25878 private final class PerformClick implements Runnable { 25879 @Override 25880 public void run() { 25881 performClickInternal(); 25882 } 25883 } 25884 25885 /** 25886 * This method returns a ViewPropertyAnimator object, which can be used to animate 25887 * specific properties on this View. 25888 * 25889 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 25890 */ 25891 public ViewPropertyAnimator animate() { 25892 if (mAnimator == null) { 25893 mAnimator = new ViewPropertyAnimator(this); 25894 } 25895 return mAnimator; 25896 } 25897 25898 /** 25899 * Sets the name of the View to be used to identify Views in Transitions. 25900 * Names should be unique in the View hierarchy. 25901 * 25902 * @param transitionName The name of the View to uniquely identify it for Transitions. 25903 */ 25904 public final void setTransitionName(String transitionName) { 25905 mTransitionName = transitionName; 25906 } 25907 25908 /** 25909 * Returns the name of the View to be used to identify Views in Transitions. 25910 * Names should be unique in the View hierarchy. 25911 * 25912 * <p>This returns null if the View has not been given a name.</p> 25913 * 25914 * @return The name used of the View to be used to identify Views in Transitions or null 25915 * if no name has been given. 25916 */ 25917 @ViewDebug.ExportedProperty 25918 public String getTransitionName() { 25919 return mTransitionName; 25920 } 25921 25922 /** 25923 * @hide 25924 */ 25925 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 25926 // Do nothing. 25927 } 25928 25929 /** 25930 * Interface definition for a callback to be invoked when a hardware key event is 25931 * dispatched to this view. The callback will be invoked before the key event is 25932 * given to the view. This is only useful for hardware keyboards; a software input 25933 * method has no obligation to trigger this listener. 25934 */ 25935 public interface OnKeyListener { 25936 /** 25937 * Called when a hardware key is dispatched to a view. This allows listeners to 25938 * get a chance to respond before the target view. 25939 * <p>Key presses in software keyboards will generally NOT trigger this method, 25940 * although some may elect to do so in some situations. Do not assume a 25941 * software input method has to be key-based; even if it is, it may use key presses 25942 * in a different way than you expect, so there is no way to reliably catch soft 25943 * input key presses. 25944 * 25945 * @param v The view the key has been dispatched to. 25946 * @param keyCode The code for the physical key that was pressed 25947 * @param event The KeyEvent object containing full information about 25948 * the event. 25949 * @return True if the listener has consumed the event, false otherwise. 25950 */ 25951 boolean onKey(View v, int keyCode, KeyEvent event); 25952 } 25953 25954 /** 25955 * Interface definition for a callback to be invoked when a hardware key event hasn't 25956 * been handled by the view hierarchy. 25957 */ 25958 public interface OnUnhandledKeyEventListener { 25959 /** 25960 * Called when a hardware key is dispatched to a view after being unhandled during normal 25961 * {@link KeyEvent} dispatch. 25962 * 25963 * @param v The view the key has been dispatched to. 25964 * @param event The KeyEvent object containing information about the event. 25965 * @return {@code true} if the listener has consumed the event, {@code false} otherwise. 25966 */ 25967 boolean onUnhandledKeyEvent(View v, KeyEvent event); 25968 } 25969 25970 /** 25971 * Interface definition for a callback to be invoked when a touch event is 25972 * dispatched to this view. The callback will be invoked before the touch 25973 * event is given to the view. 25974 */ 25975 public interface OnTouchListener { 25976 /** 25977 * Called when a touch event is dispatched to a view. This allows listeners to 25978 * get a chance to respond before the target view. 25979 * 25980 * @param v The view the touch event has been dispatched to. 25981 * @param event The MotionEvent object containing full information about 25982 * the event. 25983 * @return True if the listener has consumed the event, false otherwise. 25984 */ 25985 boolean onTouch(View v, MotionEvent event); 25986 } 25987 25988 /** 25989 * Interface definition for a callback to be invoked when a hover event is 25990 * dispatched to this view. The callback will be invoked before the hover 25991 * event is given to the view. 25992 */ 25993 public interface OnHoverListener { 25994 /** 25995 * Called when a hover event is dispatched to a view. This allows listeners to 25996 * get a chance to respond before the target view. 25997 * 25998 * @param v The view the hover event has been dispatched to. 25999 * @param event The MotionEvent object containing full information about 26000 * the event. 26001 * @return True if the listener has consumed the event, false otherwise. 26002 */ 26003 boolean onHover(View v, MotionEvent event); 26004 } 26005 26006 /** 26007 * Interface definition for a callback to be invoked when a generic motion event is 26008 * dispatched to this view. The callback will be invoked before the generic motion 26009 * event is given to the view. 26010 */ 26011 public interface OnGenericMotionListener { 26012 /** 26013 * Called when a generic motion event is dispatched to a view. This allows listeners to 26014 * get a chance to respond before the target view. 26015 * 26016 * @param v The view the generic motion event has been dispatched to. 26017 * @param event The MotionEvent object containing full information about 26018 * the event. 26019 * @return True if the listener has consumed the event, false otherwise. 26020 */ 26021 boolean onGenericMotion(View v, MotionEvent event); 26022 } 26023 26024 /** 26025 * Interface definition for a callback to be invoked when a view has been clicked and held. 26026 */ 26027 public interface OnLongClickListener { 26028 /** 26029 * Called when a view has been clicked and held. 26030 * 26031 * @param v The view that was clicked and held. 26032 * 26033 * @return true if the callback consumed the long click, false otherwise. 26034 */ 26035 boolean onLongClick(View v); 26036 } 26037 26038 /** 26039 * Interface definition for a callback to be invoked when a drag is being dispatched 26040 * to this view. The callback will be invoked before the hosting view's own 26041 * onDrag(event) method. If the listener wants to fall back to the hosting view's 26042 * onDrag(event) behavior, it should return 'false' from this callback. 26043 * 26044 * <div class="special reference"> 26045 * <h3>Developer Guides</h3> 26046 * <p>For a guide to implementing drag and drop features, read the 26047 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 26048 * </div> 26049 */ 26050 public interface OnDragListener { 26051 /** 26052 * Called when a drag event is dispatched to a view. This allows listeners 26053 * to get a chance to override base View behavior. 26054 * 26055 * @param v The View that received the drag event. 26056 * @param event The {@link android.view.DragEvent} object for the drag event. 26057 * @return {@code true} if the drag event was handled successfully, or {@code false} 26058 * if the drag event was not handled. Note that {@code false} will trigger the View 26059 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 26060 */ 26061 boolean onDrag(View v, DragEvent event); 26062 } 26063 26064 /** 26065 * Interface definition for a callback to be invoked when the focus state of 26066 * a view changed. 26067 */ 26068 public interface OnFocusChangeListener { 26069 /** 26070 * Called when the focus state of a view has changed. 26071 * 26072 * @param v The view whose state has changed. 26073 * @param hasFocus The new focus state of v. 26074 */ 26075 void onFocusChange(View v, boolean hasFocus); 26076 } 26077 26078 /** 26079 * Interface definition for a callback to be invoked when a view is clicked. 26080 */ 26081 public interface OnClickListener { 26082 /** 26083 * Called when a view has been clicked. 26084 * 26085 * @param v The view that was clicked. 26086 */ 26087 void onClick(View v); 26088 } 26089 26090 /** 26091 * Interface definition for a callback to be invoked when a view is context clicked. 26092 */ 26093 public interface OnContextClickListener { 26094 /** 26095 * Called when a view is context clicked. 26096 * 26097 * @param v The view that has been context clicked. 26098 * @return true if the callback consumed the context click, false otherwise. 26099 */ 26100 boolean onContextClick(View v); 26101 } 26102 26103 /** 26104 * Interface definition for a callback to be invoked when the context menu 26105 * for this view is being built. 26106 */ 26107 public interface OnCreateContextMenuListener { 26108 /** 26109 * Called when the context menu for this view is being built. It is not 26110 * safe to hold onto the menu after this method returns. 26111 * 26112 * @param menu The context menu that is being built 26113 * @param v The view for which the context menu is being built 26114 * @param menuInfo Extra information about the item for which the 26115 * context menu should be shown. This information will vary 26116 * depending on the class of v. 26117 */ 26118 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 26119 } 26120 26121 /** 26122 * Interface definition for a callback to be invoked when the status bar changes 26123 * visibility. This reports <strong>global</strong> changes to the system UI 26124 * state, not what the application is requesting. 26125 * 26126 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 26127 */ 26128 public interface OnSystemUiVisibilityChangeListener { 26129 /** 26130 * Called when the status bar changes visibility because of a call to 26131 * {@link View#setSystemUiVisibility(int)}. 26132 * 26133 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 26134 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 26135 * This tells you the <strong>global</strong> state of these UI visibility 26136 * flags, not what your app is currently applying. 26137 */ 26138 public void onSystemUiVisibilityChange(int visibility); 26139 } 26140 26141 /** 26142 * Interface definition for a callback to be invoked when this view is attached 26143 * or detached from its window. 26144 */ 26145 public interface OnAttachStateChangeListener { 26146 /** 26147 * Called when the view is attached to a window. 26148 * @param v The view that was attached 26149 */ 26150 public void onViewAttachedToWindow(View v); 26151 /** 26152 * Called when the view is detached from a window. 26153 * @param v The view that was detached 26154 */ 26155 public void onViewDetachedFromWindow(View v); 26156 } 26157 26158 /** 26159 * Listener for applying window insets on a view in a custom way. 26160 * 26161 * <p>Apps may choose to implement this interface if they want to apply custom policy 26162 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 26163 * is set, its 26164 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 26165 * method will be called instead of the View's own 26166 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 26167 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 26168 * the View's normal behavior as part of its own.</p> 26169 */ 26170 public interface OnApplyWindowInsetsListener { 26171 /** 26172 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 26173 * on a View, this listener method will be called instead of the view's own 26174 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 26175 * 26176 * @param v The view applying window insets 26177 * @param insets The insets to apply 26178 * @return The insets supplied, minus any insets that were consumed 26179 */ 26180 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 26181 } 26182 26183 private final class UnsetPressedState implements Runnable { 26184 @Override 26185 public void run() { 26186 setPressed(false); 26187 } 26188 } 26189 26190 /** 26191 * When a view becomes invisible checks if autofill considers the view invisible too. This 26192 * happens after the regular removal operation to make sure the operation is finished by the 26193 * time this is called. 26194 */ 26195 private static class VisibilityChangeForAutofillHandler extends Handler { 26196 private final AutofillManager mAfm; 26197 private final View mView; 26198 26199 private VisibilityChangeForAutofillHandler(@NonNull AutofillManager afm, 26200 @NonNull View view) { 26201 mAfm = afm; 26202 mView = view; 26203 } 26204 26205 @Override 26206 public void handleMessage(Message msg) { 26207 mAfm.notifyViewVisibilityChanged(mView, mView.isShown()); 26208 } 26209 } 26210 26211 /** 26212 * Base class for derived classes that want to save and restore their own 26213 * state in {@link android.view.View#onSaveInstanceState()}. 26214 */ 26215 public static class BaseSavedState extends AbsSavedState { 26216 static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1; 26217 static final int IS_AUTOFILLED = 0b10; 26218 static final int AUTOFILL_ID = 0b100; 26219 26220 // Flags that describe what data in this state is valid 26221 int mSavedData; 26222 String mStartActivityRequestWhoSaved; 26223 boolean mIsAutofilled; 26224 int mAutofillViewId; 26225 26226 /** 26227 * Constructor used when reading from a parcel. Reads the state of the superclass. 26228 * 26229 * @param source parcel to read from 26230 */ 26231 public BaseSavedState(Parcel source) { 26232 this(source, null); 26233 } 26234 26235 /** 26236 * Constructor used when reading from a parcel using a given class loader. 26237 * Reads the state of the superclass. 26238 * 26239 * @param source parcel to read from 26240 * @param loader ClassLoader to use for reading 26241 */ 26242 public BaseSavedState(Parcel source, ClassLoader loader) { 26243 super(source, loader); 26244 mSavedData = source.readInt(); 26245 mStartActivityRequestWhoSaved = source.readString(); 26246 mIsAutofilled = source.readBoolean(); 26247 mAutofillViewId = source.readInt(); 26248 } 26249 26250 /** 26251 * Constructor called by derived classes when creating their SavedState objects 26252 * 26253 * @param superState The state of the superclass of this view 26254 */ 26255 public BaseSavedState(Parcelable superState) { 26256 super(superState); 26257 } 26258 26259 @Override 26260 public void writeToParcel(Parcel out, int flags) { 26261 super.writeToParcel(out, flags); 26262 26263 out.writeInt(mSavedData); 26264 out.writeString(mStartActivityRequestWhoSaved); 26265 out.writeBoolean(mIsAutofilled); 26266 out.writeInt(mAutofillViewId); 26267 } 26268 26269 public static final Parcelable.Creator<BaseSavedState> CREATOR 26270 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 26271 @Override 26272 public BaseSavedState createFromParcel(Parcel in) { 26273 return new BaseSavedState(in); 26274 } 26275 26276 @Override 26277 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 26278 return new BaseSavedState(in, loader); 26279 } 26280 26281 @Override 26282 public BaseSavedState[] newArray(int size) { 26283 return new BaseSavedState[size]; 26284 } 26285 }; 26286 } 26287 26288 /** 26289 * A set of information given to a view when it is attached to its parent 26290 * window. 26291 */ 26292 final static class AttachInfo { 26293 interface Callbacks { 26294 void playSoundEffect(int effectId); 26295 boolean performHapticFeedback(int effectId, boolean always); 26296 } 26297 26298 /** 26299 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 26300 * to a Handler. This class contains the target (View) to invalidate and 26301 * the coordinates of the dirty rectangle. 26302 * 26303 * For performance purposes, this class also implements a pool of up to 26304 * POOL_LIMIT objects that get reused. This reduces memory allocations 26305 * whenever possible. 26306 */ 26307 static class InvalidateInfo { 26308 private static final int POOL_LIMIT = 10; 26309 26310 private static final SynchronizedPool<InvalidateInfo> sPool = 26311 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 26312 26313 View target; 26314 26315 int left; 26316 int top; 26317 int right; 26318 int bottom; 26319 26320 public static InvalidateInfo obtain() { 26321 InvalidateInfo instance = sPool.acquire(); 26322 return (instance != null) ? instance : new InvalidateInfo(); 26323 } 26324 26325 public void recycle() { 26326 target = null; 26327 sPool.release(this); 26328 } 26329 } 26330 26331 final IWindowSession mSession; 26332 26333 final IWindow mWindow; 26334 26335 final IBinder mWindowToken; 26336 26337 Display mDisplay; 26338 26339 final Callbacks mRootCallbacks; 26340 26341 IWindowId mIWindowId; 26342 WindowId mWindowId; 26343 26344 /** 26345 * The top view of the hierarchy. 26346 */ 26347 View mRootView; 26348 26349 IBinder mPanelParentWindowToken; 26350 26351 boolean mHardwareAccelerated; 26352 boolean mHardwareAccelerationRequested; 26353 ThreadedRenderer mThreadedRenderer; 26354 List<RenderNode> mPendingAnimatingRenderNodes; 26355 26356 /** 26357 * The state of the display to which the window is attached, as reported 26358 * by {@link Display#getState()}. Note that the display state constants 26359 * declared by {@link Display} do not exactly line up with the screen state 26360 * constants declared by {@link View} (there are more display states than 26361 * screen states). 26362 */ 26363 int mDisplayState = Display.STATE_UNKNOWN; 26364 26365 /** 26366 * Scale factor used by the compatibility mode 26367 */ 26368 float mApplicationScale; 26369 26370 /** 26371 * Indicates whether the application is in compatibility mode 26372 */ 26373 boolean mScalingRequired; 26374 26375 /** 26376 * Left position of this view's window 26377 */ 26378 int mWindowLeft; 26379 26380 /** 26381 * Top position of this view's window 26382 */ 26383 int mWindowTop; 26384 26385 /** 26386 * Indicates whether views need to use 32-bit drawing caches 26387 */ 26388 boolean mUse32BitDrawingCache; 26389 26390 /** 26391 * For windows that are full-screen but using insets to layout inside 26392 * of the screen areas, these are the current insets to appear inside 26393 * the overscan area of the display. 26394 */ 26395 final Rect mOverscanInsets = new Rect(); 26396 26397 /** 26398 * For windows that are full-screen but using insets to layout inside 26399 * of the screen decorations, these are the current insets for the 26400 * content of the window. 26401 */ 26402 final Rect mContentInsets = new Rect(); 26403 26404 /** 26405 * For windows that are full-screen but using insets to layout inside 26406 * of the screen decorations, these are the current insets for the 26407 * actual visible parts of the window. 26408 */ 26409 final Rect mVisibleInsets = new Rect(); 26410 26411 /** 26412 * For windows that are full-screen but using insets to layout inside 26413 * of the screen decorations, these are the current insets for the 26414 * stable system windows. 26415 */ 26416 final Rect mStableInsets = new Rect(); 26417 26418 final DisplayCutout.ParcelableWrapper mDisplayCutout = 26419 new DisplayCutout.ParcelableWrapper(DisplayCutout.NO_CUTOUT); 26420 26421 /** 26422 * For windows that include areas that are not covered by real surface these are the outsets 26423 * for real surface. 26424 */ 26425 final Rect mOutsets = new Rect(); 26426 26427 /** 26428 * In multi-window we force show the navigation bar. Because we don't want that the surface 26429 * size changes in this mode, we instead have a flag whether the navigation bar size should 26430 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 26431 */ 26432 boolean mAlwaysConsumeNavBar; 26433 26434 /** 26435 * The internal insets given by this window. This value is 26436 * supplied by the client (through 26437 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 26438 * be given to the window manager when changed to be used in laying 26439 * out windows behind it. 26440 */ 26441 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 26442 = new ViewTreeObserver.InternalInsetsInfo(); 26443 26444 /** 26445 * Set to true when mGivenInternalInsets is non-empty. 26446 */ 26447 boolean mHasNonEmptyGivenInternalInsets; 26448 26449 /** 26450 * All views in the window's hierarchy that serve as scroll containers, 26451 * used to determine if the window can be resized or must be panned 26452 * to adjust for a soft input area. 26453 */ 26454 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 26455 26456 final KeyEvent.DispatcherState mKeyDispatchState 26457 = new KeyEvent.DispatcherState(); 26458 26459 /** 26460 * Indicates whether the view's window currently has the focus. 26461 */ 26462 boolean mHasWindowFocus; 26463 26464 /** 26465 * The current visibility of the window. 26466 */ 26467 int mWindowVisibility; 26468 26469 /** 26470 * Indicates the time at which drawing started to occur. 26471 */ 26472 long mDrawingTime; 26473 26474 /** 26475 * Indicates whether or not ignoring the DIRTY_MASK flags. 26476 */ 26477 boolean mIgnoreDirtyState; 26478 26479 /** 26480 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 26481 * to avoid clearing that flag prematurely. 26482 */ 26483 boolean mSetIgnoreDirtyState = false; 26484 26485 /** 26486 * Indicates whether the view's window is currently in touch mode. 26487 */ 26488 boolean mInTouchMode; 26489 26490 /** 26491 * Indicates whether the view has requested unbuffered input dispatching for the current 26492 * event stream. 26493 */ 26494 boolean mUnbufferedDispatchRequested; 26495 26496 /** 26497 * Indicates that ViewAncestor should trigger a global layout change 26498 * the next time it performs a traversal 26499 */ 26500 boolean mRecomputeGlobalAttributes; 26501 26502 /** 26503 * Always report new attributes at next traversal. 26504 */ 26505 boolean mForceReportNewAttributes; 26506 26507 /** 26508 * Set during a traveral if any views want to keep the screen on. 26509 */ 26510 boolean mKeepScreenOn; 26511 26512 /** 26513 * Set during a traveral if the light center needs to be updated. 26514 */ 26515 boolean mNeedsUpdateLightCenter; 26516 26517 /** 26518 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 26519 */ 26520 int mSystemUiVisibility; 26521 26522 /** 26523 * Hack to force certain system UI visibility flags to be cleared. 26524 */ 26525 int mDisabledSystemUiVisibility; 26526 26527 /** 26528 * Last global system UI visibility reported by the window manager. 26529 */ 26530 int mGlobalSystemUiVisibility = -1; 26531 26532 /** 26533 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 26534 * attached. 26535 */ 26536 boolean mHasSystemUiListeners; 26537 26538 /** 26539 * Set if the window has requested to extend into the overscan region 26540 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 26541 */ 26542 boolean mOverscanRequested; 26543 26544 /** 26545 * Set if the visibility of any views has changed. 26546 */ 26547 boolean mViewVisibilityChanged; 26548 26549 /** 26550 * Set to true if a view has been scrolled. 26551 */ 26552 boolean mViewScrollChanged; 26553 26554 /** 26555 * Set to true if a pointer event is currently being handled. 26556 */ 26557 boolean mHandlingPointerEvent; 26558 26559 /** 26560 * Global to the view hierarchy used as a temporary for dealing with 26561 * x/y points in the transparent region computations. 26562 */ 26563 final int[] mTransparentLocation = new int[2]; 26564 26565 /** 26566 * Global to the view hierarchy used as a temporary for dealing with 26567 * x/y points in the ViewGroup.invalidateChild implementation. 26568 */ 26569 final int[] mInvalidateChildLocation = new int[2]; 26570 26571 /** 26572 * Global to the view hierarchy used as a temporary for dealing with 26573 * computing absolute on-screen location. 26574 */ 26575 final int[] mTmpLocation = new int[2]; 26576 26577 /** 26578 * Global to the view hierarchy used as a temporary for dealing with 26579 * x/y location when view is transformed. 26580 */ 26581 final float[] mTmpTransformLocation = new float[2]; 26582 26583 /** 26584 * The view tree observer used to dispatch global events like 26585 * layout, pre-draw, touch mode change, etc. 26586 */ 26587 final ViewTreeObserver mTreeObserver; 26588 26589 /** 26590 * A Canvas used by the view hierarchy to perform bitmap caching. 26591 */ 26592 Canvas mCanvas; 26593 26594 /** 26595 * The view root impl. 26596 */ 26597 final ViewRootImpl mViewRootImpl; 26598 26599 /** 26600 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 26601 * handler can be used to pump events in the UI events queue. 26602 */ 26603 final Handler mHandler; 26604 26605 /** 26606 * Temporary for use in computing invalidate rectangles while 26607 * calling up the hierarchy. 26608 */ 26609 final Rect mTmpInvalRect = new Rect(); 26610 26611 /** 26612 * Temporary for use in computing hit areas with transformed views 26613 */ 26614 final RectF mTmpTransformRect = new RectF(); 26615 26616 /** 26617 * Temporary for use in computing hit areas with transformed views 26618 */ 26619 final RectF mTmpTransformRect1 = new RectF(); 26620 26621 /** 26622 * Temporary list of rectanges. 26623 */ 26624 final List<RectF> mTmpRectList = new ArrayList<>(); 26625 26626 /** 26627 * Temporary for use in transforming invalidation rect 26628 */ 26629 final Matrix mTmpMatrix = new Matrix(); 26630 26631 /** 26632 * Temporary for use in transforming invalidation rect 26633 */ 26634 final Transformation mTmpTransformation = new Transformation(); 26635 26636 /** 26637 * Temporary for use in querying outlines from OutlineProviders 26638 */ 26639 final Outline mTmpOutline = new Outline(); 26640 26641 /** 26642 * Temporary list for use in collecting focusable descendents of a view. 26643 */ 26644 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 26645 26646 /** 26647 * The id of the window for accessibility purposes. 26648 */ 26649 int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID; 26650 26651 /** 26652 * Flags related to accessibility processing. 26653 * 26654 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 26655 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 26656 */ 26657 int mAccessibilityFetchFlags; 26658 26659 /** 26660 * The drawable for highlighting accessibility focus. 26661 */ 26662 Drawable mAccessibilityFocusDrawable; 26663 26664 /** 26665 * The drawable for highlighting autofilled views. 26666 * 26667 * @see #isAutofilled() 26668 */ 26669 Drawable mAutofilledDrawable; 26670 26671 /** 26672 * Show where the margins, bounds and layout bounds are for each view. 26673 */ 26674 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 26675 26676 /** 26677 * Point used to compute visible regions. 26678 */ 26679 final Point mPoint = new Point(); 26680 26681 /** 26682 * Used to track which View originated a requestLayout() call, used when 26683 * requestLayout() is called during layout. 26684 */ 26685 View mViewRequestingLayout; 26686 26687 /** 26688 * Used to track views that need (at least) a partial relayout at their current size 26689 * during the next traversal. 26690 */ 26691 List<View> mPartialLayoutViews = new ArrayList<>(); 26692 26693 /** 26694 * Swapped with mPartialLayoutViews during layout to avoid concurrent 26695 * modification. Lazily assigned during ViewRootImpl layout. 26696 */ 26697 List<View> mEmptyPartialLayoutViews; 26698 26699 /** 26700 * Used to track the identity of the current drag operation. 26701 */ 26702 IBinder mDragToken; 26703 26704 /** 26705 * The drag shadow surface for the current drag operation. 26706 */ 26707 public Surface mDragSurface; 26708 26709 26710 /** 26711 * The view that currently has a tooltip displayed. 26712 */ 26713 View mTooltipHost; 26714 26715 /** 26716 * Creates a new set of attachment information with the specified 26717 * events handler and thread. 26718 * 26719 * @param handler the events handler the view must use 26720 */ 26721 AttachInfo(IWindowSession session, IWindow window, Display display, 26722 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer, 26723 Context context) { 26724 mSession = session; 26725 mWindow = window; 26726 mWindowToken = window.asBinder(); 26727 mDisplay = display; 26728 mViewRootImpl = viewRootImpl; 26729 mHandler = handler; 26730 mRootCallbacks = effectPlayer; 26731 mTreeObserver = new ViewTreeObserver(context); 26732 } 26733 } 26734 26735 /** 26736 * <p>ScrollabilityCache holds various fields used by a View when scrolling 26737 * is supported. This avoids keeping too many unused fields in most 26738 * instances of View.</p> 26739 */ 26740 private static class ScrollabilityCache implements Runnable { 26741 26742 /** 26743 * Scrollbars are not visible 26744 */ 26745 public static final int OFF = 0; 26746 26747 /** 26748 * Scrollbars are visible 26749 */ 26750 public static final int ON = 1; 26751 26752 /** 26753 * Scrollbars are fading away 26754 */ 26755 public static final int FADING = 2; 26756 26757 public boolean fadeScrollBars; 26758 26759 public int fadingEdgeLength; 26760 public int scrollBarDefaultDelayBeforeFade; 26761 public int scrollBarFadeDuration; 26762 26763 public int scrollBarSize; 26764 public int scrollBarMinTouchTarget; 26765 public ScrollBarDrawable scrollBar; 26766 public float[] interpolatorValues; 26767 public View host; 26768 26769 public final Paint paint; 26770 public final Matrix matrix; 26771 public Shader shader; 26772 26773 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 26774 26775 private static final float[] OPAQUE = { 255 }; 26776 private static final float[] TRANSPARENT = { 0.0f }; 26777 26778 /** 26779 * When fading should start. This time moves into the future every time 26780 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 26781 */ 26782 public long fadeStartTime; 26783 26784 26785 /** 26786 * The current state of the scrollbars: ON, OFF, or FADING 26787 */ 26788 public int state = OFF; 26789 26790 private int mLastColor; 26791 26792 public final Rect mScrollBarBounds = new Rect(); 26793 public final Rect mScrollBarTouchBounds = new Rect(); 26794 26795 public static final int NOT_DRAGGING = 0; 26796 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 26797 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 26798 public int mScrollBarDraggingState = NOT_DRAGGING; 26799 26800 public float mScrollBarDraggingPos = 0; 26801 26802 public ScrollabilityCache(ViewConfiguration configuration, View host) { 26803 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 26804 scrollBarSize = configuration.getScaledScrollBarSize(); 26805 scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget(); 26806 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 26807 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 26808 26809 paint = new Paint(); 26810 matrix = new Matrix(); 26811 // use use a height of 1, and then wack the matrix each time we 26812 // actually use it. 26813 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 26814 paint.setShader(shader); 26815 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 26816 26817 this.host = host; 26818 } 26819 26820 public void setFadeColor(int color) { 26821 if (color != mLastColor) { 26822 mLastColor = color; 26823 26824 if (color != 0) { 26825 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 26826 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 26827 paint.setShader(shader); 26828 // Restore the default transfer mode (src_over) 26829 paint.setXfermode(null); 26830 } else { 26831 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 26832 paint.setShader(shader); 26833 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 26834 } 26835 } 26836 } 26837 26838 public void run() { 26839 long now = AnimationUtils.currentAnimationTimeMillis(); 26840 if (now >= fadeStartTime) { 26841 26842 // the animation fades the scrollbars out by changing 26843 // the opacity (alpha) from fully opaque to fully 26844 // transparent 26845 int nextFrame = (int) now; 26846 int framesCount = 0; 26847 26848 Interpolator interpolator = scrollBarInterpolator; 26849 26850 // Start opaque 26851 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 26852 26853 // End transparent 26854 nextFrame += scrollBarFadeDuration; 26855 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 26856 26857 state = FADING; 26858 26859 // Kick off the fade animation 26860 host.invalidate(true); 26861 } 26862 } 26863 } 26864 26865 /** 26866 * Resuable callback for sending 26867 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 26868 */ 26869 private class SendViewScrolledAccessibilityEvent implements Runnable { 26870 public volatile boolean mIsPending; 26871 public int mDeltaX; 26872 public int mDeltaY; 26873 26874 public void post(int dx, int dy) { 26875 mDeltaX += dx; 26876 mDeltaY += dy; 26877 if (!mIsPending) { 26878 mIsPending = true; 26879 postDelayed(this, ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 26880 } 26881 } 26882 26883 @Override 26884 public void run() { 26885 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 26886 AccessibilityEvent event = AccessibilityEvent.obtain( 26887 AccessibilityEvent.TYPE_VIEW_SCROLLED); 26888 event.setScrollDeltaX(mDeltaX); 26889 event.setScrollDeltaY(mDeltaY); 26890 sendAccessibilityEventUnchecked(event); 26891 } 26892 reset(); 26893 } 26894 26895 private void reset() { 26896 mIsPending = false; 26897 mDeltaX = 0; 26898 mDeltaY = 0; 26899 } 26900 } 26901 26902 /** 26903 * Remove the pending callback for sending a 26904 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 26905 */ 26906 private void cancel(@Nullable SendViewScrolledAccessibilityEvent callback) { 26907 if (callback == null || !callback.mIsPending) return; 26908 removeCallbacks(callback); 26909 callback.reset(); 26910 } 26911 26912 /** 26913 * <p> 26914 * This class represents a delegate that can be registered in a {@link View} 26915 * to enhance accessibility support via composition rather via inheritance. 26916 * It is specifically targeted to widget developers that extend basic View 26917 * classes i.e. classes in package android.view, that would like their 26918 * applications to be backwards compatible. 26919 * </p> 26920 * <div class="special reference"> 26921 * <h3>Developer Guides</h3> 26922 * <p>For more information about making applications accessible, read the 26923 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 26924 * developer guide.</p> 26925 * </div> 26926 * <p> 26927 * A scenario in which a developer would like to use an accessibility delegate 26928 * is overriding a method introduced in a later API version than the minimal API 26929 * version supported by the application. For example, the method 26930 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 26931 * in API version 4 when the accessibility APIs were first introduced. If a 26932 * developer would like his application to run on API version 4 devices (assuming 26933 * all other APIs used by the application are version 4 or lower) and take advantage 26934 * of this method, instead of overriding the method which would break the application's 26935 * backwards compatibility, he can override the corresponding method in this 26936 * delegate and register the delegate in the target View if the API version of 26937 * the system is high enough, i.e. the API version is the same as or higher than the API 26938 * version that introduced 26939 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 26940 * </p> 26941 * <p> 26942 * Here is an example implementation: 26943 * </p> 26944 * <code><pre><p> 26945 * if (Build.VERSION.SDK_INT >= 14) { 26946 * // If the API version is equal of higher than the version in 26947 * // which onInitializeAccessibilityNodeInfo was introduced we 26948 * // register a delegate with a customized implementation. 26949 * View view = findViewById(R.id.view_id); 26950 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 26951 * public void onInitializeAccessibilityNodeInfo(View host, 26952 * AccessibilityNodeInfo info) { 26953 * // Let the default implementation populate the info. 26954 * super.onInitializeAccessibilityNodeInfo(host, info); 26955 * // Set some other information. 26956 * info.setEnabled(host.isEnabled()); 26957 * } 26958 * }); 26959 * } 26960 * </code></pre></p> 26961 * <p> 26962 * This delegate contains methods that correspond to the accessibility methods 26963 * in View. If a delegate has been specified the implementation in View hands 26964 * off handling to the corresponding method in this delegate. The default 26965 * implementation the delegate methods behaves exactly as the corresponding 26966 * method in View for the case of no accessibility delegate been set. Hence, 26967 * to customize the behavior of a View method, clients can override only the 26968 * corresponding delegate method without altering the behavior of the rest 26969 * accessibility related methods of the host view. 26970 * </p> 26971 * <p> 26972 * <strong>Note:</strong> On platform versions prior to 26973 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 26974 * views in the {@code android.widget.*} package are called <i>before</i> 26975 * host methods. This prevents certain properties such as class name from 26976 * being modified by overriding 26977 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 26978 * as any changes will be overwritten by the host class. 26979 * <p> 26980 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 26981 * methods are called <i>after</i> host methods, which all properties to be 26982 * modified without being overwritten by the host class. 26983 */ 26984 public static class AccessibilityDelegate { 26985 26986 /** 26987 * Sends an accessibility event of the given type. If accessibility is not 26988 * enabled this method has no effect. 26989 * <p> 26990 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 26991 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 26992 * been set. 26993 * </p> 26994 * 26995 * @param host The View hosting the delegate. 26996 * @param eventType The type of the event to send. 26997 * 26998 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 26999 */ 27000 public void sendAccessibilityEvent(View host, int eventType) { 27001 host.sendAccessibilityEventInternal(eventType); 27002 } 27003 27004 /** 27005 * Performs the specified accessibility action on the view. For 27006 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 27007 * <p> 27008 * The default implementation behaves as 27009 * {@link View#performAccessibilityAction(int, Bundle) 27010 * View#performAccessibilityAction(int, Bundle)} for the case of 27011 * no accessibility delegate been set. 27012 * </p> 27013 * 27014 * @param action The action to perform. 27015 * @return Whether the action was performed. 27016 * 27017 * @see View#performAccessibilityAction(int, Bundle) 27018 * View#performAccessibilityAction(int, Bundle) 27019 */ 27020 public boolean performAccessibilityAction(View host, int action, Bundle args) { 27021 return host.performAccessibilityActionInternal(action, args); 27022 } 27023 27024 /** 27025 * Sends an accessibility event. This method behaves exactly as 27026 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 27027 * empty {@link AccessibilityEvent} and does not perform a check whether 27028 * accessibility is enabled. 27029 * <p> 27030 * The default implementation behaves as 27031 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 27032 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 27033 * the case of no accessibility delegate been set. 27034 * </p> 27035 * 27036 * @param host The View hosting the delegate. 27037 * @param event The event to send. 27038 * 27039 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 27040 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 27041 */ 27042 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 27043 host.sendAccessibilityEventUncheckedInternal(event); 27044 } 27045 27046 /** 27047 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 27048 * to its children for adding their text content to the event. 27049 * <p> 27050 * The default implementation behaves as 27051 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 27052 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 27053 * the case of no accessibility delegate been set. 27054 * </p> 27055 * 27056 * @param host The View hosting the delegate. 27057 * @param event The event. 27058 * @return True if the event population was completed. 27059 * 27060 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 27061 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 27062 */ 27063 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 27064 return host.dispatchPopulateAccessibilityEventInternal(event); 27065 } 27066 27067 /** 27068 * Gives a chance to the host View to populate the accessibility event with its 27069 * text content. 27070 * <p> 27071 * The default implementation behaves as 27072 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 27073 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 27074 * the case of no accessibility delegate been set. 27075 * </p> 27076 * 27077 * @param host The View hosting the delegate. 27078 * @param event The accessibility event which to populate. 27079 * 27080 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 27081 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 27082 */ 27083 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 27084 host.onPopulateAccessibilityEventInternal(event); 27085 } 27086 27087 /** 27088 * Initializes an {@link AccessibilityEvent} with information about the 27089 * the host View which is the event source. 27090 * <p> 27091 * The default implementation behaves as 27092 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 27093 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 27094 * the case of no accessibility delegate been set. 27095 * </p> 27096 * 27097 * @param host The View hosting the delegate. 27098 * @param event The event to initialize. 27099 * 27100 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 27101 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 27102 */ 27103 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 27104 host.onInitializeAccessibilityEventInternal(event); 27105 } 27106 27107 /** 27108 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 27109 * <p> 27110 * The default implementation behaves as 27111 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 27112 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 27113 * the case of no accessibility delegate been set. 27114 * </p> 27115 * 27116 * @param host The View hosting the delegate. 27117 * @param info The instance to initialize. 27118 * 27119 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 27120 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 27121 */ 27122 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 27123 host.onInitializeAccessibilityNodeInfoInternal(info); 27124 } 27125 27126 /** 27127 * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the 27128 * additional data. 27129 * <p> 27130 * This method only needs to be implemented if the View offers to provide additional data. 27131 * </p> 27132 * <p> 27133 * The default implementation behaves as 27134 * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, String, Bundle) 27135 * for the case where no accessibility delegate is set. 27136 * </p> 27137 * 27138 * @param host The View hosting the delegate. Never {@code null}. 27139 * @param info The info to which to add the extra data. Never {@code null}. 27140 * @param extraDataKey A key specifying the type of extra data to add to the info. The 27141 * extra data should be added to the {@link Bundle} returned by 27142 * the info's {@link AccessibilityNodeInfo#getExtras} method. Never 27143 * {@code null}. 27144 * @param arguments A {@link Bundle} holding any arguments relevant for this request. 27145 * May be {@code null} if the if the service provided no arguments. 27146 * 27147 * @see AccessibilityNodeInfo#setExtraAvailableData 27148 */ 27149 public void addExtraDataToAccessibilityNodeInfo(@NonNull View host, 27150 @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey, 27151 @Nullable Bundle arguments) { 27152 host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments); 27153 } 27154 27155 /** 27156 * Called when a child of the host View has requested sending an 27157 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 27158 * to augment the event. 27159 * <p> 27160 * The default implementation behaves as 27161 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 27162 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 27163 * the case of no accessibility delegate been set. 27164 * </p> 27165 * 27166 * @param host The View hosting the delegate. 27167 * @param child The child which requests sending the event. 27168 * @param event The event to be sent. 27169 * @return True if the event should be sent 27170 * 27171 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 27172 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 27173 */ 27174 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 27175 AccessibilityEvent event) { 27176 return host.onRequestSendAccessibilityEventInternal(child, event); 27177 } 27178 27179 /** 27180 * Gets the provider for managing a virtual view hierarchy rooted at this View 27181 * and reported to {@link android.accessibilityservice.AccessibilityService}s 27182 * that explore the window content. 27183 * <p> 27184 * The default implementation behaves as 27185 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 27186 * the case of no accessibility delegate been set. 27187 * </p> 27188 * 27189 * @return The provider. 27190 * 27191 * @see AccessibilityNodeProvider 27192 */ 27193 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 27194 return null; 27195 } 27196 27197 /** 27198 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 27199 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 27200 * This method is responsible for obtaining an accessibility node info from a 27201 * pool of reusable instances and calling 27202 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 27203 * view to initialize the former. 27204 * <p> 27205 * <strong>Note:</strong> The client is responsible for recycling the obtained 27206 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 27207 * creation. 27208 * </p> 27209 * <p> 27210 * The default implementation behaves as 27211 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 27212 * the case of no accessibility delegate been set. 27213 * </p> 27214 * @return A populated {@link AccessibilityNodeInfo}. 27215 * 27216 * @see AccessibilityNodeInfo 27217 * 27218 * @hide 27219 */ 27220 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 27221 return host.createAccessibilityNodeInfoInternal(); 27222 } 27223 } 27224 27225 private static class MatchIdPredicate implements Predicate<View> { 27226 public int mId; 27227 27228 @Override 27229 public boolean test(View view) { 27230 return (view.mID == mId); 27231 } 27232 } 27233 27234 private static class MatchLabelForPredicate implements Predicate<View> { 27235 private int mLabeledId; 27236 27237 @Override 27238 public boolean test(View view) { 27239 return (view.mLabelForId == mLabeledId); 27240 } 27241 } 27242 27243 /** 27244 * Dump all private flags in readable format, useful for documentation and 27245 * sanity checking. 27246 */ 27247 private static void dumpFlags() { 27248 final HashMap<String, String> found = Maps.newHashMap(); 27249 try { 27250 for (Field field : View.class.getDeclaredFields()) { 27251 final int modifiers = field.getModifiers(); 27252 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 27253 if (field.getType().equals(int.class)) { 27254 final int value = field.getInt(null); 27255 dumpFlag(found, field.getName(), value); 27256 } else if (field.getType().equals(int[].class)) { 27257 final int[] values = (int[]) field.get(null); 27258 for (int i = 0; i < values.length; i++) { 27259 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 27260 } 27261 } 27262 } 27263 } 27264 } catch (IllegalAccessException e) { 27265 throw new RuntimeException(e); 27266 } 27267 27268 final ArrayList<String> keys = Lists.newArrayList(); 27269 keys.addAll(found.keySet()); 27270 Collections.sort(keys); 27271 for (String key : keys) { 27272 Log.d(VIEW_LOG_TAG, found.get(key)); 27273 } 27274 } 27275 27276 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 27277 // Sort flags by prefix, then by bits, always keeping unique keys 27278 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 27279 final int prefix = name.indexOf('_'); 27280 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 27281 final String output = bits + " " + name; 27282 found.put(key, output); 27283 } 27284 27285 /** {@hide} */ 27286 public void encode(@NonNull ViewHierarchyEncoder stream) { 27287 stream.beginObject(this); 27288 encodeProperties(stream); 27289 stream.endObject(); 27290 } 27291 27292 /** {@hide} */ 27293 @CallSuper 27294 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 27295 Object resolveId = ViewDebug.resolveId(getContext(), mID); 27296 if (resolveId instanceof String) { 27297 stream.addProperty("id", (String) resolveId); 27298 } else { 27299 stream.addProperty("id", mID); 27300 } 27301 27302 stream.addProperty("misc:transformation.alpha", 27303 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 27304 stream.addProperty("misc:transitionName", getTransitionName()); 27305 27306 // layout 27307 stream.addProperty("layout:left", mLeft); 27308 stream.addProperty("layout:right", mRight); 27309 stream.addProperty("layout:top", mTop); 27310 stream.addProperty("layout:bottom", mBottom); 27311 stream.addProperty("layout:width", getWidth()); 27312 stream.addProperty("layout:height", getHeight()); 27313 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 27314 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 27315 stream.addProperty("layout:hasTransientState", hasTransientState()); 27316 stream.addProperty("layout:baseline", getBaseline()); 27317 27318 // layout params 27319 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 27320 if (layoutParams != null) { 27321 stream.addPropertyKey("layoutParams"); 27322 layoutParams.encode(stream); 27323 } 27324 27325 // scrolling 27326 stream.addProperty("scrolling:scrollX", mScrollX); 27327 stream.addProperty("scrolling:scrollY", mScrollY); 27328 27329 // padding 27330 stream.addProperty("padding:paddingLeft", mPaddingLeft); 27331 stream.addProperty("padding:paddingRight", mPaddingRight); 27332 stream.addProperty("padding:paddingTop", mPaddingTop); 27333 stream.addProperty("padding:paddingBottom", mPaddingBottom); 27334 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 27335 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 27336 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 27337 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 27338 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 27339 27340 // measurement 27341 stream.addProperty("measurement:minHeight", mMinHeight); 27342 stream.addProperty("measurement:minWidth", mMinWidth); 27343 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 27344 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 27345 27346 // drawing 27347 stream.addProperty("drawing:elevation", getElevation()); 27348 stream.addProperty("drawing:translationX", getTranslationX()); 27349 stream.addProperty("drawing:translationY", getTranslationY()); 27350 stream.addProperty("drawing:translationZ", getTranslationZ()); 27351 stream.addProperty("drawing:rotation", getRotation()); 27352 stream.addProperty("drawing:rotationX", getRotationX()); 27353 stream.addProperty("drawing:rotationY", getRotationY()); 27354 stream.addProperty("drawing:scaleX", getScaleX()); 27355 stream.addProperty("drawing:scaleY", getScaleY()); 27356 stream.addProperty("drawing:pivotX", getPivotX()); 27357 stream.addProperty("drawing:pivotY", getPivotY()); 27358 stream.addProperty("drawing:clipBounds", 27359 mClipBounds == null ? null : mClipBounds.toString()); 27360 stream.addProperty("drawing:opaque", isOpaque()); 27361 stream.addProperty("drawing:alpha", getAlpha()); 27362 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 27363 stream.addProperty("drawing:shadow", hasShadow()); 27364 stream.addProperty("drawing:solidColor", getSolidColor()); 27365 stream.addProperty("drawing:layerType", mLayerType); 27366 stream.addProperty("drawing:willNotDraw", willNotDraw()); 27367 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 27368 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 27369 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 27370 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 27371 stream.addProperty("drawing:outlineAmbientShadowColor", getOutlineAmbientShadowColor()); 27372 stream.addProperty("drawing:outlineSpotShadowColor", getOutlineSpotShadowColor()); 27373 27374 // focus 27375 stream.addProperty("focus:hasFocus", hasFocus()); 27376 stream.addProperty("focus:isFocused", isFocused()); 27377 stream.addProperty("focus:focusable", getFocusable()); 27378 stream.addProperty("focus:isFocusable", isFocusable()); 27379 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 27380 27381 stream.addProperty("misc:clickable", isClickable()); 27382 stream.addProperty("misc:pressed", isPressed()); 27383 stream.addProperty("misc:selected", isSelected()); 27384 stream.addProperty("misc:touchMode", isInTouchMode()); 27385 stream.addProperty("misc:hovered", isHovered()); 27386 stream.addProperty("misc:activated", isActivated()); 27387 27388 stream.addProperty("misc:visibility", getVisibility()); 27389 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 27390 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 27391 27392 stream.addProperty("misc:enabled", isEnabled()); 27393 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 27394 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 27395 27396 // theme attributes 27397 Resources.Theme theme = getContext().getTheme(); 27398 if (theme != null) { 27399 stream.addPropertyKey("theme"); 27400 theme.encode(stream); 27401 } 27402 27403 // view attribute information 27404 int n = mAttributes != null ? mAttributes.length : 0; 27405 stream.addProperty("meta:__attrCount__", n/2); 27406 for (int i = 0; i < n; i += 2) { 27407 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 27408 } 27409 27410 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 27411 27412 // text 27413 stream.addProperty("text:textDirection", getTextDirection()); 27414 stream.addProperty("text:textAlignment", getTextAlignment()); 27415 27416 // accessibility 27417 CharSequence contentDescription = getContentDescription(); 27418 stream.addProperty("accessibility:contentDescription", 27419 contentDescription == null ? "" : contentDescription.toString()); 27420 stream.addProperty("accessibility:labelFor", getLabelFor()); 27421 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 27422 } 27423 27424 /** 27425 * Determine if this view is rendered on a round wearable device and is the main view 27426 * on the screen. 27427 */ 27428 boolean shouldDrawRoundScrollbar() { 27429 if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) { 27430 return false; 27431 } 27432 27433 final View rootView = getRootView(); 27434 final WindowInsets insets = getRootWindowInsets(); 27435 27436 int height = getHeight(); 27437 int width = getWidth(); 27438 int displayHeight = rootView.getHeight(); 27439 int displayWidth = rootView.getWidth(); 27440 27441 if (height != displayHeight || width != displayWidth) { 27442 return false; 27443 } 27444 27445 getLocationInWindow(mAttachInfo.mTmpLocation); 27446 return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft() 27447 && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop(); 27448 } 27449 27450 /** 27451 * Sets the tooltip text which will be displayed in a small popup next to the view. 27452 * <p> 27453 * The tooltip will be displayed: 27454 * <ul> 27455 * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context 27456 * menu). </li> 27457 * <li>On hover, after a brief delay since the pointer has stopped moving </li> 27458 * </ul> 27459 * <p> 27460 * <strong>Note:</strong> Do not override this method, as it will have no 27461 * effect on the text displayed in the tooltip. 27462 * 27463 * @param tooltipText the tooltip text, or null if no tooltip is required 27464 * @see #getTooltipText() 27465 * @attr ref android.R.styleable#View_tooltipText 27466 */ 27467 public void setTooltipText(@Nullable CharSequence tooltipText) { 27468 if (TextUtils.isEmpty(tooltipText)) { 27469 setFlags(0, TOOLTIP); 27470 hideTooltip(); 27471 mTooltipInfo = null; 27472 } else { 27473 setFlags(TOOLTIP, TOOLTIP); 27474 if (mTooltipInfo == null) { 27475 mTooltipInfo = new TooltipInfo(); 27476 mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip; 27477 mTooltipInfo.mHideTooltipRunnable = this::hideTooltip; 27478 mTooltipInfo.mHoverSlop = ViewConfiguration.get(mContext).getScaledHoverSlop(); 27479 mTooltipInfo.clearAnchorPos(); 27480 } 27481 mTooltipInfo.mTooltipText = tooltipText; 27482 } 27483 } 27484 27485 /** 27486 * @hide Binary compatibility stub. To be removed when we finalize O APIs. 27487 */ 27488 public void setTooltip(@Nullable CharSequence tooltipText) { 27489 setTooltipText(tooltipText); 27490 } 27491 27492 /** 27493 * Returns the view's tooltip text. 27494 * 27495 * <strong>Note:</strong> Do not override this method, as it will have no 27496 * effect on the text displayed in the tooltip. You must call 27497 * {@link #setTooltipText(CharSequence)} to modify the tooltip text. 27498 * 27499 * @return the tooltip text 27500 * @see #setTooltipText(CharSequence) 27501 * @attr ref android.R.styleable#View_tooltipText 27502 */ 27503 @Nullable 27504 public CharSequence getTooltipText() { 27505 return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null; 27506 } 27507 27508 /** 27509 * @hide Binary compatibility stub. To be removed when we finalize O APIs. 27510 */ 27511 @Nullable 27512 public CharSequence getTooltip() { 27513 return getTooltipText(); 27514 } 27515 27516 private boolean showTooltip(int x, int y, boolean fromLongClick) { 27517 if (mAttachInfo == null || mTooltipInfo == null) { 27518 return false; 27519 } 27520 if (fromLongClick && (mViewFlags & ENABLED_MASK) != ENABLED) { 27521 return false; 27522 } 27523 if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) { 27524 return false; 27525 } 27526 hideTooltip(); 27527 mTooltipInfo.mTooltipFromLongClick = fromLongClick; 27528 mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext()); 27529 final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN; 27530 mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText); 27531 mAttachInfo.mTooltipHost = this; 27532 // The available accessibility actions have changed 27533 notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED); 27534 return true; 27535 } 27536 27537 void hideTooltip() { 27538 if (mTooltipInfo == null) { 27539 return; 27540 } 27541 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 27542 if (mTooltipInfo.mTooltipPopup == null) { 27543 return; 27544 } 27545 mTooltipInfo.mTooltipPopup.hide(); 27546 mTooltipInfo.mTooltipPopup = null; 27547 mTooltipInfo.mTooltipFromLongClick = false; 27548 mTooltipInfo.clearAnchorPos(); 27549 if (mAttachInfo != null) { 27550 mAttachInfo.mTooltipHost = null; 27551 } 27552 // The available accessibility actions have changed 27553 notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED); 27554 } 27555 27556 private boolean showLongClickTooltip(int x, int y) { 27557 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 27558 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 27559 return showTooltip(x, y, true); 27560 } 27561 27562 private boolean showHoverTooltip() { 27563 return showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false); 27564 } 27565 27566 boolean dispatchTooltipHoverEvent(MotionEvent event) { 27567 if (mTooltipInfo == null) { 27568 return false; 27569 } 27570 switch(event.getAction()) { 27571 case MotionEvent.ACTION_HOVER_MOVE: 27572 if ((mViewFlags & TOOLTIP) != TOOLTIP) { 27573 break; 27574 } 27575 if (!mTooltipInfo.mTooltipFromLongClick && mTooltipInfo.updateAnchorPos(event)) { 27576 if (mTooltipInfo.mTooltipPopup == null) { 27577 // Schedule showing the tooltip after a timeout. 27578 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 27579 postDelayed(mTooltipInfo.mShowTooltipRunnable, 27580 ViewConfiguration.getHoverTooltipShowTimeout()); 27581 } 27582 27583 // Hide hover-triggered tooltip after a period of inactivity. 27584 // Match the timeout used by NativeInputManager to hide the mouse pointer 27585 // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set). 27586 final int timeout; 27587 if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE) 27588 == SYSTEM_UI_FLAG_LOW_PROFILE) { 27589 timeout = ViewConfiguration.getHoverTooltipHideShortTimeout(); 27590 } else { 27591 timeout = ViewConfiguration.getHoverTooltipHideTimeout(); 27592 } 27593 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 27594 postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout); 27595 } 27596 return true; 27597 27598 case MotionEvent.ACTION_HOVER_EXIT: 27599 mTooltipInfo.clearAnchorPos(); 27600 if (!mTooltipInfo.mTooltipFromLongClick) { 27601 hideTooltip(); 27602 } 27603 break; 27604 } 27605 return false; 27606 } 27607 27608 void handleTooltipKey(KeyEvent event) { 27609 switch (event.getAction()) { 27610 case KeyEvent.ACTION_DOWN: 27611 if (event.getRepeatCount() == 0) { 27612 hideTooltip(); 27613 } 27614 break; 27615 27616 case KeyEvent.ACTION_UP: 27617 handleTooltipUp(); 27618 break; 27619 } 27620 } 27621 27622 private void handleTooltipUp() { 27623 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 27624 return; 27625 } 27626 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 27627 postDelayed(mTooltipInfo.mHideTooltipRunnable, 27628 ViewConfiguration.getLongPressTooltipHideTimeout()); 27629 } 27630 27631 private int getFocusableAttribute(TypedArray attributes) { 27632 TypedValue val = new TypedValue(); 27633 if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) { 27634 if (val.type == TypedValue.TYPE_INT_BOOLEAN) { 27635 return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE); 27636 } else { 27637 return val.data; 27638 } 27639 } else { 27640 return FOCUSABLE_AUTO; 27641 } 27642 } 27643 27644 /** 27645 * @return The content view of the tooltip popup currently being shown, or null if the tooltip 27646 * is not showing. 27647 * @hide 27648 */ 27649 @TestApi 27650 public View getTooltipView() { 27651 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 27652 return null; 27653 } 27654 return mTooltipInfo.mTooltipPopup.getContentView(); 27655 } 27656 27657 /** 27658 * @return {@code true} if the default focus highlight is enabled, {@code false} otherwies. 27659 * @hide 27660 */ 27661 @TestApi 27662 public static boolean isDefaultFocusHighlightEnabled() { 27663 return sUseDefaultFocusHighlight; 27664 } 27665 27666 /** 27667 * Dispatch a previously unhandled {@link KeyEvent} to this view. Unlike normal key dispatch, 27668 * this dispatches to ALL child views until it is consumed. The dispatch order is z-order 27669 * (visually on-top views first). 27670 * 27671 * @param evt the previously unhandled {@link KeyEvent}. 27672 * @return the {@link View} which consumed the event or {@code null} if not consumed. 27673 */ 27674 View dispatchUnhandledKeyEvent(KeyEvent evt) { 27675 if (onUnhandledKeyEvent(evt)) { 27676 return this; 27677 } 27678 return null; 27679 } 27680 27681 /** 27682 * Allows this view to handle {@link KeyEvent}s which weren't handled by normal dispatch. This 27683 * occurs after the normal view hierarchy dispatch, but before the window callback. By default, 27684 * this will dispatch into all the listeners registered via 27685 * {@link #addOnUnhandledKeyEventListener(OnUnhandledKeyEventListener)} in last-in-first-out 27686 * order (most recently added will receive events first). 27687 * 27688 * @param event An unhandled event. 27689 * @return {@code true} if the event was handled, {@code false} otherwise. 27690 * @see #addOnUnhandledKeyEventListener 27691 */ 27692 boolean onUnhandledKeyEvent(@NonNull KeyEvent event) { 27693 if (mListenerInfo != null && mListenerInfo.mUnhandledKeyListeners != null) { 27694 for (int i = mListenerInfo.mUnhandledKeyListeners.size() - 1; i >= 0; --i) { 27695 if (mListenerInfo.mUnhandledKeyListeners.get(i).onUnhandledKeyEvent(this, event)) { 27696 return true; 27697 } 27698 } 27699 } 27700 return false; 27701 } 27702 27703 boolean hasUnhandledKeyListener() { 27704 return (mListenerInfo != null && mListenerInfo.mUnhandledKeyListeners != null 27705 && !mListenerInfo.mUnhandledKeyListeners.isEmpty()); 27706 } 27707 27708 /** 27709 * Adds a listener which will receive unhandled {@link KeyEvent}s. This must be called on the 27710 * UI thread. 27711 * 27712 * @param listener a receiver of unhandled {@link KeyEvent}s. 27713 * @see #removeOnUnhandledKeyEventListener 27714 */ 27715 public void addOnUnhandledKeyEventListener(OnUnhandledKeyEventListener listener) { 27716 ArrayList<OnUnhandledKeyEventListener> listeners = getListenerInfo().mUnhandledKeyListeners; 27717 if (listeners == null) { 27718 listeners = new ArrayList<>(); 27719 getListenerInfo().mUnhandledKeyListeners = listeners; 27720 } 27721 listeners.add(listener); 27722 if (listeners.size() == 1 && mParent instanceof ViewGroup) { 27723 ((ViewGroup) mParent).incrementChildUnhandledKeyListeners(); 27724 } 27725 } 27726 27727 /** 27728 * Removes a listener which will receive unhandled {@link KeyEvent}s. This must be called on the 27729 * UI thread. 27730 * 27731 * @param listener a receiver of unhandled {@link KeyEvent}s. 27732 * @see #addOnUnhandledKeyEventListener 27733 */ 27734 public void removeOnUnhandledKeyEventListener(OnUnhandledKeyEventListener listener) { 27735 if (mListenerInfo != null) { 27736 if (mListenerInfo.mUnhandledKeyListeners != null 27737 && !mListenerInfo.mUnhandledKeyListeners.isEmpty()) { 27738 mListenerInfo.mUnhandledKeyListeners.remove(listener); 27739 if (mListenerInfo.mUnhandledKeyListeners.isEmpty()) { 27740 mListenerInfo.mUnhandledKeyListeners = null; 27741 if (mParent instanceof ViewGroup) { 27742 ((ViewGroup) mParent).decrementChildUnhandledKeyListeners(); 27743 } 27744 } 27745 } 27746 } 27747 } 27748} 27749